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>
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 {
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 */
52 /* userfaultfd syscall flags */
55 enum userfaultfd_state state;
58 /* mm with one ore more vmas attached to this userfaultfd_ctx */
62 struct userfaultfd_wait_queue {
65 struct userfaultfd_ctx *ctx;
69 struct userfaultfd_wake_range {
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;
79 struct userfaultfd_wait_queue *uwq;
80 unsigned long start, len;
82 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
84 /* len == 0 means wake all */
87 if (len && (start > uwq->msg.arg.pagefault.address ||
88 start + len <= uwq->msg.arg.pagefault.address))
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
96 ret = wake_up_state(wq->private, mode);
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);
118 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
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))
131 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
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));
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,
164 unsigned long reason)
168 msg.event = UFFD_EVENT_PAGEFAULT;
169 msg.arg.pagefault.address = address;
170 if (flags & FAULT_FLAG_WRITE)
172 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP 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
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;
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
198 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
199 unsigned long address,
201 unsigned long reason)
203 struct mm_struct *mm = ctx->mm;
210 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
212 pgd = pgd_offset(mm, address);
213 if (!pgd_present(*pgd))
215 pud = pud_offset(pgd, address);
216 if (!pud_present(*pud))
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))
232 if (pmd_trans_huge(_pmd))
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
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
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
267 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
269 struct mm_struct *mm = vmf->vma->vm_mm;
270 struct userfaultfd_ctx *ctx;
271 struct userfaultfd_wait_queue uwq;
273 bool must_wait, return_to_userland;
276 BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
278 ret = VM_FAULT_SIGBUS;
279 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
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)))
297 * We don't do userfault handling for the final child pid update.
299 if (current->flags & PF_EXITING)
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(!(vmf->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(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
319 #ifdef CONFIG_DEBUG_VM
320 if (printk_ratelimit()) {
322 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
331 * Handle nowait, not much to do other than tell it to retry
334 ret = VM_FAULT_RETRY;
335 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
338 /* take the reference before dropping the mmap_sem */
339 userfaultfd_ctx_get(ctx);
341 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
342 uwq.wq.private = current;
343 uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
348 (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
349 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
350 blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
353 spin_lock(&ctx->fault_pending_wqh.lock);
355 * After the __add_wait_queue the uwq is visible to userland
356 * through poll/read().
358 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
360 * The smp_mb() after __set_current_state prevents the reads
361 * following the spin_unlock to happen before the list_add in
364 set_current_state(blocking_state);
365 spin_unlock(&ctx->fault_pending_wqh.lock);
367 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
369 up_read(&mm->mmap_sem);
371 if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
372 (return_to_userland ? !signal_pending(current) :
373 !fatal_signal_pending(current)))) {
374 wake_up_poll(&ctx->fd_wqh, POLLIN);
376 ret |= VM_FAULT_MAJOR;
379 * False wakeups can orginate even from rwsem before
380 * up_read() however userfaults will wait either for a
381 * targeted wakeup on the specific uwq waitqueue from
382 * wake_userfault() or for signals or for uffd
385 while (!READ_ONCE(uwq.waken)) {
387 * This needs the full smp_store_mb()
388 * guarantee as the state write must be
389 * visible to other CPUs before reading
390 * uwq.waken from other CPUs.
392 set_current_state(blocking_state);
393 if (READ_ONCE(uwq.waken) ||
394 READ_ONCE(ctx->released) ||
395 (return_to_userland ? signal_pending(current) :
396 fatal_signal_pending(current)))
402 __set_current_state(TASK_RUNNING);
404 if (return_to_userland) {
405 if (signal_pending(current) &&
406 !fatal_signal_pending(current)) {
408 * If we got a SIGSTOP or SIGCONT and this is
409 * a normal userland page fault, just let
410 * userland return so the signal will be
411 * handled and gdb debugging works. The page
412 * fault code immediately after we return from
413 * this function is going to release the
414 * mmap_sem and it's not depending on it
415 * (unlike gup would if we were not to return
418 * If a fatal signal is pending we still take
419 * the streamlined VM_FAULT_RETRY failure path
420 * and there's no need to retake the mmap_sem
423 down_read(&mm->mmap_sem);
429 * Here we race with the list_del; list_add in
430 * userfaultfd_ctx_read(), however because we don't ever run
431 * list_del_init() to refile across the two lists, the prev
432 * and next pointers will never point to self. list_add also
433 * would never let any of the two pointers to point to
434 * self. So list_empty_careful won't risk to see both pointers
435 * pointing to self at any time during the list refile. The
436 * only case where list_del_init() is called is the full
437 * removal in the wake function and there we don't re-list_add
438 * and it's fine not to block on the spinlock. The uwq on this
439 * kernel stack can be released after the list_del_init.
441 if (!list_empty_careful(&uwq.wq.task_list)) {
442 spin_lock(&ctx->fault_pending_wqh.lock);
444 * No need of list_del_init(), the uwq on the stack
445 * will be freed shortly anyway.
447 list_del(&uwq.wq.task_list);
448 spin_unlock(&ctx->fault_pending_wqh.lock);
452 * ctx may go away after this if the userfault pseudo fd is
455 userfaultfd_ctx_put(ctx);
461 static int userfaultfd_release(struct inode *inode, struct file *file)
463 struct userfaultfd_ctx *ctx = file->private_data;
464 struct mm_struct *mm = ctx->mm;
465 struct vm_area_struct *vma, *prev;
466 /* len == 0 means wake all */
467 struct userfaultfd_wake_range range = { .len = 0, };
468 unsigned long new_flags;
470 ACCESS_ONCE(ctx->released) = true;
472 if (!mmget_not_zero(mm))
476 * Flush page faults out of all CPUs. NOTE: all page faults
477 * must be retried without returning VM_FAULT_SIGBUS if
478 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
479 * changes while handle_userfault released the mmap_sem. So
480 * it's critical that released is set to true (above), before
481 * taking the mmap_sem for writing.
483 down_write(&mm->mmap_sem);
485 for (vma = mm->mmap; vma; vma = vma->vm_next) {
487 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
488 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
489 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
493 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
494 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
495 new_flags, vma->anon_vma,
496 vma->vm_file, vma->vm_pgoff,
503 vma->vm_flags = new_flags;
504 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
506 up_write(&mm->mmap_sem);
510 * After no new page faults can wait on this fault_*wqh, flush
511 * the last page faults that may have been already waiting on
514 spin_lock(&ctx->fault_pending_wqh.lock);
515 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
516 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
517 spin_unlock(&ctx->fault_pending_wqh.lock);
519 wake_up_poll(&ctx->fd_wqh, POLLHUP);
520 userfaultfd_ctx_put(ctx);
524 /* fault_pending_wqh.lock must be hold by the caller */
525 static inline struct userfaultfd_wait_queue *find_userfault_in(
526 wait_queue_head_t *wqh)
529 struct userfaultfd_wait_queue *uwq;
531 VM_BUG_ON(!spin_is_locked(&wqh->lock));
534 if (!waitqueue_active(wqh))
536 /* walk in reverse to provide FIFO behavior to read userfaults */
537 wq = list_last_entry(&wqh->task_list, typeof(*wq), task_list);
538 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
543 static inline struct userfaultfd_wait_queue *find_userfault(
544 struct userfaultfd_ctx *ctx)
546 return find_userfault_in(&ctx->fault_pending_wqh);
549 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
551 struct userfaultfd_ctx *ctx = file->private_data;
554 poll_wait(file, &ctx->fd_wqh, wait);
556 switch (ctx->state) {
557 case UFFD_STATE_WAIT_API:
559 case UFFD_STATE_RUNNING:
561 * poll() never guarantees that read won't block.
562 * userfaults can be waken before they're read().
564 if (unlikely(!(file->f_flags & O_NONBLOCK)))
567 * lockless access to see if there are pending faults
568 * __pollwait last action is the add_wait_queue but
569 * the spin_unlock would allow the waitqueue_active to
570 * pass above the actual list_add inside
571 * add_wait_queue critical section. So use a full
572 * memory barrier to serialize the list_add write of
573 * add_wait_queue() with the waitqueue_active read
578 if (waitqueue_active(&ctx->fault_pending_wqh))
587 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
588 struct uffd_msg *msg)
591 DECLARE_WAITQUEUE(wait, current);
592 struct userfaultfd_wait_queue *uwq;
594 /* always take the fd_wqh lock before the fault_pending_wqh lock */
595 spin_lock(&ctx->fd_wqh.lock);
596 __add_wait_queue(&ctx->fd_wqh, &wait);
598 set_current_state(TASK_INTERRUPTIBLE);
599 spin_lock(&ctx->fault_pending_wqh.lock);
600 uwq = find_userfault(ctx);
603 * Use a seqcount to repeat the lockless check
604 * in wake_userfault() to avoid missing
605 * wakeups because during the refile both
606 * waitqueue could become empty if this is the
609 write_seqcount_begin(&ctx->refile_seq);
612 * The fault_pending_wqh.lock prevents the uwq
613 * to disappear from under us.
615 * Refile this userfault from
616 * fault_pending_wqh to fault_wqh, it's not
617 * pending anymore after we read it.
619 * Use list_del() by hand (as
620 * userfaultfd_wake_function also uses
621 * list_del_init() by hand) to be sure nobody
622 * changes __remove_wait_queue() to use
623 * list_del_init() in turn breaking the
624 * !list_empty_careful() check in
625 * handle_userfault(). The uwq->wq.task_list
626 * must never be empty at any time during the
627 * refile, or the waitqueue could disappear
628 * from under us. The "wait_queue_head_t"
629 * parameter of __remove_wait_queue() is unused
632 list_del(&uwq->wq.task_list);
633 __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
635 write_seqcount_end(&ctx->refile_seq);
637 /* careful to always initialize msg if ret == 0 */
639 spin_unlock(&ctx->fault_pending_wqh.lock);
643 spin_unlock(&ctx->fault_pending_wqh.lock);
644 if (signal_pending(current)) {
652 spin_unlock(&ctx->fd_wqh.lock);
654 spin_lock(&ctx->fd_wqh.lock);
656 __remove_wait_queue(&ctx->fd_wqh, &wait);
657 __set_current_state(TASK_RUNNING);
658 spin_unlock(&ctx->fd_wqh.lock);
663 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
664 size_t count, loff_t *ppos)
666 struct userfaultfd_ctx *ctx = file->private_data;
667 ssize_t _ret, ret = 0;
669 int no_wait = file->f_flags & O_NONBLOCK;
671 if (ctx->state == UFFD_STATE_WAIT_API)
675 if (count < sizeof(msg))
676 return ret ? ret : -EINVAL;
677 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
679 return ret ? ret : _ret;
680 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
681 return ret ? ret : -EFAULT;
684 count -= sizeof(msg);
686 * Allow to read more than one fault at time but only
687 * block if waiting for the very first one.
689 no_wait = O_NONBLOCK;
693 static void __wake_userfault(struct userfaultfd_ctx *ctx,
694 struct userfaultfd_wake_range *range)
696 unsigned long start, end;
698 start = range->start;
699 end = range->start + range->len;
701 spin_lock(&ctx->fault_pending_wqh.lock);
702 /* wake all in the range and autoremove */
703 if (waitqueue_active(&ctx->fault_pending_wqh))
704 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
706 if (waitqueue_active(&ctx->fault_wqh))
707 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
708 spin_unlock(&ctx->fault_pending_wqh.lock);
711 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
712 struct userfaultfd_wake_range *range)
718 * To be sure waitqueue_active() is not reordered by the CPU
719 * before the pagetable update, use an explicit SMP memory
720 * barrier here. PT lock release or up_read(mmap_sem) still
721 * have release semantics that can allow the
722 * waitqueue_active() to be reordered before the pte update.
727 * Use waitqueue_active because it's very frequent to
728 * change the address space atomically even if there are no
729 * userfaults yet. So we take the spinlock only when we're
730 * sure we've userfaults to wake.
733 seq = read_seqcount_begin(&ctx->refile_seq);
734 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
735 waitqueue_active(&ctx->fault_wqh);
737 } while (read_seqcount_retry(&ctx->refile_seq, seq));
739 __wake_userfault(ctx, range);
742 static __always_inline int validate_range(struct mm_struct *mm,
743 __u64 start, __u64 len)
745 __u64 task_size = mm->task_size;
747 if (start & ~PAGE_MASK)
749 if (len & ~PAGE_MASK)
753 if (start < mmap_min_addr)
755 if (start >= task_size)
757 if (len > task_size - start)
762 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
765 struct mm_struct *mm = ctx->mm;
766 struct vm_area_struct *vma, *prev, *cur;
768 struct uffdio_register uffdio_register;
769 struct uffdio_register __user *user_uffdio_register;
770 unsigned long vm_flags, new_flags;
772 unsigned long start, end, vma_end;
774 user_uffdio_register = (struct uffdio_register __user *) arg;
777 if (copy_from_user(&uffdio_register, user_uffdio_register,
778 sizeof(uffdio_register)-sizeof(__u64)))
782 if (!uffdio_register.mode)
784 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
785 UFFDIO_REGISTER_MODE_WP))
788 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
789 vm_flags |= VM_UFFD_MISSING;
790 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
791 vm_flags |= VM_UFFD_WP;
793 * FIXME: remove the below error constraint by
794 * implementing the wprotect tracking mode.
800 ret = validate_range(mm, uffdio_register.range.start,
801 uffdio_register.range.len);
805 start = uffdio_register.range.start;
806 end = start + uffdio_register.range.len;
809 if (!mmget_not_zero(mm))
812 down_write(&mm->mmap_sem);
813 vma = find_vma_prev(mm, start, &prev);
817 /* check that there's at least one vma in the range */
819 if (vma->vm_start >= end)
823 * Search for not compatible vmas.
825 * FIXME: this shall be relaxed later so that it doesn't fail
826 * on tmpfs backed vmas (in addition to the current allowance
827 * on anonymous vmas).
830 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
833 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
834 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
836 /* check not compatible vmas */
838 if (!vma_is_anonymous(cur))
842 * Check that this vma isn't already owned by a
843 * different userfaultfd. We can't allow more than one
844 * userfaultfd to own a single vma simultaneously or we
845 * wouldn't know which one to deliver the userfaults to.
848 if (cur->vm_userfaultfd_ctx.ctx &&
849 cur->vm_userfaultfd_ctx.ctx != ctx)
856 if (vma->vm_start < start)
863 BUG_ON(!vma_is_anonymous(vma));
864 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
865 vma->vm_userfaultfd_ctx.ctx != ctx);
868 * Nothing to do: this vma is already registered into this
869 * userfaultfd and with the right tracking mode too.
871 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
872 (vma->vm_flags & vm_flags) == vm_flags)
875 if (vma->vm_start > start)
876 start = vma->vm_start;
877 vma_end = min(end, vma->vm_end);
879 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
880 prev = vma_merge(mm, prev, start, vma_end, new_flags,
881 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
883 ((struct vm_userfaultfd_ctx){ ctx }));
888 if (vma->vm_start < start) {
889 ret = split_vma(mm, vma, start, 1);
893 if (vma->vm_end > end) {
894 ret = split_vma(mm, vma, end, 0);
900 * In the vma_merge() successful mprotect-like case 8:
901 * the next vma was merged into the current one and
902 * the current one has not been updated yet.
904 vma->vm_flags = new_flags;
905 vma->vm_userfaultfd_ctx.ctx = ctx;
911 } while (vma && vma->vm_start < end);
913 up_write(&mm->mmap_sem);
917 * Now that we scanned all vmas we can already tell
918 * userland which ioctls methods are guaranteed to
919 * succeed on this range.
921 if (put_user(UFFD_API_RANGE_IOCTLS,
922 &user_uffdio_register->ioctls))
929 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
932 struct mm_struct *mm = ctx->mm;
933 struct vm_area_struct *vma, *prev, *cur;
935 struct uffdio_range uffdio_unregister;
936 unsigned long new_flags;
938 unsigned long start, end, vma_end;
939 const void __user *buf = (void __user *)arg;
942 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
945 ret = validate_range(mm, uffdio_unregister.start,
946 uffdio_unregister.len);
950 start = uffdio_unregister.start;
951 end = start + uffdio_unregister.len;
954 if (!mmget_not_zero(mm))
957 down_write(&mm->mmap_sem);
958 vma = find_vma_prev(mm, start, &prev);
962 /* check that there's at least one vma in the range */
964 if (vma->vm_start >= end)
968 * Search for not compatible vmas.
970 * FIXME: this shall be relaxed later so that it doesn't fail
971 * on tmpfs backed vmas (in addition to the current allowance
972 * on anonymous vmas).
976 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
979 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
980 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
983 * Check not compatible vmas, not strictly required
984 * here as not compatible vmas cannot have an
985 * userfaultfd_ctx registered on them, but this
986 * provides for more strict behavior to notice
987 * unregistration errors.
989 if (!vma_is_anonymous(cur))
996 if (vma->vm_start < start)
1003 BUG_ON(!vma_is_anonymous(vma));
1006 * Nothing to do: this vma is already registered into this
1007 * userfaultfd and with the right tracking mode too.
1009 if (!vma->vm_userfaultfd_ctx.ctx)
1012 if (vma->vm_start > start)
1013 start = vma->vm_start;
1014 vma_end = min(end, vma->vm_end);
1016 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1017 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1018 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1025 if (vma->vm_start < start) {
1026 ret = split_vma(mm, vma, start, 1);
1030 if (vma->vm_end > end) {
1031 ret = split_vma(mm, vma, end, 0);
1037 * In the vma_merge() successful mprotect-like case 8:
1038 * the next vma was merged into the current one and
1039 * the current one has not been updated yet.
1041 vma->vm_flags = new_flags;
1042 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1046 start = vma->vm_end;
1048 } while (vma && vma->vm_start < end);
1050 up_write(&mm->mmap_sem);
1057 * userfaultfd_wake may be used in combination with the
1058 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1060 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1064 struct uffdio_range uffdio_wake;
1065 struct userfaultfd_wake_range range;
1066 const void __user *buf = (void __user *)arg;
1069 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1072 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1076 range.start = uffdio_wake.start;
1077 range.len = uffdio_wake.len;
1080 * len == 0 means wake all and we don't want to wake all here,
1081 * so check it again to be sure.
1083 VM_BUG_ON(!range.len);
1085 wake_userfault(ctx, &range);
1092 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1096 struct uffdio_copy uffdio_copy;
1097 struct uffdio_copy __user *user_uffdio_copy;
1098 struct userfaultfd_wake_range range;
1100 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1103 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1104 /* don't copy "copy" last field */
1105 sizeof(uffdio_copy)-sizeof(__s64)))
1108 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1112 * double check for wraparound just in case. copy_from_user()
1113 * will later check uffdio_copy.src + uffdio_copy.len to fit
1114 * in the userland range.
1117 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1119 if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1121 if (mmget_not_zero(ctx->mm)) {
1122 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1126 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1131 /* len == 0 would wake all */
1133 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1134 range.start = uffdio_copy.dst;
1135 wake_userfault(ctx, &range);
1137 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1142 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1146 struct uffdio_zeropage uffdio_zeropage;
1147 struct uffdio_zeropage __user *user_uffdio_zeropage;
1148 struct userfaultfd_wake_range range;
1150 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1153 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1154 /* don't copy "zeropage" last field */
1155 sizeof(uffdio_zeropage)-sizeof(__s64)))
1158 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1159 uffdio_zeropage.range.len);
1163 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1166 if (mmget_not_zero(ctx->mm)) {
1167 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1168 uffdio_zeropage.range.len);
1171 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1175 /* len == 0 would wake all */
1178 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1179 range.start = uffdio_zeropage.range.start;
1180 wake_userfault(ctx, &range);
1182 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1188 * userland asks for a certain API version and we return which bits
1189 * and ioctl commands are implemented in this kernel for such API
1190 * version or -EINVAL if unknown.
1192 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1195 struct uffdio_api uffdio_api;
1196 void __user *buf = (void __user *)arg;
1200 if (ctx->state != UFFD_STATE_WAIT_API)
1203 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1205 if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1206 memset(&uffdio_api, 0, sizeof(uffdio_api));
1207 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1212 uffdio_api.features = UFFD_API_FEATURES;
1213 uffdio_api.ioctls = UFFD_API_IOCTLS;
1215 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1217 ctx->state = UFFD_STATE_RUNNING;
1223 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1227 struct userfaultfd_ctx *ctx = file->private_data;
1229 if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1234 ret = userfaultfd_api(ctx, arg);
1236 case UFFDIO_REGISTER:
1237 ret = userfaultfd_register(ctx, arg);
1239 case UFFDIO_UNREGISTER:
1240 ret = userfaultfd_unregister(ctx, arg);
1243 ret = userfaultfd_wake(ctx, arg);
1246 ret = userfaultfd_copy(ctx, arg);
1248 case UFFDIO_ZEROPAGE:
1249 ret = userfaultfd_zeropage(ctx, arg);
1255 #ifdef CONFIG_PROC_FS
1256 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1258 struct userfaultfd_ctx *ctx = f->private_data;
1260 struct userfaultfd_wait_queue *uwq;
1261 unsigned long pending = 0, total = 0;
1263 spin_lock(&ctx->fault_pending_wqh.lock);
1264 list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1265 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1269 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1270 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1273 spin_unlock(&ctx->fault_pending_wqh.lock);
1276 * If more protocols will be added, there will be all shown
1277 * separated by a space. Like this:
1278 * protocols: aa:... bb:...
1280 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1281 pending, total, UFFD_API, UFFD_API_FEATURES,
1282 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1286 static const struct file_operations userfaultfd_fops = {
1287 #ifdef CONFIG_PROC_FS
1288 .show_fdinfo = userfaultfd_show_fdinfo,
1290 .release = userfaultfd_release,
1291 .poll = userfaultfd_poll,
1292 .read = userfaultfd_read,
1293 .unlocked_ioctl = userfaultfd_ioctl,
1294 .compat_ioctl = userfaultfd_ioctl,
1295 .llseek = noop_llseek,
1298 static void init_once_userfaultfd_ctx(void *mem)
1300 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1302 init_waitqueue_head(&ctx->fault_pending_wqh);
1303 init_waitqueue_head(&ctx->fault_wqh);
1304 init_waitqueue_head(&ctx->fd_wqh);
1305 seqcount_init(&ctx->refile_seq);
1309 * userfaultfd_file_create - Creates an userfaultfd file pointer.
1310 * @flags: Flags for the userfaultfd file.
1312 * This function creates an userfaultfd file pointer, w/out installing
1313 * it into the fd table. This is useful when the userfaultfd file is
1314 * used during the initialization of data structures that require
1315 * extra setup after the userfaultfd creation. So the userfaultfd
1316 * creation is split into the file pointer creation phase, and the
1317 * file descriptor installation phase. In this way races with
1318 * userspace closing the newly installed file descriptor can be
1319 * avoided. Returns an userfaultfd file pointer, or a proper error
1322 static struct file *userfaultfd_file_create(int flags)
1325 struct userfaultfd_ctx *ctx;
1327 BUG_ON(!current->mm);
1329 /* Check the UFFD_* constants for consistency. */
1330 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1331 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1333 file = ERR_PTR(-EINVAL);
1334 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1337 file = ERR_PTR(-ENOMEM);
1338 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1342 atomic_set(&ctx->refcount, 1);
1344 ctx->state = UFFD_STATE_WAIT_API;
1345 ctx->released = false;
1346 ctx->mm = current->mm;
1347 /* prevent the mm struct to be freed */
1348 atomic_inc(&ctx->mm->mm_count);
1350 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1351 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1354 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1360 SYSCALL_DEFINE1(userfaultfd, int, flags)
1365 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1370 file = userfaultfd_file_create(flags);
1372 error = PTR_ERR(file);
1373 goto err_put_unused_fd;
1375 fd_install(fd, file);
1385 static int __init userfaultfd_init(void)
1387 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1388 sizeof(struct userfaultfd_ctx),
1390 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1391 init_once_userfaultfd_ctx);
1394 __initcall(userfaultfd_init);