USB: dummy-hcd: fix connection failures (wrong speed)
[linux/fpc-iii.git] / fs / userfaultfd.c
blobb86054cc41db625893d5a9adbf5262117504a08f
1 /*
2 * fs/userfaultfd.c
4 * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
5 * Copyright (C) 2008-2009 Red Hat, Inc.
6 * Copyright (C) 2015 Red Hat, Inc.
8 * This work is licensed under the terms of the GNU GPL, version 2. See
9 * the COPYING file in the top-level directory.
11 * Some part derived from fs/eventfd.c (anon inode setup) and
12 * mm/ksm.c (mm hashing).
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>
30 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
32 enum userfaultfd_state {
33 UFFD_STATE_WAIT_API,
34 UFFD_STATE_RUNNING,
38 * Start with fault_pending_wqh and fault_wqh so they're more likely
39 * to be in the same cacheline.
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;
62 struct userfaultfd_wait_queue {
63 struct uffd_msg msg;
64 wait_queue_t wq;
65 struct userfaultfd_ctx *ctx;
66 bool waken;
69 struct userfaultfd_wake_range {
70 unsigned long start;
71 unsigned long len;
74 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
75 int wake_flags, void *key)
77 struct userfaultfd_wake_range *range = key;
78 int ret;
79 struct userfaultfd_wait_queue *uwq;
80 unsigned long start, len;
82 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
83 ret = 0;
84 /* len == 0 means wake all */
85 start = range->start;
86 len = range->len;
87 if (len && (start > uwq->msg.arg.pagefault.address ||
88 start + len <= uwq->msg.arg.pagefault.address))
89 goto out;
90 WRITE_ONCE(uwq->waken, true);
92 * The implicit smp_mb__before_spinlock in try_to_wake_up()
93 * renders uwq->waken visible to other CPUs before the task is
94 * waken.
96 ret = wake_up_state(wq->private, mode);
97 if (ret)
99 * Wake only once, autoremove behavior.
101 * After the effect of list_del_init is visible to the
102 * other CPUs, the waitqueue may disappear from under
103 * us, see the !list_empty_careful() in
104 * handle_userfault(). try_to_wake_up() has an
105 * implicit smp_mb__before_spinlock, and the
106 * wq->private is read before calling the extern
107 * function "wake_up_state" (which in turns calls
108 * try_to_wake_up). While the spin_lock;spin_unlock;
109 * wouldn't be enough, the smp_mb__before_spinlock is
110 * enough to avoid an explicit smp_mb() here.
112 list_del_init(&wq->task_list);
113 out:
114 return ret;
118 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
119 * context.
120 * @ctx: [in] Pointer to the userfaultfd context.
122 * Returns: In case of success, returns not zero.
124 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
126 if (!atomic_inc_not_zero(&ctx->refcount))
127 BUG();
131 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
132 * context.
133 * @ctx: [in] Pointer to userfaultfd context.
135 * The userfaultfd context reference must have been previously acquired either
136 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
138 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
140 if (atomic_dec_and_test(&ctx->refcount)) {
141 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
142 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
143 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
144 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
145 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
146 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
147 mmdrop(ctx->mm);
148 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
152 static inline void msg_init(struct uffd_msg *msg)
154 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
156 * Must use memset to zero out the paddings or kernel data is
157 * leaked to userland.
159 memset(msg, 0, sizeof(struct uffd_msg));
162 static inline struct uffd_msg userfault_msg(unsigned long address,
163 unsigned int flags,
164 unsigned long reason)
166 struct uffd_msg msg;
167 msg_init(&msg);
168 msg.event = UFFD_EVENT_PAGEFAULT;
169 msg.arg.pagefault.address = address;
170 if (flags & FAULT_FLAG_WRITE)
172 * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the
173 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
174 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
175 * was a read fault, otherwise if set it means it's
176 * a write fault.
178 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
179 if (reason & VM_UFFD_WP)
181 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
182 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
183 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
184 * a missing fault, otherwise if set it means it's a
185 * write protect fault.
187 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
188 return msg;
192 * Verify the pagetables are still not ok after having reigstered into
193 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
194 * userfault that has already been resolved, if userfaultfd_read and
195 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
196 * threads.
198 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
199 unsigned long address,
200 unsigned long flags,
201 unsigned long reason)
203 struct mm_struct *mm = ctx->mm;
204 pgd_t *pgd;
205 pud_t *pud;
206 pmd_t *pmd, _pmd;
207 pte_t *pte;
208 bool ret = true;
210 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
212 pgd = pgd_offset(mm, address);
213 if (!pgd_present(*pgd))
214 goto out;
215 pud = pud_offset(pgd, address);
216 if (!pud_present(*pud))
217 goto out;
218 pmd = pmd_offset(pud, address);
220 * READ_ONCE must function as a barrier with narrower scope
221 * and it must be equivalent to:
222 * _pmd = *pmd; barrier();
224 * This is to deal with the instability (as in
225 * pmd_trans_unstable) of the pmd.
227 _pmd = READ_ONCE(*pmd);
228 if (!pmd_present(_pmd))
229 goto out;
231 ret = false;
232 if (pmd_trans_huge(_pmd))
233 goto out;
236 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
237 * and use the standard pte_offset_map() instead of parsing _pmd.
239 pte = pte_offset_map(pmd, address);
241 * Lockless access: we're in a wait_event so it's ok if it
242 * changes under us.
244 if (pte_none(*pte))
245 ret = true;
246 pte_unmap(pte);
248 out:
249 return ret;
253 * The locking rules involved in returning VM_FAULT_RETRY depending on
254 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
255 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
256 * recommendation in __lock_page_or_retry is not an understatement.
258 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
259 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
260 * not set.
262 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
263 * set, VM_FAULT_RETRY can still be returned if and only if there are
264 * fatal_signal_pending()s, and the mmap_sem must be released before
265 * returning it.
267 int handle_userfault(struct fault_env *fe, unsigned long reason)
269 struct mm_struct *mm = fe->vma->vm_mm;
270 struct userfaultfd_ctx *ctx;
271 struct userfaultfd_wait_queue uwq;
272 int ret;
273 bool must_wait, return_to_userland;
274 long blocking_state;
276 BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
278 ret = VM_FAULT_SIGBUS;
279 ctx = fe->vma->vm_userfaultfd_ctx.ctx;
280 if (!ctx)
281 goto out;
283 BUG_ON(ctx->mm != mm);
285 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
286 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
289 * If it's already released don't get it. This avoids to loop
290 * in __get_user_pages if userfaultfd_release waits on the
291 * caller of handle_userfault to release the mmap_sem.
293 if (unlikely(ACCESS_ONCE(ctx->released)))
294 goto out;
297 * We don't do userfault handling for the final child pid update.
299 if (current->flags & PF_EXITING)
300 goto out;
303 * Check that we can return VM_FAULT_RETRY.
305 * NOTE: it should become possible to return VM_FAULT_RETRY
306 * even if FAULT_FLAG_TRIED is set without leading to gup()
307 * -EBUSY failures, if the userfaultfd is to be extended for
308 * VM_UFFD_WP tracking and we intend to arm the userfault
309 * without first stopping userland access to the memory. For
310 * VM_UFFD_MISSING userfaults this is enough for now.
312 if (unlikely(!(fe->flags & FAULT_FLAG_ALLOW_RETRY))) {
314 * Validate the invariant that nowait must allow retry
315 * to be sure not to return SIGBUS erroneously on
316 * nowait invocations.
318 BUG_ON(fe->flags & FAULT_FLAG_RETRY_NOWAIT);
319 #ifdef CONFIG_DEBUG_VM
320 if (printk_ratelimit()) {
321 printk(KERN_WARNING
322 "FAULT_FLAG_ALLOW_RETRY missing %x\n", fe->flags);
323 dump_stack();
325 #endif
326 goto out;
330 * Handle nowait, not much to do other than tell it to retry
331 * and wait.
333 ret = VM_FAULT_RETRY;
334 if (fe->flags & FAULT_FLAG_RETRY_NOWAIT)
335 goto out;
337 /* take the reference before dropping the mmap_sem */
338 userfaultfd_ctx_get(ctx);
340 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
341 uwq.wq.private = current;
342 uwq.msg = userfault_msg(fe->address, fe->flags, reason);
343 uwq.ctx = ctx;
344 uwq.waken = false;
346 return_to_userland =
347 (fe->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
348 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
349 blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
350 TASK_KILLABLE;
352 spin_lock(&ctx->fault_pending_wqh.lock);
354 * After the __add_wait_queue the uwq is visible to userland
355 * through poll/read().
357 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
359 * The smp_mb() after __set_current_state prevents the reads
360 * following the spin_unlock to happen before the list_add in
361 * __add_wait_queue.
363 set_current_state(blocking_state);
364 spin_unlock(&ctx->fault_pending_wqh.lock);
366 must_wait = userfaultfd_must_wait(ctx, fe->address, fe->flags, reason);
367 up_read(&mm->mmap_sem);
369 if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
370 (return_to_userland ? !signal_pending(current) :
371 !fatal_signal_pending(current)))) {
372 wake_up_poll(&ctx->fd_wqh, POLLIN);
373 schedule();
374 ret |= VM_FAULT_MAJOR;
377 * False wakeups can orginate even from rwsem before
378 * up_read() however userfaults will wait either for a
379 * targeted wakeup on the specific uwq waitqueue from
380 * wake_userfault() or for signals or for uffd
381 * release.
383 while (!READ_ONCE(uwq.waken)) {
385 * This needs the full smp_store_mb()
386 * guarantee as the state write must be
387 * visible to other CPUs before reading
388 * uwq.waken from other CPUs.
390 set_current_state(blocking_state);
391 if (READ_ONCE(uwq.waken) ||
392 READ_ONCE(ctx->released) ||
393 (return_to_userland ? signal_pending(current) :
394 fatal_signal_pending(current)))
395 break;
396 schedule();
400 __set_current_state(TASK_RUNNING);
402 if (return_to_userland) {
403 if (signal_pending(current) &&
404 !fatal_signal_pending(current)) {
406 * If we got a SIGSTOP or SIGCONT and this is
407 * a normal userland page fault, just let
408 * userland return so the signal will be
409 * handled and gdb debugging works. The page
410 * fault code immediately after we return from
411 * this function is going to release the
412 * mmap_sem and it's not depending on it
413 * (unlike gup would if we were not to return
414 * VM_FAULT_RETRY).
416 * If a fatal signal is pending we still take
417 * the streamlined VM_FAULT_RETRY failure path
418 * and there's no need to retake the mmap_sem
419 * in such case.
421 down_read(&mm->mmap_sem);
422 ret = 0;
427 * Here we race with the list_del; list_add in
428 * userfaultfd_ctx_read(), however because we don't ever run
429 * list_del_init() to refile across the two lists, the prev
430 * and next pointers will never point to self. list_add also
431 * would never let any of the two pointers to point to
432 * self. So list_empty_careful won't risk to see both pointers
433 * pointing to self at any time during the list refile. The
434 * only case where list_del_init() is called is the full
435 * removal in the wake function and there we don't re-list_add
436 * and it's fine not to block on the spinlock. The uwq on this
437 * kernel stack can be released after the list_del_init.
439 if (!list_empty_careful(&uwq.wq.task_list)) {
440 spin_lock(&ctx->fault_pending_wqh.lock);
442 * No need of list_del_init(), the uwq on the stack
443 * will be freed shortly anyway.
445 list_del(&uwq.wq.task_list);
446 spin_unlock(&ctx->fault_pending_wqh.lock);
450 * ctx may go away after this if the userfault pseudo fd is
451 * already released.
453 userfaultfd_ctx_put(ctx);
455 out:
456 return ret;
459 static int userfaultfd_release(struct inode *inode, struct file *file)
461 struct userfaultfd_ctx *ctx = file->private_data;
462 struct mm_struct *mm = ctx->mm;
463 struct vm_area_struct *vma, *prev;
464 /* len == 0 means wake all */
465 struct userfaultfd_wake_range range = { .len = 0, };
466 unsigned long new_flags;
468 ACCESS_ONCE(ctx->released) = true;
470 if (!mmget_not_zero(mm))
471 goto wakeup;
474 * Flush page faults out of all CPUs. NOTE: all page faults
475 * must be retried without returning VM_FAULT_SIGBUS if
476 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
477 * changes while handle_userfault released the mmap_sem. So
478 * it's critical that released is set to true (above), before
479 * taking the mmap_sem for writing.
481 down_write(&mm->mmap_sem);
482 prev = NULL;
483 for (vma = mm->mmap; vma; vma = vma->vm_next) {
484 cond_resched();
485 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
486 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
487 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
488 prev = vma;
489 continue;
491 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
492 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
493 new_flags, vma->anon_vma,
494 vma->vm_file, vma->vm_pgoff,
495 vma_policy(vma),
496 NULL_VM_UFFD_CTX);
497 if (prev)
498 vma = prev;
499 else
500 prev = vma;
501 vma->vm_flags = new_flags;
502 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
504 up_write(&mm->mmap_sem);
505 mmput(mm);
506 wakeup:
508 * After no new page faults can wait on this fault_*wqh, flush
509 * the last page faults that may have been already waiting on
510 * the fault_*wqh.
512 spin_lock(&ctx->fault_pending_wqh.lock);
513 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
514 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
515 spin_unlock(&ctx->fault_pending_wqh.lock);
517 wake_up_poll(&ctx->fd_wqh, POLLHUP);
518 userfaultfd_ctx_put(ctx);
519 return 0;
522 /* fault_pending_wqh.lock must be hold by the caller */
523 static inline struct userfaultfd_wait_queue *find_userfault(
524 struct userfaultfd_ctx *ctx)
526 wait_queue_t *wq;
527 struct userfaultfd_wait_queue *uwq;
529 VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
531 uwq = NULL;
532 if (!waitqueue_active(&ctx->fault_pending_wqh))
533 goto out;
534 /* walk in reverse to provide FIFO behavior to read userfaults */
535 wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
536 typeof(*wq), task_list);
537 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
538 out:
539 return uwq;
542 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
544 struct userfaultfd_ctx *ctx = file->private_data;
545 unsigned int ret;
547 poll_wait(file, &ctx->fd_wqh, wait);
549 switch (ctx->state) {
550 case UFFD_STATE_WAIT_API:
551 return POLLERR;
552 case UFFD_STATE_RUNNING:
554 * poll() never guarantees that read won't block.
555 * userfaults can be waken before they're read().
557 if (unlikely(!(file->f_flags & O_NONBLOCK)))
558 return POLLERR;
560 * lockless access to see if there are pending faults
561 * __pollwait last action is the add_wait_queue but
562 * the spin_unlock would allow the waitqueue_active to
563 * pass above the actual list_add inside
564 * add_wait_queue critical section. So use a full
565 * memory barrier to serialize the list_add write of
566 * add_wait_queue() with the waitqueue_active read
567 * below.
569 ret = 0;
570 smp_mb();
571 if (waitqueue_active(&ctx->fault_pending_wqh))
572 ret = POLLIN;
573 return ret;
574 default:
575 BUG();
579 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
580 struct uffd_msg *msg)
582 ssize_t ret;
583 DECLARE_WAITQUEUE(wait, current);
584 struct userfaultfd_wait_queue *uwq;
586 /* always take the fd_wqh lock before the fault_pending_wqh lock */
587 spin_lock(&ctx->fd_wqh.lock);
588 __add_wait_queue(&ctx->fd_wqh, &wait);
589 for (;;) {
590 set_current_state(TASK_INTERRUPTIBLE);
591 spin_lock(&ctx->fault_pending_wqh.lock);
592 uwq = find_userfault(ctx);
593 if (uwq) {
595 * Use a seqcount to repeat the lockless check
596 * in wake_userfault() to avoid missing
597 * wakeups because during the refile both
598 * waitqueue could become empty if this is the
599 * only userfault.
601 write_seqcount_begin(&ctx->refile_seq);
604 * The fault_pending_wqh.lock prevents the uwq
605 * to disappear from under us.
607 * Refile this userfault from
608 * fault_pending_wqh to fault_wqh, it's not
609 * pending anymore after we read it.
611 * Use list_del() by hand (as
612 * userfaultfd_wake_function also uses
613 * list_del_init() by hand) to be sure nobody
614 * changes __remove_wait_queue() to use
615 * list_del_init() in turn breaking the
616 * !list_empty_careful() check in
617 * handle_userfault(). The uwq->wq.task_list
618 * must never be empty at any time during the
619 * refile, or the waitqueue could disappear
620 * from under us. The "wait_queue_head_t"
621 * parameter of __remove_wait_queue() is unused
622 * anyway.
624 list_del(&uwq->wq.task_list);
625 __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
627 write_seqcount_end(&ctx->refile_seq);
629 /* careful to always initialize msg if ret == 0 */
630 *msg = uwq->msg;
631 spin_unlock(&ctx->fault_pending_wqh.lock);
632 ret = 0;
633 break;
635 spin_unlock(&ctx->fault_pending_wqh.lock);
636 if (signal_pending(current)) {
637 ret = -ERESTARTSYS;
638 break;
640 if (no_wait) {
641 ret = -EAGAIN;
642 break;
644 spin_unlock(&ctx->fd_wqh.lock);
645 schedule();
646 spin_lock(&ctx->fd_wqh.lock);
648 __remove_wait_queue(&ctx->fd_wqh, &wait);
649 __set_current_state(TASK_RUNNING);
650 spin_unlock(&ctx->fd_wqh.lock);
652 return ret;
655 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
656 size_t count, loff_t *ppos)
658 struct userfaultfd_ctx *ctx = file->private_data;
659 ssize_t _ret, ret = 0;
660 struct uffd_msg msg;
661 int no_wait = file->f_flags & O_NONBLOCK;
663 if (ctx->state == UFFD_STATE_WAIT_API)
664 return -EINVAL;
666 for (;;) {
667 if (count < sizeof(msg))
668 return ret ? ret : -EINVAL;
669 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
670 if (_ret < 0)
671 return ret ? ret : _ret;
672 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
673 return ret ? ret : -EFAULT;
674 ret += sizeof(msg);
675 buf += sizeof(msg);
676 count -= sizeof(msg);
678 * Allow to read more than one fault at time but only
679 * block if waiting for the very first one.
681 no_wait = O_NONBLOCK;
685 static void __wake_userfault(struct userfaultfd_ctx *ctx,
686 struct userfaultfd_wake_range *range)
688 unsigned long start, end;
690 start = range->start;
691 end = range->start + range->len;
693 spin_lock(&ctx->fault_pending_wqh.lock);
694 /* wake all in the range and autoremove */
695 if (waitqueue_active(&ctx->fault_pending_wqh))
696 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
697 range);
698 if (waitqueue_active(&ctx->fault_wqh))
699 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
700 spin_unlock(&ctx->fault_pending_wqh.lock);
703 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
704 struct userfaultfd_wake_range *range)
706 unsigned seq;
707 bool need_wakeup;
710 * To be sure waitqueue_active() is not reordered by the CPU
711 * before the pagetable update, use an explicit SMP memory
712 * barrier here. PT lock release or up_read(mmap_sem) still
713 * have release semantics that can allow the
714 * waitqueue_active() to be reordered before the pte update.
716 smp_mb();
719 * Use waitqueue_active because it's very frequent to
720 * change the address space atomically even if there are no
721 * userfaults yet. So we take the spinlock only when we're
722 * sure we've userfaults to wake.
724 do {
725 seq = read_seqcount_begin(&ctx->refile_seq);
726 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
727 waitqueue_active(&ctx->fault_wqh);
728 cond_resched();
729 } while (read_seqcount_retry(&ctx->refile_seq, seq));
730 if (need_wakeup)
731 __wake_userfault(ctx, range);
734 static __always_inline int validate_range(struct mm_struct *mm,
735 __u64 start, __u64 len)
737 __u64 task_size = mm->task_size;
739 if (start & ~PAGE_MASK)
740 return -EINVAL;
741 if (len & ~PAGE_MASK)
742 return -EINVAL;
743 if (!len)
744 return -EINVAL;
745 if (start < mmap_min_addr)
746 return -EINVAL;
747 if (start >= task_size)
748 return -EINVAL;
749 if (len > task_size - start)
750 return -EINVAL;
751 return 0;
754 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
755 unsigned long arg)
757 struct mm_struct *mm = ctx->mm;
758 struct vm_area_struct *vma, *prev, *cur;
759 int ret;
760 struct uffdio_register uffdio_register;
761 struct uffdio_register __user *user_uffdio_register;
762 unsigned long vm_flags, new_flags;
763 bool found;
764 unsigned long start, end, vma_end;
766 user_uffdio_register = (struct uffdio_register __user *) arg;
768 ret = -EFAULT;
769 if (copy_from_user(&uffdio_register, user_uffdio_register,
770 sizeof(uffdio_register)-sizeof(__u64)))
771 goto out;
773 ret = -EINVAL;
774 if (!uffdio_register.mode)
775 goto out;
776 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
777 UFFDIO_REGISTER_MODE_WP))
778 goto out;
779 vm_flags = 0;
780 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
781 vm_flags |= VM_UFFD_MISSING;
782 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
783 vm_flags |= VM_UFFD_WP;
785 * FIXME: remove the below error constraint by
786 * implementing the wprotect tracking mode.
788 ret = -EINVAL;
789 goto out;
792 ret = validate_range(mm, uffdio_register.range.start,
793 uffdio_register.range.len);
794 if (ret)
795 goto out;
797 start = uffdio_register.range.start;
798 end = start + uffdio_register.range.len;
800 ret = -ENOMEM;
801 if (!mmget_not_zero(mm))
802 goto out;
804 down_write(&mm->mmap_sem);
805 vma = find_vma_prev(mm, start, &prev);
806 if (!vma)
807 goto out_unlock;
809 /* check that there's at least one vma in the range */
810 ret = -EINVAL;
811 if (vma->vm_start >= end)
812 goto out_unlock;
815 * Search for not compatible vmas.
817 * FIXME: this shall be relaxed later so that it doesn't fail
818 * on tmpfs backed vmas (in addition to the current allowance
819 * on anonymous vmas).
821 found = false;
822 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
823 cond_resched();
825 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
826 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
828 /* check not compatible vmas */
829 ret = -EINVAL;
830 if (cur->vm_ops)
831 goto out_unlock;
834 * Check that this vma isn't already owned by a
835 * different userfaultfd. We can't allow more than one
836 * userfaultfd to own a single vma simultaneously or we
837 * wouldn't know which one to deliver the userfaults to.
839 ret = -EBUSY;
840 if (cur->vm_userfaultfd_ctx.ctx &&
841 cur->vm_userfaultfd_ctx.ctx != ctx)
842 goto out_unlock;
844 found = true;
846 BUG_ON(!found);
848 if (vma->vm_start < start)
849 prev = vma;
851 ret = 0;
852 do {
853 cond_resched();
855 BUG_ON(vma->vm_ops);
856 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
857 vma->vm_userfaultfd_ctx.ctx != ctx);
860 * Nothing to do: this vma is already registered into this
861 * userfaultfd and with the right tracking mode too.
863 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
864 (vma->vm_flags & vm_flags) == vm_flags)
865 goto skip;
867 if (vma->vm_start > start)
868 start = vma->vm_start;
869 vma_end = min(end, vma->vm_end);
871 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
872 prev = vma_merge(mm, prev, start, vma_end, new_flags,
873 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
874 vma_policy(vma),
875 ((struct vm_userfaultfd_ctx){ ctx }));
876 if (prev) {
877 vma = prev;
878 goto next;
880 if (vma->vm_start < start) {
881 ret = split_vma(mm, vma, start, 1);
882 if (ret)
883 break;
885 if (vma->vm_end > end) {
886 ret = split_vma(mm, vma, end, 0);
887 if (ret)
888 break;
890 next:
892 * In the vma_merge() successful mprotect-like case 8:
893 * the next vma was merged into the current one and
894 * the current one has not been updated yet.
896 vma->vm_flags = new_flags;
897 vma->vm_userfaultfd_ctx.ctx = ctx;
899 skip:
900 prev = vma;
901 start = vma->vm_end;
902 vma = vma->vm_next;
903 } while (vma && vma->vm_start < end);
904 out_unlock:
905 up_write(&mm->mmap_sem);
906 mmput(mm);
907 if (!ret) {
909 * Now that we scanned all vmas we can already tell
910 * userland which ioctls methods are guaranteed to
911 * succeed on this range.
913 if (put_user(UFFD_API_RANGE_IOCTLS,
914 &user_uffdio_register->ioctls))
915 ret = -EFAULT;
917 out:
918 return ret;
921 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
922 unsigned long arg)
924 struct mm_struct *mm = ctx->mm;
925 struct vm_area_struct *vma, *prev, *cur;
926 int ret;
927 struct uffdio_range uffdio_unregister;
928 unsigned long new_flags;
929 bool found;
930 unsigned long start, end, vma_end;
931 const void __user *buf = (void __user *)arg;
933 ret = -EFAULT;
934 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
935 goto out;
937 ret = validate_range(mm, uffdio_unregister.start,
938 uffdio_unregister.len);
939 if (ret)
940 goto out;
942 start = uffdio_unregister.start;
943 end = start + uffdio_unregister.len;
945 ret = -ENOMEM;
946 if (!mmget_not_zero(mm))
947 goto out;
949 down_write(&mm->mmap_sem);
950 vma = find_vma_prev(mm, start, &prev);
951 if (!vma)
952 goto out_unlock;
954 /* check that there's at least one vma in the range */
955 ret = -EINVAL;
956 if (vma->vm_start >= end)
957 goto out_unlock;
960 * Search for not compatible vmas.
962 * FIXME: this shall be relaxed later so that it doesn't fail
963 * on tmpfs backed vmas (in addition to the current allowance
964 * on anonymous vmas).
966 found = false;
967 ret = -EINVAL;
968 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
969 cond_resched();
971 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
972 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
975 * Check not compatible vmas, not strictly required
976 * here as not compatible vmas cannot have an
977 * userfaultfd_ctx registered on them, but this
978 * provides for more strict behavior to notice
979 * unregistration errors.
981 if (cur->vm_ops)
982 goto out_unlock;
984 found = true;
986 BUG_ON(!found);
988 if (vma->vm_start < start)
989 prev = vma;
991 ret = 0;
992 do {
993 cond_resched();
995 BUG_ON(vma->vm_ops);
998 * Nothing to do: this vma is already registered into this
999 * userfaultfd and with the right tracking mode too.
1001 if (!vma->vm_userfaultfd_ctx.ctx)
1002 goto skip;
1004 if (vma->vm_start > start)
1005 start = vma->vm_start;
1006 vma_end = min(end, vma->vm_end);
1008 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1009 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1010 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1011 vma_policy(vma),
1012 NULL_VM_UFFD_CTX);
1013 if (prev) {
1014 vma = prev;
1015 goto next;
1017 if (vma->vm_start < start) {
1018 ret = split_vma(mm, vma, start, 1);
1019 if (ret)
1020 break;
1022 if (vma->vm_end > end) {
1023 ret = split_vma(mm, vma, end, 0);
1024 if (ret)
1025 break;
1027 next:
1029 * In the vma_merge() successful mprotect-like case 8:
1030 * the next vma was merged into the current one and
1031 * the current one has not been updated yet.
1033 vma->vm_flags = new_flags;
1034 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1036 skip:
1037 prev = vma;
1038 start = vma->vm_end;
1039 vma = vma->vm_next;
1040 } while (vma && vma->vm_start < end);
1041 out_unlock:
1042 up_write(&mm->mmap_sem);
1043 mmput(mm);
1044 out:
1045 return ret;
1049 * userfaultfd_wake may be used in combination with the
1050 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1052 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1053 unsigned long arg)
1055 int ret;
1056 struct uffdio_range uffdio_wake;
1057 struct userfaultfd_wake_range range;
1058 const void __user *buf = (void __user *)arg;
1060 ret = -EFAULT;
1061 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1062 goto out;
1064 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1065 if (ret)
1066 goto out;
1068 range.start = uffdio_wake.start;
1069 range.len = uffdio_wake.len;
1072 * len == 0 means wake all and we don't want to wake all here,
1073 * so check it again to be sure.
1075 VM_BUG_ON(!range.len);
1077 wake_userfault(ctx, &range);
1078 ret = 0;
1080 out:
1081 return ret;
1084 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1085 unsigned long arg)
1087 __s64 ret;
1088 struct uffdio_copy uffdio_copy;
1089 struct uffdio_copy __user *user_uffdio_copy;
1090 struct userfaultfd_wake_range range;
1092 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1094 ret = -EFAULT;
1095 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1096 /* don't copy "copy" last field */
1097 sizeof(uffdio_copy)-sizeof(__s64)))
1098 goto out;
1100 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1101 if (ret)
1102 goto out;
1104 * double check for wraparound just in case. copy_from_user()
1105 * will later check uffdio_copy.src + uffdio_copy.len to fit
1106 * in the userland range.
1108 ret = -EINVAL;
1109 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1110 goto out;
1111 if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1112 goto out;
1113 if (mmget_not_zero(ctx->mm)) {
1114 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1115 uffdio_copy.len);
1116 mmput(ctx->mm);
1118 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1119 return -EFAULT;
1120 if (ret < 0)
1121 goto out;
1122 BUG_ON(!ret);
1123 /* len == 0 would wake all */
1124 range.len = ret;
1125 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1126 range.start = uffdio_copy.dst;
1127 wake_userfault(ctx, &range);
1129 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1130 out:
1131 return ret;
1134 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1135 unsigned long arg)
1137 __s64 ret;
1138 struct uffdio_zeropage uffdio_zeropage;
1139 struct uffdio_zeropage __user *user_uffdio_zeropage;
1140 struct userfaultfd_wake_range range;
1142 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1144 ret = -EFAULT;
1145 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1146 /* don't copy "zeropage" last field */
1147 sizeof(uffdio_zeropage)-sizeof(__s64)))
1148 goto out;
1150 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1151 uffdio_zeropage.range.len);
1152 if (ret)
1153 goto out;
1154 ret = -EINVAL;
1155 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1156 goto out;
1158 if (mmget_not_zero(ctx->mm)) {
1159 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1160 uffdio_zeropage.range.len);
1161 mmput(ctx->mm);
1163 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1164 return -EFAULT;
1165 if (ret < 0)
1166 goto out;
1167 /* len == 0 would wake all */
1168 BUG_ON(!ret);
1169 range.len = ret;
1170 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1171 range.start = uffdio_zeropage.range.start;
1172 wake_userfault(ctx, &range);
1174 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1175 out:
1176 return ret;
1180 * userland asks for a certain API version and we return which bits
1181 * and ioctl commands are implemented in this kernel for such API
1182 * version or -EINVAL if unknown.
1184 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1185 unsigned long arg)
1187 struct uffdio_api uffdio_api;
1188 void __user *buf = (void __user *)arg;
1189 int ret;
1191 ret = -EINVAL;
1192 if (ctx->state != UFFD_STATE_WAIT_API)
1193 goto out;
1194 ret = -EFAULT;
1195 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1196 goto out;
1197 if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1198 memset(&uffdio_api, 0, sizeof(uffdio_api));
1199 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1200 goto out;
1201 ret = -EINVAL;
1202 goto out;
1204 uffdio_api.features = UFFD_API_FEATURES;
1205 uffdio_api.ioctls = UFFD_API_IOCTLS;
1206 ret = -EFAULT;
1207 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1208 goto out;
1209 ctx->state = UFFD_STATE_RUNNING;
1210 ret = 0;
1211 out:
1212 return ret;
1215 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1216 unsigned long arg)
1218 int ret = -EINVAL;
1219 struct userfaultfd_ctx *ctx = file->private_data;
1221 if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1222 return -EINVAL;
1224 switch(cmd) {
1225 case UFFDIO_API:
1226 ret = userfaultfd_api(ctx, arg);
1227 break;
1228 case UFFDIO_REGISTER:
1229 ret = userfaultfd_register(ctx, arg);
1230 break;
1231 case UFFDIO_UNREGISTER:
1232 ret = userfaultfd_unregister(ctx, arg);
1233 break;
1234 case UFFDIO_WAKE:
1235 ret = userfaultfd_wake(ctx, arg);
1236 break;
1237 case UFFDIO_COPY:
1238 ret = userfaultfd_copy(ctx, arg);
1239 break;
1240 case UFFDIO_ZEROPAGE:
1241 ret = userfaultfd_zeropage(ctx, arg);
1242 break;
1244 return ret;
1247 #ifdef CONFIG_PROC_FS
1248 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1250 struct userfaultfd_ctx *ctx = f->private_data;
1251 wait_queue_t *wq;
1252 struct userfaultfd_wait_queue *uwq;
1253 unsigned long pending = 0, total = 0;
1255 spin_lock(&ctx->fault_pending_wqh.lock);
1256 list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1257 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1258 pending++;
1259 total++;
1261 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1262 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1263 total++;
1265 spin_unlock(&ctx->fault_pending_wqh.lock);
1268 * If more protocols will be added, there will be all shown
1269 * separated by a space. Like this:
1270 * protocols: aa:... bb:...
1272 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1273 pending, total, UFFD_API, UFFD_API_FEATURES,
1274 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1276 #endif
1278 static const struct file_operations userfaultfd_fops = {
1279 #ifdef CONFIG_PROC_FS
1280 .show_fdinfo = userfaultfd_show_fdinfo,
1281 #endif
1282 .release = userfaultfd_release,
1283 .poll = userfaultfd_poll,
1284 .read = userfaultfd_read,
1285 .unlocked_ioctl = userfaultfd_ioctl,
1286 .compat_ioctl = userfaultfd_ioctl,
1287 .llseek = noop_llseek,
1290 static void init_once_userfaultfd_ctx(void *mem)
1292 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1294 init_waitqueue_head(&ctx->fault_pending_wqh);
1295 init_waitqueue_head(&ctx->fault_wqh);
1296 init_waitqueue_head(&ctx->fd_wqh);
1297 seqcount_init(&ctx->refile_seq);
1301 * userfaultfd_file_create - Creates an userfaultfd file pointer.
1302 * @flags: Flags for the userfaultfd file.
1304 * This function creates an userfaultfd file pointer, w/out installing
1305 * it into the fd table. This is useful when the userfaultfd file is
1306 * used during the initialization of data structures that require
1307 * extra setup after the userfaultfd creation. So the userfaultfd
1308 * creation is split into the file pointer creation phase, and the
1309 * file descriptor installation phase. In this way races with
1310 * userspace closing the newly installed file descriptor can be
1311 * avoided. Returns an userfaultfd file pointer, or a proper error
1312 * pointer.
1314 static struct file *userfaultfd_file_create(int flags)
1316 struct file *file;
1317 struct userfaultfd_ctx *ctx;
1319 BUG_ON(!current->mm);
1321 /* Check the UFFD_* constants for consistency. */
1322 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1323 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1325 file = ERR_PTR(-EINVAL);
1326 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1327 goto out;
1329 file = ERR_PTR(-ENOMEM);
1330 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1331 if (!ctx)
1332 goto out;
1334 atomic_set(&ctx->refcount, 1);
1335 ctx->flags = flags;
1336 ctx->state = UFFD_STATE_WAIT_API;
1337 ctx->released = false;
1338 ctx->mm = current->mm;
1339 /* prevent the mm struct to be freed */
1340 atomic_inc(&ctx->mm->mm_count);
1342 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1343 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1344 if (IS_ERR(file)) {
1345 mmdrop(ctx->mm);
1346 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1348 out:
1349 return file;
1352 SYSCALL_DEFINE1(userfaultfd, int, flags)
1354 int fd, error;
1355 struct file *file;
1357 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1358 if (error < 0)
1359 return error;
1360 fd = error;
1362 file = userfaultfd_file_create(flags);
1363 if (IS_ERR(file)) {
1364 error = PTR_ERR(file);
1365 goto err_put_unused_fd;
1367 fd_install(fd, file);
1369 return fd;
1371 err_put_unused_fd:
1372 put_unused_fd(fd);
1374 return error;
1377 static int __init userfaultfd_init(void)
1379 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1380 sizeof(struct userfaultfd_ctx),
1382 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1383 init_once_userfaultfd_ctx);
1384 return 0;
1386 __initcall(userfaultfd_init);