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 int sysctl_unprivileged_userfaultfd __read_mostly;
37 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
40 * Start with fault_pending_wqh and fault_wqh so they're more likely
41 * to be in the same cacheline.
45 * fault_pending_wqh.lock
49 * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
50 * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
51 * also taken in IRQ context.
53 struct userfaultfd_ctx {
54 /* waitqueue head for the pending (i.e. not read) userfaults */
55 wait_queue_head_t fault_pending_wqh;
56 /* waitqueue head for the userfaults */
57 wait_queue_head_t fault_wqh;
58 /* waitqueue head for the pseudo fd to wakeup poll/read */
59 wait_queue_head_t fd_wqh;
60 /* waitqueue head for events */
61 wait_queue_head_t event_wqh;
62 /* a refile sequence protected by fault_pending_wqh lock */
63 seqcount_spinlock_t refile_seq;
64 /* pseudo fd refcounting */
66 /* userfaultfd syscall flags */
68 /* features requested from the userspace */
69 unsigned int features;
72 /* memory mappings are changing because of non-cooperative event */
73 atomic_t mmap_changing;
74 /* mm with one ore more vmas attached to this userfaultfd_ctx */
78 struct userfaultfd_fork_ctx {
79 struct userfaultfd_ctx *orig;
80 struct userfaultfd_ctx *new;
81 struct list_head list;
84 struct userfaultfd_unmap_ctx {
85 struct userfaultfd_ctx *ctx;
88 struct list_head list;
91 struct userfaultfd_wait_queue {
93 wait_queue_entry_t wq;
94 struct userfaultfd_ctx *ctx;
98 struct userfaultfd_wake_range {
103 /* internal indication that UFFD_API ioctl was successfully executed */
104 #define UFFD_FEATURE_INITIALIZED (1u << 31)
106 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
108 return ctx->features & UFFD_FEATURE_INITIALIZED;
111 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
114 const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
116 vm_flags_reset(vma, flags);
118 * For shared mappings, we want to enable writenotify while
119 * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
120 * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
122 if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
123 vma_set_page_prot(vma);
126 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
127 int wake_flags, void *key)
129 struct userfaultfd_wake_range *range = key;
131 struct userfaultfd_wait_queue *uwq;
132 unsigned long start, len;
134 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
136 /* len == 0 means wake all */
137 start = range->start;
139 if (len && (start > uwq->msg.arg.pagefault.address ||
140 start + len <= uwq->msg.arg.pagefault.address))
142 WRITE_ONCE(uwq->waken, true);
144 * The Program-Order guarantees provided by the scheduler
145 * ensure uwq->waken is visible before the task is woken.
147 ret = wake_up_state(wq->private, mode);
150 * Wake only once, autoremove behavior.
152 * After the effect of list_del_init is visible to the other
153 * CPUs, the waitqueue may disappear from under us, see the
154 * !list_empty_careful() in handle_userfault().
156 * try_to_wake_up() has an implicit smp_mb(), and the
157 * wq->private is read before calling the extern function
158 * "wake_up_state" (which in turns calls try_to_wake_up).
160 list_del_init(&wq->entry);
167 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
169 * @ctx: [in] Pointer to the userfaultfd context.
171 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
173 refcount_inc(&ctx->refcount);
177 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
179 * @ctx: [in] Pointer to userfaultfd context.
181 * The userfaultfd context reference must have been previously acquired either
182 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
184 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
186 if (refcount_dec_and_test(&ctx->refcount)) {
187 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
188 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
189 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
190 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
191 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
192 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
193 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
194 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
196 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
200 static inline void msg_init(struct uffd_msg *msg)
202 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
204 * Must use memset to zero out the paddings or kernel data is
205 * leaked to userland.
207 memset(msg, 0, sizeof(struct uffd_msg));
210 static inline struct uffd_msg userfault_msg(unsigned long address,
211 unsigned long real_address,
213 unsigned long reason,
214 unsigned int features)
219 msg.event = UFFD_EVENT_PAGEFAULT;
221 msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
222 real_address : address;
225 * These flags indicate why the userfault occurred:
226 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
227 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
228 * - Neither of these flags being set indicates a MISSING fault.
230 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
231 * fault. Otherwise, it was a read fault.
233 if (flags & FAULT_FLAG_WRITE)
234 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
235 if (reason & VM_UFFD_WP)
236 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
237 if (reason & VM_UFFD_MINOR)
238 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
239 if (features & UFFD_FEATURE_THREAD_ID)
240 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
244 #ifdef CONFIG_HUGETLB_PAGE
246 * Same functionality as userfaultfd_must_wait below with modifications for
249 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
250 struct vm_area_struct *vma,
251 unsigned long address,
253 unsigned long reason)
258 mmap_assert_locked(ctx->mm);
260 ptep = hugetlb_walk(vma, address, vma_mmu_pagesize(vma));
265 pte = huge_ptep_get(ptep);
268 * Lockless access: we're in a wait_event so it's ok if it
269 * changes under us. PTE markers should be handled the same as none
272 if (huge_pte_none_mostly(pte))
274 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
280 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
281 struct vm_area_struct *vma,
282 unsigned long address,
284 unsigned long reason)
286 return false; /* should never get here */
288 #endif /* CONFIG_HUGETLB_PAGE */
291 * Verify the pagetables are still not ok after having reigstered into
292 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
293 * userfault that has already been resolved, if userfaultfd_read and
294 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
297 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
298 unsigned long address,
300 unsigned long reason)
302 struct mm_struct *mm = ctx->mm;
310 mmap_assert_locked(mm);
312 pgd = pgd_offset(mm, address);
313 if (!pgd_present(*pgd))
315 p4d = p4d_offset(pgd, address);
316 if (!p4d_present(*p4d))
318 pud = pud_offset(p4d, address);
319 if (!pud_present(*pud))
321 pmd = pmd_offset(pud, address);
323 * READ_ONCE must function as a barrier with narrower scope
324 * and it must be equivalent to:
325 * _pmd = *pmd; barrier();
327 * This is to deal with the instability (as in
328 * pmd_trans_unstable) of the pmd.
330 _pmd = READ_ONCE(*pmd);
335 if (!pmd_present(_pmd))
338 if (pmd_trans_huge(_pmd)) {
339 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
345 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
346 * and use the standard pte_offset_map() instead of parsing _pmd.
348 pte = pte_offset_map(pmd, address);
350 * Lockless access: we're in a wait_event so it's ok if it
351 * changes under us. PTE markers should be handled the same as none
354 if (pte_none_mostly(*pte))
356 if (!pte_write(*pte) && (reason & VM_UFFD_WP))
364 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
366 if (flags & FAULT_FLAG_INTERRUPTIBLE)
367 return TASK_INTERRUPTIBLE;
369 if (flags & FAULT_FLAG_KILLABLE)
370 return TASK_KILLABLE;
372 return TASK_UNINTERRUPTIBLE;
376 * The locking rules involved in returning VM_FAULT_RETRY depending on
377 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
378 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
379 * recommendation in __lock_page_or_retry is not an understatement.
381 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
382 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
385 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
386 * set, VM_FAULT_RETRY can still be returned if and only if there are
387 * fatal_signal_pending()s, and the mmap_lock must be released before
390 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
392 struct vm_area_struct *vma = vmf->vma;
393 struct mm_struct *mm = vma->vm_mm;
394 struct userfaultfd_ctx *ctx;
395 struct userfaultfd_wait_queue uwq;
396 vm_fault_t ret = VM_FAULT_SIGBUS;
398 unsigned int blocking_state;
401 * We don't do userfault handling for the final child pid update.
403 * We also don't do userfault handling during
404 * coredumping. hugetlbfs has the special
405 * follow_hugetlb_page() to skip missing pages in the
406 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
407 * the no_page_table() helper in follow_page_mask(), but the
408 * shmem_vm_ops->fault method is invoked even during
409 * coredumping without mmap_lock and it ends up here.
411 if (current->flags & (PF_EXITING|PF_DUMPCORE))
415 * Coredumping runs without mmap_lock so we can only check that
416 * the mmap_lock is held, if PF_DUMPCORE was not set.
418 mmap_assert_locked(mm);
420 ctx = vma->vm_userfaultfd_ctx.ctx;
424 BUG_ON(ctx->mm != mm);
426 /* Any unrecognized flag is a bug. */
427 VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
428 /* 0 or > 1 flags set is a bug; we expect exactly 1. */
429 VM_BUG_ON(!reason || (reason & (reason - 1)));
431 if (ctx->features & UFFD_FEATURE_SIGBUS)
433 if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
437 * If it's already released don't get it. This avoids to loop
438 * in __get_user_pages if userfaultfd_release waits on the
439 * caller of handle_userfault to release the mmap_lock.
441 if (unlikely(READ_ONCE(ctx->released))) {
443 * Don't return VM_FAULT_SIGBUS in this case, so a non
444 * cooperative manager can close the uffd after the
445 * last UFFDIO_COPY, without risking to trigger an
446 * involuntary SIGBUS if the process was starting the
447 * userfaultfd while the userfaultfd was still armed
448 * (but after the last UFFDIO_COPY). If the uffd
449 * wasn't already closed when the userfault reached
450 * this point, that would normally be solved by
451 * userfaultfd_must_wait returning 'false'.
453 * If we were to return VM_FAULT_SIGBUS here, the non
454 * cooperative manager would be instead forced to
455 * always call UFFDIO_UNREGISTER before it can safely
458 ret = VM_FAULT_NOPAGE;
463 * Check that we can return VM_FAULT_RETRY.
465 * NOTE: it should become possible to return VM_FAULT_RETRY
466 * even if FAULT_FLAG_TRIED is set without leading to gup()
467 * -EBUSY failures, if the userfaultfd is to be extended for
468 * VM_UFFD_WP tracking and we intend to arm the userfault
469 * without first stopping userland access to the memory. For
470 * VM_UFFD_MISSING userfaults this is enough for now.
472 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
474 * Validate the invariant that nowait must allow retry
475 * to be sure not to return SIGBUS erroneously on
476 * nowait invocations.
478 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
479 #ifdef CONFIG_DEBUG_VM
480 if (printk_ratelimit()) {
482 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
491 * Handle nowait, not much to do other than tell it to retry
494 ret = VM_FAULT_RETRY;
495 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
498 /* take the reference before dropping the mmap_lock */
499 userfaultfd_ctx_get(ctx);
501 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
502 uwq.wq.private = current;
503 uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
504 reason, ctx->features);
508 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
511 * Take the vma lock now, in order to safely call
512 * userfaultfd_huge_must_wait() later. Since acquiring the
513 * (sleepable) vma lock can modify the current task state, that
514 * must be before explicitly calling set_current_state().
516 if (is_vm_hugetlb_page(vma))
517 hugetlb_vma_lock_read(vma);
519 spin_lock_irq(&ctx->fault_pending_wqh.lock);
521 * After the __add_wait_queue the uwq is visible to userland
522 * through poll/read().
524 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
526 * The smp_mb() after __set_current_state prevents the reads
527 * following the spin_unlock to happen before the list_add in
530 set_current_state(blocking_state);
531 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
533 if (!is_vm_hugetlb_page(vma))
534 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
537 must_wait = userfaultfd_huge_must_wait(ctx, vma,
540 if (is_vm_hugetlb_page(vma))
541 hugetlb_vma_unlock_read(vma);
542 mmap_read_unlock(mm);
544 if (likely(must_wait && !READ_ONCE(ctx->released))) {
545 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
549 __set_current_state(TASK_RUNNING);
552 * Here we race with the list_del; list_add in
553 * userfaultfd_ctx_read(), however because we don't ever run
554 * list_del_init() to refile across the two lists, the prev
555 * and next pointers will never point to self. list_add also
556 * would never let any of the two pointers to point to
557 * self. So list_empty_careful won't risk to see both pointers
558 * pointing to self at any time during the list refile. The
559 * only case where list_del_init() is called is the full
560 * removal in the wake function and there we don't re-list_add
561 * and it's fine not to block on the spinlock. The uwq on this
562 * kernel stack can be released after the list_del_init.
564 if (!list_empty_careful(&uwq.wq.entry)) {
565 spin_lock_irq(&ctx->fault_pending_wqh.lock);
567 * No need of list_del_init(), the uwq on the stack
568 * will be freed shortly anyway.
570 list_del(&uwq.wq.entry);
571 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
575 * ctx may go away after this if the userfault pseudo fd is
578 userfaultfd_ctx_put(ctx);
584 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
585 struct userfaultfd_wait_queue *ewq)
587 struct userfaultfd_ctx *release_new_ctx;
589 if (WARN_ON_ONCE(current->flags & PF_EXITING))
593 init_waitqueue_entry(&ewq->wq, current);
594 release_new_ctx = NULL;
596 spin_lock_irq(&ctx->event_wqh.lock);
598 * After the __add_wait_queue the uwq is visible to userland
599 * through poll/read().
601 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
603 set_current_state(TASK_KILLABLE);
604 if (ewq->msg.event == 0)
606 if (READ_ONCE(ctx->released) ||
607 fatal_signal_pending(current)) {
609 * &ewq->wq may be queued in fork_event, but
610 * __remove_wait_queue ignores the head
611 * parameter. It would be a problem if it
614 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
615 if (ewq->msg.event == UFFD_EVENT_FORK) {
616 struct userfaultfd_ctx *new;
618 new = (struct userfaultfd_ctx *)
620 ewq->msg.arg.reserved.reserved1;
621 release_new_ctx = new;
626 spin_unlock_irq(&ctx->event_wqh.lock);
628 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
631 spin_lock_irq(&ctx->event_wqh.lock);
633 __set_current_state(TASK_RUNNING);
634 spin_unlock_irq(&ctx->event_wqh.lock);
636 if (release_new_ctx) {
637 struct vm_area_struct *vma;
638 struct mm_struct *mm = release_new_ctx->mm;
639 VMA_ITERATOR(vmi, mm, 0);
641 /* the various vma->vm_userfaultfd_ctx still points to it */
643 for_each_vma(vmi, vma) {
644 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
645 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
646 userfaultfd_set_vm_flags(vma,
647 vma->vm_flags & ~__VM_UFFD_FLAGS);
650 mmap_write_unlock(mm);
652 userfaultfd_ctx_put(release_new_ctx);
656 * ctx may go away after this if the userfault pseudo fd is
660 atomic_dec(&ctx->mmap_changing);
661 VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
662 userfaultfd_ctx_put(ctx);
665 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
666 struct userfaultfd_wait_queue *ewq)
669 wake_up_locked(&ctx->event_wqh);
670 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
673 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
675 struct userfaultfd_ctx *ctx = NULL, *octx;
676 struct userfaultfd_fork_ctx *fctx;
678 octx = vma->vm_userfaultfd_ctx.ctx;
679 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
680 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
681 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
685 list_for_each_entry(fctx, fcs, list)
686 if (fctx->orig == octx) {
692 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
696 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
702 refcount_set(&ctx->refcount, 1);
703 ctx->flags = octx->flags;
704 ctx->features = octx->features;
705 ctx->released = false;
706 atomic_set(&ctx->mmap_changing, 0);
707 ctx->mm = vma->vm_mm;
710 userfaultfd_ctx_get(octx);
711 atomic_inc(&octx->mmap_changing);
714 list_add_tail(&fctx->list, fcs);
717 vma->vm_userfaultfd_ctx.ctx = ctx;
721 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
723 struct userfaultfd_ctx *ctx = fctx->orig;
724 struct userfaultfd_wait_queue ewq;
728 ewq.msg.event = UFFD_EVENT_FORK;
729 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
731 userfaultfd_event_wait_completion(ctx, &ewq);
734 void dup_userfaultfd_complete(struct list_head *fcs)
736 struct userfaultfd_fork_ctx *fctx, *n;
738 list_for_each_entry_safe(fctx, n, fcs, list) {
740 list_del(&fctx->list);
745 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
746 struct vm_userfaultfd_ctx *vm_ctx)
748 struct userfaultfd_ctx *ctx;
750 ctx = vma->vm_userfaultfd_ctx.ctx;
755 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
757 userfaultfd_ctx_get(ctx);
758 atomic_inc(&ctx->mmap_changing);
760 /* Drop uffd context if remap feature not enabled */
761 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
762 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
766 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
767 unsigned long from, unsigned long to,
770 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
771 struct userfaultfd_wait_queue ewq;
776 if (to & ~PAGE_MASK) {
777 userfaultfd_ctx_put(ctx);
783 ewq.msg.event = UFFD_EVENT_REMAP;
784 ewq.msg.arg.remap.from = from;
785 ewq.msg.arg.remap.to = to;
786 ewq.msg.arg.remap.len = len;
788 userfaultfd_event_wait_completion(ctx, &ewq);
791 bool userfaultfd_remove(struct vm_area_struct *vma,
792 unsigned long start, unsigned long end)
794 struct mm_struct *mm = vma->vm_mm;
795 struct userfaultfd_ctx *ctx;
796 struct userfaultfd_wait_queue ewq;
798 ctx = vma->vm_userfaultfd_ctx.ctx;
799 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
802 userfaultfd_ctx_get(ctx);
803 atomic_inc(&ctx->mmap_changing);
804 mmap_read_unlock(mm);
808 ewq.msg.event = UFFD_EVENT_REMOVE;
809 ewq.msg.arg.remove.start = start;
810 ewq.msg.arg.remove.end = end;
812 userfaultfd_event_wait_completion(ctx, &ewq);
817 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
818 unsigned long start, unsigned long end)
820 struct userfaultfd_unmap_ctx *unmap_ctx;
822 list_for_each_entry(unmap_ctx, unmaps, list)
823 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
824 unmap_ctx->end == end)
830 int userfaultfd_unmap_prep(struct mm_struct *mm, unsigned long start,
831 unsigned long end, struct list_head *unmaps)
833 VMA_ITERATOR(vmi, mm, start);
834 struct vm_area_struct *vma;
836 for_each_vma_range(vmi, vma, end) {
837 struct userfaultfd_unmap_ctx *unmap_ctx;
838 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
840 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
841 has_unmap_ctx(ctx, unmaps, start, end))
844 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
848 userfaultfd_ctx_get(ctx);
849 atomic_inc(&ctx->mmap_changing);
850 unmap_ctx->ctx = ctx;
851 unmap_ctx->start = start;
852 unmap_ctx->end = end;
853 list_add_tail(&unmap_ctx->list, unmaps);
859 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
861 struct userfaultfd_unmap_ctx *ctx, *n;
862 struct userfaultfd_wait_queue ewq;
864 list_for_each_entry_safe(ctx, n, uf, list) {
867 ewq.msg.event = UFFD_EVENT_UNMAP;
868 ewq.msg.arg.remove.start = ctx->start;
869 ewq.msg.arg.remove.end = ctx->end;
871 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
873 list_del(&ctx->list);
878 static int userfaultfd_release(struct inode *inode, struct file *file)
880 struct userfaultfd_ctx *ctx = file->private_data;
881 struct mm_struct *mm = ctx->mm;
882 struct vm_area_struct *vma, *prev;
883 /* len == 0 means wake all */
884 struct userfaultfd_wake_range range = { .len = 0, };
885 unsigned long new_flags;
886 VMA_ITERATOR(vmi, mm, 0);
888 WRITE_ONCE(ctx->released, true);
890 if (!mmget_not_zero(mm))
894 * Flush page faults out of all CPUs. NOTE: all page faults
895 * must be retried without returning VM_FAULT_SIGBUS if
896 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
897 * changes while handle_userfault released the mmap_lock. So
898 * it's critical that released is set to true (above), before
899 * taking the mmap_lock for writing.
903 for_each_vma(vmi, vma) {
905 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
906 !!(vma->vm_flags & __VM_UFFD_FLAGS));
907 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
911 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
912 prev = vma_merge(&vmi, mm, prev, vma->vm_start, vma->vm_end,
913 new_flags, vma->anon_vma,
914 vma->vm_file, vma->vm_pgoff,
916 NULL_VM_UFFD_CTX, anon_vma_name(vma));
923 userfaultfd_set_vm_flags(vma, new_flags);
924 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
926 mmap_write_unlock(mm);
930 * After no new page faults can wait on this fault_*wqh, flush
931 * the last page faults that may have been already waiting on
934 spin_lock_irq(&ctx->fault_pending_wqh.lock);
935 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
936 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
937 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
939 /* Flush pending events that may still wait on event_wqh */
940 wake_up_all(&ctx->event_wqh);
942 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
943 userfaultfd_ctx_put(ctx);
947 /* fault_pending_wqh.lock must be hold by the caller */
948 static inline struct userfaultfd_wait_queue *find_userfault_in(
949 wait_queue_head_t *wqh)
951 wait_queue_entry_t *wq;
952 struct userfaultfd_wait_queue *uwq;
954 lockdep_assert_held(&wqh->lock);
957 if (!waitqueue_active(wqh))
959 /* walk in reverse to provide FIFO behavior to read userfaults */
960 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
961 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
966 static inline struct userfaultfd_wait_queue *find_userfault(
967 struct userfaultfd_ctx *ctx)
969 return find_userfault_in(&ctx->fault_pending_wqh);
972 static inline struct userfaultfd_wait_queue *find_userfault_evt(
973 struct userfaultfd_ctx *ctx)
975 return find_userfault_in(&ctx->event_wqh);
978 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
980 struct userfaultfd_ctx *ctx = file->private_data;
983 poll_wait(file, &ctx->fd_wqh, wait);
985 if (!userfaultfd_is_initialized(ctx))
989 * poll() never guarantees that read won't block.
990 * userfaults can be waken before they're read().
992 if (unlikely(!(file->f_flags & O_NONBLOCK)))
995 * lockless access to see if there are pending faults
996 * __pollwait last action is the add_wait_queue but
997 * the spin_unlock would allow the waitqueue_active to
998 * pass above the actual list_add inside
999 * add_wait_queue critical section. So use a full
1000 * memory barrier to serialize the list_add write of
1001 * add_wait_queue() with the waitqueue_active read
1006 if (waitqueue_active(&ctx->fault_pending_wqh))
1008 else if (waitqueue_active(&ctx->event_wqh))
1014 static const struct file_operations userfaultfd_fops;
1016 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
1017 struct inode *inode,
1018 struct uffd_msg *msg)
1022 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
1023 O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
1027 msg->arg.reserved.reserved1 = 0;
1028 msg->arg.fork.ufd = fd;
1032 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1033 struct uffd_msg *msg, struct inode *inode)
1036 DECLARE_WAITQUEUE(wait, current);
1037 struct userfaultfd_wait_queue *uwq;
1039 * Handling fork event requires sleeping operations, so
1040 * we drop the event_wqh lock, then do these ops, then
1041 * lock it back and wake up the waiter. While the lock is
1042 * dropped the ewq may go away so we keep track of it
1045 LIST_HEAD(fork_event);
1046 struct userfaultfd_ctx *fork_nctx = NULL;
1048 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1049 spin_lock_irq(&ctx->fd_wqh.lock);
1050 __add_wait_queue(&ctx->fd_wqh, &wait);
1052 set_current_state(TASK_INTERRUPTIBLE);
1053 spin_lock(&ctx->fault_pending_wqh.lock);
1054 uwq = find_userfault(ctx);
1057 * Use a seqcount to repeat the lockless check
1058 * in wake_userfault() to avoid missing
1059 * wakeups because during the refile both
1060 * waitqueue could become empty if this is the
1063 write_seqcount_begin(&ctx->refile_seq);
1066 * The fault_pending_wqh.lock prevents the uwq
1067 * to disappear from under us.
1069 * Refile this userfault from
1070 * fault_pending_wqh to fault_wqh, it's not
1071 * pending anymore after we read it.
1073 * Use list_del() by hand (as
1074 * userfaultfd_wake_function also uses
1075 * list_del_init() by hand) to be sure nobody
1076 * changes __remove_wait_queue() to use
1077 * list_del_init() in turn breaking the
1078 * !list_empty_careful() check in
1079 * handle_userfault(). The uwq->wq.head list
1080 * must never be empty at any time during the
1081 * refile, or the waitqueue could disappear
1082 * from under us. The "wait_queue_head_t"
1083 * parameter of __remove_wait_queue() is unused
1086 list_del(&uwq->wq.entry);
1087 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1089 write_seqcount_end(&ctx->refile_seq);
1091 /* careful to always initialize msg if ret == 0 */
1093 spin_unlock(&ctx->fault_pending_wqh.lock);
1097 spin_unlock(&ctx->fault_pending_wqh.lock);
1099 spin_lock(&ctx->event_wqh.lock);
1100 uwq = find_userfault_evt(ctx);
1104 if (uwq->msg.event == UFFD_EVENT_FORK) {
1105 fork_nctx = (struct userfaultfd_ctx *)
1107 uwq->msg.arg.reserved.reserved1;
1108 list_move(&uwq->wq.entry, &fork_event);
1110 * fork_nctx can be freed as soon as
1111 * we drop the lock, unless we take a
1114 userfaultfd_ctx_get(fork_nctx);
1115 spin_unlock(&ctx->event_wqh.lock);
1120 userfaultfd_event_complete(ctx, uwq);
1121 spin_unlock(&ctx->event_wqh.lock);
1125 spin_unlock(&ctx->event_wqh.lock);
1127 if (signal_pending(current)) {
1135 spin_unlock_irq(&ctx->fd_wqh.lock);
1137 spin_lock_irq(&ctx->fd_wqh.lock);
1139 __remove_wait_queue(&ctx->fd_wqh, &wait);
1140 __set_current_state(TASK_RUNNING);
1141 spin_unlock_irq(&ctx->fd_wqh.lock);
1143 if (!ret && msg->event == UFFD_EVENT_FORK) {
1144 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1145 spin_lock_irq(&ctx->event_wqh.lock);
1146 if (!list_empty(&fork_event)) {
1148 * The fork thread didn't abort, so we can
1149 * drop the temporary refcount.
1151 userfaultfd_ctx_put(fork_nctx);
1153 uwq = list_first_entry(&fork_event,
1157 * If fork_event list wasn't empty and in turn
1158 * the event wasn't already released by fork
1159 * (the event is allocated on fork kernel
1160 * stack), put the event back to its place in
1161 * the event_wq. fork_event head will be freed
1162 * as soon as we return so the event cannot
1163 * stay queued there no matter the current
1166 list_del(&uwq->wq.entry);
1167 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1170 * Leave the event in the waitqueue and report
1171 * error to userland if we failed to resolve
1172 * the userfault fork.
1175 userfaultfd_event_complete(ctx, uwq);
1178 * Here the fork thread aborted and the
1179 * refcount from the fork thread on fork_nctx
1180 * has already been released. We still hold
1181 * the reference we took before releasing the
1182 * lock above. If resolve_userfault_fork
1183 * failed we've to drop it because the
1184 * fork_nctx has to be freed in such case. If
1185 * it succeeded we'll hold it because the new
1186 * uffd references it.
1189 userfaultfd_ctx_put(fork_nctx);
1191 spin_unlock_irq(&ctx->event_wqh.lock);
1197 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1198 size_t count, loff_t *ppos)
1200 struct userfaultfd_ctx *ctx = file->private_data;
1201 ssize_t _ret, ret = 0;
1202 struct uffd_msg msg;
1203 int no_wait = file->f_flags & O_NONBLOCK;
1204 struct inode *inode = file_inode(file);
1206 if (!userfaultfd_is_initialized(ctx))
1210 if (count < sizeof(msg))
1211 return ret ? ret : -EINVAL;
1212 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1214 return ret ? ret : _ret;
1215 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1216 return ret ? ret : -EFAULT;
1219 count -= sizeof(msg);
1221 * Allow to read more than one fault at time but only
1222 * block if waiting for the very first one.
1224 no_wait = O_NONBLOCK;
1228 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1229 struct userfaultfd_wake_range *range)
1231 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1232 /* wake all in the range and autoremove */
1233 if (waitqueue_active(&ctx->fault_pending_wqh))
1234 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1236 if (waitqueue_active(&ctx->fault_wqh))
1237 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1238 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1241 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1242 struct userfaultfd_wake_range *range)
1248 * To be sure waitqueue_active() is not reordered by the CPU
1249 * before the pagetable update, use an explicit SMP memory
1250 * barrier here. PT lock release or mmap_read_unlock(mm) still
1251 * have release semantics that can allow the
1252 * waitqueue_active() to be reordered before the pte update.
1257 * Use waitqueue_active because it's very frequent to
1258 * change the address space atomically even if there are no
1259 * userfaults yet. So we take the spinlock only when we're
1260 * sure we've userfaults to wake.
1263 seq = read_seqcount_begin(&ctx->refile_seq);
1264 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1265 waitqueue_active(&ctx->fault_wqh);
1267 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1269 __wake_userfault(ctx, range);
1272 static __always_inline int validate_range(struct mm_struct *mm,
1273 __u64 start, __u64 len)
1275 __u64 task_size = mm->task_size;
1277 if (start & ~PAGE_MASK)
1279 if (len & ~PAGE_MASK)
1283 if (start < mmap_min_addr)
1285 if (start >= task_size)
1287 if (len > task_size - start)
1292 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1295 struct mm_struct *mm = ctx->mm;
1296 struct vm_area_struct *vma, *prev, *cur;
1298 struct uffdio_register uffdio_register;
1299 struct uffdio_register __user *user_uffdio_register;
1300 unsigned long vm_flags, new_flags;
1303 unsigned long start, end, vma_end;
1304 struct vma_iterator vmi;
1306 user_uffdio_register = (struct uffdio_register __user *) arg;
1309 if (copy_from_user(&uffdio_register, user_uffdio_register,
1310 sizeof(uffdio_register)-sizeof(__u64)))
1314 if (!uffdio_register.mode)
1316 if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1319 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1320 vm_flags |= VM_UFFD_MISSING;
1321 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1322 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1325 vm_flags |= VM_UFFD_WP;
1327 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1328 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1331 vm_flags |= VM_UFFD_MINOR;
1334 ret = validate_range(mm, uffdio_register.range.start,
1335 uffdio_register.range.len);
1339 start = uffdio_register.range.start;
1340 end = start + uffdio_register.range.len;
1343 if (!mmget_not_zero(mm))
1347 mmap_write_lock(mm);
1348 vma_iter_init(&vmi, mm, start);
1349 vma = vma_find(&vmi, end);
1354 * If the first vma contains huge pages, make sure start address
1355 * is aligned to huge page size.
1357 if (is_vm_hugetlb_page(vma)) {
1358 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1360 if (start & (vma_hpagesize - 1))
1365 * Search for not compatible vmas.
1368 basic_ioctls = false;
1373 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1374 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1376 /* check not compatible vmas */
1378 if (!vma_can_userfault(cur, vm_flags))
1382 * UFFDIO_COPY will fill file holes even without
1383 * PROT_WRITE. This check enforces that if this is a
1384 * MAP_SHARED, the process has write permission to the backing
1385 * file. If VM_MAYWRITE is set it also enforces that on a
1386 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1387 * F_WRITE_SEAL can be taken until the vma is destroyed.
1390 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1394 * If this vma contains ending address, and huge pages
1397 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1398 end > cur->vm_start) {
1399 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1403 if (end & (vma_hpagesize - 1))
1406 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1410 * Check that this vma isn't already owned by a
1411 * different userfaultfd. We can't allow more than one
1412 * userfaultfd to own a single vma simultaneously or we
1413 * wouldn't know which one to deliver the userfaults to.
1416 if (cur->vm_userfaultfd_ctx.ctx &&
1417 cur->vm_userfaultfd_ctx.ctx != ctx)
1421 * Note vmas containing huge pages
1423 if (is_vm_hugetlb_page(cur))
1424 basic_ioctls = true;
1427 } for_each_vma_range(vmi, cur, end);
1430 vma_iter_set(&vmi, start);
1431 prev = vma_prev(&vmi);
1434 for_each_vma_range(vmi, vma, end) {
1437 BUG_ON(!vma_can_userfault(vma, vm_flags));
1438 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1439 vma->vm_userfaultfd_ctx.ctx != ctx);
1440 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1443 * Nothing to do: this vma is already registered into this
1444 * userfaultfd and with the right tracking mode too.
1446 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1447 (vma->vm_flags & vm_flags) == vm_flags)
1450 if (vma->vm_start > start)
1451 start = vma->vm_start;
1452 vma_end = min(end, vma->vm_end);
1454 new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1455 prev = vma_merge(&vmi, mm, prev, start, vma_end, new_flags,
1456 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1458 ((struct vm_userfaultfd_ctx){ ctx }),
1459 anon_vma_name(vma));
1461 /* vma_merge() invalidated the mas */
1465 if (vma->vm_start < start) {
1466 ret = split_vma(&vmi, vma, start, 1);
1470 if (vma->vm_end > end) {
1471 ret = split_vma(&vmi, vma, end, 0);
1477 * In the vma_merge() successful mprotect-like case 8:
1478 * the next vma was merged into the current one and
1479 * the current one has not been updated yet.
1481 userfaultfd_set_vm_flags(vma, new_flags);
1482 vma->vm_userfaultfd_ctx.ctx = ctx;
1484 if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1485 hugetlb_unshare_all_pmds(vma);
1489 start = vma->vm_end;
1493 mmap_write_unlock(mm);
1498 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1499 UFFD_API_RANGE_IOCTLS;
1502 * Declare the WP ioctl only if the WP mode is
1503 * specified and all checks passed with the range
1505 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1506 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1508 /* CONTINUE ioctl is only supported for MINOR ranges. */
1509 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1510 ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1513 * Now that we scanned all vmas we can already tell
1514 * userland which ioctls methods are guaranteed to
1515 * succeed on this range.
1517 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1524 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1527 struct mm_struct *mm = ctx->mm;
1528 struct vm_area_struct *vma, *prev, *cur;
1530 struct uffdio_range uffdio_unregister;
1531 unsigned long new_flags;
1533 unsigned long start, end, vma_end;
1534 const void __user *buf = (void __user *)arg;
1535 struct vma_iterator vmi;
1538 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1541 ret = validate_range(mm, uffdio_unregister.start,
1542 uffdio_unregister.len);
1546 start = uffdio_unregister.start;
1547 end = start + uffdio_unregister.len;
1550 if (!mmget_not_zero(mm))
1553 mmap_write_lock(mm);
1555 vma_iter_init(&vmi, mm, start);
1556 vma = vma_find(&vmi, end);
1561 * If the first vma contains huge pages, make sure start address
1562 * is aligned to huge page size.
1564 if (is_vm_hugetlb_page(vma)) {
1565 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1567 if (start & (vma_hpagesize - 1))
1572 * Search for not compatible vmas.
1579 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1580 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1583 * Check not compatible vmas, not strictly required
1584 * here as not compatible vmas cannot have an
1585 * userfaultfd_ctx registered on them, but this
1586 * provides for more strict behavior to notice
1587 * unregistration errors.
1589 if (!vma_can_userfault(cur, cur->vm_flags))
1593 } for_each_vma_range(vmi, cur, end);
1596 vma_iter_set(&vmi, start);
1597 prev = vma_prev(&vmi);
1599 for_each_vma_range(vmi, vma, end) {
1602 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1605 * Nothing to do: this vma is already registered into this
1606 * userfaultfd and with the right tracking mode too.
1608 if (!vma->vm_userfaultfd_ctx.ctx)
1611 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1613 if (vma->vm_start > start)
1614 start = vma->vm_start;
1615 vma_end = min(end, vma->vm_end);
1617 if (userfaultfd_missing(vma)) {
1619 * Wake any concurrent pending userfault while
1620 * we unregister, so they will not hang
1621 * permanently and it avoids userland to call
1622 * UFFDIO_WAKE explicitly.
1624 struct userfaultfd_wake_range range;
1625 range.start = start;
1626 range.len = vma_end - start;
1627 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1630 /* Reset ptes for the whole vma range if wr-protected */
1631 if (userfaultfd_wp(vma))
1632 uffd_wp_range(mm, vma, start, vma_end - start, false);
1634 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1635 prev = vma_merge(&vmi, mm, prev, start, vma_end, new_flags,
1636 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1638 NULL_VM_UFFD_CTX, anon_vma_name(vma));
1643 if (vma->vm_start < start) {
1644 ret = split_vma(&vmi, vma, start, 1);
1648 if (vma->vm_end > end) {
1649 ret = split_vma(&vmi, vma, end, 0);
1655 * In the vma_merge() successful mprotect-like case 8:
1656 * the next vma was merged into the current one and
1657 * the current one has not been updated yet.
1659 userfaultfd_set_vm_flags(vma, new_flags);
1660 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1664 start = vma->vm_end;
1668 mmap_write_unlock(mm);
1675 * userfaultfd_wake may be used in combination with the
1676 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1678 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1682 struct uffdio_range uffdio_wake;
1683 struct userfaultfd_wake_range range;
1684 const void __user *buf = (void __user *)arg;
1687 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1690 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1694 range.start = uffdio_wake.start;
1695 range.len = uffdio_wake.len;
1698 * len == 0 means wake all and we don't want to wake all here,
1699 * so check it again to be sure.
1701 VM_BUG_ON(!range.len);
1703 wake_userfault(ctx, &range);
1710 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1714 struct uffdio_copy uffdio_copy;
1715 struct uffdio_copy __user *user_uffdio_copy;
1716 struct userfaultfd_wake_range range;
1718 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1721 if (atomic_read(&ctx->mmap_changing))
1725 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1726 /* don't copy "copy" last field */
1727 sizeof(uffdio_copy)-sizeof(__s64)))
1730 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1734 * double check for wraparound just in case. copy_from_user()
1735 * will later check uffdio_copy.src + uffdio_copy.len to fit
1736 * in the userland range.
1739 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1741 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1743 if (mmget_not_zero(ctx->mm)) {
1744 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1745 uffdio_copy.len, &ctx->mmap_changing,
1751 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1756 /* len == 0 would wake all */
1758 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1759 range.start = uffdio_copy.dst;
1760 wake_userfault(ctx, &range);
1762 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1767 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1771 struct uffdio_zeropage uffdio_zeropage;
1772 struct uffdio_zeropage __user *user_uffdio_zeropage;
1773 struct userfaultfd_wake_range range;
1775 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1778 if (atomic_read(&ctx->mmap_changing))
1782 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1783 /* don't copy "zeropage" last field */
1784 sizeof(uffdio_zeropage)-sizeof(__s64)))
1787 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1788 uffdio_zeropage.range.len);
1792 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1795 if (mmget_not_zero(ctx->mm)) {
1796 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1797 uffdio_zeropage.range.len,
1798 &ctx->mmap_changing);
1803 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1807 /* len == 0 would wake all */
1810 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1811 range.start = uffdio_zeropage.range.start;
1812 wake_userfault(ctx, &range);
1814 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1819 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1823 struct uffdio_writeprotect uffdio_wp;
1824 struct uffdio_writeprotect __user *user_uffdio_wp;
1825 struct userfaultfd_wake_range range;
1826 bool mode_wp, mode_dontwake;
1828 if (atomic_read(&ctx->mmap_changing))
1831 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1833 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1834 sizeof(struct uffdio_writeprotect)))
1837 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1838 uffdio_wp.range.len);
1842 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1843 UFFDIO_WRITEPROTECT_MODE_WP))
1846 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1847 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1849 if (mode_wp && mode_dontwake)
1852 if (mmget_not_zero(ctx->mm)) {
1853 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1854 uffdio_wp.range.len, mode_wp,
1855 &ctx->mmap_changing);
1864 if (!mode_wp && !mode_dontwake) {
1865 range.start = uffdio_wp.range.start;
1866 range.len = uffdio_wp.range.len;
1867 wake_userfault(ctx, &range);
1872 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1875 struct uffdio_continue uffdio_continue;
1876 struct uffdio_continue __user *user_uffdio_continue;
1877 struct userfaultfd_wake_range range;
1879 user_uffdio_continue = (struct uffdio_continue __user *)arg;
1882 if (atomic_read(&ctx->mmap_changing))
1886 if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1887 /* don't copy the output fields */
1888 sizeof(uffdio_continue) - (sizeof(__s64))))
1891 ret = validate_range(ctx->mm, uffdio_continue.range.start,
1892 uffdio_continue.range.len);
1897 /* double check for wraparound just in case. */
1898 if (uffdio_continue.range.start + uffdio_continue.range.len <=
1899 uffdio_continue.range.start) {
1902 if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1905 if (mmget_not_zero(ctx->mm)) {
1906 ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1907 uffdio_continue.range.len,
1908 &ctx->mmap_changing);
1914 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1919 /* len == 0 would wake all */
1922 if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1923 range.start = uffdio_continue.range.start;
1924 wake_userfault(ctx, &range);
1926 ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1932 static inline unsigned int uffd_ctx_features(__u64 user_features)
1935 * For the current set of features the bits just coincide. Set
1936 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1938 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1942 * userland asks for a certain API version and we return which bits
1943 * and ioctl commands are implemented in this kernel for such API
1944 * version or -EINVAL if unknown.
1946 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1949 struct uffdio_api uffdio_api;
1950 void __user *buf = (void __user *)arg;
1951 unsigned int ctx_features;
1956 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1958 /* Ignore unsupported features (userspace built against newer kernel) */
1959 features = uffdio_api.features & UFFD_API_FEATURES;
1961 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1963 /* report all available features and ioctls to userland */
1964 uffdio_api.features = UFFD_API_FEATURES;
1965 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1966 uffdio_api.features &=
1967 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1969 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1970 uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1972 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1973 uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1975 uffdio_api.ioctls = UFFD_API_IOCTLS;
1977 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1980 /* only enable the requested features for this uffd context */
1981 ctx_features = uffd_ctx_features(features);
1983 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1990 memset(&uffdio_api, 0, sizeof(uffdio_api));
1991 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1996 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2000 struct userfaultfd_ctx *ctx = file->private_data;
2002 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2007 ret = userfaultfd_api(ctx, arg);
2009 case UFFDIO_REGISTER:
2010 ret = userfaultfd_register(ctx, arg);
2012 case UFFDIO_UNREGISTER:
2013 ret = userfaultfd_unregister(ctx, arg);
2016 ret = userfaultfd_wake(ctx, arg);
2019 ret = userfaultfd_copy(ctx, arg);
2021 case UFFDIO_ZEROPAGE:
2022 ret = userfaultfd_zeropage(ctx, arg);
2024 case UFFDIO_WRITEPROTECT:
2025 ret = userfaultfd_writeprotect(ctx, arg);
2027 case UFFDIO_CONTINUE:
2028 ret = userfaultfd_continue(ctx, arg);
2034 #ifdef CONFIG_PROC_FS
2035 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2037 struct userfaultfd_ctx *ctx = f->private_data;
2038 wait_queue_entry_t *wq;
2039 unsigned long pending = 0, total = 0;
2041 spin_lock_irq(&ctx->fault_pending_wqh.lock);
2042 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2046 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2049 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2052 * If more protocols will be added, there will be all shown
2053 * separated by a space. Like this:
2054 * protocols: aa:... bb:...
2056 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2057 pending, total, UFFD_API, ctx->features,
2058 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2062 static const struct file_operations userfaultfd_fops = {
2063 #ifdef CONFIG_PROC_FS
2064 .show_fdinfo = userfaultfd_show_fdinfo,
2066 .release = userfaultfd_release,
2067 .poll = userfaultfd_poll,
2068 .read = userfaultfd_read,
2069 .unlocked_ioctl = userfaultfd_ioctl,
2070 .compat_ioctl = compat_ptr_ioctl,
2071 .llseek = noop_llseek,
2074 static void init_once_userfaultfd_ctx(void *mem)
2076 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2078 init_waitqueue_head(&ctx->fault_pending_wqh);
2079 init_waitqueue_head(&ctx->fault_wqh);
2080 init_waitqueue_head(&ctx->event_wqh);
2081 init_waitqueue_head(&ctx->fd_wqh);
2082 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2085 static int new_userfaultfd(int flags)
2087 struct userfaultfd_ctx *ctx;
2090 BUG_ON(!current->mm);
2092 /* Check the UFFD_* constants for consistency. */
2093 BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2094 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2095 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2097 if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2100 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2104 refcount_set(&ctx->refcount, 1);
2107 ctx->released = false;
2108 atomic_set(&ctx->mmap_changing, 0);
2109 ctx->mm = current->mm;
2110 /* prevent the mm struct to be freed */
2113 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2114 O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2117 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2122 static inline bool userfaultfd_syscall_allowed(int flags)
2124 /* Userspace-only page faults are always allowed */
2125 if (flags & UFFD_USER_MODE_ONLY)
2129 * The user is requesting a userfaultfd which can handle kernel faults.
2130 * Privileged users are always allowed to do this.
2132 if (capable(CAP_SYS_PTRACE))
2135 /* Otherwise, access to kernel fault handling is sysctl controlled. */
2136 return sysctl_unprivileged_userfaultfd;
2139 SYSCALL_DEFINE1(userfaultfd, int, flags)
2141 if (!userfaultfd_syscall_allowed(flags))
2144 return new_userfaultfd(flags);
2147 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2149 if (cmd != USERFAULTFD_IOC_NEW)
2152 return new_userfaultfd(flags);
2155 static const struct file_operations userfaultfd_dev_fops = {
2156 .unlocked_ioctl = userfaultfd_dev_ioctl,
2157 .compat_ioctl = userfaultfd_dev_ioctl,
2158 .owner = THIS_MODULE,
2159 .llseek = noop_llseek,
2162 static struct miscdevice userfaultfd_misc = {
2163 .minor = MISC_DYNAMIC_MINOR,
2164 .name = "userfaultfd",
2165 .fops = &userfaultfd_dev_fops
2168 static int __init userfaultfd_init(void)
2172 ret = misc_register(&userfaultfd_misc);
2176 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2177 sizeof(struct userfaultfd_ctx),
2179 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2180 init_once_userfaultfd_ctx);
2183 __initcall(userfaultfd_init);