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/list.h>
16 #include <linux/hashtable.h>
17 #include <linux/sched.h>
19 #include <linux/poll.h>
20 #include <linux/slab.h>
21 #include <linux/seq_file.h>
22 #include <linux/file.h>
23 #include <linux/bug.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/syscalls.h>
26 #include <linux/userfaultfd_k.h>
27 #include <linux/mempolicy.h>
28 #include <linux/ioctl.h>
29 #include <linux/security.h>
31 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
33 enum userfaultfd_state {
39 * Start with fault_pending_wqh and fault_wqh so they're more likely
40 * to be in the same cacheline.
42 struct userfaultfd_ctx {
43 /* waitqueue head for the pending (i.e. not read) userfaults */
44 wait_queue_head_t fault_pending_wqh;
45 /* waitqueue head for the userfaults */
46 wait_queue_head_t fault_wqh;
47 /* waitqueue head for the pseudo fd to wakeup poll/read */
48 wait_queue_head_t fd_wqh;
49 /* waitqueue head for events */
50 wait_queue_head_t event_wqh;
51 /* a refile sequence protected by fault_pending_wqh lock */
52 struct seqcount refile_seq;
53 /* pseudo fd refcounting */
55 /* userfaultfd syscall flags */
57 /* features requested from the userspace */
58 unsigned int features;
60 enum userfaultfd_state state;
63 /* mm with one ore more vmas attached to this userfaultfd_ctx */
67 struct userfaultfd_fork_ctx {
68 struct userfaultfd_ctx *orig;
69 struct userfaultfd_ctx *new;
70 struct list_head list;
73 struct userfaultfd_wait_queue {
76 struct userfaultfd_ctx *ctx;
80 struct userfaultfd_wake_range {
85 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
86 int wake_flags, void *key)
88 struct userfaultfd_wake_range *range = key;
90 struct userfaultfd_wait_queue *uwq;
91 unsigned long start, len;
93 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
95 /* len == 0 means wake all */
98 if (len && (start > uwq->msg.arg.pagefault.address ||
99 start + len <= uwq->msg.arg.pagefault.address))
101 WRITE_ONCE(uwq->waken, true);
103 * The implicit smp_mb__before_spinlock in try_to_wake_up()
104 * renders uwq->waken visible to other CPUs before the task is
107 ret = wake_up_state(wq->private, mode);
110 * Wake only once, autoremove behavior.
112 * After the effect of list_del_init is visible to the
113 * other CPUs, the waitqueue may disappear from under
114 * us, see the !list_empty_careful() in
115 * handle_userfault(). try_to_wake_up() has an
116 * implicit smp_mb__before_spinlock, and the
117 * wq->private is read before calling the extern
118 * function "wake_up_state" (which in turns calls
119 * try_to_wake_up). While the spin_lock;spin_unlock;
120 * wouldn't be enough, the smp_mb__before_spinlock is
121 * enough to avoid an explicit smp_mb() here.
123 list_del_init(&wq->task_list);
129 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
131 * @ctx: [in] Pointer to the userfaultfd context.
133 * Returns: In case of success, returns not zero.
135 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
137 if (!atomic_inc_not_zero(&ctx->refcount))
142 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
144 * @ctx: [in] Pointer to userfaultfd context.
146 * The userfaultfd context reference must have been previously acquired either
147 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
149 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
151 if (atomic_dec_and_test(&ctx->refcount)) {
152 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
153 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
154 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
155 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
156 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
157 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
158 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
159 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
161 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
165 static inline void msg_init(struct uffd_msg *msg)
167 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
169 * Must use memset to zero out the paddings or kernel data is
170 * leaked to userland.
172 memset(msg, 0, sizeof(struct uffd_msg));
175 static inline struct uffd_msg userfault_msg(unsigned long address,
177 unsigned long reason)
181 msg.event = UFFD_EVENT_PAGEFAULT;
182 msg.arg.pagefault.address = address;
183 if (flags & FAULT_FLAG_WRITE)
185 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
186 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
187 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
188 * was a read fault, otherwise if set it means it's
191 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
192 if (reason & VM_UFFD_WP)
194 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
195 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
196 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
197 * a missing fault, otherwise if set it means it's a
198 * write protect fault.
200 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
205 * Verify the pagetables are still not ok after having reigstered into
206 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
207 * userfault that has already been resolved, if userfaultfd_read and
208 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
211 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
212 unsigned long address,
214 unsigned long reason)
216 struct mm_struct *mm = ctx->mm;
223 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
225 pgd = pgd_offset(mm, address);
226 if (!pgd_present(*pgd))
228 pud = pud_offset(pgd, address);
229 if (!pud_present(*pud))
231 pmd = pmd_offset(pud, address);
233 * READ_ONCE must function as a barrier with narrower scope
234 * and it must be equivalent to:
235 * _pmd = *pmd; barrier();
237 * This is to deal with the instability (as in
238 * pmd_trans_unstable) of the pmd.
240 _pmd = READ_ONCE(*pmd);
241 if (!pmd_present(_pmd))
245 if (pmd_trans_huge(_pmd))
249 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
250 * and use the standard pte_offset_map() instead of parsing _pmd.
252 pte = pte_offset_map(pmd, address);
254 * Lockless access: we're in a wait_event so it's ok if it
266 * The locking rules involved in returning VM_FAULT_RETRY depending on
267 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
268 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
269 * recommendation in __lock_page_or_retry is not an understatement.
271 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
272 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
275 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
276 * set, VM_FAULT_RETRY can still be returned if and only if there are
277 * fatal_signal_pending()s, and the mmap_sem must be released before
280 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
282 struct mm_struct *mm = vmf->vma->vm_mm;
283 struct userfaultfd_ctx *ctx;
284 struct userfaultfd_wait_queue uwq;
286 bool must_wait, return_to_userland;
289 BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
291 ret = VM_FAULT_SIGBUS;
292 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
296 BUG_ON(ctx->mm != mm);
298 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
299 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
302 * If it's already released don't get it. This avoids to loop
303 * in __get_user_pages if userfaultfd_release waits on the
304 * caller of handle_userfault to release the mmap_sem.
306 if (unlikely(ACCESS_ONCE(ctx->released)))
310 * We don't do userfault handling for the final child pid update.
312 if (current->flags & PF_EXITING)
316 * Check that we can return VM_FAULT_RETRY.
318 * NOTE: it should become possible to return VM_FAULT_RETRY
319 * even if FAULT_FLAG_TRIED is set without leading to gup()
320 * -EBUSY failures, if the userfaultfd is to be extended for
321 * VM_UFFD_WP tracking and we intend to arm the userfault
322 * without first stopping userland access to the memory. For
323 * VM_UFFD_MISSING userfaults this is enough for now.
325 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
327 * Validate the invariant that nowait must allow retry
328 * to be sure not to return SIGBUS erroneously on
329 * nowait invocations.
331 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
332 #ifdef CONFIG_DEBUG_VM
333 if (printk_ratelimit()) {
335 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
344 * Handle nowait, not much to do other than tell it to retry
347 ret = VM_FAULT_RETRY;
348 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
351 /* take the reference before dropping the mmap_sem */
352 userfaultfd_ctx_get(ctx);
354 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
355 uwq.wq.private = current;
356 uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
361 (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
362 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
363 blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
366 spin_lock(&ctx->fault_pending_wqh.lock);
368 * After the __add_wait_queue the uwq is visible to userland
369 * through poll/read().
371 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
373 * The smp_mb() after __set_current_state prevents the reads
374 * following the spin_unlock to happen before the list_add in
377 set_current_state(blocking_state);
378 spin_unlock(&ctx->fault_pending_wqh.lock);
380 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
382 up_read(&mm->mmap_sem);
384 if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
385 (return_to_userland ? !signal_pending(current) :
386 !fatal_signal_pending(current)))) {
387 wake_up_poll(&ctx->fd_wqh, POLLIN);
389 ret |= VM_FAULT_MAJOR;
392 * False wakeups can orginate even from rwsem before
393 * up_read() however userfaults will wait either for a
394 * targeted wakeup on the specific uwq waitqueue from
395 * wake_userfault() or for signals or for uffd
398 while (!READ_ONCE(uwq.waken)) {
400 * This needs the full smp_store_mb()
401 * guarantee as the state write must be
402 * visible to other CPUs before reading
403 * uwq.waken from other CPUs.
405 set_current_state(blocking_state);
406 if (READ_ONCE(uwq.waken) ||
407 READ_ONCE(ctx->released) ||
408 (return_to_userland ? signal_pending(current) :
409 fatal_signal_pending(current)))
415 __set_current_state(TASK_RUNNING);
417 if (return_to_userland) {
418 if (signal_pending(current) &&
419 !fatal_signal_pending(current)) {
421 * If we got a SIGSTOP or SIGCONT and this is
422 * a normal userland page fault, just let
423 * userland return so the signal will be
424 * handled and gdb debugging works. The page
425 * fault code immediately after we return from
426 * this function is going to release the
427 * mmap_sem and it's not depending on it
428 * (unlike gup would if we were not to return
431 * If a fatal signal is pending we still take
432 * the streamlined VM_FAULT_RETRY failure path
433 * and there's no need to retake the mmap_sem
436 down_read(&mm->mmap_sem);
442 * Here we race with the list_del; list_add in
443 * userfaultfd_ctx_read(), however because we don't ever run
444 * list_del_init() to refile across the two lists, the prev
445 * and next pointers will never point to self. list_add also
446 * would never let any of the two pointers to point to
447 * self. So list_empty_careful won't risk to see both pointers
448 * pointing to self at any time during the list refile. The
449 * only case where list_del_init() is called is the full
450 * removal in the wake function and there we don't re-list_add
451 * and it's fine not to block on the spinlock. The uwq on this
452 * kernel stack can be released after the list_del_init.
454 if (!list_empty_careful(&uwq.wq.task_list)) {
455 spin_lock(&ctx->fault_pending_wqh.lock);
457 * No need of list_del_init(), the uwq on the stack
458 * will be freed shortly anyway.
460 list_del(&uwq.wq.task_list);
461 spin_unlock(&ctx->fault_pending_wqh.lock);
465 * ctx may go away after this if the userfault pseudo fd is
468 userfaultfd_ctx_put(ctx);
474 static int userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
475 struct userfaultfd_wait_queue *ewq)
480 init_waitqueue_entry(&ewq->wq, current);
482 spin_lock(&ctx->event_wqh.lock);
484 * After the __add_wait_queue the uwq is visible to userland
485 * through poll/read().
487 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
489 set_current_state(TASK_KILLABLE);
490 if (ewq->msg.event == 0)
492 if (ACCESS_ONCE(ctx->released) ||
493 fatal_signal_pending(current)) {
495 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
499 spin_unlock(&ctx->event_wqh.lock);
501 wake_up_poll(&ctx->fd_wqh, POLLIN);
504 spin_lock(&ctx->event_wqh.lock);
506 __set_current_state(TASK_RUNNING);
507 spin_unlock(&ctx->event_wqh.lock);
510 * ctx may go away after this if the userfault pseudo fd is
514 userfaultfd_ctx_put(ctx);
518 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
519 struct userfaultfd_wait_queue *ewq)
522 wake_up_locked(&ctx->event_wqh);
523 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
526 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
528 struct userfaultfd_ctx *ctx = NULL, *octx;
529 struct userfaultfd_fork_ctx *fctx;
531 octx = vma->vm_userfaultfd_ctx.ctx;
532 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
533 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
534 vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
538 list_for_each_entry(fctx, fcs, list)
539 if (fctx->orig == octx) {
545 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
549 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
555 atomic_set(&ctx->refcount, 1);
556 ctx->flags = octx->flags;
557 ctx->state = UFFD_STATE_RUNNING;
558 ctx->features = octx->features;
559 ctx->released = false;
560 ctx->mm = vma->vm_mm;
561 atomic_inc(&ctx->mm->mm_count);
563 userfaultfd_ctx_get(octx);
566 list_add_tail(&fctx->list, fcs);
569 vma->vm_userfaultfd_ctx.ctx = ctx;
573 static int dup_fctx(struct userfaultfd_fork_ctx *fctx)
575 struct userfaultfd_ctx *ctx = fctx->orig;
576 struct userfaultfd_wait_queue ewq;
580 ewq.msg.event = UFFD_EVENT_FORK;
581 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
583 return userfaultfd_event_wait_completion(ctx, &ewq);
586 void dup_userfaultfd_complete(struct list_head *fcs)
589 struct userfaultfd_fork_ctx *fctx, *n;
591 list_for_each_entry_safe(fctx, n, fcs, list) {
593 ret = dup_fctx(fctx);
594 list_del(&fctx->list);
599 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
600 struct vm_userfaultfd_ctx *vm_ctx)
602 struct userfaultfd_ctx *ctx;
604 ctx = vma->vm_userfaultfd_ctx.ctx;
605 if (ctx && (ctx->features & UFFD_FEATURE_EVENT_REMAP)) {
607 userfaultfd_ctx_get(ctx);
611 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
612 unsigned long from, unsigned long to,
615 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
616 struct userfaultfd_wait_queue ewq;
621 if (to & ~PAGE_MASK) {
622 userfaultfd_ctx_put(ctx);
628 ewq.msg.event = UFFD_EVENT_REMAP;
629 ewq.msg.arg.remap.from = from;
630 ewq.msg.arg.remap.to = to;
631 ewq.msg.arg.remap.len = len;
633 userfaultfd_event_wait_completion(ctx, &ewq);
636 static int userfaultfd_release(struct inode *inode, struct file *file)
638 struct userfaultfd_ctx *ctx = file->private_data;
639 struct mm_struct *mm = ctx->mm;
640 struct vm_area_struct *vma, *prev;
641 /* len == 0 means wake all */
642 struct userfaultfd_wake_range range = { .len = 0, };
643 unsigned long new_flags;
645 ACCESS_ONCE(ctx->released) = true;
647 if (!mmget_not_zero(mm))
651 * Flush page faults out of all CPUs. NOTE: all page faults
652 * must be retried without returning VM_FAULT_SIGBUS if
653 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
654 * changes while handle_userfault released the mmap_sem. So
655 * it's critical that released is set to true (above), before
656 * taking the mmap_sem for writing.
658 down_write(&mm->mmap_sem);
660 for (vma = mm->mmap; vma; vma = vma->vm_next) {
662 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
663 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
664 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
668 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
669 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
670 new_flags, vma->anon_vma,
671 vma->vm_file, vma->vm_pgoff,
678 vma->vm_flags = new_flags;
679 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
681 up_write(&mm->mmap_sem);
685 * After no new page faults can wait on this fault_*wqh, flush
686 * the last page faults that may have been already waiting on
689 spin_lock(&ctx->fault_pending_wqh.lock);
690 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
691 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
692 spin_unlock(&ctx->fault_pending_wqh.lock);
694 wake_up_poll(&ctx->fd_wqh, POLLHUP);
695 userfaultfd_ctx_put(ctx);
699 /* fault_pending_wqh.lock must be hold by the caller */
700 static inline struct userfaultfd_wait_queue *find_userfault_in(
701 wait_queue_head_t *wqh)
704 struct userfaultfd_wait_queue *uwq;
706 VM_BUG_ON(!spin_is_locked(&wqh->lock));
709 if (!waitqueue_active(wqh))
711 /* walk in reverse to provide FIFO behavior to read userfaults */
712 wq = list_last_entry(&wqh->task_list, typeof(*wq), task_list);
713 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
718 static inline struct userfaultfd_wait_queue *find_userfault(
719 struct userfaultfd_ctx *ctx)
721 return find_userfault_in(&ctx->fault_pending_wqh);
724 static inline struct userfaultfd_wait_queue *find_userfault_evt(
725 struct userfaultfd_ctx *ctx)
727 return find_userfault_in(&ctx->event_wqh);
730 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
732 struct userfaultfd_ctx *ctx = file->private_data;
735 poll_wait(file, &ctx->fd_wqh, wait);
737 switch (ctx->state) {
738 case UFFD_STATE_WAIT_API:
740 case UFFD_STATE_RUNNING:
742 * poll() never guarantees that read won't block.
743 * userfaults can be waken before they're read().
745 if (unlikely(!(file->f_flags & O_NONBLOCK)))
748 * lockless access to see if there are pending faults
749 * __pollwait last action is the add_wait_queue but
750 * the spin_unlock would allow the waitqueue_active to
751 * pass above the actual list_add inside
752 * add_wait_queue critical section. So use a full
753 * memory barrier to serialize the list_add write of
754 * add_wait_queue() with the waitqueue_active read
759 if (waitqueue_active(&ctx->fault_pending_wqh))
761 else if (waitqueue_active(&ctx->event_wqh))
771 static const struct file_operations userfaultfd_fops;
773 static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
774 struct userfaultfd_ctx *new,
775 struct uffd_msg *msg)
779 unsigned int flags = new->flags & UFFD_SHARED_FCNTL_FLAGS;
781 fd = get_unused_fd_flags(flags);
785 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, new,
789 return PTR_ERR(file);
792 fd_install(fd, file);
793 msg->arg.reserved.reserved1 = 0;
794 msg->arg.fork.ufd = fd;
799 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
800 struct uffd_msg *msg)
803 DECLARE_WAITQUEUE(wait, current);
804 struct userfaultfd_wait_queue *uwq;
806 * Handling fork event requires sleeping operations, so
807 * we drop the event_wqh lock, then do these ops, then
808 * lock it back and wake up the waiter. While the lock is
809 * dropped the ewq may go away so we keep track of it
812 LIST_HEAD(fork_event);
813 struct userfaultfd_ctx *fork_nctx = NULL;
815 /* always take the fd_wqh lock before the fault_pending_wqh lock */
816 spin_lock(&ctx->fd_wqh.lock);
817 __add_wait_queue(&ctx->fd_wqh, &wait);
819 set_current_state(TASK_INTERRUPTIBLE);
820 spin_lock(&ctx->fault_pending_wqh.lock);
821 uwq = find_userfault(ctx);
824 * Use a seqcount to repeat the lockless check
825 * in wake_userfault() to avoid missing
826 * wakeups because during the refile both
827 * waitqueue could become empty if this is the
830 write_seqcount_begin(&ctx->refile_seq);
833 * The fault_pending_wqh.lock prevents the uwq
834 * to disappear from under us.
836 * Refile this userfault from
837 * fault_pending_wqh to fault_wqh, it's not
838 * pending anymore after we read it.
840 * Use list_del() by hand (as
841 * userfaultfd_wake_function also uses
842 * list_del_init() by hand) to be sure nobody
843 * changes __remove_wait_queue() to use
844 * list_del_init() in turn breaking the
845 * !list_empty_careful() check in
846 * handle_userfault(). The uwq->wq.task_list
847 * must never be empty at any time during the
848 * refile, or the waitqueue could disappear
849 * from under us. The "wait_queue_head_t"
850 * parameter of __remove_wait_queue() is unused
853 list_del(&uwq->wq.task_list);
854 __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
856 write_seqcount_end(&ctx->refile_seq);
858 /* careful to always initialize msg if ret == 0 */
860 spin_unlock(&ctx->fault_pending_wqh.lock);
864 spin_unlock(&ctx->fault_pending_wqh.lock);
866 spin_lock(&ctx->event_wqh.lock);
867 uwq = find_userfault_evt(ctx);
871 if (uwq->msg.event == UFFD_EVENT_FORK) {
872 fork_nctx = (struct userfaultfd_ctx *)
874 uwq->msg.arg.reserved.reserved1;
875 list_move(&uwq->wq.task_list, &fork_event);
876 spin_unlock(&ctx->event_wqh.lock);
881 userfaultfd_event_complete(ctx, uwq);
882 spin_unlock(&ctx->event_wqh.lock);
886 spin_unlock(&ctx->event_wqh.lock);
888 if (signal_pending(current)) {
896 spin_unlock(&ctx->fd_wqh.lock);
898 spin_lock(&ctx->fd_wqh.lock);
900 __remove_wait_queue(&ctx->fd_wqh, &wait);
901 __set_current_state(TASK_RUNNING);
902 spin_unlock(&ctx->fd_wqh.lock);
904 if (!ret && msg->event == UFFD_EVENT_FORK) {
905 ret = resolve_userfault_fork(ctx, fork_nctx, msg);
908 spin_lock(&ctx->event_wqh.lock);
909 if (!list_empty(&fork_event)) {
910 uwq = list_first_entry(&fork_event,
913 list_del(&uwq->wq.task_list);
914 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
915 userfaultfd_event_complete(ctx, uwq);
917 spin_unlock(&ctx->event_wqh.lock);
924 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
925 size_t count, loff_t *ppos)
927 struct userfaultfd_ctx *ctx = file->private_data;
928 ssize_t _ret, ret = 0;
930 int no_wait = file->f_flags & O_NONBLOCK;
932 if (ctx->state == UFFD_STATE_WAIT_API)
936 if (count < sizeof(msg))
937 return ret ? ret : -EINVAL;
938 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
940 return ret ? ret : _ret;
941 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
942 return ret ? ret : -EFAULT;
945 count -= sizeof(msg);
947 * Allow to read more than one fault at time but only
948 * block if waiting for the very first one.
950 no_wait = O_NONBLOCK;
954 static void __wake_userfault(struct userfaultfd_ctx *ctx,
955 struct userfaultfd_wake_range *range)
957 unsigned long start, end;
959 start = range->start;
960 end = range->start + range->len;
962 spin_lock(&ctx->fault_pending_wqh.lock);
963 /* wake all in the range and autoremove */
964 if (waitqueue_active(&ctx->fault_pending_wqh))
965 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
967 if (waitqueue_active(&ctx->fault_wqh))
968 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
969 spin_unlock(&ctx->fault_pending_wqh.lock);
972 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
973 struct userfaultfd_wake_range *range)
979 * To be sure waitqueue_active() is not reordered by the CPU
980 * before the pagetable update, use an explicit SMP memory
981 * barrier here. PT lock release or up_read(mmap_sem) still
982 * have release semantics that can allow the
983 * waitqueue_active() to be reordered before the pte update.
988 * Use waitqueue_active because it's very frequent to
989 * change the address space atomically even if there are no
990 * userfaults yet. So we take the spinlock only when we're
991 * sure we've userfaults to wake.
994 seq = read_seqcount_begin(&ctx->refile_seq);
995 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
996 waitqueue_active(&ctx->fault_wqh);
998 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1000 __wake_userfault(ctx, range);
1003 static __always_inline int validate_range(struct mm_struct *mm,
1004 __u64 start, __u64 len)
1006 __u64 task_size = mm->task_size;
1008 if (start & ~PAGE_MASK)
1010 if (len & ~PAGE_MASK)
1014 if (start < mmap_min_addr)
1016 if (start >= task_size)
1018 if (len > task_size - start)
1023 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1026 struct mm_struct *mm = ctx->mm;
1027 struct vm_area_struct *vma, *prev, *cur;
1029 struct uffdio_register uffdio_register;
1030 struct uffdio_register __user *user_uffdio_register;
1031 unsigned long vm_flags, new_flags;
1033 unsigned long start, end, vma_end;
1035 user_uffdio_register = (struct uffdio_register __user *) arg;
1038 if (copy_from_user(&uffdio_register, user_uffdio_register,
1039 sizeof(uffdio_register)-sizeof(__u64)))
1043 if (!uffdio_register.mode)
1045 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
1046 UFFDIO_REGISTER_MODE_WP))
1049 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1050 vm_flags |= VM_UFFD_MISSING;
1051 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1052 vm_flags |= VM_UFFD_WP;
1054 * FIXME: remove the below error constraint by
1055 * implementing the wprotect tracking mode.
1061 ret = validate_range(mm, uffdio_register.range.start,
1062 uffdio_register.range.len);
1066 start = uffdio_register.range.start;
1067 end = start + uffdio_register.range.len;
1070 if (!mmget_not_zero(mm))
1073 down_write(&mm->mmap_sem);
1074 vma = find_vma_prev(mm, start, &prev);
1078 /* check that there's at least one vma in the range */
1080 if (vma->vm_start >= end)
1084 * Search for not compatible vmas.
1086 * FIXME: this shall be relaxed later so that it doesn't fail
1087 * on tmpfs backed vmas (in addition to the current allowance
1088 * on anonymous vmas).
1091 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1094 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1095 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1097 /* check not compatible vmas */
1099 if (!vma_is_anonymous(cur))
1103 * Check that this vma isn't already owned by a
1104 * different userfaultfd. We can't allow more than one
1105 * userfaultfd to own a single vma simultaneously or we
1106 * wouldn't know which one to deliver the userfaults to.
1109 if (cur->vm_userfaultfd_ctx.ctx &&
1110 cur->vm_userfaultfd_ctx.ctx != ctx)
1117 if (vma->vm_start < start)
1124 BUG_ON(!vma_is_anonymous(vma));
1125 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1126 vma->vm_userfaultfd_ctx.ctx != ctx);
1129 * Nothing to do: this vma is already registered into this
1130 * userfaultfd and with the right tracking mode too.
1132 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1133 (vma->vm_flags & vm_flags) == vm_flags)
1136 if (vma->vm_start > start)
1137 start = vma->vm_start;
1138 vma_end = min(end, vma->vm_end);
1140 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
1141 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1142 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1144 ((struct vm_userfaultfd_ctx){ ctx }));
1149 if (vma->vm_start < start) {
1150 ret = split_vma(mm, vma, start, 1);
1154 if (vma->vm_end > end) {
1155 ret = split_vma(mm, vma, end, 0);
1161 * In the vma_merge() successful mprotect-like case 8:
1162 * the next vma was merged into the current one and
1163 * the current one has not been updated yet.
1165 vma->vm_flags = new_flags;
1166 vma->vm_userfaultfd_ctx.ctx = ctx;
1170 start = vma->vm_end;
1172 } while (vma && vma->vm_start < end);
1174 up_write(&mm->mmap_sem);
1178 * Now that we scanned all vmas we can already tell
1179 * userland which ioctls methods are guaranteed to
1180 * succeed on this range.
1182 if (put_user(UFFD_API_RANGE_IOCTLS,
1183 &user_uffdio_register->ioctls))
1190 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1193 struct mm_struct *mm = ctx->mm;
1194 struct vm_area_struct *vma, *prev, *cur;
1196 struct uffdio_range uffdio_unregister;
1197 unsigned long new_flags;
1199 unsigned long start, end, vma_end;
1200 const void __user *buf = (void __user *)arg;
1203 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1206 ret = validate_range(mm, uffdio_unregister.start,
1207 uffdio_unregister.len);
1211 start = uffdio_unregister.start;
1212 end = start + uffdio_unregister.len;
1215 if (!mmget_not_zero(mm))
1218 down_write(&mm->mmap_sem);
1219 vma = find_vma_prev(mm, start, &prev);
1223 /* check that there's at least one vma in the range */
1225 if (vma->vm_start >= end)
1229 * Search for not compatible vmas.
1231 * FIXME: this shall be relaxed later so that it doesn't fail
1232 * on tmpfs backed vmas (in addition to the current allowance
1233 * on anonymous vmas).
1237 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1240 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1241 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1244 * Check not compatible vmas, not strictly required
1245 * here as not compatible vmas cannot have an
1246 * userfaultfd_ctx registered on them, but this
1247 * provides for more strict behavior to notice
1248 * unregistration errors.
1250 if (!vma_is_anonymous(cur))
1257 if (vma->vm_start < start)
1264 BUG_ON(!vma_is_anonymous(vma));
1267 * Nothing to do: this vma is already registered into this
1268 * userfaultfd and with the right tracking mode too.
1270 if (!vma->vm_userfaultfd_ctx.ctx)
1273 if (vma->vm_start > start)
1274 start = vma->vm_start;
1275 vma_end = min(end, vma->vm_end);
1277 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1278 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1279 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1286 if (vma->vm_start < start) {
1287 ret = split_vma(mm, vma, start, 1);
1291 if (vma->vm_end > end) {
1292 ret = split_vma(mm, vma, end, 0);
1298 * In the vma_merge() successful mprotect-like case 8:
1299 * the next vma was merged into the current one and
1300 * the current one has not been updated yet.
1302 vma->vm_flags = new_flags;
1303 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1307 start = vma->vm_end;
1309 } while (vma && vma->vm_start < end);
1311 up_write(&mm->mmap_sem);
1318 * userfaultfd_wake may be used in combination with the
1319 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1321 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1325 struct uffdio_range uffdio_wake;
1326 struct userfaultfd_wake_range range;
1327 const void __user *buf = (void __user *)arg;
1330 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1333 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1337 range.start = uffdio_wake.start;
1338 range.len = uffdio_wake.len;
1341 * len == 0 means wake all and we don't want to wake all here,
1342 * so check it again to be sure.
1344 VM_BUG_ON(!range.len);
1346 wake_userfault(ctx, &range);
1353 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1357 struct uffdio_copy uffdio_copy;
1358 struct uffdio_copy __user *user_uffdio_copy;
1359 struct userfaultfd_wake_range range;
1361 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1364 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1365 /* don't copy "copy" last field */
1366 sizeof(uffdio_copy)-sizeof(__s64)))
1369 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1373 * double check for wraparound just in case. copy_from_user()
1374 * will later check uffdio_copy.src + uffdio_copy.len to fit
1375 * in the userland range.
1378 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1380 if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1382 if (mmget_not_zero(ctx->mm)) {
1383 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1387 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1392 /* len == 0 would wake all */
1394 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1395 range.start = uffdio_copy.dst;
1396 wake_userfault(ctx, &range);
1398 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1403 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1407 struct uffdio_zeropage uffdio_zeropage;
1408 struct uffdio_zeropage __user *user_uffdio_zeropage;
1409 struct userfaultfd_wake_range range;
1411 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1414 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1415 /* don't copy "zeropage" last field */
1416 sizeof(uffdio_zeropage)-sizeof(__s64)))
1419 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1420 uffdio_zeropage.range.len);
1424 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1427 if (mmget_not_zero(ctx->mm)) {
1428 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1429 uffdio_zeropage.range.len);
1432 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1436 /* len == 0 would wake all */
1439 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1440 range.start = uffdio_zeropage.range.start;
1441 wake_userfault(ctx, &range);
1443 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1448 static inline unsigned int uffd_ctx_features(__u64 user_features)
1451 * For the current set of features the bits just coincide
1453 return (unsigned int)user_features;
1457 * userland asks for a certain API version and we return which bits
1458 * and ioctl commands are implemented in this kernel for such API
1459 * version or -EINVAL if unknown.
1461 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1464 struct uffdio_api uffdio_api;
1465 void __user *buf = (void __user *)arg;
1470 if (ctx->state != UFFD_STATE_WAIT_API)
1473 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1475 features = uffdio_api.features;
1476 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES)) {
1477 memset(&uffdio_api, 0, sizeof(uffdio_api));
1478 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1483 /* report all available features and ioctls to userland */
1484 uffdio_api.features = UFFD_API_FEATURES;
1485 uffdio_api.ioctls = UFFD_API_IOCTLS;
1487 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1489 ctx->state = UFFD_STATE_RUNNING;
1490 /* only enable the requested features for this uffd context */
1491 ctx->features = uffd_ctx_features(features);
1497 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1501 struct userfaultfd_ctx *ctx = file->private_data;
1503 if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1508 ret = userfaultfd_api(ctx, arg);
1510 case UFFDIO_REGISTER:
1511 ret = userfaultfd_register(ctx, arg);
1513 case UFFDIO_UNREGISTER:
1514 ret = userfaultfd_unregister(ctx, arg);
1517 ret = userfaultfd_wake(ctx, arg);
1520 ret = userfaultfd_copy(ctx, arg);
1522 case UFFDIO_ZEROPAGE:
1523 ret = userfaultfd_zeropage(ctx, arg);
1529 #ifdef CONFIG_PROC_FS
1530 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1532 struct userfaultfd_ctx *ctx = f->private_data;
1534 struct userfaultfd_wait_queue *uwq;
1535 unsigned long pending = 0, total = 0;
1537 spin_lock(&ctx->fault_pending_wqh.lock);
1538 list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1539 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1543 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1544 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1547 spin_unlock(&ctx->fault_pending_wqh.lock);
1550 * If more protocols will be added, there will be all shown
1551 * separated by a space. Like this:
1552 * protocols: aa:... bb:...
1554 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1555 pending, total, UFFD_API, UFFD_API_FEATURES,
1556 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1560 static const struct file_operations userfaultfd_fops = {
1561 #ifdef CONFIG_PROC_FS
1562 .show_fdinfo = userfaultfd_show_fdinfo,
1564 .release = userfaultfd_release,
1565 .poll = userfaultfd_poll,
1566 .read = userfaultfd_read,
1567 .unlocked_ioctl = userfaultfd_ioctl,
1568 .compat_ioctl = userfaultfd_ioctl,
1569 .llseek = noop_llseek,
1572 static void init_once_userfaultfd_ctx(void *mem)
1574 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1576 init_waitqueue_head(&ctx->fault_pending_wqh);
1577 init_waitqueue_head(&ctx->fault_wqh);
1578 init_waitqueue_head(&ctx->event_wqh);
1579 init_waitqueue_head(&ctx->fd_wqh);
1580 seqcount_init(&ctx->refile_seq);
1584 * userfaultfd_file_create - Creates an userfaultfd file pointer.
1585 * @flags: Flags for the userfaultfd file.
1587 * This function creates an userfaultfd file pointer, w/out installing
1588 * it into the fd table. This is useful when the userfaultfd file is
1589 * used during the initialization of data structures that require
1590 * extra setup after the userfaultfd creation. So the userfaultfd
1591 * creation is split into the file pointer creation phase, and the
1592 * file descriptor installation phase. In this way races with
1593 * userspace closing the newly installed file descriptor can be
1594 * avoided. Returns an userfaultfd file pointer, or a proper error
1597 static struct file *userfaultfd_file_create(int flags)
1600 struct userfaultfd_ctx *ctx;
1602 BUG_ON(!current->mm);
1604 /* Check the UFFD_* constants for consistency. */
1605 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1606 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1608 file = ERR_PTR(-EINVAL);
1609 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1612 file = ERR_PTR(-ENOMEM);
1613 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1617 atomic_set(&ctx->refcount, 1);
1620 ctx->state = UFFD_STATE_WAIT_API;
1621 ctx->released = false;
1622 ctx->mm = current->mm;
1623 /* prevent the mm struct to be freed */
1624 atomic_inc(&ctx->mm->mm_count);
1626 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1627 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1630 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1636 SYSCALL_DEFINE1(userfaultfd, int, flags)
1641 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1646 file = userfaultfd_file_create(flags);
1648 error = PTR_ERR(file);
1649 goto err_put_unused_fd;
1651 fd_install(fd, file);
1661 static int __init userfaultfd_init(void)
1663 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1664 sizeof(struct userfaultfd_ctx),
1666 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1667 init_once_userfaultfd_ctx);
1670 __initcall(userfaultfd_init);