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>
33 int sysctl_unprivileged_userfaultfd __read_mostly;
35 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
38 * Start with fault_pending_wqh and fault_wqh so they're more likely
39 * to be in the same cacheline.
43 * fault_pending_wqh.lock
47 * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
48 * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
49 * also taken in IRQ context.
51 struct userfaultfd_ctx {
52 /* waitqueue head for the pending (i.e. not read) userfaults */
53 wait_queue_head_t fault_pending_wqh;
54 /* waitqueue head for the userfaults */
55 wait_queue_head_t fault_wqh;
56 /* waitqueue head for the pseudo fd to wakeup poll/read */
57 wait_queue_head_t fd_wqh;
58 /* waitqueue head for events */
59 wait_queue_head_t event_wqh;
60 /* a refile sequence protected by fault_pending_wqh lock */
61 seqcount_spinlock_t refile_seq;
62 /* pseudo fd refcounting */
64 /* userfaultfd syscall flags */
66 /* features requested from the userspace */
67 unsigned int features;
70 /* memory mappings are changing because of non-cooperative event */
71 atomic_t mmap_changing;
72 /* mm with one ore more vmas attached to this userfaultfd_ctx */
76 struct userfaultfd_fork_ctx {
77 struct userfaultfd_ctx *orig;
78 struct userfaultfd_ctx *new;
79 struct list_head list;
82 struct userfaultfd_unmap_ctx {
83 struct userfaultfd_ctx *ctx;
86 struct list_head list;
89 struct userfaultfd_wait_queue {
91 wait_queue_entry_t wq;
92 struct userfaultfd_ctx *ctx;
96 struct userfaultfd_wake_range {
101 /* internal indication that UFFD_API ioctl was successfully executed */
102 #define UFFD_FEATURE_INITIALIZED (1u << 31)
104 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
106 return ctx->features & UFFD_FEATURE_INITIALIZED;
109 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
110 int wake_flags, void *key)
112 struct userfaultfd_wake_range *range = key;
114 struct userfaultfd_wait_queue *uwq;
115 unsigned long start, len;
117 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
119 /* len == 0 means wake all */
120 start = range->start;
122 if (len && (start > uwq->msg.arg.pagefault.address ||
123 start + len <= uwq->msg.arg.pagefault.address))
125 WRITE_ONCE(uwq->waken, true);
127 * The Program-Order guarantees provided by the scheduler
128 * ensure uwq->waken is visible before the task is woken.
130 ret = wake_up_state(wq->private, mode);
133 * Wake only once, autoremove behavior.
135 * After the effect of list_del_init is visible to the other
136 * CPUs, the waitqueue may disappear from under us, see the
137 * !list_empty_careful() in handle_userfault().
139 * try_to_wake_up() has an implicit smp_mb(), and the
140 * wq->private is read before calling the extern function
141 * "wake_up_state" (which in turns calls try_to_wake_up).
143 list_del_init(&wq->entry);
150 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
152 * @ctx: [in] Pointer to the userfaultfd context.
154 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
156 refcount_inc(&ctx->refcount);
160 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
162 * @ctx: [in] Pointer to userfaultfd context.
164 * The userfaultfd context reference must have been previously acquired either
165 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
167 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
169 if (refcount_dec_and_test(&ctx->refcount)) {
170 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
171 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
172 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
173 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
174 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
175 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
176 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
177 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
179 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
183 static inline void msg_init(struct uffd_msg *msg)
185 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
187 * Must use memset to zero out the paddings or kernel data is
188 * leaked to userland.
190 memset(msg, 0, sizeof(struct uffd_msg));
193 static inline struct uffd_msg userfault_msg(unsigned long address,
195 unsigned long reason,
196 unsigned int features)
200 msg.event = UFFD_EVENT_PAGEFAULT;
201 msg.arg.pagefault.address = address;
203 * These flags indicate why the userfault occurred:
204 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
205 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
206 * - Neither of these flags being set indicates a MISSING fault.
208 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
209 * fault. Otherwise, it was a read fault.
211 if (flags & FAULT_FLAG_WRITE)
212 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
213 if (reason & VM_UFFD_WP)
214 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
215 if (reason & VM_UFFD_MINOR)
216 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
217 if (features & UFFD_FEATURE_THREAD_ID)
218 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
222 #ifdef CONFIG_HUGETLB_PAGE
224 * Same functionality as userfaultfd_must_wait below with modifications for
227 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
228 struct vm_area_struct *vma,
229 unsigned long address,
231 unsigned long reason)
233 struct mm_struct *mm = ctx->mm;
237 mmap_assert_locked(mm);
239 ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
245 pte = huge_ptep_get(ptep);
248 * Lockless access: we're in a wait_event so it's ok if it
251 if (huge_pte_none(pte))
253 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
259 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
260 struct vm_area_struct *vma,
261 unsigned long address,
263 unsigned long reason)
265 return false; /* should never get here */
267 #endif /* CONFIG_HUGETLB_PAGE */
270 * Verify the pagetables are still not ok after having reigstered into
271 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
272 * userfault that has already been resolved, if userfaultfd_read and
273 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
276 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
277 unsigned long address,
279 unsigned long reason)
281 struct mm_struct *mm = ctx->mm;
289 mmap_assert_locked(mm);
291 pgd = pgd_offset(mm, address);
292 if (!pgd_present(*pgd))
294 p4d = p4d_offset(pgd, address);
295 if (!p4d_present(*p4d))
297 pud = pud_offset(p4d, address);
298 if (!pud_present(*pud))
300 pmd = pmd_offset(pud, address);
302 * READ_ONCE must function as a barrier with narrower scope
303 * and it must be equivalent to:
304 * _pmd = *pmd; barrier();
306 * This is to deal with the instability (as in
307 * pmd_trans_unstable) of the pmd.
309 _pmd = READ_ONCE(*pmd);
314 if (!pmd_present(_pmd))
317 if (pmd_trans_huge(_pmd)) {
318 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
324 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
325 * and use the standard pte_offset_map() instead of parsing _pmd.
327 pte = pte_offset_map(pmd, address);
329 * Lockless access: we're in a wait_event so it's ok if it
334 if (!pte_write(*pte) && (reason & VM_UFFD_WP))
342 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
344 if (flags & FAULT_FLAG_INTERRUPTIBLE)
345 return TASK_INTERRUPTIBLE;
347 if (flags & FAULT_FLAG_KILLABLE)
348 return TASK_KILLABLE;
350 return TASK_UNINTERRUPTIBLE;
354 * The locking rules involved in returning VM_FAULT_RETRY depending on
355 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
356 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
357 * recommendation in __lock_page_or_retry is not an understatement.
359 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
360 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
363 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
364 * set, VM_FAULT_RETRY can still be returned if and only if there are
365 * fatal_signal_pending()s, and the mmap_lock must be released before
368 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
370 struct mm_struct *mm = vmf->vma->vm_mm;
371 struct userfaultfd_ctx *ctx;
372 struct userfaultfd_wait_queue uwq;
373 vm_fault_t ret = VM_FAULT_SIGBUS;
375 unsigned int blocking_state;
378 * We don't do userfault handling for the final child pid update.
380 * We also don't do userfault handling during
381 * coredumping. hugetlbfs has the special
382 * follow_hugetlb_page() to skip missing pages in the
383 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
384 * the no_page_table() helper in follow_page_mask(), but the
385 * shmem_vm_ops->fault method is invoked even during
386 * coredumping without mmap_lock and it ends up here.
388 if (current->flags & (PF_EXITING|PF_DUMPCORE))
392 * Coredumping runs without mmap_lock so we can only check that
393 * the mmap_lock is held, if PF_DUMPCORE was not set.
395 mmap_assert_locked(mm);
397 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
401 BUG_ON(ctx->mm != mm);
403 /* Any unrecognized flag is a bug. */
404 VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
405 /* 0 or > 1 flags set is a bug; we expect exactly 1. */
406 VM_BUG_ON(!reason || (reason & (reason - 1)));
408 if (ctx->features & UFFD_FEATURE_SIGBUS)
410 if ((vmf->flags & FAULT_FLAG_USER) == 0 &&
411 ctx->flags & UFFD_USER_MODE_ONLY) {
412 printk_once(KERN_WARNING "uffd: Set unprivileged_userfaultfd "
413 "sysctl knob to 1 if kernel faults must be handled "
414 "without obtaining CAP_SYS_PTRACE capability\n");
419 * If it's already released don't get it. This avoids to loop
420 * in __get_user_pages if userfaultfd_release waits on the
421 * caller of handle_userfault to release the mmap_lock.
423 if (unlikely(READ_ONCE(ctx->released))) {
425 * Don't return VM_FAULT_SIGBUS in this case, so a non
426 * cooperative manager can close the uffd after the
427 * last UFFDIO_COPY, without risking to trigger an
428 * involuntary SIGBUS if the process was starting the
429 * userfaultfd while the userfaultfd was still armed
430 * (but after the last UFFDIO_COPY). If the uffd
431 * wasn't already closed when the userfault reached
432 * this point, that would normally be solved by
433 * userfaultfd_must_wait returning 'false'.
435 * If we were to return VM_FAULT_SIGBUS here, the non
436 * cooperative manager would be instead forced to
437 * always call UFFDIO_UNREGISTER before it can safely
440 ret = VM_FAULT_NOPAGE;
445 * Check that we can return VM_FAULT_RETRY.
447 * NOTE: it should become possible to return VM_FAULT_RETRY
448 * even if FAULT_FLAG_TRIED is set without leading to gup()
449 * -EBUSY failures, if the userfaultfd is to be extended for
450 * VM_UFFD_WP tracking and we intend to arm the userfault
451 * without first stopping userland access to the memory. For
452 * VM_UFFD_MISSING userfaults this is enough for now.
454 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
456 * Validate the invariant that nowait must allow retry
457 * to be sure not to return SIGBUS erroneously on
458 * nowait invocations.
460 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
461 #ifdef CONFIG_DEBUG_VM
462 if (printk_ratelimit()) {
464 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
473 * Handle nowait, not much to do other than tell it to retry
476 ret = VM_FAULT_RETRY;
477 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
480 /* take the reference before dropping the mmap_lock */
481 userfaultfd_ctx_get(ctx);
483 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
484 uwq.wq.private = current;
485 uwq.msg = userfault_msg(vmf->address, vmf->flags, reason,
490 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
492 spin_lock_irq(&ctx->fault_pending_wqh.lock);
494 * After the __add_wait_queue the uwq is visible to userland
495 * through poll/read().
497 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
499 * The smp_mb() after __set_current_state prevents the reads
500 * following the spin_unlock to happen before the list_add in
503 set_current_state(blocking_state);
504 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
506 if (!is_vm_hugetlb_page(vmf->vma))
507 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
510 must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
513 mmap_read_unlock(mm);
515 if (likely(must_wait && !READ_ONCE(ctx->released))) {
516 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
520 __set_current_state(TASK_RUNNING);
523 * Here we race with the list_del; list_add in
524 * userfaultfd_ctx_read(), however because we don't ever run
525 * list_del_init() to refile across the two lists, the prev
526 * and next pointers will never point to self. list_add also
527 * would never let any of the two pointers to point to
528 * self. So list_empty_careful won't risk to see both pointers
529 * pointing to self at any time during the list refile. The
530 * only case where list_del_init() is called is the full
531 * removal in the wake function and there we don't re-list_add
532 * and it's fine not to block on the spinlock. The uwq on this
533 * kernel stack can be released after the list_del_init.
535 if (!list_empty_careful(&uwq.wq.entry)) {
536 spin_lock_irq(&ctx->fault_pending_wqh.lock);
538 * No need of list_del_init(), the uwq on the stack
539 * will be freed shortly anyway.
541 list_del(&uwq.wq.entry);
542 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
546 * ctx may go away after this if the userfault pseudo fd is
549 userfaultfd_ctx_put(ctx);
555 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
556 struct userfaultfd_wait_queue *ewq)
558 struct userfaultfd_ctx *release_new_ctx;
560 if (WARN_ON_ONCE(current->flags & PF_EXITING))
564 init_waitqueue_entry(&ewq->wq, current);
565 release_new_ctx = NULL;
567 spin_lock_irq(&ctx->event_wqh.lock);
569 * After the __add_wait_queue the uwq is visible to userland
570 * through poll/read().
572 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
574 set_current_state(TASK_KILLABLE);
575 if (ewq->msg.event == 0)
577 if (READ_ONCE(ctx->released) ||
578 fatal_signal_pending(current)) {
580 * &ewq->wq may be queued in fork_event, but
581 * __remove_wait_queue ignores the head
582 * parameter. It would be a problem if it
585 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
586 if (ewq->msg.event == UFFD_EVENT_FORK) {
587 struct userfaultfd_ctx *new;
589 new = (struct userfaultfd_ctx *)
591 ewq->msg.arg.reserved.reserved1;
592 release_new_ctx = new;
597 spin_unlock_irq(&ctx->event_wqh.lock);
599 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
602 spin_lock_irq(&ctx->event_wqh.lock);
604 __set_current_state(TASK_RUNNING);
605 spin_unlock_irq(&ctx->event_wqh.lock);
607 if (release_new_ctx) {
608 struct vm_area_struct *vma;
609 struct mm_struct *mm = release_new_ctx->mm;
611 /* the various vma->vm_userfaultfd_ctx still points to it */
613 for (vma = mm->mmap; vma; vma = vma->vm_next)
614 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
615 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
616 vma->vm_flags &= ~__VM_UFFD_FLAGS;
618 mmap_write_unlock(mm);
620 userfaultfd_ctx_put(release_new_ctx);
624 * ctx may go away after this if the userfault pseudo fd is
628 atomic_dec(&ctx->mmap_changing);
629 VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
630 userfaultfd_ctx_put(ctx);
633 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
634 struct userfaultfd_wait_queue *ewq)
637 wake_up_locked(&ctx->event_wqh);
638 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
641 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
643 struct userfaultfd_ctx *ctx = NULL, *octx;
644 struct userfaultfd_fork_ctx *fctx;
646 octx = vma->vm_userfaultfd_ctx.ctx;
647 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
648 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
649 vma->vm_flags &= ~__VM_UFFD_FLAGS;
653 list_for_each_entry(fctx, fcs, list)
654 if (fctx->orig == octx) {
660 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
664 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
670 refcount_set(&ctx->refcount, 1);
671 ctx->flags = octx->flags;
672 ctx->features = octx->features;
673 ctx->released = false;
674 atomic_set(&ctx->mmap_changing, 0);
675 ctx->mm = vma->vm_mm;
678 userfaultfd_ctx_get(octx);
679 atomic_inc(&octx->mmap_changing);
682 list_add_tail(&fctx->list, fcs);
685 vma->vm_userfaultfd_ctx.ctx = ctx;
689 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
691 struct userfaultfd_ctx *ctx = fctx->orig;
692 struct userfaultfd_wait_queue ewq;
696 ewq.msg.event = UFFD_EVENT_FORK;
697 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
699 userfaultfd_event_wait_completion(ctx, &ewq);
702 void dup_userfaultfd_complete(struct list_head *fcs)
704 struct userfaultfd_fork_ctx *fctx, *n;
706 list_for_each_entry_safe(fctx, n, fcs, list) {
708 list_del(&fctx->list);
713 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
714 struct vm_userfaultfd_ctx *vm_ctx)
716 struct userfaultfd_ctx *ctx;
718 ctx = vma->vm_userfaultfd_ctx.ctx;
723 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
725 userfaultfd_ctx_get(ctx);
726 atomic_inc(&ctx->mmap_changing);
728 /* Drop uffd context if remap feature not enabled */
729 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
730 vma->vm_flags &= ~__VM_UFFD_FLAGS;
734 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
735 unsigned long from, unsigned long to,
738 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
739 struct userfaultfd_wait_queue ewq;
744 if (to & ~PAGE_MASK) {
745 userfaultfd_ctx_put(ctx);
751 ewq.msg.event = UFFD_EVENT_REMAP;
752 ewq.msg.arg.remap.from = from;
753 ewq.msg.arg.remap.to = to;
754 ewq.msg.arg.remap.len = len;
756 userfaultfd_event_wait_completion(ctx, &ewq);
759 bool userfaultfd_remove(struct vm_area_struct *vma,
760 unsigned long start, unsigned long end)
762 struct mm_struct *mm = vma->vm_mm;
763 struct userfaultfd_ctx *ctx;
764 struct userfaultfd_wait_queue ewq;
766 ctx = vma->vm_userfaultfd_ctx.ctx;
767 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
770 userfaultfd_ctx_get(ctx);
771 atomic_inc(&ctx->mmap_changing);
772 mmap_read_unlock(mm);
776 ewq.msg.event = UFFD_EVENT_REMOVE;
777 ewq.msg.arg.remove.start = start;
778 ewq.msg.arg.remove.end = end;
780 userfaultfd_event_wait_completion(ctx, &ewq);
785 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
786 unsigned long start, unsigned long end)
788 struct userfaultfd_unmap_ctx *unmap_ctx;
790 list_for_each_entry(unmap_ctx, unmaps, list)
791 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
792 unmap_ctx->end == end)
798 int userfaultfd_unmap_prep(struct vm_area_struct *vma,
799 unsigned long start, unsigned long end,
800 struct list_head *unmaps)
802 for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
803 struct userfaultfd_unmap_ctx *unmap_ctx;
804 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
806 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
807 has_unmap_ctx(ctx, unmaps, start, end))
810 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
814 userfaultfd_ctx_get(ctx);
815 atomic_inc(&ctx->mmap_changing);
816 unmap_ctx->ctx = ctx;
817 unmap_ctx->start = start;
818 unmap_ctx->end = end;
819 list_add_tail(&unmap_ctx->list, unmaps);
825 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
827 struct userfaultfd_unmap_ctx *ctx, *n;
828 struct userfaultfd_wait_queue ewq;
830 list_for_each_entry_safe(ctx, n, uf, list) {
833 ewq.msg.event = UFFD_EVENT_UNMAP;
834 ewq.msg.arg.remove.start = ctx->start;
835 ewq.msg.arg.remove.end = ctx->end;
837 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
839 list_del(&ctx->list);
844 static int userfaultfd_release(struct inode *inode, struct file *file)
846 struct userfaultfd_ctx *ctx = file->private_data;
847 struct mm_struct *mm = ctx->mm;
848 struct vm_area_struct *vma, *prev;
849 /* len == 0 means wake all */
850 struct userfaultfd_wake_range range = { .len = 0, };
851 unsigned long new_flags;
853 WRITE_ONCE(ctx->released, true);
855 if (!mmget_not_zero(mm))
859 * Flush page faults out of all CPUs. NOTE: all page faults
860 * must be retried without returning VM_FAULT_SIGBUS if
861 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
862 * changes while handle_userfault released the mmap_lock. So
863 * it's critical that released is set to true (above), before
864 * taking the mmap_lock for writing.
868 for (vma = mm->mmap; vma; vma = vma->vm_next) {
870 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
871 !!(vma->vm_flags & __VM_UFFD_FLAGS));
872 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
876 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
877 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
878 new_flags, vma->anon_vma,
879 vma->vm_file, vma->vm_pgoff,
881 NULL_VM_UFFD_CTX, anon_vma_name(vma));
886 vma->vm_flags = new_flags;
887 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
889 mmap_write_unlock(mm);
893 * After no new page faults can wait on this fault_*wqh, flush
894 * the last page faults that may have been already waiting on
897 spin_lock_irq(&ctx->fault_pending_wqh.lock);
898 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
899 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
900 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
902 /* Flush pending events that may still wait on event_wqh */
903 wake_up_all(&ctx->event_wqh);
905 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
906 userfaultfd_ctx_put(ctx);
910 /* fault_pending_wqh.lock must be hold by the caller */
911 static inline struct userfaultfd_wait_queue *find_userfault_in(
912 wait_queue_head_t *wqh)
914 wait_queue_entry_t *wq;
915 struct userfaultfd_wait_queue *uwq;
917 lockdep_assert_held(&wqh->lock);
920 if (!waitqueue_active(wqh))
922 /* walk in reverse to provide FIFO behavior to read userfaults */
923 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
924 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
929 static inline struct userfaultfd_wait_queue *find_userfault(
930 struct userfaultfd_ctx *ctx)
932 return find_userfault_in(&ctx->fault_pending_wqh);
935 static inline struct userfaultfd_wait_queue *find_userfault_evt(
936 struct userfaultfd_ctx *ctx)
938 return find_userfault_in(&ctx->event_wqh);
941 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
943 struct userfaultfd_ctx *ctx = file->private_data;
946 poll_wait(file, &ctx->fd_wqh, wait);
948 if (!userfaultfd_is_initialized(ctx))
952 * poll() never guarantees that read won't block.
953 * userfaults can be waken before they're read().
955 if (unlikely(!(file->f_flags & O_NONBLOCK)))
958 * lockless access to see if there are pending faults
959 * __pollwait last action is the add_wait_queue but
960 * the spin_unlock would allow the waitqueue_active to
961 * pass above the actual list_add inside
962 * add_wait_queue critical section. So use a full
963 * memory barrier to serialize the list_add write of
964 * add_wait_queue() with the waitqueue_active read
969 if (waitqueue_active(&ctx->fault_pending_wqh))
971 else if (waitqueue_active(&ctx->event_wqh))
977 static const struct file_operations userfaultfd_fops;
979 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
981 struct uffd_msg *msg)
985 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
986 O_RDWR | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
990 msg->arg.reserved.reserved1 = 0;
991 msg->arg.fork.ufd = fd;
995 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
996 struct uffd_msg *msg, struct inode *inode)
999 DECLARE_WAITQUEUE(wait, current);
1000 struct userfaultfd_wait_queue *uwq;
1002 * Handling fork event requires sleeping operations, so
1003 * we drop the event_wqh lock, then do these ops, then
1004 * lock it back and wake up the waiter. While the lock is
1005 * dropped the ewq may go away so we keep track of it
1008 LIST_HEAD(fork_event);
1009 struct userfaultfd_ctx *fork_nctx = NULL;
1011 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1012 spin_lock_irq(&ctx->fd_wqh.lock);
1013 __add_wait_queue(&ctx->fd_wqh, &wait);
1015 set_current_state(TASK_INTERRUPTIBLE);
1016 spin_lock(&ctx->fault_pending_wqh.lock);
1017 uwq = find_userfault(ctx);
1020 * Use a seqcount to repeat the lockless check
1021 * in wake_userfault() to avoid missing
1022 * wakeups because during the refile both
1023 * waitqueue could become empty if this is the
1026 write_seqcount_begin(&ctx->refile_seq);
1029 * The fault_pending_wqh.lock prevents the uwq
1030 * to disappear from under us.
1032 * Refile this userfault from
1033 * fault_pending_wqh to fault_wqh, it's not
1034 * pending anymore after we read it.
1036 * Use list_del() by hand (as
1037 * userfaultfd_wake_function also uses
1038 * list_del_init() by hand) to be sure nobody
1039 * changes __remove_wait_queue() to use
1040 * list_del_init() in turn breaking the
1041 * !list_empty_careful() check in
1042 * handle_userfault(). The uwq->wq.head list
1043 * must never be empty at any time during the
1044 * refile, or the waitqueue could disappear
1045 * from under us. The "wait_queue_head_t"
1046 * parameter of __remove_wait_queue() is unused
1049 list_del(&uwq->wq.entry);
1050 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1052 write_seqcount_end(&ctx->refile_seq);
1054 /* careful to always initialize msg if ret == 0 */
1056 spin_unlock(&ctx->fault_pending_wqh.lock);
1060 spin_unlock(&ctx->fault_pending_wqh.lock);
1062 spin_lock(&ctx->event_wqh.lock);
1063 uwq = find_userfault_evt(ctx);
1067 if (uwq->msg.event == UFFD_EVENT_FORK) {
1068 fork_nctx = (struct userfaultfd_ctx *)
1070 uwq->msg.arg.reserved.reserved1;
1071 list_move(&uwq->wq.entry, &fork_event);
1073 * fork_nctx can be freed as soon as
1074 * we drop the lock, unless we take a
1077 userfaultfd_ctx_get(fork_nctx);
1078 spin_unlock(&ctx->event_wqh.lock);
1083 userfaultfd_event_complete(ctx, uwq);
1084 spin_unlock(&ctx->event_wqh.lock);
1088 spin_unlock(&ctx->event_wqh.lock);
1090 if (signal_pending(current)) {
1098 spin_unlock_irq(&ctx->fd_wqh.lock);
1100 spin_lock_irq(&ctx->fd_wqh.lock);
1102 __remove_wait_queue(&ctx->fd_wqh, &wait);
1103 __set_current_state(TASK_RUNNING);
1104 spin_unlock_irq(&ctx->fd_wqh.lock);
1106 if (!ret && msg->event == UFFD_EVENT_FORK) {
1107 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1108 spin_lock_irq(&ctx->event_wqh.lock);
1109 if (!list_empty(&fork_event)) {
1111 * The fork thread didn't abort, so we can
1112 * drop the temporary refcount.
1114 userfaultfd_ctx_put(fork_nctx);
1116 uwq = list_first_entry(&fork_event,
1120 * If fork_event list wasn't empty and in turn
1121 * the event wasn't already released by fork
1122 * (the event is allocated on fork kernel
1123 * stack), put the event back to its place in
1124 * the event_wq. fork_event head will be freed
1125 * as soon as we return so the event cannot
1126 * stay queued there no matter the current
1129 list_del(&uwq->wq.entry);
1130 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1133 * Leave the event in the waitqueue and report
1134 * error to userland if we failed to resolve
1135 * the userfault fork.
1138 userfaultfd_event_complete(ctx, uwq);
1141 * Here the fork thread aborted and the
1142 * refcount from the fork thread on fork_nctx
1143 * has already been released. We still hold
1144 * the reference we took before releasing the
1145 * lock above. If resolve_userfault_fork
1146 * failed we've to drop it because the
1147 * fork_nctx has to be freed in such case. If
1148 * it succeeded we'll hold it because the new
1149 * uffd references it.
1152 userfaultfd_ctx_put(fork_nctx);
1154 spin_unlock_irq(&ctx->event_wqh.lock);
1160 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1161 size_t count, loff_t *ppos)
1163 struct userfaultfd_ctx *ctx = file->private_data;
1164 ssize_t _ret, ret = 0;
1165 struct uffd_msg msg;
1166 int no_wait = file->f_flags & O_NONBLOCK;
1167 struct inode *inode = file_inode(file);
1169 if (!userfaultfd_is_initialized(ctx))
1173 if (count < sizeof(msg))
1174 return ret ? ret : -EINVAL;
1175 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1177 return ret ? ret : _ret;
1178 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1179 return ret ? ret : -EFAULT;
1182 count -= sizeof(msg);
1184 * Allow to read more than one fault at time but only
1185 * block if waiting for the very first one.
1187 no_wait = O_NONBLOCK;
1191 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1192 struct userfaultfd_wake_range *range)
1194 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1195 /* wake all in the range and autoremove */
1196 if (waitqueue_active(&ctx->fault_pending_wqh))
1197 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1199 if (waitqueue_active(&ctx->fault_wqh))
1200 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1201 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1204 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1205 struct userfaultfd_wake_range *range)
1211 * To be sure waitqueue_active() is not reordered by the CPU
1212 * before the pagetable update, use an explicit SMP memory
1213 * barrier here. PT lock release or mmap_read_unlock(mm) still
1214 * have release semantics that can allow the
1215 * waitqueue_active() to be reordered before the pte update.
1220 * Use waitqueue_active because it's very frequent to
1221 * change the address space atomically even if there are no
1222 * userfaults yet. So we take the spinlock only when we're
1223 * sure we've userfaults to wake.
1226 seq = read_seqcount_begin(&ctx->refile_seq);
1227 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1228 waitqueue_active(&ctx->fault_wqh);
1230 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1232 __wake_userfault(ctx, range);
1235 static __always_inline int validate_range(struct mm_struct *mm,
1236 __u64 start, __u64 len)
1238 __u64 task_size = mm->task_size;
1240 if (start & ~PAGE_MASK)
1242 if (len & ~PAGE_MASK)
1246 if (start < mmap_min_addr)
1248 if (start >= task_size)
1250 if (len > task_size - start)
1255 static inline bool vma_can_userfault(struct vm_area_struct *vma,
1256 unsigned long vm_flags)
1258 /* FIXME: add WP support to hugetlbfs and shmem */
1259 if (vm_flags & VM_UFFD_WP) {
1260 if (is_vm_hugetlb_page(vma) || vma_is_shmem(vma))
1264 if (vm_flags & VM_UFFD_MINOR) {
1265 if (!(is_vm_hugetlb_page(vma) || vma_is_shmem(vma)))
1269 return vma_is_anonymous(vma) || is_vm_hugetlb_page(vma) ||
1273 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1276 struct mm_struct *mm = ctx->mm;
1277 struct vm_area_struct *vma, *prev, *cur;
1279 struct uffdio_register uffdio_register;
1280 struct uffdio_register __user *user_uffdio_register;
1281 unsigned long vm_flags, new_flags;
1284 unsigned long start, end, vma_end;
1286 user_uffdio_register = (struct uffdio_register __user *) arg;
1289 if (copy_from_user(&uffdio_register, user_uffdio_register,
1290 sizeof(uffdio_register)-sizeof(__u64)))
1294 if (!uffdio_register.mode)
1296 if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1299 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1300 vm_flags |= VM_UFFD_MISSING;
1301 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1302 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1305 vm_flags |= VM_UFFD_WP;
1307 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1308 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1311 vm_flags |= VM_UFFD_MINOR;
1314 ret = validate_range(mm, uffdio_register.range.start,
1315 uffdio_register.range.len);
1319 start = uffdio_register.range.start;
1320 end = start + uffdio_register.range.len;
1323 if (!mmget_not_zero(mm))
1326 mmap_write_lock(mm);
1327 vma = find_vma_prev(mm, start, &prev);
1331 /* check that there's at least one vma in the range */
1333 if (vma->vm_start >= end)
1337 * If the first vma contains huge pages, make sure start address
1338 * is aligned to huge page size.
1340 if (is_vm_hugetlb_page(vma)) {
1341 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1343 if (start & (vma_hpagesize - 1))
1348 * Search for not compatible vmas.
1351 basic_ioctls = false;
1352 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1355 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1356 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1358 /* check not compatible vmas */
1360 if (!vma_can_userfault(cur, vm_flags))
1364 * UFFDIO_COPY will fill file holes even without
1365 * PROT_WRITE. This check enforces that if this is a
1366 * MAP_SHARED, the process has write permission to the backing
1367 * file. If VM_MAYWRITE is set it also enforces that on a
1368 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1369 * F_WRITE_SEAL can be taken until the vma is destroyed.
1372 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1376 * If this vma contains ending address, and huge pages
1379 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1380 end > cur->vm_start) {
1381 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1385 if (end & (vma_hpagesize - 1))
1388 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1392 * Check that this vma isn't already owned by a
1393 * different userfaultfd. We can't allow more than one
1394 * userfaultfd to own a single vma simultaneously or we
1395 * wouldn't know which one to deliver the userfaults to.
1398 if (cur->vm_userfaultfd_ctx.ctx &&
1399 cur->vm_userfaultfd_ctx.ctx != ctx)
1403 * Note vmas containing huge pages
1405 if (is_vm_hugetlb_page(cur))
1406 basic_ioctls = true;
1412 if (vma->vm_start < start)
1419 BUG_ON(!vma_can_userfault(vma, vm_flags));
1420 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1421 vma->vm_userfaultfd_ctx.ctx != ctx);
1422 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1425 * Nothing to do: this vma is already registered into this
1426 * userfaultfd and with the right tracking mode too.
1428 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1429 (vma->vm_flags & vm_flags) == vm_flags)
1432 if (vma->vm_start > start)
1433 start = vma->vm_start;
1434 vma_end = min(end, vma->vm_end);
1436 new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1437 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1438 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1440 ((struct vm_userfaultfd_ctx){ ctx }),
1441 anon_vma_name(vma));
1446 if (vma->vm_start < start) {
1447 ret = split_vma(mm, vma, start, 1);
1451 if (vma->vm_end > end) {
1452 ret = split_vma(mm, vma, end, 0);
1458 * In the vma_merge() successful mprotect-like case 8:
1459 * the next vma was merged into the current one and
1460 * the current one has not been updated yet.
1462 vma->vm_flags = new_flags;
1463 vma->vm_userfaultfd_ctx.ctx = ctx;
1465 if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1466 hugetlb_unshare_all_pmds(vma);
1470 start = vma->vm_end;
1472 } while (vma && vma->vm_start < end);
1474 mmap_write_unlock(mm);
1479 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1480 UFFD_API_RANGE_IOCTLS;
1483 * Declare the WP ioctl only if the WP mode is
1484 * specified and all checks passed with the range
1486 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1487 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1489 /* CONTINUE ioctl is only supported for MINOR ranges. */
1490 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1491 ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1494 * Now that we scanned all vmas we can already tell
1495 * userland which ioctls methods are guaranteed to
1496 * succeed on this range.
1498 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1505 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1508 struct mm_struct *mm = ctx->mm;
1509 struct vm_area_struct *vma, *prev, *cur;
1511 struct uffdio_range uffdio_unregister;
1512 unsigned long new_flags;
1514 unsigned long start, end, vma_end;
1515 const void __user *buf = (void __user *)arg;
1518 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1521 ret = validate_range(mm, uffdio_unregister.start,
1522 uffdio_unregister.len);
1526 start = uffdio_unregister.start;
1527 end = start + uffdio_unregister.len;
1530 if (!mmget_not_zero(mm))
1533 mmap_write_lock(mm);
1534 vma = find_vma_prev(mm, start, &prev);
1538 /* check that there's at least one vma in the range */
1540 if (vma->vm_start >= end)
1544 * If the first vma contains huge pages, make sure start address
1545 * is aligned to huge page size.
1547 if (is_vm_hugetlb_page(vma)) {
1548 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1550 if (start & (vma_hpagesize - 1))
1555 * Search for not compatible vmas.
1559 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1562 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1563 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1566 * Check not compatible vmas, not strictly required
1567 * here as not compatible vmas cannot have an
1568 * userfaultfd_ctx registered on them, but this
1569 * provides for more strict behavior to notice
1570 * unregistration errors.
1572 if (!vma_can_userfault(cur, cur->vm_flags))
1579 if (vma->vm_start < start)
1586 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1589 * Nothing to do: this vma is already registered into this
1590 * userfaultfd and with the right tracking mode too.
1592 if (!vma->vm_userfaultfd_ctx.ctx)
1595 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1597 if (vma->vm_start > start)
1598 start = vma->vm_start;
1599 vma_end = min(end, vma->vm_end);
1601 if (userfaultfd_missing(vma)) {
1603 * Wake any concurrent pending userfault while
1604 * we unregister, so they will not hang
1605 * permanently and it avoids userland to call
1606 * UFFDIO_WAKE explicitly.
1608 struct userfaultfd_wake_range range;
1609 range.start = start;
1610 range.len = vma_end - start;
1611 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1614 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1615 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1616 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1618 NULL_VM_UFFD_CTX, anon_vma_name(vma));
1623 if (vma->vm_start < start) {
1624 ret = split_vma(mm, vma, start, 1);
1628 if (vma->vm_end > end) {
1629 ret = split_vma(mm, vma, end, 0);
1635 * In the vma_merge() successful mprotect-like case 8:
1636 * the next vma was merged into the current one and
1637 * the current one has not been updated yet.
1639 vma->vm_flags = new_flags;
1640 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1644 start = vma->vm_end;
1646 } while (vma && vma->vm_start < end);
1648 mmap_write_unlock(mm);
1655 * userfaultfd_wake may be used in combination with the
1656 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1658 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1662 struct uffdio_range uffdio_wake;
1663 struct userfaultfd_wake_range range;
1664 const void __user *buf = (void __user *)arg;
1667 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1670 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1674 range.start = uffdio_wake.start;
1675 range.len = uffdio_wake.len;
1678 * len == 0 means wake all and we don't want to wake all here,
1679 * so check it again to be sure.
1681 VM_BUG_ON(!range.len);
1683 wake_userfault(ctx, &range);
1690 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1694 struct uffdio_copy uffdio_copy;
1695 struct uffdio_copy __user *user_uffdio_copy;
1696 struct userfaultfd_wake_range range;
1698 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1701 if (atomic_read(&ctx->mmap_changing))
1705 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1706 /* don't copy "copy" last field */
1707 sizeof(uffdio_copy)-sizeof(__s64)))
1710 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1714 * double check for wraparound just in case. copy_from_user()
1715 * will later check uffdio_copy.src + uffdio_copy.len to fit
1716 * in the userland range.
1719 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1721 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1723 if (mmget_not_zero(ctx->mm)) {
1724 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1725 uffdio_copy.len, &ctx->mmap_changing,
1731 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1736 /* len == 0 would wake all */
1738 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1739 range.start = uffdio_copy.dst;
1740 wake_userfault(ctx, &range);
1742 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1747 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1751 struct uffdio_zeropage uffdio_zeropage;
1752 struct uffdio_zeropage __user *user_uffdio_zeropage;
1753 struct userfaultfd_wake_range range;
1755 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1758 if (atomic_read(&ctx->mmap_changing))
1762 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1763 /* don't copy "zeropage" last field */
1764 sizeof(uffdio_zeropage)-sizeof(__s64)))
1767 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1768 uffdio_zeropage.range.len);
1772 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1775 if (mmget_not_zero(ctx->mm)) {
1776 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1777 uffdio_zeropage.range.len,
1778 &ctx->mmap_changing);
1783 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1787 /* len == 0 would wake all */
1790 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1791 range.start = uffdio_zeropage.range.start;
1792 wake_userfault(ctx, &range);
1794 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1799 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1803 struct uffdio_writeprotect uffdio_wp;
1804 struct uffdio_writeprotect __user *user_uffdio_wp;
1805 struct userfaultfd_wake_range range;
1806 bool mode_wp, mode_dontwake;
1808 if (atomic_read(&ctx->mmap_changing))
1811 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1813 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1814 sizeof(struct uffdio_writeprotect)))
1817 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1818 uffdio_wp.range.len);
1822 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1823 UFFDIO_WRITEPROTECT_MODE_WP))
1826 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1827 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1829 if (mode_wp && mode_dontwake)
1832 if (mmget_not_zero(ctx->mm)) {
1833 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1834 uffdio_wp.range.len, mode_wp,
1835 &ctx->mmap_changing);
1844 if (!mode_wp && !mode_dontwake) {
1845 range.start = uffdio_wp.range.start;
1846 range.len = uffdio_wp.range.len;
1847 wake_userfault(ctx, &range);
1852 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1855 struct uffdio_continue uffdio_continue;
1856 struct uffdio_continue __user *user_uffdio_continue;
1857 struct userfaultfd_wake_range range;
1859 user_uffdio_continue = (struct uffdio_continue __user *)arg;
1862 if (atomic_read(&ctx->mmap_changing))
1866 if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1867 /* don't copy the output fields */
1868 sizeof(uffdio_continue) - (sizeof(__s64))))
1871 ret = validate_range(ctx->mm, uffdio_continue.range.start,
1872 uffdio_continue.range.len);
1877 /* double check for wraparound just in case. */
1878 if (uffdio_continue.range.start + uffdio_continue.range.len <=
1879 uffdio_continue.range.start) {
1882 if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1885 if (mmget_not_zero(ctx->mm)) {
1886 ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1887 uffdio_continue.range.len,
1888 &ctx->mmap_changing);
1894 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1899 /* len == 0 would wake all */
1902 if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1903 range.start = uffdio_continue.range.start;
1904 wake_userfault(ctx, &range);
1906 ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1912 static inline unsigned int uffd_ctx_features(__u64 user_features)
1915 * For the current set of features the bits just coincide. Set
1916 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1918 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1922 * userland asks for a certain API version and we return which bits
1923 * and ioctl commands are implemented in this kernel for such API
1924 * version or -EINVAL if unknown.
1926 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1929 struct uffdio_api uffdio_api;
1930 void __user *buf = (void __user *)arg;
1931 unsigned int ctx_features;
1936 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1938 features = uffdio_api.features;
1940 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
1943 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1945 /* report all available features and ioctls to userland */
1946 uffdio_api.features = UFFD_API_FEATURES;
1947 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1948 uffdio_api.features &=
1949 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1951 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1952 uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1954 uffdio_api.ioctls = UFFD_API_IOCTLS;
1956 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1959 /* only enable the requested features for this uffd context */
1960 ctx_features = uffd_ctx_features(features);
1962 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1969 memset(&uffdio_api, 0, sizeof(uffdio_api));
1970 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1975 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1979 struct userfaultfd_ctx *ctx = file->private_data;
1981 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
1986 ret = userfaultfd_api(ctx, arg);
1988 case UFFDIO_REGISTER:
1989 ret = userfaultfd_register(ctx, arg);
1991 case UFFDIO_UNREGISTER:
1992 ret = userfaultfd_unregister(ctx, arg);
1995 ret = userfaultfd_wake(ctx, arg);
1998 ret = userfaultfd_copy(ctx, arg);
2000 case UFFDIO_ZEROPAGE:
2001 ret = userfaultfd_zeropage(ctx, arg);
2003 case UFFDIO_WRITEPROTECT:
2004 ret = userfaultfd_writeprotect(ctx, arg);
2006 case UFFDIO_CONTINUE:
2007 ret = userfaultfd_continue(ctx, arg);
2013 #ifdef CONFIG_PROC_FS
2014 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2016 struct userfaultfd_ctx *ctx = f->private_data;
2017 wait_queue_entry_t *wq;
2018 unsigned long pending = 0, total = 0;
2020 spin_lock_irq(&ctx->fault_pending_wqh.lock);
2021 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2025 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2028 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2031 * If more protocols will be added, there will be all shown
2032 * separated by a space. Like this:
2033 * protocols: aa:... bb:...
2035 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2036 pending, total, UFFD_API, ctx->features,
2037 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2041 static const struct file_operations userfaultfd_fops = {
2042 #ifdef CONFIG_PROC_FS
2043 .show_fdinfo = userfaultfd_show_fdinfo,
2045 .release = userfaultfd_release,
2046 .poll = userfaultfd_poll,
2047 .read = userfaultfd_read,
2048 .unlocked_ioctl = userfaultfd_ioctl,
2049 .compat_ioctl = compat_ptr_ioctl,
2050 .llseek = noop_llseek,
2053 static void init_once_userfaultfd_ctx(void *mem)
2055 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2057 init_waitqueue_head(&ctx->fault_pending_wqh);
2058 init_waitqueue_head(&ctx->fault_wqh);
2059 init_waitqueue_head(&ctx->event_wqh);
2060 init_waitqueue_head(&ctx->fd_wqh);
2061 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2064 SYSCALL_DEFINE1(userfaultfd, int, flags)
2066 struct userfaultfd_ctx *ctx;
2069 if (!sysctl_unprivileged_userfaultfd &&
2070 (flags & UFFD_USER_MODE_ONLY) == 0 &&
2071 !capable(CAP_SYS_PTRACE)) {
2072 printk_once(KERN_WARNING "uffd: Set unprivileged_userfaultfd "
2073 "sysctl knob to 1 if kernel faults must be handled "
2074 "without obtaining CAP_SYS_PTRACE capability\n");
2078 BUG_ON(!current->mm);
2080 /* Check the UFFD_* constants for consistency. */
2081 BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2082 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2083 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2085 if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2088 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2092 refcount_set(&ctx->refcount, 1);
2095 ctx->released = false;
2096 atomic_set(&ctx->mmap_changing, 0);
2097 ctx->mm = current->mm;
2098 /* prevent the mm struct to be freed */
2101 fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2102 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2105 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2110 static int __init userfaultfd_init(void)
2112 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2113 sizeof(struct userfaultfd_ctx),
2115 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2116 init_once_userfaultfd_ctx);
2119 __initcall(userfaultfd_init);