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 vma->vm_flags = 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)
255 struct mm_struct *mm = ctx->mm;
259 mmap_assert_locked(mm);
261 ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
267 pte = huge_ptep_get(ptep);
270 * Lockless access: we're in a wait_event so it's ok if it
271 * changes under us. PTE markers should be handled the same as none
274 if (huge_pte_none_mostly(pte))
276 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
282 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
283 struct vm_area_struct *vma,
284 unsigned long address,
286 unsigned long reason)
288 return false; /* should never get here */
290 #endif /* CONFIG_HUGETLB_PAGE */
293 * Verify the pagetables are still not ok after having reigstered into
294 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
295 * userfault that has already been resolved, if userfaultfd_read and
296 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
299 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
300 unsigned long address,
302 unsigned long reason)
304 struct mm_struct *mm = ctx->mm;
312 mmap_assert_locked(mm);
314 pgd = pgd_offset(mm, address);
315 if (!pgd_present(*pgd))
317 p4d = p4d_offset(pgd, address);
318 if (!p4d_present(*p4d))
320 pud = pud_offset(p4d, address);
321 if (!pud_present(*pud))
323 pmd = pmd_offset(pud, address);
325 * READ_ONCE must function as a barrier with narrower scope
326 * and it must be equivalent to:
327 * _pmd = *pmd; barrier();
329 * This is to deal with the instability (as in
330 * pmd_trans_unstable) of the pmd.
332 _pmd = READ_ONCE(*pmd);
337 if (!pmd_present(_pmd))
340 if (pmd_trans_huge(_pmd)) {
341 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
347 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
348 * and use the standard pte_offset_map() instead of parsing _pmd.
350 pte = pte_offset_map(pmd, address);
352 * Lockless access: we're in a wait_event so it's ok if it
353 * changes under us. PTE markers should be handled the same as none
356 if (pte_none_mostly(*pte))
358 if (!pte_write(*pte) && (reason & VM_UFFD_WP))
366 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
368 if (flags & FAULT_FLAG_INTERRUPTIBLE)
369 return TASK_INTERRUPTIBLE;
371 if (flags & FAULT_FLAG_KILLABLE)
372 return TASK_KILLABLE;
374 return TASK_UNINTERRUPTIBLE;
378 * The locking rules involved in returning VM_FAULT_RETRY depending on
379 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
380 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
381 * recommendation in __lock_page_or_retry is not an understatement.
383 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
384 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
387 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
388 * set, VM_FAULT_RETRY can still be returned if and only if there are
389 * fatal_signal_pending()s, and the mmap_lock must be released before
392 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
394 struct mm_struct *mm = vmf->vma->vm_mm;
395 struct userfaultfd_ctx *ctx;
396 struct userfaultfd_wait_queue uwq;
397 vm_fault_t ret = VM_FAULT_SIGBUS;
399 unsigned int blocking_state;
402 * We don't do userfault handling for the final child pid update.
404 * We also don't do userfault handling during
405 * coredumping. hugetlbfs has the special
406 * follow_hugetlb_page() to skip missing pages in the
407 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
408 * the no_page_table() helper in follow_page_mask(), but the
409 * shmem_vm_ops->fault method is invoked even during
410 * coredumping without mmap_lock and it ends up here.
412 if (current->flags & (PF_EXITING|PF_DUMPCORE))
416 * Coredumping runs without mmap_lock so we can only check that
417 * the mmap_lock is held, if PF_DUMPCORE was not set.
419 mmap_assert_locked(mm);
421 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
425 BUG_ON(ctx->mm != mm);
427 /* Any unrecognized flag is a bug. */
428 VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
429 /* 0 or > 1 flags set is a bug; we expect exactly 1. */
430 VM_BUG_ON(!reason || (reason & (reason - 1)));
432 if (ctx->features & UFFD_FEATURE_SIGBUS)
434 if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
438 * If it's already released don't get it. This avoids to loop
439 * in __get_user_pages if userfaultfd_release waits on the
440 * caller of handle_userfault to release the mmap_lock.
442 if (unlikely(READ_ONCE(ctx->released))) {
444 * Don't return VM_FAULT_SIGBUS in this case, so a non
445 * cooperative manager can close the uffd after the
446 * last UFFDIO_COPY, without risking to trigger an
447 * involuntary SIGBUS if the process was starting the
448 * userfaultfd while the userfaultfd was still armed
449 * (but after the last UFFDIO_COPY). If the uffd
450 * wasn't already closed when the userfault reached
451 * this point, that would normally be solved by
452 * userfaultfd_must_wait returning 'false'.
454 * If we were to return VM_FAULT_SIGBUS here, the non
455 * cooperative manager would be instead forced to
456 * always call UFFDIO_UNREGISTER before it can safely
459 ret = VM_FAULT_NOPAGE;
464 * Check that we can return VM_FAULT_RETRY.
466 * NOTE: it should become possible to return VM_FAULT_RETRY
467 * even if FAULT_FLAG_TRIED is set without leading to gup()
468 * -EBUSY failures, if the userfaultfd is to be extended for
469 * VM_UFFD_WP tracking and we intend to arm the userfault
470 * without first stopping userland access to the memory. For
471 * VM_UFFD_MISSING userfaults this is enough for now.
473 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
475 * Validate the invariant that nowait must allow retry
476 * to be sure not to return SIGBUS erroneously on
477 * nowait invocations.
479 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
480 #ifdef CONFIG_DEBUG_VM
481 if (printk_ratelimit()) {
483 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
492 * Handle nowait, not much to do other than tell it to retry
495 ret = VM_FAULT_RETRY;
496 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
499 /* take the reference before dropping the mmap_lock */
500 userfaultfd_ctx_get(ctx);
502 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
503 uwq.wq.private = current;
504 uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
505 reason, ctx->features);
509 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
511 spin_lock_irq(&ctx->fault_pending_wqh.lock);
513 * After the __add_wait_queue the uwq is visible to userland
514 * through poll/read().
516 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
518 * The smp_mb() after __set_current_state prevents the reads
519 * following the spin_unlock to happen before the list_add in
522 set_current_state(blocking_state);
523 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
525 if (!is_vm_hugetlb_page(vmf->vma))
526 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
529 must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
532 mmap_read_unlock(mm);
534 if (likely(must_wait && !READ_ONCE(ctx->released))) {
535 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
539 __set_current_state(TASK_RUNNING);
542 * Here we race with the list_del; list_add in
543 * userfaultfd_ctx_read(), however because we don't ever run
544 * list_del_init() to refile across the two lists, the prev
545 * and next pointers will never point to self. list_add also
546 * would never let any of the two pointers to point to
547 * self. So list_empty_careful won't risk to see both pointers
548 * pointing to self at any time during the list refile. The
549 * only case where list_del_init() is called is the full
550 * removal in the wake function and there we don't re-list_add
551 * and it's fine not to block on the spinlock. The uwq on this
552 * kernel stack can be released after the list_del_init.
554 if (!list_empty_careful(&uwq.wq.entry)) {
555 spin_lock_irq(&ctx->fault_pending_wqh.lock);
557 * No need of list_del_init(), the uwq on the stack
558 * will be freed shortly anyway.
560 list_del(&uwq.wq.entry);
561 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
565 * ctx may go away after this if the userfault pseudo fd is
568 userfaultfd_ctx_put(ctx);
574 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
575 struct userfaultfd_wait_queue *ewq)
577 struct userfaultfd_ctx *release_new_ctx;
579 if (WARN_ON_ONCE(current->flags & PF_EXITING))
583 init_waitqueue_entry(&ewq->wq, current);
584 release_new_ctx = NULL;
586 spin_lock_irq(&ctx->event_wqh.lock);
588 * After the __add_wait_queue the uwq is visible to userland
589 * through poll/read().
591 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
593 set_current_state(TASK_KILLABLE);
594 if (ewq->msg.event == 0)
596 if (READ_ONCE(ctx->released) ||
597 fatal_signal_pending(current)) {
599 * &ewq->wq may be queued in fork_event, but
600 * __remove_wait_queue ignores the head
601 * parameter. It would be a problem if it
604 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
605 if (ewq->msg.event == UFFD_EVENT_FORK) {
606 struct userfaultfd_ctx *new;
608 new = (struct userfaultfd_ctx *)
610 ewq->msg.arg.reserved.reserved1;
611 release_new_ctx = new;
616 spin_unlock_irq(&ctx->event_wqh.lock);
618 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
621 spin_lock_irq(&ctx->event_wqh.lock);
623 __set_current_state(TASK_RUNNING);
624 spin_unlock_irq(&ctx->event_wqh.lock);
626 if (release_new_ctx) {
627 struct vm_area_struct *vma;
628 struct mm_struct *mm = release_new_ctx->mm;
629 VMA_ITERATOR(vmi, mm, 0);
631 /* the various vma->vm_userfaultfd_ctx still points to it */
633 for_each_vma(vmi, vma) {
634 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
635 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
636 userfaultfd_set_vm_flags(vma,
637 vma->vm_flags & ~__VM_UFFD_FLAGS);
640 mmap_write_unlock(mm);
642 userfaultfd_ctx_put(release_new_ctx);
646 * ctx may go away after this if the userfault pseudo fd is
650 atomic_dec(&ctx->mmap_changing);
651 VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
652 userfaultfd_ctx_put(ctx);
655 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
656 struct userfaultfd_wait_queue *ewq)
659 wake_up_locked(&ctx->event_wqh);
660 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
663 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
665 struct userfaultfd_ctx *ctx = NULL, *octx;
666 struct userfaultfd_fork_ctx *fctx;
668 octx = vma->vm_userfaultfd_ctx.ctx;
669 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
670 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
671 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
675 list_for_each_entry(fctx, fcs, list)
676 if (fctx->orig == octx) {
682 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
686 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
692 refcount_set(&ctx->refcount, 1);
693 ctx->flags = octx->flags;
694 ctx->features = octx->features;
695 ctx->released = false;
696 atomic_set(&ctx->mmap_changing, 0);
697 ctx->mm = vma->vm_mm;
700 userfaultfd_ctx_get(octx);
701 atomic_inc(&octx->mmap_changing);
704 list_add_tail(&fctx->list, fcs);
707 vma->vm_userfaultfd_ctx.ctx = ctx;
711 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
713 struct userfaultfd_ctx *ctx = fctx->orig;
714 struct userfaultfd_wait_queue ewq;
718 ewq.msg.event = UFFD_EVENT_FORK;
719 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
721 userfaultfd_event_wait_completion(ctx, &ewq);
724 void dup_userfaultfd_complete(struct list_head *fcs)
726 struct userfaultfd_fork_ctx *fctx, *n;
728 list_for_each_entry_safe(fctx, n, fcs, list) {
730 list_del(&fctx->list);
735 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
736 struct vm_userfaultfd_ctx *vm_ctx)
738 struct userfaultfd_ctx *ctx;
740 ctx = vma->vm_userfaultfd_ctx.ctx;
745 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
747 userfaultfd_ctx_get(ctx);
748 atomic_inc(&ctx->mmap_changing);
750 /* Drop uffd context if remap feature not enabled */
751 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
752 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
756 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
757 unsigned long from, unsigned long to,
760 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
761 struct userfaultfd_wait_queue ewq;
766 if (to & ~PAGE_MASK) {
767 userfaultfd_ctx_put(ctx);
773 ewq.msg.event = UFFD_EVENT_REMAP;
774 ewq.msg.arg.remap.from = from;
775 ewq.msg.arg.remap.to = to;
776 ewq.msg.arg.remap.len = len;
778 userfaultfd_event_wait_completion(ctx, &ewq);
781 bool userfaultfd_remove(struct vm_area_struct *vma,
782 unsigned long start, unsigned long end)
784 struct mm_struct *mm = vma->vm_mm;
785 struct userfaultfd_ctx *ctx;
786 struct userfaultfd_wait_queue ewq;
788 ctx = vma->vm_userfaultfd_ctx.ctx;
789 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
792 userfaultfd_ctx_get(ctx);
793 atomic_inc(&ctx->mmap_changing);
794 mmap_read_unlock(mm);
798 ewq.msg.event = UFFD_EVENT_REMOVE;
799 ewq.msg.arg.remove.start = start;
800 ewq.msg.arg.remove.end = end;
802 userfaultfd_event_wait_completion(ctx, &ewq);
807 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
808 unsigned long start, unsigned long end)
810 struct userfaultfd_unmap_ctx *unmap_ctx;
812 list_for_each_entry(unmap_ctx, unmaps, list)
813 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
814 unmap_ctx->end == end)
820 int userfaultfd_unmap_prep(struct mm_struct *mm, unsigned long start,
821 unsigned long end, struct list_head *unmaps)
823 VMA_ITERATOR(vmi, mm, start);
824 struct vm_area_struct *vma;
826 for_each_vma_range(vmi, vma, end) {
827 struct userfaultfd_unmap_ctx *unmap_ctx;
828 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
830 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
831 has_unmap_ctx(ctx, unmaps, start, end))
834 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
838 userfaultfd_ctx_get(ctx);
839 atomic_inc(&ctx->mmap_changing);
840 unmap_ctx->ctx = ctx;
841 unmap_ctx->start = start;
842 unmap_ctx->end = end;
843 list_add_tail(&unmap_ctx->list, unmaps);
849 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
851 struct userfaultfd_unmap_ctx *ctx, *n;
852 struct userfaultfd_wait_queue ewq;
854 list_for_each_entry_safe(ctx, n, uf, list) {
857 ewq.msg.event = UFFD_EVENT_UNMAP;
858 ewq.msg.arg.remove.start = ctx->start;
859 ewq.msg.arg.remove.end = ctx->end;
861 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
863 list_del(&ctx->list);
868 static int userfaultfd_release(struct inode *inode, struct file *file)
870 struct userfaultfd_ctx *ctx = file->private_data;
871 struct mm_struct *mm = ctx->mm;
872 struct vm_area_struct *vma, *prev;
873 /* len == 0 means wake all */
874 struct userfaultfd_wake_range range = { .len = 0, };
875 unsigned long new_flags;
876 MA_STATE(mas, &mm->mm_mt, 0, 0);
878 WRITE_ONCE(ctx->released, true);
880 if (!mmget_not_zero(mm))
884 * Flush page faults out of all CPUs. NOTE: all page faults
885 * must be retried without returning VM_FAULT_SIGBUS if
886 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
887 * changes while handle_userfault released the mmap_lock. So
888 * it's critical that released is set to true (above), before
889 * taking the mmap_lock for writing.
893 mas_for_each(&mas, vma, ULONG_MAX) {
895 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
896 !!(vma->vm_flags & __VM_UFFD_FLAGS));
897 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
901 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
902 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
903 new_flags, vma->anon_vma,
904 vma->vm_file, vma->vm_pgoff,
906 NULL_VM_UFFD_CTX, anon_vma_name(vma));
914 userfaultfd_set_vm_flags(vma, new_flags);
915 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
917 mmap_write_unlock(mm);
921 * After no new page faults can wait on this fault_*wqh, flush
922 * the last page faults that may have been already waiting on
925 spin_lock_irq(&ctx->fault_pending_wqh.lock);
926 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
927 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
928 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
930 /* Flush pending events that may still wait on event_wqh */
931 wake_up_all(&ctx->event_wqh);
933 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
934 userfaultfd_ctx_put(ctx);
938 /* fault_pending_wqh.lock must be hold by the caller */
939 static inline struct userfaultfd_wait_queue *find_userfault_in(
940 wait_queue_head_t *wqh)
942 wait_queue_entry_t *wq;
943 struct userfaultfd_wait_queue *uwq;
945 lockdep_assert_held(&wqh->lock);
948 if (!waitqueue_active(wqh))
950 /* walk in reverse to provide FIFO behavior to read userfaults */
951 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
952 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
957 static inline struct userfaultfd_wait_queue *find_userfault(
958 struct userfaultfd_ctx *ctx)
960 return find_userfault_in(&ctx->fault_pending_wqh);
963 static inline struct userfaultfd_wait_queue *find_userfault_evt(
964 struct userfaultfd_ctx *ctx)
966 return find_userfault_in(&ctx->event_wqh);
969 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
971 struct userfaultfd_ctx *ctx = file->private_data;
974 poll_wait(file, &ctx->fd_wqh, wait);
976 if (!userfaultfd_is_initialized(ctx))
980 * poll() never guarantees that read won't block.
981 * userfaults can be waken before they're read().
983 if (unlikely(!(file->f_flags & O_NONBLOCK)))
986 * lockless access to see if there are pending faults
987 * __pollwait last action is the add_wait_queue but
988 * the spin_unlock would allow the waitqueue_active to
989 * pass above the actual list_add inside
990 * add_wait_queue critical section. So use a full
991 * memory barrier to serialize the list_add write of
992 * add_wait_queue() with the waitqueue_active read
997 if (waitqueue_active(&ctx->fault_pending_wqh))
999 else if (waitqueue_active(&ctx->event_wqh))
1005 static const struct file_operations userfaultfd_fops;
1007 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
1008 struct inode *inode,
1009 struct uffd_msg *msg)
1013 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
1014 O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
1018 msg->arg.reserved.reserved1 = 0;
1019 msg->arg.fork.ufd = fd;
1023 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1024 struct uffd_msg *msg, struct inode *inode)
1027 DECLARE_WAITQUEUE(wait, current);
1028 struct userfaultfd_wait_queue *uwq;
1030 * Handling fork event requires sleeping operations, so
1031 * we drop the event_wqh lock, then do these ops, then
1032 * lock it back and wake up the waiter. While the lock is
1033 * dropped the ewq may go away so we keep track of it
1036 LIST_HEAD(fork_event);
1037 struct userfaultfd_ctx *fork_nctx = NULL;
1039 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1040 spin_lock_irq(&ctx->fd_wqh.lock);
1041 __add_wait_queue(&ctx->fd_wqh, &wait);
1043 set_current_state(TASK_INTERRUPTIBLE);
1044 spin_lock(&ctx->fault_pending_wqh.lock);
1045 uwq = find_userfault(ctx);
1048 * Use a seqcount to repeat the lockless check
1049 * in wake_userfault() to avoid missing
1050 * wakeups because during the refile both
1051 * waitqueue could become empty if this is the
1054 write_seqcount_begin(&ctx->refile_seq);
1057 * The fault_pending_wqh.lock prevents the uwq
1058 * to disappear from under us.
1060 * Refile this userfault from
1061 * fault_pending_wqh to fault_wqh, it's not
1062 * pending anymore after we read it.
1064 * Use list_del() by hand (as
1065 * userfaultfd_wake_function also uses
1066 * list_del_init() by hand) to be sure nobody
1067 * changes __remove_wait_queue() to use
1068 * list_del_init() in turn breaking the
1069 * !list_empty_careful() check in
1070 * handle_userfault(). The uwq->wq.head list
1071 * must never be empty at any time during the
1072 * refile, or the waitqueue could disappear
1073 * from under us. The "wait_queue_head_t"
1074 * parameter of __remove_wait_queue() is unused
1077 list_del(&uwq->wq.entry);
1078 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1080 write_seqcount_end(&ctx->refile_seq);
1082 /* careful to always initialize msg if ret == 0 */
1084 spin_unlock(&ctx->fault_pending_wqh.lock);
1088 spin_unlock(&ctx->fault_pending_wqh.lock);
1090 spin_lock(&ctx->event_wqh.lock);
1091 uwq = find_userfault_evt(ctx);
1095 if (uwq->msg.event == UFFD_EVENT_FORK) {
1096 fork_nctx = (struct userfaultfd_ctx *)
1098 uwq->msg.arg.reserved.reserved1;
1099 list_move(&uwq->wq.entry, &fork_event);
1101 * fork_nctx can be freed as soon as
1102 * we drop the lock, unless we take a
1105 userfaultfd_ctx_get(fork_nctx);
1106 spin_unlock(&ctx->event_wqh.lock);
1111 userfaultfd_event_complete(ctx, uwq);
1112 spin_unlock(&ctx->event_wqh.lock);
1116 spin_unlock(&ctx->event_wqh.lock);
1118 if (signal_pending(current)) {
1126 spin_unlock_irq(&ctx->fd_wqh.lock);
1128 spin_lock_irq(&ctx->fd_wqh.lock);
1130 __remove_wait_queue(&ctx->fd_wqh, &wait);
1131 __set_current_state(TASK_RUNNING);
1132 spin_unlock_irq(&ctx->fd_wqh.lock);
1134 if (!ret && msg->event == UFFD_EVENT_FORK) {
1135 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1136 spin_lock_irq(&ctx->event_wqh.lock);
1137 if (!list_empty(&fork_event)) {
1139 * The fork thread didn't abort, so we can
1140 * drop the temporary refcount.
1142 userfaultfd_ctx_put(fork_nctx);
1144 uwq = list_first_entry(&fork_event,
1148 * If fork_event list wasn't empty and in turn
1149 * the event wasn't already released by fork
1150 * (the event is allocated on fork kernel
1151 * stack), put the event back to its place in
1152 * the event_wq. fork_event head will be freed
1153 * as soon as we return so the event cannot
1154 * stay queued there no matter the current
1157 list_del(&uwq->wq.entry);
1158 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1161 * Leave the event in the waitqueue and report
1162 * error to userland if we failed to resolve
1163 * the userfault fork.
1166 userfaultfd_event_complete(ctx, uwq);
1169 * Here the fork thread aborted and the
1170 * refcount from the fork thread on fork_nctx
1171 * has already been released. We still hold
1172 * the reference we took before releasing the
1173 * lock above. If resolve_userfault_fork
1174 * failed we've to drop it because the
1175 * fork_nctx has to be freed in such case. If
1176 * it succeeded we'll hold it because the new
1177 * uffd references it.
1180 userfaultfd_ctx_put(fork_nctx);
1182 spin_unlock_irq(&ctx->event_wqh.lock);
1188 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1189 size_t count, loff_t *ppos)
1191 struct userfaultfd_ctx *ctx = file->private_data;
1192 ssize_t _ret, ret = 0;
1193 struct uffd_msg msg;
1194 int no_wait = file->f_flags & O_NONBLOCK;
1195 struct inode *inode = file_inode(file);
1197 if (!userfaultfd_is_initialized(ctx))
1201 if (count < sizeof(msg))
1202 return ret ? ret : -EINVAL;
1203 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1205 return ret ? ret : _ret;
1206 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1207 return ret ? ret : -EFAULT;
1210 count -= sizeof(msg);
1212 * Allow to read more than one fault at time but only
1213 * block if waiting for the very first one.
1215 no_wait = O_NONBLOCK;
1219 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1220 struct userfaultfd_wake_range *range)
1222 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1223 /* wake all in the range and autoremove */
1224 if (waitqueue_active(&ctx->fault_pending_wqh))
1225 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1227 if (waitqueue_active(&ctx->fault_wqh))
1228 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1229 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1232 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1233 struct userfaultfd_wake_range *range)
1239 * To be sure waitqueue_active() is not reordered by the CPU
1240 * before the pagetable update, use an explicit SMP memory
1241 * barrier here. PT lock release or mmap_read_unlock(mm) still
1242 * have release semantics that can allow the
1243 * waitqueue_active() to be reordered before the pte update.
1248 * Use waitqueue_active because it's very frequent to
1249 * change the address space atomically even if there are no
1250 * userfaults yet. So we take the spinlock only when we're
1251 * sure we've userfaults to wake.
1254 seq = read_seqcount_begin(&ctx->refile_seq);
1255 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1256 waitqueue_active(&ctx->fault_wqh);
1258 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1260 __wake_userfault(ctx, range);
1263 static __always_inline int validate_range(struct mm_struct *mm,
1264 __u64 start, __u64 len)
1266 __u64 task_size = mm->task_size;
1268 if (start & ~PAGE_MASK)
1270 if (len & ~PAGE_MASK)
1274 if (start < mmap_min_addr)
1276 if (start >= task_size)
1278 if (len > task_size - start)
1283 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1286 struct mm_struct *mm = ctx->mm;
1287 struct vm_area_struct *vma, *prev, *cur;
1289 struct uffdio_register uffdio_register;
1290 struct uffdio_register __user *user_uffdio_register;
1291 unsigned long vm_flags, new_flags;
1294 unsigned long start, end, vma_end;
1295 MA_STATE(mas, &mm->mm_mt, 0, 0);
1297 user_uffdio_register = (struct uffdio_register __user *) arg;
1300 if (copy_from_user(&uffdio_register, user_uffdio_register,
1301 sizeof(uffdio_register)-sizeof(__u64)))
1305 if (!uffdio_register.mode)
1307 if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1310 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1311 vm_flags |= VM_UFFD_MISSING;
1312 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1313 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1316 vm_flags |= VM_UFFD_WP;
1318 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1319 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1322 vm_flags |= VM_UFFD_MINOR;
1325 ret = validate_range(mm, uffdio_register.range.start,
1326 uffdio_register.range.len);
1330 start = uffdio_register.range.start;
1331 end = start + uffdio_register.range.len;
1334 if (!mmget_not_zero(mm))
1337 mmap_write_lock(mm);
1338 mas_set(&mas, start);
1339 vma = mas_find(&mas, ULONG_MAX);
1343 /* check that there's at least one vma in the range */
1345 if (vma->vm_start >= end)
1349 * If the first vma contains huge pages, make sure start address
1350 * is aligned to huge page size.
1352 if (is_vm_hugetlb_page(vma)) {
1353 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1355 if (start & (vma_hpagesize - 1))
1360 * Search for not compatible vmas.
1363 basic_ioctls = false;
1364 for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
1367 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1368 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1370 /* check not compatible vmas */
1372 if (!vma_can_userfault(cur, vm_flags))
1376 * UFFDIO_COPY will fill file holes even without
1377 * PROT_WRITE. This check enforces that if this is a
1378 * MAP_SHARED, the process has write permission to the backing
1379 * file. If VM_MAYWRITE is set it also enforces that on a
1380 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1381 * F_WRITE_SEAL can be taken until the vma is destroyed.
1384 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1388 * If this vma contains ending address, and huge pages
1391 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1392 end > cur->vm_start) {
1393 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1397 if (end & (vma_hpagesize - 1))
1400 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1404 * Check that this vma isn't already owned by a
1405 * different userfaultfd. We can't allow more than one
1406 * userfaultfd to own a single vma simultaneously or we
1407 * wouldn't know which one to deliver the userfaults to.
1410 if (cur->vm_userfaultfd_ctx.ctx &&
1411 cur->vm_userfaultfd_ctx.ctx != ctx)
1415 * Note vmas containing huge pages
1417 if (is_vm_hugetlb_page(cur))
1418 basic_ioctls = true;
1424 mas_set(&mas, start);
1425 prev = mas_prev(&mas, 0);
1427 mas_next(&mas, ULONG_MAX);
1433 BUG_ON(!vma_can_userfault(vma, vm_flags));
1434 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1435 vma->vm_userfaultfd_ctx.ctx != ctx);
1436 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1439 * Nothing to do: this vma is already registered into this
1440 * userfaultfd and with the right tracking mode too.
1442 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1443 (vma->vm_flags & vm_flags) == vm_flags)
1446 if (vma->vm_start > start)
1447 start = vma->vm_start;
1448 vma_end = min(end, vma->vm_end);
1450 new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1451 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1452 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1454 ((struct vm_userfaultfd_ctx){ ctx }),
1455 anon_vma_name(vma));
1457 /* vma_merge() invalidated the mas */
1462 if (vma->vm_start < start) {
1463 ret = split_vma(mm, vma, start, 1);
1466 /* split_vma() invalidated the mas */
1469 if (vma->vm_end > end) {
1470 ret = split_vma(mm, vma, end, 0);
1473 /* split_vma() invalidated the mas */
1478 * In the vma_merge() successful mprotect-like case 8:
1479 * the next vma was merged into the current one and
1480 * the current one has not been updated yet.
1482 userfaultfd_set_vm_flags(vma, new_flags);
1483 vma->vm_userfaultfd_ctx.ctx = ctx;
1485 if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1486 hugetlb_unshare_all_pmds(vma);
1490 start = vma->vm_end;
1491 vma = mas_next(&mas, end - 1);
1494 mmap_write_unlock(mm);
1499 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1500 UFFD_API_RANGE_IOCTLS;
1503 * Declare the WP ioctl only if the WP mode is
1504 * specified and all checks passed with the range
1506 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1507 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1509 /* CONTINUE ioctl is only supported for MINOR ranges. */
1510 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1511 ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1514 * Now that we scanned all vmas we can already tell
1515 * userland which ioctls methods are guaranteed to
1516 * succeed on this range.
1518 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1525 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1528 struct mm_struct *mm = ctx->mm;
1529 struct vm_area_struct *vma, *prev, *cur;
1531 struct uffdio_range uffdio_unregister;
1532 unsigned long new_flags;
1534 unsigned long start, end, vma_end;
1535 const void __user *buf = (void __user *)arg;
1536 MA_STATE(mas, &mm->mm_mt, 0, 0);
1539 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1542 ret = validate_range(mm, uffdio_unregister.start,
1543 uffdio_unregister.len);
1547 start = uffdio_unregister.start;
1548 end = start + uffdio_unregister.len;
1551 if (!mmget_not_zero(mm))
1554 mmap_write_lock(mm);
1555 mas_set(&mas, start);
1556 vma = mas_find(&mas, ULONG_MAX);
1560 /* check that there's at least one vma in the range */
1562 if (vma->vm_start >= end)
1566 * If the first vma contains huge pages, make sure start address
1567 * is aligned to huge page size.
1569 if (is_vm_hugetlb_page(vma)) {
1570 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1572 if (start & (vma_hpagesize - 1))
1577 * Search for not compatible vmas.
1581 for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
1584 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1585 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1588 * Check not compatible vmas, not strictly required
1589 * here as not compatible vmas cannot have an
1590 * userfaultfd_ctx registered on them, but this
1591 * provides for more strict behavior to notice
1592 * unregistration errors.
1594 if (!vma_can_userfault(cur, cur->vm_flags))
1601 mas_set(&mas, start);
1602 prev = mas_prev(&mas, 0);
1604 mas_next(&mas, ULONG_MAX);
1610 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1613 * Nothing to do: this vma is already registered into this
1614 * userfaultfd and with the right tracking mode too.
1616 if (!vma->vm_userfaultfd_ctx.ctx)
1619 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1621 if (vma->vm_start > start)
1622 start = vma->vm_start;
1623 vma_end = min(end, vma->vm_end);
1625 if (userfaultfd_missing(vma)) {
1627 * Wake any concurrent pending userfault while
1628 * we unregister, so they will not hang
1629 * permanently and it avoids userland to call
1630 * UFFDIO_WAKE explicitly.
1632 struct userfaultfd_wake_range range;
1633 range.start = start;
1634 range.len = vma_end - start;
1635 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1638 /* Reset ptes for the whole vma range if wr-protected */
1639 if (userfaultfd_wp(vma))
1640 uffd_wp_range(mm, vma, start, vma_end - start, false);
1642 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1643 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1644 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1646 NULL_VM_UFFD_CTX, anon_vma_name(vma));
1652 if (vma->vm_start < start) {
1653 ret = split_vma(mm, vma, start, 1);
1658 if (vma->vm_end > end) {
1659 ret = split_vma(mm, vma, end, 0);
1666 * In the vma_merge() successful mprotect-like case 8:
1667 * the next vma was merged into the current one and
1668 * the current one has not been updated yet.
1670 userfaultfd_set_vm_flags(vma, new_flags);
1671 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1675 start = vma->vm_end;
1676 vma = mas_next(&mas, end - 1);
1679 mmap_write_unlock(mm);
1686 * userfaultfd_wake may be used in combination with the
1687 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1689 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1693 struct uffdio_range uffdio_wake;
1694 struct userfaultfd_wake_range range;
1695 const void __user *buf = (void __user *)arg;
1698 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1701 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1705 range.start = uffdio_wake.start;
1706 range.len = uffdio_wake.len;
1709 * len == 0 means wake all and we don't want to wake all here,
1710 * so check it again to be sure.
1712 VM_BUG_ON(!range.len);
1714 wake_userfault(ctx, &range);
1721 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1725 struct uffdio_copy uffdio_copy;
1726 struct uffdio_copy __user *user_uffdio_copy;
1727 struct userfaultfd_wake_range range;
1729 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1732 if (atomic_read(&ctx->mmap_changing))
1736 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1737 /* don't copy "copy" last field */
1738 sizeof(uffdio_copy)-sizeof(__s64)))
1741 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1745 * double check for wraparound just in case. copy_from_user()
1746 * will later check uffdio_copy.src + uffdio_copy.len to fit
1747 * in the userland range.
1750 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1752 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1754 if (mmget_not_zero(ctx->mm)) {
1755 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1756 uffdio_copy.len, &ctx->mmap_changing,
1762 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1767 /* len == 0 would wake all */
1769 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1770 range.start = uffdio_copy.dst;
1771 wake_userfault(ctx, &range);
1773 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1778 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1782 struct uffdio_zeropage uffdio_zeropage;
1783 struct uffdio_zeropage __user *user_uffdio_zeropage;
1784 struct userfaultfd_wake_range range;
1786 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1789 if (atomic_read(&ctx->mmap_changing))
1793 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1794 /* don't copy "zeropage" last field */
1795 sizeof(uffdio_zeropage)-sizeof(__s64)))
1798 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1799 uffdio_zeropage.range.len);
1803 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1806 if (mmget_not_zero(ctx->mm)) {
1807 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1808 uffdio_zeropage.range.len,
1809 &ctx->mmap_changing);
1814 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1818 /* len == 0 would wake all */
1821 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1822 range.start = uffdio_zeropage.range.start;
1823 wake_userfault(ctx, &range);
1825 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1830 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1834 struct uffdio_writeprotect uffdio_wp;
1835 struct uffdio_writeprotect __user *user_uffdio_wp;
1836 struct userfaultfd_wake_range range;
1837 bool mode_wp, mode_dontwake;
1839 if (atomic_read(&ctx->mmap_changing))
1842 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1844 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1845 sizeof(struct uffdio_writeprotect)))
1848 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1849 uffdio_wp.range.len);
1853 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1854 UFFDIO_WRITEPROTECT_MODE_WP))
1857 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1858 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1860 if (mode_wp && mode_dontwake)
1863 if (mmget_not_zero(ctx->mm)) {
1864 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1865 uffdio_wp.range.len, mode_wp,
1866 &ctx->mmap_changing);
1875 if (!mode_wp && !mode_dontwake) {
1876 range.start = uffdio_wp.range.start;
1877 range.len = uffdio_wp.range.len;
1878 wake_userfault(ctx, &range);
1883 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1886 struct uffdio_continue uffdio_continue;
1887 struct uffdio_continue __user *user_uffdio_continue;
1888 struct userfaultfd_wake_range range;
1890 user_uffdio_continue = (struct uffdio_continue __user *)arg;
1893 if (atomic_read(&ctx->mmap_changing))
1897 if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1898 /* don't copy the output fields */
1899 sizeof(uffdio_continue) - (sizeof(__s64))))
1902 ret = validate_range(ctx->mm, uffdio_continue.range.start,
1903 uffdio_continue.range.len);
1908 /* double check for wraparound just in case. */
1909 if (uffdio_continue.range.start + uffdio_continue.range.len <=
1910 uffdio_continue.range.start) {
1913 if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1916 if (mmget_not_zero(ctx->mm)) {
1917 ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1918 uffdio_continue.range.len,
1919 &ctx->mmap_changing);
1925 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1930 /* len == 0 would wake all */
1933 if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1934 range.start = uffdio_continue.range.start;
1935 wake_userfault(ctx, &range);
1937 ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1943 static inline unsigned int uffd_ctx_features(__u64 user_features)
1946 * For the current set of features the bits just coincide. Set
1947 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1949 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1953 * userland asks for a certain API version and we return which bits
1954 * and ioctl commands are implemented in this kernel for such API
1955 * version or -EINVAL if unknown.
1957 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1960 struct uffdio_api uffdio_api;
1961 void __user *buf = (void __user *)arg;
1962 unsigned int ctx_features;
1967 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1969 features = uffdio_api.features;
1971 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
1974 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1976 /* report all available features and ioctls to userland */
1977 uffdio_api.features = UFFD_API_FEATURES;
1978 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1979 uffdio_api.features &=
1980 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1982 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1983 uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1985 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1986 uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1988 uffdio_api.ioctls = UFFD_API_IOCTLS;
1990 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1993 /* only enable the requested features for this uffd context */
1994 ctx_features = uffd_ctx_features(features);
1996 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
2003 memset(&uffdio_api, 0, sizeof(uffdio_api));
2004 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2009 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2013 struct userfaultfd_ctx *ctx = file->private_data;
2015 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2020 ret = userfaultfd_api(ctx, arg);
2022 case UFFDIO_REGISTER:
2023 ret = userfaultfd_register(ctx, arg);
2025 case UFFDIO_UNREGISTER:
2026 ret = userfaultfd_unregister(ctx, arg);
2029 ret = userfaultfd_wake(ctx, arg);
2032 ret = userfaultfd_copy(ctx, arg);
2034 case UFFDIO_ZEROPAGE:
2035 ret = userfaultfd_zeropage(ctx, arg);
2037 case UFFDIO_WRITEPROTECT:
2038 ret = userfaultfd_writeprotect(ctx, arg);
2040 case UFFDIO_CONTINUE:
2041 ret = userfaultfd_continue(ctx, arg);
2047 #ifdef CONFIG_PROC_FS
2048 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2050 struct userfaultfd_ctx *ctx = f->private_data;
2051 wait_queue_entry_t *wq;
2052 unsigned long pending = 0, total = 0;
2054 spin_lock_irq(&ctx->fault_pending_wqh.lock);
2055 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2059 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2062 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2065 * If more protocols will be added, there will be all shown
2066 * separated by a space. Like this:
2067 * protocols: aa:... bb:...
2069 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2070 pending, total, UFFD_API, ctx->features,
2071 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2075 static const struct file_operations userfaultfd_fops = {
2076 #ifdef CONFIG_PROC_FS
2077 .show_fdinfo = userfaultfd_show_fdinfo,
2079 .release = userfaultfd_release,
2080 .poll = userfaultfd_poll,
2081 .read = userfaultfd_read,
2082 .unlocked_ioctl = userfaultfd_ioctl,
2083 .compat_ioctl = compat_ptr_ioctl,
2084 .llseek = noop_llseek,
2087 static void init_once_userfaultfd_ctx(void *mem)
2089 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2091 init_waitqueue_head(&ctx->fault_pending_wqh);
2092 init_waitqueue_head(&ctx->fault_wqh);
2093 init_waitqueue_head(&ctx->event_wqh);
2094 init_waitqueue_head(&ctx->fd_wqh);
2095 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2098 static int new_userfaultfd(int flags)
2100 struct userfaultfd_ctx *ctx;
2103 BUG_ON(!current->mm);
2105 /* Check the UFFD_* constants for consistency. */
2106 BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2107 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2108 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2110 if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2113 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2117 refcount_set(&ctx->refcount, 1);
2120 ctx->released = false;
2121 atomic_set(&ctx->mmap_changing, 0);
2122 ctx->mm = current->mm;
2123 /* prevent the mm struct to be freed */
2126 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2127 O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2130 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2135 static inline bool userfaultfd_syscall_allowed(int flags)
2137 /* Userspace-only page faults are always allowed */
2138 if (flags & UFFD_USER_MODE_ONLY)
2142 * The user is requesting a userfaultfd which can handle kernel faults.
2143 * Privileged users are always allowed to do this.
2145 if (capable(CAP_SYS_PTRACE))
2148 /* Otherwise, access to kernel fault handling is sysctl controlled. */
2149 return sysctl_unprivileged_userfaultfd;
2152 SYSCALL_DEFINE1(userfaultfd, int, flags)
2154 if (!userfaultfd_syscall_allowed(flags))
2157 return new_userfaultfd(flags);
2160 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2162 if (cmd != USERFAULTFD_IOC_NEW)
2165 return new_userfaultfd(flags);
2168 static const struct file_operations userfaultfd_dev_fops = {
2169 .unlocked_ioctl = userfaultfd_dev_ioctl,
2170 .compat_ioctl = userfaultfd_dev_ioctl,
2171 .owner = THIS_MODULE,
2172 .llseek = noop_llseek,
2175 static struct miscdevice userfaultfd_misc = {
2176 .minor = MISC_DYNAMIC_MINOR,
2177 .name = "userfaultfd",
2178 .fops = &userfaultfd_dev_fops
2181 static int __init userfaultfd_init(void)
2185 ret = misc_register(&userfaultfd_misc);
2189 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2190 sizeof(struct userfaultfd_ctx),
2192 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2193 init_once_userfaultfd_ctx);
2196 __initcall(userfaultfd_init);