1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
6 * Copyright (C) 2008-2009 Red Hat, Inc.
7 * Copyright (C) 2015 Red Hat, Inc.
9 * Some part derived from fs/eventfd.c (anon inode setup) and
10 * mm/ksm.c (mm hashing).
13 #include <linux/list.h>
14 #include <linux/hashtable.h>
15 #include <linux/sched/signal.h>
16 #include <linux/sched/mm.h>
18 #include <linux/mm_inline.h>
19 #include <linux/mmu_notifier.h>
20 #include <linux/poll.h>
21 #include <linux/slab.h>
22 #include <linux/seq_file.h>
23 #include <linux/file.h>
24 #include <linux/bug.h>
25 #include <linux/anon_inodes.h>
26 #include <linux/syscalls.h>
27 #include <linux/userfaultfd_k.h>
28 #include <linux/mempolicy.h>
29 #include <linux/ioctl.h>
30 #include <linux/security.h>
31 #include <linux/hugetlb.h>
32 #include <linux/swapops.h>
33 #include <linux/miscdevice.h>
35 static int sysctl_unprivileged_userfaultfd __read_mostly;
38 static struct ctl_table vm_userfaultfd_table[] = {
40 .procname = "unprivileged_userfaultfd",
41 .data = &sysctl_unprivileged_userfaultfd,
42 .maxlen = sizeof(sysctl_unprivileged_userfaultfd),
44 .proc_handler = proc_dointvec_minmax,
45 .extra1 = SYSCTL_ZERO,
52 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
55 * Start with fault_pending_wqh and fault_wqh so they're more likely
56 * to be in the same cacheline.
60 * fault_pending_wqh.lock
64 * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
65 * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
66 * also taken in IRQ context.
68 struct userfaultfd_ctx {
69 /* waitqueue head for the pending (i.e. not read) userfaults */
70 wait_queue_head_t fault_pending_wqh;
71 /* waitqueue head for the userfaults */
72 wait_queue_head_t fault_wqh;
73 /* waitqueue head for the pseudo fd to wakeup poll/read */
74 wait_queue_head_t fd_wqh;
75 /* waitqueue head for events */
76 wait_queue_head_t event_wqh;
77 /* a refile sequence protected by fault_pending_wqh lock */
78 seqcount_spinlock_t refile_seq;
79 /* pseudo fd refcounting */
81 /* userfaultfd syscall flags */
83 /* features requested from the userspace */
84 unsigned int features;
87 /* memory mappings are changing because of non-cooperative event */
88 atomic_t mmap_changing;
89 /* mm with one ore more vmas attached to this userfaultfd_ctx */
93 struct userfaultfd_fork_ctx {
94 struct userfaultfd_ctx *orig;
95 struct userfaultfd_ctx *new;
96 struct list_head list;
99 struct userfaultfd_unmap_ctx {
100 struct userfaultfd_ctx *ctx;
103 struct list_head list;
106 struct userfaultfd_wait_queue {
108 wait_queue_entry_t wq;
109 struct userfaultfd_ctx *ctx;
113 struct userfaultfd_wake_range {
118 /* internal indication that UFFD_API ioctl was successfully executed */
119 #define UFFD_FEATURE_INITIALIZED (1u << 31)
121 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
123 return ctx->features & UFFD_FEATURE_INITIALIZED;
127 * Whether WP_UNPOPULATED is enabled on the uffd context. It is only
128 * meaningful when userfaultfd_wp()==true on the vma and when it's
131 bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma)
133 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
138 return ctx->features & UFFD_FEATURE_WP_UNPOPULATED;
141 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
144 const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
146 vm_flags_reset(vma, flags);
148 * For shared mappings, we want to enable writenotify while
149 * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
150 * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
152 if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
153 vma_set_page_prot(vma);
156 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
157 int wake_flags, void *key)
159 struct userfaultfd_wake_range *range = key;
161 struct userfaultfd_wait_queue *uwq;
162 unsigned long start, len;
164 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
166 /* len == 0 means wake all */
167 start = range->start;
169 if (len && (start > uwq->msg.arg.pagefault.address ||
170 start + len <= uwq->msg.arg.pagefault.address))
172 WRITE_ONCE(uwq->waken, true);
174 * The Program-Order guarantees provided by the scheduler
175 * ensure uwq->waken is visible before the task is woken.
177 ret = wake_up_state(wq->private, mode);
180 * Wake only once, autoremove behavior.
182 * After the effect of list_del_init is visible to the other
183 * CPUs, the waitqueue may disappear from under us, see the
184 * !list_empty_careful() in handle_userfault().
186 * try_to_wake_up() has an implicit smp_mb(), and the
187 * wq->private is read before calling the extern function
188 * "wake_up_state" (which in turns calls try_to_wake_up).
190 list_del_init(&wq->entry);
197 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
199 * @ctx: [in] Pointer to the userfaultfd context.
201 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
203 refcount_inc(&ctx->refcount);
207 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
209 * @ctx: [in] Pointer to userfaultfd context.
211 * The userfaultfd context reference must have been previously acquired either
212 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
214 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
216 if (refcount_dec_and_test(&ctx->refcount)) {
217 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
218 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
219 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
220 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
221 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
222 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
223 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
224 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
226 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
230 static inline void msg_init(struct uffd_msg *msg)
232 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
234 * Must use memset to zero out the paddings or kernel data is
235 * leaked to userland.
237 memset(msg, 0, sizeof(struct uffd_msg));
240 static inline struct uffd_msg userfault_msg(unsigned long address,
241 unsigned long real_address,
243 unsigned long reason,
244 unsigned int features)
249 msg.event = UFFD_EVENT_PAGEFAULT;
251 msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
252 real_address : address;
255 * These flags indicate why the userfault occurred:
256 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
257 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
258 * - Neither of these flags being set indicates a MISSING fault.
260 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
261 * fault. Otherwise, it was a read fault.
263 if (flags & FAULT_FLAG_WRITE)
264 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
265 if (reason & VM_UFFD_WP)
266 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
267 if (reason & VM_UFFD_MINOR)
268 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
269 if (features & UFFD_FEATURE_THREAD_ID)
270 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
274 #ifdef CONFIG_HUGETLB_PAGE
276 * Same functionality as userfaultfd_must_wait below with modifications for
279 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
280 struct vm_fault *vmf,
281 unsigned long reason)
283 struct vm_area_struct *vma = vmf->vma;
287 assert_fault_locked(vmf);
289 ptep = hugetlb_walk(vma, vmf->address, vma_mmu_pagesize(vma));
294 pte = huge_ptep_get(ptep);
297 * Lockless access: we're in a wait_event so it's ok if it
298 * changes under us. PTE markers should be handled the same as none
301 if (huge_pte_none_mostly(pte))
303 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
309 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
310 struct vm_fault *vmf,
311 unsigned long reason)
313 return false; /* should never get here */
315 #endif /* CONFIG_HUGETLB_PAGE */
318 * Verify the pagetables are still not ok after having reigstered into
319 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
320 * userfault that has already been resolved, if userfaultfd_read and
321 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
324 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
325 struct vm_fault *vmf,
326 unsigned long reason)
328 struct mm_struct *mm = ctx->mm;
329 unsigned long address = vmf->address;
338 assert_fault_locked(vmf);
340 pgd = pgd_offset(mm, address);
341 if (!pgd_present(*pgd))
343 p4d = p4d_offset(pgd, address);
344 if (!p4d_present(*p4d))
346 pud = pud_offset(p4d, address);
347 if (!pud_present(*pud))
349 pmd = pmd_offset(pud, address);
351 _pmd = pmdp_get_lockless(pmd);
356 if (!pmd_present(_pmd) || pmd_devmap(_pmd))
359 if (pmd_trans_huge(_pmd)) {
360 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
365 pte = pte_offset_map(pmd, address);
371 * Lockless access: we're in a wait_event so it's ok if it
372 * changes under us. PTE markers should be handled the same as none
375 ptent = ptep_get(pte);
376 if (pte_none_mostly(ptent))
378 if (!pte_write(ptent) && (reason & VM_UFFD_WP))
386 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
388 if (flags & FAULT_FLAG_INTERRUPTIBLE)
389 return TASK_INTERRUPTIBLE;
391 if (flags & FAULT_FLAG_KILLABLE)
392 return TASK_KILLABLE;
394 return TASK_UNINTERRUPTIBLE;
398 * The locking rules involved in returning VM_FAULT_RETRY depending on
399 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
400 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
401 * recommendation in __lock_page_or_retry is not an understatement.
403 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
404 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
407 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
408 * set, VM_FAULT_RETRY can still be returned if and only if there are
409 * fatal_signal_pending()s, and the mmap_lock must be released before
412 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
414 struct vm_area_struct *vma = vmf->vma;
415 struct mm_struct *mm = vma->vm_mm;
416 struct userfaultfd_ctx *ctx;
417 struct userfaultfd_wait_queue uwq;
418 vm_fault_t ret = VM_FAULT_SIGBUS;
420 unsigned int blocking_state;
423 * We don't do userfault handling for the final child pid update.
425 * We also don't do userfault handling during
426 * coredumping. hugetlbfs has the special
427 * hugetlb_follow_page_mask() to skip missing pages in the
428 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
429 * the no_page_table() helper in follow_page_mask(), but the
430 * shmem_vm_ops->fault method is invoked even during
431 * coredumping and it ends up here.
433 if (current->flags & (PF_EXITING|PF_DUMPCORE))
436 assert_fault_locked(vmf);
438 ctx = vma->vm_userfaultfd_ctx.ctx;
442 BUG_ON(ctx->mm != mm);
444 /* Any unrecognized flag is a bug. */
445 VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
446 /* 0 or > 1 flags set is a bug; we expect exactly 1. */
447 VM_BUG_ON(!reason || (reason & (reason - 1)));
449 if (ctx->features & UFFD_FEATURE_SIGBUS)
451 if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
455 * If it's already released don't get it. This avoids to loop
456 * in __get_user_pages if userfaultfd_release waits on the
457 * caller of handle_userfault to release the mmap_lock.
459 if (unlikely(READ_ONCE(ctx->released))) {
461 * Don't return VM_FAULT_SIGBUS in this case, so a non
462 * cooperative manager can close the uffd after the
463 * last UFFDIO_COPY, without risking to trigger an
464 * involuntary SIGBUS if the process was starting the
465 * userfaultfd while the userfaultfd was still armed
466 * (but after the last UFFDIO_COPY). If the uffd
467 * wasn't already closed when the userfault reached
468 * this point, that would normally be solved by
469 * userfaultfd_must_wait returning 'false'.
471 * If we were to return VM_FAULT_SIGBUS here, the non
472 * cooperative manager would be instead forced to
473 * always call UFFDIO_UNREGISTER before it can safely
476 ret = VM_FAULT_NOPAGE;
481 * Check that we can return VM_FAULT_RETRY.
483 * NOTE: it should become possible to return VM_FAULT_RETRY
484 * even if FAULT_FLAG_TRIED is set without leading to gup()
485 * -EBUSY failures, if the userfaultfd is to be extended for
486 * VM_UFFD_WP tracking and we intend to arm the userfault
487 * without first stopping userland access to the memory. For
488 * VM_UFFD_MISSING userfaults this is enough for now.
490 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
492 * Validate the invariant that nowait must allow retry
493 * to be sure not to return SIGBUS erroneously on
494 * nowait invocations.
496 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
497 #ifdef CONFIG_DEBUG_VM
498 if (printk_ratelimit()) {
500 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
509 * Handle nowait, not much to do other than tell it to retry
512 ret = VM_FAULT_RETRY;
513 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
516 /* take the reference before dropping the mmap_lock */
517 userfaultfd_ctx_get(ctx);
519 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
520 uwq.wq.private = current;
521 uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
522 reason, ctx->features);
526 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
529 * Take the vma lock now, in order to safely call
530 * userfaultfd_huge_must_wait() later. Since acquiring the
531 * (sleepable) vma lock can modify the current task state, that
532 * must be before explicitly calling set_current_state().
534 if (is_vm_hugetlb_page(vma))
535 hugetlb_vma_lock_read(vma);
537 spin_lock_irq(&ctx->fault_pending_wqh.lock);
539 * After the __add_wait_queue the uwq is visible to userland
540 * through poll/read().
542 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
544 * The smp_mb() after __set_current_state prevents the reads
545 * following the spin_unlock to happen before the list_add in
548 set_current_state(blocking_state);
549 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
551 if (!is_vm_hugetlb_page(vma))
552 must_wait = userfaultfd_must_wait(ctx, vmf, reason);
554 must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);
555 if (is_vm_hugetlb_page(vma))
556 hugetlb_vma_unlock_read(vma);
557 release_fault_lock(vmf);
559 if (likely(must_wait && !READ_ONCE(ctx->released))) {
560 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
564 __set_current_state(TASK_RUNNING);
567 * Here we race with the list_del; list_add in
568 * userfaultfd_ctx_read(), however because we don't ever run
569 * list_del_init() to refile across the two lists, the prev
570 * and next pointers will never point to self. list_add also
571 * would never let any of the two pointers to point to
572 * self. So list_empty_careful won't risk to see both pointers
573 * pointing to self at any time during the list refile. The
574 * only case where list_del_init() is called is the full
575 * removal in the wake function and there we don't re-list_add
576 * and it's fine not to block on the spinlock. The uwq on this
577 * kernel stack can be released after the list_del_init.
579 if (!list_empty_careful(&uwq.wq.entry)) {
580 spin_lock_irq(&ctx->fault_pending_wqh.lock);
582 * No need of list_del_init(), the uwq on the stack
583 * will be freed shortly anyway.
585 list_del(&uwq.wq.entry);
586 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
590 * ctx may go away after this if the userfault pseudo fd is
593 userfaultfd_ctx_put(ctx);
599 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
600 struct userfaultfd_wait_queue *ewq)
602 struct userfaultfd_ctx *release_new_ctx;
604 if (WARN_ON_ONCE(current->flags & PF_EXITING))
608 init_waitqueue_entry(&ewq->wq, current);
609 release_new_ctx = NULL;
611 spin_lock_irq(&ctx->event_wqh.lock);
613 * After the __add_wait_queue the uwq is visible to userland
614 * through poll/read().
616 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
618 set_current_state(TASK_KILLABLE);
619 if (ewq->msg.event == 0)
621 if (READ_ONCE(ctx->released) ||
622 fatal_signal_pending(current)) {
624 * &ewq->wq may be queued in fork_event, but
625 * __remove_wait_queue ignores the head
626 * parameter. It would be a problem if it
629 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
630 if (ewq->msg.event == UFFD_EVENT_FORK) {
631 struct userfaultfd_ctx *new;
633 new = (struct userfaultfd_ctx *)
635 ewq->msg.arg.reserved.reserved1;
636 release_new_ctx = new;
641 spin_unlock_irq(&ctx->event_wqh.lock);
643 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
646 spin_lock_irq(&ctx->event_wqh.lock);
648 __set_current_state(TASK_RUNNING);
649 spin_unlock_irq(&ctx->event_wqh.lock);
651 if (release_new_ctx) {
652 struct vm_area_struct *vma;
653 struct mm_struct *mm = release_new_ctx->mm;
654 VMA_ITERATOR(vmi, mm, 0);
656 /* the various vma->vm_userfaultfd_ctx still points to it */
658 for_each_vma(vmi, vma) {
659 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
660 vma_start_write(vma);
661 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
662 userfaultfd_set_vm_flags(vma,
663 vma->vm_flags & ~__VM_UFFD_FLAGS);
666 mmap_write_unlock(mm);
668 userfaultfd_ctx_put(release_new_ctx);
672 * ctx may go away after this if the userfault pseudo fd is
676 atomic_dec(&ctx->mmap_changing);
677 VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
678 userfaultfd_ctx_put(ctx);
681 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
682 struct userfaultfd_wait_queue *ewq)
685 wake_up_locked(&ctx->event_wqh);
686 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
689 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
691 struct userfaultfd_ctx *ctx = NULL, *octx;
692 struct userfaultfd_fork_ctx *fctx;
694 octx = vma->vm_userfaultfd_ctx.ctx;
695 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
696 vma_start_write(vma);
697 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
698 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
702 list_for_each_entry(fctx, fcs, list)
703 if (fctx->orig == octx) {
709 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
713 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
719 refcount_set(&ctx->refcount, 1);
720 ctx->flags = octx->flags;
721 ctx->features = octx->features;
722 ctx->released = false;
723 atomic_set(&ctx->mmap_changing, 0);
724 ctx->mm = vma->vm_mm;
727 userfaultfd_ctx_get(octx);
728 atomic_inc(&octx->mmap_changing);
731 list_add_tail(&fctx->list, fcs);
734 vma->vm_userfaultfd_ctx.ctx = ctx;
738 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
740 struct userfaultfd_ctx *ctx = fctx->orig;
741 struct userfaultfd_wait_queue ewq;
745 ewq.msg.event = UFFD_EVENT_FORK;
746 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
748 userfaultfd_event_wait_completion(ctx, &ewq);
751 void dup_userfaultfd_complete(struct list_head *fcs)
753 struct userfaultfd_fork_ctx *fctx, *n;
755 list_for_each_entry_safe(fctx, n, fcs, list) {
757 list_del(&fctx->list);
762 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
763 struct vm_userfaultfd_ctx *vm_ctx)
765 struct userfaultfd_ctx *ctx;
767 ctx = vma->vm_userfaultfd_ctx.ctx;
772 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
774 userfaultfd_ctx_get(ctx);
775 atomic_inc(&ctx->mmap_changing);
777 /* Drop uffd context if remap feature not enabled */
778 vma_start_write(vma);
779 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
780 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
784 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
785 unsigned long from, unsigned long to,
788 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
789 struct userfaultfd_wait_queue ewq;
794 if (to & ~PAGE_MASK) {
795 userfaultfd_ctx_put(ctx);
801 ewq.msg.event = UFFD_EVENT_REMAP;
802 ewq.msg.arg.remap.from = from;
803 ewq.msg.arg.remap.to = to;
804 ewq.msg.arg.remap.len = len;
806 userfaultfd_event_wait_completion(ctx, &ewq);
809 bool userfaultfd_remove(struct vm_area_struct *vma,
810 unsigned long start, unsigned long end)
812 struct mm_struct *mm = vma->vm_mm;
813 struct userfaultfd_ctx *ctx;
814 struct userfaultfd_wait_queue ewq;
816 ctx = vma->vm_userfaultfd_ctx.ctx;
817 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
820 userfaultfd_ctx_get(ctx);
821 atomic_inc(&ctx->mmap_changing);
822 mmap_read_unlock(mm);
826 ewq.msg.event = UFFD_EVENT_REMOVE;
827 ewq.msg.arg.remove.start = start;
828 ewq.msg.arg.remove.end = end;
830 userfaultfd_event_wait_completion(ctx, &ewq);
835 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
836 unsigned long start, unsigned long end)
838 struct userfaultfd_unmap_ctx *unmap_ctx;
840 list_for_each_entry(unmap_ctx, unmaps, list)
841 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
842 unmap_ctx->end == end)
848 int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start,
849 unsigned long end, struct list_head *unmaps)
851 struct userfaultfd_unmap_ctx *unmap_ctx;
852 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
854 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
855 has_unmap_ctx(ctx, unmaps, start, end))
858 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
862 userfaultfd_ctx_get(ctx);
863 atomic_inc(&ctx->mmap_changing);
864 unmap_ctx->ctx = ctx;
865 unmap_ctx->start = start;
866 unmap_ctx->end = end;
867 list_add_tail(&unmap_ctx->list, unmaps);
872 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
874 struct userfaultfd_unmap_ctx *ctx, *n;
875 struct userfaultfd_wait_queue ewq;
877 list_for_each_entry_safe(ctx, n, uf, list) {
880 ewq.msg.event = UFFD_EVENT_UNMAP;
881 ewq.msg.arg.remove.start = ctx->start;
882 ewq.msg.arg.remove.end = ctx->end;
884 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
886 list_del(&ctx->list);
891 static int userfaultfd_release(struct inode *inode, struct file *file)
893 struct userfaultfd_ctx *ctx = file->private_data;
894 struct mm_struct *mm = ctx->mm;
895 struct vm_area_struct *vma, *prev;
896 /* len == 0 means wake all */
897 struct userfaultfd_wake_range range = { .len = 0, };
898 unsigned long new_flags;
899 VMA_ITERATOR(vmi, mm, 0);
901 WRITE_ONCE(ctx->released, true);
903 if (!mmget_not_zero(mm))
907 * Flush page faults out of all CPUs. NOTE: all page faults
908 * must be retried without returning VM_FAULT_SIGBUS if
909 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
910 * changes while handle_userfault released the mmap_lock. So
911 * it's critical that released is set to true (above), before
912 * taking the mmap_lock for writing.
916 for_each_vma(vmi, vma) {
918 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
919 !!(vma->vm_flags & __VM_UFFD_FLAGS));
920 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
924 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
925 prev = vma_merge(&vmi, mm, prev, vma->vm_start, vma->vm_end,
926 new_flags, vma->anon_vma,
927 vma->vm_file, vma->vm_pgoff,
929 NULL_VM_UFFD_CTX, anon_vma_name(vma));
936 vma_start_write(vma);
937 userfaultfd_set_vm_flags(vma, new_flags);
938 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
940 mmap_write_unlock(mm);
944 * After no new page faults can wait on this fault_*wqh, flush
945 * the last page faults that may have been already waiting on
948 spin_lock_irq(&ctx->fault_pending_wqh.lock);
949 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
950 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
951 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
953 /* Flush pending events that may still wait on event_wqh */
954 wake_up_all(&ctx->event_wqh);
956 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
957 userfaultfd_ctx_put(ctx);
961 /* fault_pending_wqh.lock must be hold by the caller */
962 static inline struct userfaultfd_wait_queue *find_userfault_in(
963 wait_queue_head_t *wqh)
965 wait_queue_entry_t *wq;
966 struct userfaultfd_wait_queue *uwq;
968 lockdep_assert_held(&wqh->lock);
971 if (!waitqueue_active(wqh))
973 /* walk in reverse to provide FIFO behavior to read userfaults */
974 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
975 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
980 static inline struct userfaultfd_wait_queue *find_userfault(
981 struct userfaultfd_ctx *ctx)
983 return find_userfault_in(&ctx->fault_pending_wqh);
986 static inline struct userfaultfd_wait_queue *find_userfault_evt(
987 struct userfaultfd_ctx *ctx)
989 return find_userfault_in(&ctx->event_wqh);
992 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
994 struct userfaultfd_ctx *ctx = file->private_data;
997 poll_wait(file, &ctx->fd_wqh, wait);
999 if (!userfaultfd_is_initialized(ctx))
1003 * poll() never guarantees that read won't block.
1004 * userfaults can be waken before they're read().
1006 if (unlikely(!(file->f_flags & O_NONBLOCK)))
1009 * lockless access to see if there are pending faults
1010 * __pollwait last action is the add_wait_queue but
1011 * the spin_unlock would allow the waitqueue_active to
1012 * pass above the actual list_add inside
1013 * add_wait_queue critical section. So use a full
1014 * memory barrier to serialize the list_add write of
1015 * add_wait_queue() with the waitqueue_active read
1020 if (waitqueue_active(&ctx->fault_pending_wqh))
1022 else if (waitqueue_active(&ctx->event_wqh))
1028 static const struct file_operations userfaultfd_fops;
1030 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
1031 struct inode *inode,
1032 struct uffd_msg *msg)
1036 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
1037 O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
1041 msg->arg.reserved.reserved1 = 0;
1042 msg->arg.fork.ufd = fd;
1046 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1047 struct uffd_msg *msg, struct inode *inode)
1050 DECLARE_WAITQUEUE(wait, current);
1051 struct userfaultfd_wait_queue *uwq;
1053 * Handling fork event requires sleeping operations, so
1054 * we drop the event_wqh lock, then do these ops, then
1055 * lock it back and wake up the waiter. While the lock is
1056 * dropped the ewq may go away so we keep track of it
1059 LIST_HEAD(fork_event);
1060 struct userfaultfd_ctx *fork_nctx = NULL;
1062 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1063 spin_lock_irq(&ctx->fd_wqh.lock);
1064 __add_wait_queue(&ctx->fd_wqh, &wait);
1066 set_current_state(TASK_INTERRUPTIBLE);
1067 spin_lock(&ctx->fault_pending_wqh.lock);
1068 uwq = find_userfault(ctx);
1071 * Use a seqcount to repeat the lockless check
1072 * in wake_userfault() to avoid missing
1073 * wakeups because during the refile both
1074 * waitqueue could become empty if this is the
1077 write_seqcount_begin(&ctx->refile_seq);
1080 * The fault_pending_wqh.lock prevents the uwq
1081 * to disappear from under us.
1083 * Refile this userfault from
1084 * fault_pending_wqh to fault_wqh, it's not
1085 * pending anymore after we read it.
1087 * Use list_del() by hand (as
1088 * userfaultfd_wake_function also uses
1089 * list_del_init() by hand) to be sure nobody
1090 * changes __remove_wait_queue() to use
1091 * list_del_init() in turn breaking the
1092 * !list_empty_careful() check in
1093 * handle_userfault(). The uwq->wq.head list
1094 * must never be empty at any time during the
1095 * refile, or the waitqueue could disappear
1096 * from under us. The "wait_queue_head_t"
1097 * parameter of __remove_wait_queue() is unused
1100 list_del(&uwq->wq.entry);
1101 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1103 write_seqcount_end(&ctx->refile_seq);
1105 /* careful to always initialize msg if ret == 0 */
1107 spin_unlock(&ctx->fault_pending_wqh.lock);
1111 spin_unlock(&ctx->fault_pending_wqh.lock);
1113 spin_lock(&ctx->event_wqh.lock);
1114 uwq = find_userfault_evt(ctx);
1118 if (uwq->msg.event == UFFD_EVENT_FORK) {
1119 fork_nctx = (struct userfaultfd_ctx *)
1121 uwq->msg.arg.reserved.reserved1;
1122 list_move(&uwq->wq.entry, &fork_event);
1124 * fork_nctx can be freed as soon as
1125 * we drop the lock, unless we take a
1128 userfaultfd_ctx_get(fork_nctx);
1129 spin_unlock(&ctx->event_wqh.lock);
1134 userfaultfd_event_complete(ctx, uwq);
1135 spin_unlock(&ctx->event_wqh.lock);
1139 spin_unlock(&ctx->event_wqh.lock);
1141 if (signal_pending(current)) {
1149 spin_unlock_irq(&ctx->fd_wqh.lock);
1151 spin_lock_irq(&ctx->fd_wqh.lock);
1153 __remove_wait_queue(&ctx->fd_wqh, &wait);
1154 __set_current_state(TASK_RUNNING);
1155 spin_unlock_irq(&ctx->fd_wqh.lock);
1157 if (!ret && msg->event == UFFD_EVENT_FORK) {
1158 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1159 spin_lock_irq(&ctx->event_wqh.lock);
1160 if (!list_empty(&fork_event)) {
1162 * The fork thread didn't abort, so we can
1163 * drop the temporary refcount.
1165 userfaultfd_ctx_put(fork_nctx);
1167 uwq = list_first_entry(&fork_event,
1171 * If fork_event list wasn't empty and in turn
1172 * the event wasn't already released by fork
1173 * (the event is allocated on fork kernel
1174 * stack), put the event back to its place in
1175 * the event_wq. fork_event head will be freed
1176 * as soon as we return so the event cannot
1177 * stay queued there no matter the current
1180 list_del(&uwq->wq.entry);
1181 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1184 * Leave the event in the waitqueue and report
1185 * error to userland if we failed to resolve
1186 * the userfault fork.
1189 userfaultfd_event_complete(ctx, uwq);
1192 * Here the fork thread aborted and the
1193 * refcount from the fork thread on fork_nctx
1194 * has already been released. We still hold
1195 * the reference we took before releasing the
1196 * lock above. If resolve_userfault_fork
1197 * failed we've to drop it because the
1198 * fork_nctx has to be freed in such case. If
1199 * it succeeded we'll hold it because the new
1200 * uffd references it.
1203 userfaultfd_ctx_put(fork_nctx);
1205 spin_unlock_irq(&ctx->event_wqh.lock);
1211 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1212 size_t count, loff_t *ppos)
1214 struct userfaultfd_ctx *ctx = file->private_data;
1215 ssize_t _ret, ret = 0;
1216 struct uffd_msg msg;
1217 int no_wait = file->f_flags & O_NONBLOCK;
1218 struct inode *inode = file_inode(file);
1220 if (!userfaultfd_is_initialized(ctx))
1224 if (count < sizeof(msg))
1225 return ret ? ret : -EINVAL;
1226 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1228 return ret ? ret : _ret;
1229 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1230 return ret ? ret : -EFAULT;
1233 count -= sizeof(msg);
1235 * Allow to read more than one fault at time but only
1236 * block if waiting for the very first one.
1238 no_wait = O_NONBLOCK;
1242 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1243 struct userfaultfd_wake_range *range)
1245 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1246 /* wake all in the range and autoremove */
1247 if (waitqueue_active(&ctx->fault_pending_wqh))
1248 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1250 if (waitqueue_active(&ctx->fault_wqh))
1251 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1252 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1255 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1256 struct userfaultfd_wake_range *range)
1262 * To be sure waitqueue_active() is not reordered by the CPU
1263 * before the pagetable update, use an explicit SMP memory
1264 * barrier here. PT lock release or mmap_read_unlock(mm) still
1265 * have release semantics that can allow the
1266 * waitqueue_active() to be reordered before the pte update.
1271 * Use waitqueue_active because it's very frequent to
1272 * change the address space atomically even if there are no
1273 * userfaults yet. So we take the spinlock only when we're
1274 * sure we've userfaults to wake.
1277 seq = read_seqcount_begin(&ctx->refile_seq);
1278 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1279 waitqueue_active(&ctx->fault_wqh);
1281 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1283 __wake_userfault(ctx, range);
1286 static __always_inline int validate_unaligned_range(
1287 struct mm_struct *mm, __u64 start, __u64 len)
1289 __u64 task_size = mm->task_size;
1291 if (len & ~PAGE_MASK)
1295 if (start < mmap_min_addr)
1297 if (start >= task_size)
1299 if (len > task_size - start)
1301 if (start + len <= start)
1306 static __always_inline int validate_range(struct mm_struct *mm,
1307 __u64 start, __u64 len)
1309 if (start & ~PAGE_MASK)
1312 return validate_unaligned_range(mm, start, len);
1315 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1318 struct mm_struct *mm = ctx->mm;
1319 struct vm_area_struct *vma, *prev, *cur;
1321 struct uffdio_register uffdio_register;
1322 struct uffdio_register __user *user_uffdio_register;
1323 unsigned long vm_flags, new_flags;
1326 unsigned long start, end, vma_end;
1327 struct vma_iterator vmi;
1330 user_uffdio_register = (struct uffdio_register __user *) arg;
1333 if (copy_from_user(&uffdio_register, user_uffdio_register,
1334 sizeof(uffdio_register)-sizeof(__u64)))
1338 if (!uffdio_register.mode)
1340 if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1343 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1344 vm_flags |= VM_UFFD_MISSING;
1345 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1346 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1349 vm_flags |= VM_UFFD_WP;
1351 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1352 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1355 vm_flags |= VM_UFFD_MINOR;
1358 ret = validate_range(mm, uffdio_register.range.start,
1359 uffdio_register.range.len);
1363 start = uffdio_register.range.start;
1364 end = start + uffdio_register.range.len;
1367 if (!mmget_not_zero(mm))
1371 mmap_write_lock(mm);
1372 vma_iter_init(&vmi, mm, start);
1373 vma = vma_find(&vmi, end);
1378 * If the first vma contains huge pages, make sure start address
1379 * is aligned to huge page size.
1381 if (is_vm_hugetlb_page(vma)) {
1382 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1384 if (start & (vma_hpagesize - 1))
1389 * Search for not compatible vmas.
1392 basic_ioctls = false;
1397 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1398 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1400 /* check not compatible vmas */
1402 if (!vma_can_userfault(cur, vm_flags))
1406 * UFFDIO_COPY will fill file holes even without
1407 * PROT_WRITE. This check enforces that if this is a
1408 * MAP_SHARED, the process has write permission to the backing
1409 * file. If VM_MAYWRITE is set it also enforces that on a
1410 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1411 * F_WRITE_SEAL can be taken until the vma is destroyed.
1414 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1418 * If this vma contains ending address, and huge pages
1421 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1422 end > cur->vm_start) {
1423 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1427 if (end & (vma_hpagesize - 1))
1430 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1434 * Check that this vma isn't already owned by a
1435 * different userfaultfd. We can't allow more than one
1436 * userfaultfd to own a single vma simultaneously or we
1437 * wouldn't know which one to deliver the userfaults to.
1440 if (cur->vm_userfaultfd_ctx.ctx &&
1441 cur->vm_userfaultfd_ctx.ctx != ctx)
1445 * Note vmas containing huge pages
1447 if (is_vm_hugetlb_page(cur))
1448 basic_ioctls = true;
1451 } for_each_vma_range(vmi, cur, end);
1454 vma_iter_set(&vmi, start);
1455 prev = vma_prev(&vmi);
1456 if (vma->vm_start < start)
1460 for_each_vma_range(vmi, vma, end) {
1463 BUG_ON(!vma_can_userfault(vma, vm_flags));
1464 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1465 vma->vm_userfaultfd_ctx.ctx != ctx);
1466 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1469 * Nothing to do: this vma is already registered into this
1470 * userfaultfd and with the right tracking mode too.
1472 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1473 (vma->vm_flags & vm_flags) == vm_flags)
1476 if (vma->vm_start > start)
1477 start = vma->vm_start;
1478 vma_end = min(end, vma->vm_end);
1480 new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1481 pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
1482 prev = vma_merge(&vmi, mm, prev, start, vma_end, new_flags,
1483 vma->anon_vma, vma->vm_file, pgoff,
1485 ((struct vm_userfaultfd_ctx){ ctx }),
1486 anon_vma_name(vma));
1488 /* vma_merge() invalidated the mas */
1492 if (vma->vm_start < start) {
1493 ret = split_vma(&vmi, vma, start, 1);
1497 if (vma->vm_end > end) {
1498 ret = split_vma(&vmi, vma, end, 0);
1504 * In the vma_merge() successful mprotect-like case 8:
1505 * the next vma was merged into the current one and
1506 * the current one has not been updated yet.
1508 vma_start_write(vma);
1509 userfaultfd_set_vm_flags(vma, new_flags);
1510 vma->vm_userfaultfd_ctx.ctx = ctx;
1512 if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1513 hugetlb_unshare_all_pmds(vma);
1517 start = vma->vm_end;
1521 mmap_write_unlock(mm);
1526 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1527 UFFD_API_RANGE_IOCTLS;
1530 * Declare the WP ioctl only if the WP mode is
1531 * specified and all checks passed with the range
1533 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1534 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1536 /* CONTINUE ioctl is only supported for MINOR ranges. */
1537 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1538 ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1541 * Now that we scanned all vmas we can already tell
1542 * userland which ioctls methods are guaranteed to
1543 * succeed on this range.
1545 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1552 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1555 struct mm_struct *mm = ctx->mm;
1556 struct vm_area_struct *vma, *prev, *cur;
1558 struct uffdio_range uffdio_unregister;
1559 unsigned long new_flags;
1561 unsigned long start, end, vma_end;
1562 const void __user *buf = (void __user *)arg;
1563 struct vma_iterator vmi;
1567 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1570 ret = validate_range(mm, uffdio_unregister.start,
1571 uffdio_unregister.len);
1575 start = uffdio_unregister.start;
1576 end = start + uffdio_unregister.len;
1579 if (!mmget_not_zero(mm))
1582 mmap_write_lock(mm);
1584 vma_iter_init(&vmi, mm, start);
1585 vma = vma_find(&vmi, end);
1590 * If the first vma contains huge pages, make sure start address
1591 * is aligned to huge page size.
1593 if (is_vm_hugetlb_page(vma)) {
1594 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1596 if (start & (vma_hpagesize - 1))
1601 * Search for not compatible vmas.
1608 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1609 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1612 * Check not compatible vmas, not strictly required
1613 * here as not compatible vmas cannot have an
1614 * userfaultfd_ctx registered on them, but this
1615 * provides for more strict behavior to notice
1616 * unregistration errors.
1618 if (!vma_can_userfault(cur, cur->vm_flags))
1622 } for_each_vma_range(vmi, cur, end);
1625 vma_iter_set(&vmi, start);
1626 prev = vma_prev(&vmi);
1627 if (vma->vm_start < start)
1631 for_each_vma_range(vmi, vma, end) {
1634 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1637 * Nothing to do: this vma is already registered into this
1638 * userfaultfd and with the right tracking mode too.
1640 if (!vma->vm_userfaultfd_ctx.ctx)
1643 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1645 if (vma->vm_start > start)
1646 start = vma->vm_start;
1647 vma_end = min(end, vma->vm_end);
1649 if (userfaultfd_missing(vma)) {
1651 * Wake any concurrent pending userfault while
1652 * we unregister, so they will not hang
1653 * permanently and it avoids userland to call
1654 * UFFDIO_WAKE explicitly.
1656 struct userfaultfd_wake_range range;
1657 range.start = start;
1658 range.len = vma_end - start;
1659 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1662 /* Reset ptes for the whole vma range if wr-protected */
1663 if (userfaultfd_wp(vma))
1664 uffd_wp_range(vma, start, vma_end - start, false);
1666 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1667 pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
1668 prev = vma_merge(&vmi, mm, prev, start, vma_end, new_flags,
1669 vma->anon_vma, vma->vm_file, pgoff,
1671 NULL_VM_UFFD_CTX, anon_vma_name(vma));
1676 if (vma->vm_start < start) {
1677 ret = split_vma(&vmi, vma, start, 1);
1681 if (vma->vm_end > end) {
1682 ret = split_vma(&vmi, vma, end, 0);
1688 * In the vma_merge() successful mprotect-like case 8:
1689 * the next vma was merged into the current one and
1690 * the current one has not been updated yet.
1692 vma_start_write(vma);
1693 userfaultfd_set_vm_flags(vma, new_flags);
1694 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1698 start = vma->vm_end;
1702 mmap_write_unlock(mm);
1709 * userfaultfd_wake may be used in combination with the
1710 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1712 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1716 struct uffdio_range uffdio_wake;
1717 struct userfaultfd_wake_range range;
1718 const void __user *buf = (void __user *)arg;
1721 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1724 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1728 range.start = uffdio_wake.start;
1729 range.len = uffdio_wake.len;
1732 * len == 0 means wake all and we don't want to wake all here,
1733 * so check it again to be sure.
1735 VM_BUG_ON(!range.len);
1737 wake_userfault(ctx, &range);
1744 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1748 struct uffdio_copy uffdio_copy;
1749 struct uffdio_copy __user *user_uffdio_copy;
1750 struct userfaultfd_wake_range range;
1751 uffd_flags_t flags = 0;
1753 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1756 if (atomic_read(&ctx->mmap_changing))
1760 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1761 /* don't copy "copy" last field */
1762 sizeof(uffdio_copy)-sizeof(__s64)))
1765 ret = validate_unaligned_range(ctx->mm, uffdio_copy.src,
1769 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1774 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1776 if (uffdio_copy.mode & UFFDIO_COPY_MODE_WP)
1777 flags |= MFILL_ATOMIC_WP;
1778 if (mmget_not_zero(ctx->mm)) {
1779 ret = mfill_atomic_copy(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1780 uffdio_copy.len, &ctx->mmap_changing,
1786 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1791 /* len == 0 would wake all */
1793 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1794 range.start = uffdio_copy.dst;
1795 wake_userfault(ctx, &range);
1797 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1802 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1806 struct uffdio_zeropage uffdio_zeropage;
1807 struct uffdio_zeropage __user *user_uffdio_zeropage;
1808 struct userfaultfd_wake_range range;
1810 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1813 if (atomic_read(&ctx->mmap_changing))
1817 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1818 /* don't copy "zeropage" last field */
1819 sizeof(uffdio_zeropage)-sizeof(__s64)))
1822 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1823 uffdio_zeropage.range.len);
1827 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1830 if (mmget_not_zero(ctx->mm)) {
1831 ret = mfill_atomic_zeropage(ctx->mm, uffdio_zeropage.range.start,
1832 uffdio_zeropage.range.len,
1833 &ctx->mmap_changing);
1838 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1842 /* len == 0 would wake all */
1845 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1846 range.start = uffdio_zeropage.range.start;
1847 wake_userfault(ctx, &range);
1849 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1854 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1858 struct uffdio_writeprotect uffdio_wp;
1859 struct uffdio_writeprotect __user *user_uffdio_wp;
1860 struct userfaultfd_wake_range range;
1861 bool mode_wp, mode_dontwake;
1863 if (atomic_read(&ctx->mmap_changing))
1866 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1868 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1869 sizeof(struct uffdio_writeprotect)))
1872 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1873 uffdio_wp.range.len);
1877 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1878 UFFDIO_WRITEPROTECT_MODE_WP))
1881 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1882 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1884 if (mode_wp && mode_dontwake)
1887 if (mmget_not_zero(ctx->mm)) {
1888 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1889 uffdio_wp.range.len, mode_wp,
1890 &ctx->mmap_changing);
1899 if (!mode_wp && !mode_dontwake) {
1900 range.start = uffdio_wp.range.start;
1901 range.len = uffdio_wp.range.len;
1902 wake_userfault(ctx, &range);
1907 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1910 struct uffdio_continue uffdio_continue;
1911 struct uffdio_continue __user *user_uffdio_continue;
1912 struct userfaultfd_wake_range range;
1913 uffd_flags_t flags = 0;
1915 user_uffdio_continue = (struct uffdio_continue __user *)arg;
1918 if (atomic_read(&ctx->mmap_changing))
1922 if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1923 /* don't copy the output fields */
1924 sizeof(uffdio_continue) - (sizeof(__s64))))
1927 ret = validate_range(ctx->mm, uffdio_continue.range.start,
1928 uffdio_continue.range.len);
1933 if (uffdio_continue.mode & ~(UFFDIO_CONTINUE_MODE_DONTWAKE |
1934 UFFDIO_CONTINUE_MODE_WP))
1936 if (uffdio_continue.mode & UFFDIO_CONTINUE_MODE_WP)
1937 flags |= MFILL_ATOMIC_WP;
1939 if (mmget_not_zero(ctx->mm)) {
1940 ret = mfill_atomic_continue(ctx->mm, uffdio_continue.range.start,
1941 uffdio_continue.range.len,
1942 &ctx->mmap_changing, flags);
1948 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1953 /* len == 0 would wake all */
1956 if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1957 range.start = uffdio_continue.range.start;
1958 wake_userfault(ctx, &range);
1960 ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1966 static inline int userfaultfd_poison(struct userfaultfd_ctx *ctx, unsigned long arg)
1969 struct uffdio_poison uffdio_poison;
1970 struct uffdio_poison __user *user_uffdio_poison;
1971 struct userfaultfd_wake_range range;
1973 user_uffdio_poison = (struct uffdio_poison __user *)arg;
1976 if (atomic_read(&ctx->mmap_changing))
1980 if (copy_from_user(&uffdio_poison, user_uffdio_poison,
1981 /* don't copy the output fields */
1982 sizeof(uffdio_poison) - (sizeof(__s64))))
1985 ret = validate_range(ctx->mm, uffdio_poison.range.start,
1986 uffdio_poison.range.len);
1991 if (uffdio_poison.mode & ~UFFDIO_POISON_MODE_DONTWAKE)
1994 if (mmget_not_zero(ctx->mm)) {
1995 ret = mfill_atomic_poison(ctx->mm, uffdio_poison.range.start,
1996 uffdio_poison.range.len,
1997 &ctx->mmap_changing, 0);
2003 if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
2008 /* len == 0 would wake all */
2011 if (!(uffdio_poison.mode & UFFDIO_POISON_MODE_DONTWAKE)) {
2012 range.start = uffdio_poison.range.start;
2013 wake_userfault(ctx, &range);
2015 ret = range.len == uffdio_poison.range.len ? 0 : -EAGAIN;
2021 static inline unsigned int uffd_ctx_features(__u64 user_features)
2024 * For the current set of features the bits just coincide. Set
2025 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
2027 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
2031 * userland asks for a certain API version and we return which bits
2032 * and ioctl commands are implemented in this kernel for such API
2033 * version or -EINVAL if unknown.
2035 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
2038 struct uffdio_api uffdio_api;
2039 void __user *buf = (void __user *)arg;
2040 unsigned int ctx_features;
2045 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
2047 features = uffdio_api.features;
2049 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
2052 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
2054 /* report all available features and ioctls to userland */
2055 uffdio_api.features = UFFD_API_FEATURES;
2056 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
2057 uffdio_api.features &=
2058 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
2060 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
2061 uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
2063 #ifndef CONFIG_PTE_MARKER_UFFD_WP
2064 uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
2065 uffdio_api.features &= ~UFFD_FEATURE_WP_UNPOPULATED;
2067 uffdio_api.ioctls = UFFD_API_IOCTLS;
2069 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2072 /* only enable the requested features for this uffd context */
2073 ctx_features = uffd_ctx_features(features);
2075 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
2082 memset(&uffdio_api, 0, sizeof(uffdio_api));
2083 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2088 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2092 struct userfaultfd_ctx *ctx = file->private_data;
2094 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2099 ret = userfaultfd_api(ctx, arg);
2101 case UFFDIO_REGISTER:
2102 ret = userfaultfd_register(ctx, arg);
2104 case UFFDIO_UNREGISTER:
2105 ret = userfaultfd_unregister(ctx, arg);
2108 ret = userfaultfd_wake(ctx, arg);
2111 ret = userfaultfd_copy(ctx, arg);
2113 case UFFDIO_ZEROPAGE:
2114 ret = userfaultfd_zeropage(ctx, arg);
2116 case UFFDIO_WRITEPROTECT:
2117 ret = userfaultfd_writeprotect(ctx, arg);
2119 case UFFDIO_CONTINUE:
2120 ret = userfaultfd_continue(ctx, arg);
2123 ret = userfaultfd_poison(ctx, arg);
2129 #ifdef CONFIG_PROC_FS
2130 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2132 struct userfaultfd_ctx *ctx = f->private_data;
2133 wait_queue_entry_t *wq;
2134 unsigned long pending = 0, total = 0;
2136 spin_lock_irq(&ctx->fault_pending_wqh.lock);
2137 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2141 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2144 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2147 * If more protocols will be added, there will be all shown
2148 * separated by a space. Like this:
2149 * protocols: aa:... bb:...
2151 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2152 pending, total, UFFD_API, ctx->features,
2153 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2157 static const struct file_operations userfaultfd_fops = {
2158 #ifdef CONFIG_PROC_FS
2159 .show_fdinfo = userfaultfd_show_fdinfo,
2161 .release = userfaultfd_release,
2162 .poll = userfaultfd_poll,
2163 .read = userfaultfd_read,
2164 .unlocked_ioctl = userfaultfd_ioctl,
2165 .compat_ioctl = compat_ptr_ioctl,
2166 .llseek = noop_llseek,
2169 static void init_once_userfaultfd_ctx(void *mem)
2171 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2173 init_waitqueue_head(&ctx->fault_pending_wqh);
2174 init_waitqueue_head(&ctx->fault_wqh);
2175 init_waitqueue_head(&ctx->event_wqh);
2176 init_waitqueue_head(&ctx->fd_wqh);
2177 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2180 static int new_userfaultfd(int flags)
2182 struct userfaultfd_ctx *ctx;
2185 BUG_ON(!current->mm);
2187 /* Check the UFFD_* constants for consistency. */
2188 BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2189 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2190 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2192 if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2195 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2199 refcount_set(&ctx->refcount, 1);
2202 ctx->released = false;
2203 atomic_set(&ctx->mmap_changing, 0);
2204 ctx->mm = current->mm;
2205 /* prevent the mm struct to be freed */
2208 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2209 O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2212 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2217 static inline bool userfaultfd_syscall_allowed(int flags)
2219 /* Userspace-only page faults are always allowed */
2220 if (flags & UFFD_USER_MODE_ONLY)
2224 * The user is requesting a userfaultfd which can handle kernel faults.
2225 * Privileged users are always allowed to do this.
2227 if (capable(CAP_SYS_PTRACE))
2230 /* Otherwise, access to kernel fault handling is sysctl controlled. */
2231 return sysctl_unprivileged_userfaultfd;
2234 SYSCALL_DEFINE1(userfaultfd, int, flags)
2236 if (!userfaultfd_syscall_allowed(flags))
2239 return new_userfaultfd(flags);
2242 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2244 if (cmd != USERFAULTFD_IOC_NEW)
2247 return new_userfaultfd(flags);
2250 static const struct file_operations userfaultfd_dev_fops = {
2251 .unlocked_ioctl = userfaultfd_dev_ioctl,
2252 .compat_ioctl = userfaultfd_dev_ioctl,
2253 .owner = THIS_MODULE,
2254 .llseek = noop_llseek,
2257 static struct miscdevice userfaultfd_misc = {
2258 .minor = MISC_DYNAMIC_MINOR,
2259 .name = "userfaultfd",
2260 .fops = &userfaultfd_dev_fops
2263 static int __init userfaultfd_init(void)
2267 ret = misc_register(&userfaultfd_misc);
2271 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2272 sizeof(struct userfaultfd_ctx),
2274 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2275 init_once_userfaultfd_ctx);
2276 #ifdef CONFIG_SYSCTL
2277 register_sysctl_init("vm", vm_userfaultfd_table);
2281 __initcall(userfaultfd_init);