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/poll.h>
19 #include <linux/slab.h>
20 #include <linux/seq_file.h>
21 #include <linux/file.h>
22 #include <linux/bug.h>
23 #include <linux/anon_inodes.h>
24 #include <linux/syscalls.h>
25 #include <linux/userfaultfd_k.h>
26 #include <linux/mempolicy.h>
27 #include <linux/ioctl.h>
28 #include <linux/security.h>
29 #include <linux/hugetlb.h>
31 int sysctl_unprivileged_userfaultfd __read_mostly = 1;
33 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
36 * Start with fault_pending_wqh and fault_wqh so they're more likely
37 * to be in the same cacheline.
41 * fault_pending_wqh.lock
45 * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
46 * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
47 * also taken in IRQ context.
49 struct userfaultfd_ctx {
50 /* waitqueue head for the pending (i.e. not read) userfaults */
51 wait_queue_head_t fault_pending_wqh;
52 /* waitqueue head for the userfaults */
53 wait_queue_head_t fault_wqh;
54 /* waitqueue head for the pseudo fd to wakeup poll/read */
55 wait_queue_head_t fd_wqh;
56 /* waitqueue head for events */
57 wait_queue_head_t event_wqh;
58 /* a refile sequence protected by fault_pending_wqh lock */
59 seqcount_spinlock_t refile_seq;
60 /* pseudo fd refcounting */
62 /* userfaultfd syscall flags */
64 /* features requested from the userspace */
65 unsigned int features;
68 /* memory mappings are changing because of non-cooperative event */
70 /* mm with one ore more vmas attached to this userfaultfd_ctx */
74 struct userfaultfd_fork_ctx {
75 struct userfaultfd_ctx *orig;
76 struct userfaultfd_ctx *new;
77 struct list_head list;
80 struct userfaultfd_unmap_ctx {
81 struct userfaultfd_ctx *ctx;
84 struct list_head list;
87 struct userfaultfd_wait_queue {
89 wait_queue_entry_t wq;
90 struct userfaultfd_ctx *ctx;
94 struct userfaultfd_wake_range {
99 /* internal indication that UFFD_API ioctl was successfully executed */
100 #define UFFD_FEATURE_INITIALIZED (1u << 31)
102 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
104 return ctx->features & UFFD_FEATURE_INITIALIZED;
107 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
108 int wake_flags, void *key)
110 struct userfaultfd_wake_range *range = key;
112 struct userfaultfd_wait_queue *uwq;
113 unsigned long start, len;
115 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
117 /* len == 0 means wake all */
118 start = range->start;
120 if (len && (start > uwq->msg.arg.pagefault.address ||
121 start + len <= uwq->msg.arg.pagefault.address))
123 WRITE_ONCE(uwq->waken, true);
125 * The Program-Order guarantees provided by the scheduler
126 * ensure uwq->waken is visible before the task is woken.
128 ret = wake_up_state(wq->private, mode);
131 * Wake only once, autoremove behavior.
133 * After the effect of list_del_init is visible to the other
134 * CPUs, the waitqueue may disappear from under us, see the
135 * !list_empty_careful() in handle_userfault().
137 * try_to_wake_up() has an implicit smp_mb(), and the
138 * wq->private is read before calling the extern function
139 * "wake_up_state" (which in turns calls try_to_wake_up).
141 list_del_init(&wq->entry);
148 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
150 * @ctx: [in] Pointer to the userfaultfd context.
152 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
154 refcount_inc(&ctx->refcount);
158 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
160 * @ctx: [in] Pointer to userfaultfd context.
162 * The userfaultfd context reference must have been previously acquired either
163 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
165 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
167 if (refcount_dec_and_test(&ctx->refcount)) {
168 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
169 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
170 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
171 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
172 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
173 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
174 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
175 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
177 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
181 static inline void msg_init(struct uffd_msg *msg)
183 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
185 * Must use memset to zero out the paddings or kernel data is
186 * leaked to userland.
188 memset(msg, 0, sizeof(struct uffd_msg));
191 static inline struct uffd_msg userfault_msg(unsigned long address,
193 unsigned long reason,
194 unsigned int features)
198 msg.event = UFFD_EVENT_PAGEFAULT;
199 msg.arg.pagefault.address = address;
200 if (flags & FAULT_FLAG_WRITE)
202 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
203 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
204 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
205 * was a read fault, otherwise if set it means it's
208 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
209 if (reason & VM_UFFD_WP)
211 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
212 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
213 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
214 * a missing fault, otherwise if set it means it's a
215 * write protect fault.
217 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
218 if (features & UFFD_FEATURE_THREAD_ID)
219 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
223 #ifdef CONFIG_HUGETLB_PAGE
225 * Same functionality as userfaultfd_must_wait below with modifications for
228 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
229 struct vm_area_struct *vma,
230 unsigned long address,
232 unsigned long reason)
234 struct mm_struct *mm = ctx->mm;
238 mmap_assert_locked(mm);
240 ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
246 pte = huge_ptep_get(ptep);
249 * Lockless access: we're in a wait_event so it's ok if it
252 if (huge_pte_none(pte))
254 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
260 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
261 struct vm_area_struct *vma,
262 unsigned long address,
264 unsigned long reason)
266 return false; /* should never get here */
268 #endif /* CONFIG_HUGETLB_PAGE */
271 * Verify the pagetables are still not ok after having reigstered into
272 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
273 * userfault that has already been resolved, if userfaultfd_read and
274 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
277 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
278 unsigned long address,
280 unsigned long reason)
282 struct mm_struct *mm = ctx->mm;
290 mmap_assert_locked(mm);
292 pgd = pgd_offset(mm, address);
293 if (!pgd_present(*pgd))
295 p4d = p4d_offset(pgd, address);
296 if (!p4d_present(*p4d))
298 pud = pud_offset(p4d, address);
299 if (!pud_present(*pud))
301 pmd = pmd_offset(pud, address);
303 * READ_ONCE must function as a barrier with narrower scope
304 * and it must be equivalent to:
305 * _pmd = *pmd; barrier();
307 * This is to deal with the instability (as in
308 * pmd_trans_unstable) of the pmd.
310 _pmd = READ_ONCE(*pmd);
315 if (!pmd_present(_pmd))
318 if (pmd_trans_huge(_pmd)) {
319 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
325 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
326 * and use the standard pte_offset_map() instead of parsing _pmd.
328 pte = pte_offset_map(pmd, address);
330 * Lockless access: we're in a wait_event so it's ok if it
335 if (!pte_write(*pte) && (reason & VM_UFFD_WP))
343 static inline long userfaultfd_get_blocking_state(unsigned int flags)
345 if (flags & FAULT_FLAG_INTERRUPTIBLE)
346 return TASK_INTERRUPTIBLE;
348 if (flags & FAULT_FLAG_KILLABLE)
349 return TASK_KILLABLE;
351 return TASK_UNINTERRUPTIBLE;
355 * The locking rules involved in returning VM_FAULT_RETRY depending on
356 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
357 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
358 * recommendation in __lock_page_or_retry is not an understatement.
360 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
361 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
364 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
365 * set, VM_FAULT_RETRY can still be returned if and only if there are
366 * fatal_signal_pending()s, and the mmap_lock must be released before
369 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
371 struct mm_struct *mm = vmf->vma->vm_mm;
372 struct userfaultfd_ctx *ctx;
373 struct userfaultfd_wait_queue uwq;
374 vm_fault_t ret = VM_FAULT_SIGBUS;
379 * We don't do userfault handling for the final child pid update.
381 * We also don't do userfault handling during
382 * coredumping. hugetlbfs has the special
383 * follow_hugetlb_page() to skip missing pages in the
384 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
385 * the no_page_table() helper in follow_page_mask(), but the
386 * shmem_vm_ops->fault method is invoked even during
387 * coredumping without mmap_lock and it ends up here.
389 if (current->flags & (PF_EXITING|PF_DUMPCORE))
393 * Coredumping runs without mmap_lock so we can only check that
394 * the mmap_lock is held, if PF_DUMPCORE was not set.
396 mmap_assert_locked(mm);
398 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
402 BUG_ON(ctx->mm != mm);
404 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
405 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
407 if (ctx->features & UFFD_FEATURE_SIGBUS)
411 * If it's already released don't get it. This avoids to loop
412 * in __get_user_pages if userfaultfd_release waits on the
413 * caller of handle_userfault to release the mmap_lock.
415 if (unlikely(READ_ONCE(ctx->released))) {
417 * Don't return VM_FAULT_SIGBUS in this case, so a non
418 * cooperative manager can close the uffd after the
419 * last UFFDIO_COPY, without risking to trigger an
420 * involuntary SIGBUS if the process was starting the
421 * userfaultfd while the userfaultfd was still armed
422 * (but after the last UFFDIO_COPY). If the uffd
423 * wasn't already closed when the userfault reached
424 * this point, that would normally be solved by
425 * userfaultfd_must_wait returning 'false'.
427 * If we were to return VM_FAULT_SIGBUS here, the non
428 * cooperative manager would be instead forced to
429 * always call UFFDIO_UNREGISTER before it can safely
432 ret = VM_FAULT_NOPAGE;
437 * Check that we can return VM_FAULT_RETRY.
439 * NOTE: it should become possible to return VM_FAULT_RETRY
440 * even if FAULT_FLAG_TRIED is set without leading to gup()
441 * -EBUSY failures, if the userfaultfd is to be extended for
442 * VM_UFFD_WP tracking and we intend to arm the userfault
443 * without first stopping userland access to the memory. For
444 * VM_UFFD_MISSING userfaults this is enough for now.
446 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
448 * Validate the invariant that nowait must allow retry
449 * to be sure not to return SIGBUS erroneously on
450 * nowait invocations.
452 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
453 #ifdef CONFIG_DEBUG_VM
454 if (printk_ratelimit()) {
456 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
465 * Handle nowait, not much to do other than tell it to retry
468 ret = VM_FAULT_RETRY;
469 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
472 /* take the reference before dropping the mmap_lock */
473 userfaultfd_ctx_get(ctx);
475 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
476 uwq.wq.private = current;
477 uwq.msg = userfault_msg(vmf->address, vmf->flags, reason,
482 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
484 spin_lock_irq(&ctx->fault_pending_wqh.lock);
486 * After the __add_wait_queue the uwq is visible to userland
487 * through poll/read().
489 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
491 * The smp_mb() after __set_current_state prevents the reads
492 * following the spin_unlock to happen before the list_add in
495 set_current_state(blocking_state);
496 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
498 if (!is_vm_hugetlb_page(vmf->vma))
499 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
502 must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
505 mmap_read_unlock(mm);
507 if (likely(must_wait && !READ_ONCE(ctx->released))) {
508 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
512 __set_current_state(TASK_RUNNING);
515 * Here we race with the list_del; list_add in
516 * userfaultfd_ctx_read(), however because we don't ever run
517 * list_del_init() to refile across the two lists, the prev
518 * and next pointers will never point to self. list_add also
519 * would never let any of the two pointers to point to
520 * self. So list_empty_careful won't risk to see both pointers
521 * pointing to self at any time during the list refile. The
522 * only case where list_del_init() is called is the full
523 * removal in the wake function and there we don't re-list_add
524 * and it's fine not to block on the spinlock. The uwq on this
525 * kernel stack can be released after the list_del_init.
527 if (!list_empty_careful(&uwq.wq.entry)) {
528 spin_lock_irq(&ctx->fault_pending_wqh.lock);
530 * No need of list_del_init(), the uwq on the stack
531 * will be freed shortly anyway.
533 list_del(&uwq.wq.entry);
534 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
538 * ctx may go away after this if the userfault pseudo fd is
541 userfaultfd_ctx_put(ctx);
547 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
548 struct userfaultfd_wait_queue *ewq)
550 struct userfaultfd_ctx *release_new_ctx;
552 if (WARN_ON_ONCE(current->flags & PF_EXITING))
556 init_waitqueue_entry(&ewq->wq, current);
557 release_new_ctx = NULL;
559 spin_lock_irq(&ctx->event_wqh.lock);
561 * After the __add_wait_queue the uwq is visible to userland
562 * through poll/read().
564 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
566 set_current_state(TASK_KILLABLE);
567 if (ewq->msg.event == 0)
569 if (READ_ONCE(ctx->released) ||
570 fatal_signal_pending(current)) {
572 * &ewq->wq may be queued in fork_event, but
573 * __remove_wait_queue ignores the head
574 * parameter. It would be a problem if it
577 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
578 if (ewq->msg.event == UFFD_EVENT_FORK) {
579 struct userfaultfd_ctx *new;
581 new = (struct userfaultfd_ctx *)
583 ewq->msg.arg.reserved.reserved1;
584 release_new_ctx = new;
589 spin_unlock_irq(&ctx->event_wqh.lock);
591 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
594 spin_lock_irq(&ctx->event_wqh.lock);
596 __set_current_state(TASK_RUNNING);
597 spin_unlock_irq(&ctx->event_wqh.lock);
599 if (release_new_ctx) {
600 struct vm_area_struct *vma;
601 struct mm_struct *mm = release_new_ctx->mm;
603 /* the various vma->vm_userfaultfd_ctx still points to it */
605 for (vma = mm->mmap; vma; vma = vma->vm_next)
606 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
607 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
608 vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
610 mmap_write_unlock(mm);
612 userfaultfd_ctx_put(release_new_ctx);
616 * ctx may go away after this if the userfault pseudo fd is
620 WRITE_ONCE(ctx->mmap_changing, false);
621 userfaultfd_ctx_put(ctx);
624 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
625 struct userfaultfd_wait_queue *ewq)
628 wake_up_locked(&ctx->event_wqh);
629 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
632 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
634 struct userfaultfd_ctx *ctx = NULL, *octx;
635 struct userfaultfd_fork_ctx *fctx;
637 octx = vma->vm_userfaultfd_ctx.ctx;
638 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
639 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
640 vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
644 list_for_each_entry(fctx, fcs, list)
645 if (fctx->orig == octx) {
651 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
655 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
661 refcount_set(&ctx->refcount, 1);
662 ctx->flags = octx->flags;
663 ctx->features = octx->features;
664 ctx->released = false;
665 ctx->mmap_changing = false;
666 ctx->mm = vma->vm_mm;
669 userfaultfd_ctx_get(octx);
670 WRITE_ONCE(octx->mmap_changing, true);
673 list_add_tail(&fctx->list, fcs);
676 vma->vm_userfaultfd_ctx.ctx = ctx;
680 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
682 struct userfaultfd_ctx *ctx = fctx->orig;
683 struct userfaultfd_wait_queue ewq;
687 ewq.msg.event = UFFD_EVENT_FORK;
688 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
690 userfaultfd_event_wait_completion(ctx, &ewq);
693 void dup_userfaultfd_complete(struct list_head *fcs)
695 struct userfaultfd_fork_ctx *fctx, *n;
697 list_for_each_entry_safe(fctx, n, fcs, list) {
699 list_del(&fctx->list);
704 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
705 struct vm_userfaultfd_ctx *vm_ctx)
707 struct userfaultfd_ctx *ctx;
709 ctx = vma->vm_userfaultfd_ctx.ctx;
714 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
716 userfaultfd_ctx_get(ctx);
717 WRITE_ONCE(ctx->mmap_changing, true);
719 /* Drop uffd context if remap feature not enabled */
720 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
721 vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
725 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
726 unsigned long from, unsigned long to,
729 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
730 struct userfaultfd_wait_queue ewq;
735 if (to & ~PAGE_MASK) {
736 userfaultfd_ctx_put(ctx);
742 ewq.msg.event = UFFD_EVENT_REMAP;
743 ewq.msg.arg.remap.from = from;
744 ewq.msg.arg.remap.to = to;
745 ewq.msg.arg.remap.len = len;
747 userfaultfd_event_wait_completion(ctx, &ewq);
750 bool userfaultfd_remove(struct vm_area_struct *vma,
751 unsigned long start, unsigned long end)
753 struct mm_struct *mm = vma->vm_mm;
754 struct userfaultfd_ctx *ctx;
755 struct userfaultfd_wait_queue ewq;
757 ctx = vma->vm_userfaultfd_ctx.ctx;
758 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
761 userfaultfd_ctx_get(ctx);
762 WRITE_ONCE(ctx->mmap_changing, true);
763 mmap_read_unlock(mm);
767 ewq.msg.event = UFFD_EVENT_REMOVE;
768 ewq.msg.arg.remove.start = start;
769 ewq.msg.arg.remove.end = end;
771 userfaultfd_event_wait_completion(ctx, &ewq);
776 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
777 unsigned long start, unsigned long end)
779 struct userfaultfd_unmap_ctx *unmap_ctx;
781 list_for_each_entry(unmap_ctx, unmaps, list)
782 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
783 unmap_ctx->end == end)
789 int userfaultfd_unmap_prep(struct vm_area_struct *vma,
790 unsigned long start, unsigned long end,
791 struct list_head *unmaps)
793 for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
794 struct userfaultfd_unmap_ctx *unmap_ctx;
795 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
797 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
798 has_unmap_ctx(ctx, unmaps, start, end))
801 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
805 userfaultfd_ctx_get(ctx);
806 WRITE_ONCE(ctx->mmap_changing, true);
807 unmap_ctx->ctx = ctx;
808 unmap_ctx->start = start;
809 unmap_ctx->end = end;
810 list_add_tail(&unmap_ctx->list, unmaps);
816 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
818 struct userfaultfd_unmap_ctx *ctx, *n;
819 struct userfaultfd_wait_queue ewq;
821 list_for_each_entry_safe(ctx, n, uf, list) {
824 ewq.msg.event = UFFD_EVENT_UNMAP;
825 ewq.msg.arg.remove.start = ctx->start;
826 ewq.msg.arg.remove.end = ctx->end;
828 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
830 list_del(&ctx->list);
835 static int userfaultfd_release(struct inode *inode, struct file *file)
837 struct userfaultfd_ctx *ctx = file->private_data;
838 struct mm_struct *mm = ctx->mm;
839 struct vm_area_struct *vma, *prev;
840 /* len == 0 means wake all */
841 struct userfaultfd_wake_range range = { .len = 0, };
842 unsigned long new_flags;
844 WRITE_ONCE(ctx->released, true);
846 if (!mmget_not_zero(mm))
850 * Flush page faults out of all CPUs. NOTE: all page faults
851 * must be retried without returning VM_FAULT_SIGBUS if
852 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
853 * changes while handle_userfault released the mmap_lock. So
854 * it's critical that released is set to true (above), before
855 * taking the mmap_lock for writing.
859 for (vma = mm->mmap; vma; vma = vma->vm_next) {
861 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
862 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
863 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
867 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
868 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
869 new_flags, vma->anon_vma,
870 vma->vm_file, vma->vm_pgoff,
877 vma->vm_flags = new_flags;
878 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
880 mmap_write_unlock(mm);
884 * After no new page faults can wait on this fault_*wqh, flush
885 * the last page faults that may have been already waiting on
888 spin_lock_irq(&ctx->fault_pending_wqh.lock);
889 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
890 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
891 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
893 /* Flush pending events that may still wait on event_wqh */
894 wake_up_all(&ctx->event_wqh);
896 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
897 userfaultfd_ctx_put(ctx);
901 /* fault_pending_wqh.lock must be hold by the caller */
902 static inline struct userfaultfd_wait_queue *find_userfault_in(
903 wait_queue_head_t *wqh)
905 wait_queue_entry_t *wq;
906 struct userfaultfd_wait_queue *uwq;
908 lockdep_assert_held(&wqh->lock);
911 if (!waitqueue_active(wqh))
913 /* walk in reverse to provide FIFO behavior to read userfaults */
914 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
915 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
920 static inline struct userfaultfd_wait_queue *find_userfault(
921 struct userfaultfd_ctx *ctx)
923 return find_userfault_in(&ctx->fault_pending_wqh);
926 static inline struct userfaultfd_wait_queue *find_userfault_evt(
927 struct userfaultfd_ctx *ctx)
929 return find_userfault_in(&ctx->event_wqh);
932 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
934 struct userfaultfd_ctx *ctx = file->private_data;
937 poll_wait(file, &ctx->fd_wqh, wait);
939 if (!userfaultfd_is_initialized(ctx))
943 * poll() never guarantees that read won't block.
944 * userfaults can be waken before they're read().
946 if (unlikely(!(file->f_flags & O_NONBLOCK)))
949 * lockless access to see if there are pending faults
950 * __pollwait last action is the add_wait_queue but
951 * the spin_unlock would allow the waitqueue_active to
952 * pass above the actual list_add inside
953 * add_wait_queue critical section. So use a full
954 * memory barrier to serialize the list_add write of
955 * add_wait_queue() with the waitqueue_active read
960 if (waitqueue_active(&ctx->fault_pending_wqh))
962 else if (waitqueue_active(&ctx->event_wqh))
968 static const struct file_operations userfaultfd_fops;
970 static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
971 struct userfaultfd_ctx *new,
972 struct uffd_msg *msg)
976 fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, new,
977 O_RDWR | (new->flags & UFFD_SHARED_FCNTL_FLAGS));
981 msg->arg.reserved.reserved1 = 0;
982 msg->arg.fork.ufd = fd;
986 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
987 struct uffd_msg *msg)
990 DECLARE_WAITQUEUE(wait, current);
991 struct userfaultfd_wait_queue *uwq;
993 * Handling fork event requires sleeping operations, so
994 * we drop the event_wqh lock, then do these ops, then
995 * lock it back and wake up the waiter. While the lock is
996 * dropped the ewq may go away so we keep track of it
999 LIST_HEAD(fork_event);
1000 struct userfaultfd_ctx *fork_nctx = NULL;
1002 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1003 spin_lock_irq(&ctx->fd_wqh.lock);
1004 __add_wait_queue(&ctx->fd_wqh, &wait);
1006 set_current_state(TASK_INTERRUPTIBLE);
1007 spin_lock(&ctx->fault_pending_wqh.lock);
1008 uwq = find_userfault(ctx);
1011 * Use a seqcount to repeat the lockless check
1012 * in wake_userfault() to avoid missing
1013 * wakeups because during the refile both
1014 * waitqueue could become empty if this is the
1017 write_seqcount_begin(&ctx->refile_seq);
1020 * The fault_pending_wqh.lock prevents the uwq
1021 * to disappear from under us.
1023 * Refile this userfault from
1024 * fault_pending_wqh to fault_wqh, it's not
1025 * pending anymore after we read it.
1027 * Use list_del() by hand (as
1028 * userfaultfd_wake_function also uses
1029 * list_del_init() by hand) to be sure nobody
1030 * changes __remove_wait_queue() to use
1031 * list_del_init() in turn breaking the
1032 * !list_empty_careful() check in
1033 * handle_userfault(). The uwq->wq.head list
1034 * must never be empty at any time during the
1035 * refile, or the waitqueue could disappear
1036 * from under us. The "wait_queue_head_t"
1037 * parameter of __remove_wait_queue() is unused
1040 list_del(&uwq->wq.entry);
1041 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1043 write_seqcount_end(&ctx->refile_seq);
1045 /* careful to always initialize msg if ret == 0 */
1047 spin_unlock(&ctx->fault_pending_wqh.lock);
1051 spin_unlock(&ctx->fault_pending_wqh.lock);
1053 spin_lock(&ctx->event_wqh.lock);
1054 uwq = find_userfault_evt(ctx);
1058 if (uwq->msg.event == UFFD_EVENT_FORK) {
1059 fork_nctx = (struct userfaultfd_ctx *)
1061 uwq->msg.arg.reserved.reserved1;
1062 list_move(&uwq->wq.entry, &fork_event);
1064 * fork_nctx can be freed as soon as
1065 * we drop the lock, unless we take a
1068 userfaultfd_ctx_get(fork_nctx);
1069 spin_unlock(&ctx->event_wqh.lock);
1074 userfaultfd_event_complete(ctx, uwq);
1075 spin_unlock(&ctx->event_wqh.lock);
1079 spin_unlock(&ctx->event_wqh.lock);
1081 if (signal_pending(current)) {
1089 spin_unlock_irq(&ctx->fd_wqh.lock);
1091 spin_lock_irq(&ctx->fd_wqh.lock);
1093 __remove_wait_queue(&ctx->fd_wqh, &wait);
1094 __set_current_state(TASK_RUNNING);
1095 spin_unlock_irq(&ctx->fd_wqh.lock);
1097 if (!ret && msg->event == UFFD_EVENT_FORK) {
1098 ret = resolve_userfault_fork(ctx, fork_nctx, msg);
1099 spin_lock_irq(&ctx->event_wqh.lock);
1100 if (!list_empty(&fork_event)) {
1102 * The fork thread didn't abort, so we can
1103 * drop the temporary refcount.
1105 userfaultfd_ctx_put(fork_nctx);
1107 uwq = list_first_entry(&fork_event,
1111 * If fork_event list wasn't empty and in turn
1112 * the event wasn't already released by fork
1113 * (the event is allocated on fork kernel
1114 * stack), put the event back to its place in
1115 * the event_wq. fork_event head will be freed
1116 * as soon as we return so the event cannot
1117 * stay queued there no matter the current
1120 list_del(&uwq->wq.entry);
1121 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1124 * Leave the event in the waitqueue and report
1125 * error to userland if we failed to resolve
1126 * the userfault fork.
1129 userfaultfd_event_complete(ctx, uwq);
1132 * Here the fork thread aborted and the
1133 * refcount from the fork thread on fork_nctx
1134 * has already been released. We still hold
1135 * the reference we took before releasing the
1136 * lock above. If resolve_userfault_fork
1137 * failed we've to drop it because the
1138 * fork_nctx has to be freed in such case. If
1139 * it succeeded we'll hold it because the new
1140 * uffd references it.
1143 userfaultfd_ctx_put(fork_nctx);
1145 spin_unlock_irq(&ctx->event_wqh.lock);
1151 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1152 size_t count, loff_t *ppos)
1154 struct userfaultfd_ctx *ctx = file->private_data;
1155 ssize_t _ret, ret = 0;
1156 struct uffd_msg msg;
1157 int no_wait = file->f_flags & O_NONBLOCK;
1159 if (!userfaultfd_is_initialized(ctx))
1163 if (count < sizeof(msg))
1164 return ret ? ret : -EINVAL;
1165 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
1167 return ret ? ret : _ret;
1168 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1169 return ret ? ret : -EFAULT;
1172 count -= sizeof(msg);
1174 * Allow to read more than one fault at time but only
1175 * block if waiting for the very first one.
1177 no_wait = O_NONBLOCK;
1181 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1182 struct userfaultfd_wake_range *range)
1184 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1185 /* wake all in the range and autoremove */
1186 if (waitqueue_active(&ctx->fault_pending_wqh))
1187 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1189 if (waitqueue_active(&ctx->fault_wqh))
1190 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1191 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1194 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1195 struct userfaultfd_wake_range *range)
1201 * To be sure waitqueue_active() is not reordered by the CPU
1202 * before the pagetable update, use an explicit SMP memory
1203 * barrier here. PT lock release or mmap_read_unlock(mm) still
1204 * have release semantics that can allow the
1205 * waitqueue_active() to be reordered before the pte update.
1210 * Use waitqueue_active because it's very frequent to
1211 * change the address space atomically even if there are no
1212 * userfaults yet. So we take the spinlock only when we're
1213 * sure we've userfaults to wake.
1216 seq = read_seqcount_begin(&ctx->refile_seq);
1217 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1218 waitqueue_active(&ctx->fault_wqh);
1220 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1222 __wake_userfault(ctx, range);
1225 static __always_inline int validate_range(struct mm_struct *mm,
1226 __u64 start, __u64 len)
1228 __u64 task_size = mm->task_size;
1230 if (start & ~PAGE_MASK)
1232 if (len & ~PAGE_MASK)
1236 if (start < mmap_min_addr)
1238 if (start >= task_size)
1240 if (len > task_size - start)
1245 static inline bool vma_can_userfault(struct vm_area_struct *vma,
1246 unsigned long vm_flags)
1248 /* FIXME: add WP support to hugetlbfs and shmem */
1249 return vma_is_anonymous(vma) ||
1250 ((is_vm_hugetlb_page(vma) || vma_is_shmem(vma)) &&
1251 !(vm_flags & VM_UFFD_WP));
1254 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1257 struct mm_struct *mm = ctx->mm;
1258 struct vm_area_struct *vma, *prev, *cur;
1260 struct uffdio_register uffdio_register;
1261 struct uffdio_register __user *user_uffdio_register;
1262 unsigned long vm_flags, new_flags;
1265 unsigned long start, end, vma_end;
1267 user_uffdio_register = (struct uffdio_register __user *) arg;
1270 if (copy_from_user(&uffdio_register, user_uffdio_register,
1271 sizeof(uffdio_register)-sizeof(__u64)))
1275 if (!uffdio_register.mode)
1277 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
1278 UFFDIO_REGISTER_MODE_WP))
1281 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1282 vm_flags |= VM_UFFD_MISSING;
1283 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP)
1284 vm_flags |= VM_UFFD_WP;
1286 ret = validate_range(mm, uffdio_register.range.start,
1287 uffdio_register.range.len);
1291 start = uffdio_register.range.start;
1292 end = start + uffdio_register.range.len;
1295 if (!mmget_not_zero(mm))
1298 mmap_write_lock(mm);
1299 vma = find_vma_prev(mm, start, &prev);
1303 /* check that there's at least one vma in the range */
1305 if (vma->vm_start >= end)
1309 * If the first vma contains huge pages, make sure start address
1310 * is aligned to huge page size.
1312 if (is_vm_hugetlb_page(vma)) {
1313 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1315 if (start & (vma_hpagesize - 1))
1320 * Search for not compatible vmas.
1323 basic_ioctls = false;
1324 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1327 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1328 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1330 /* check not compatible vmas */
1332 if (!vma_can_userfault(cur, vm_flags))
1336 * UFFDIO_COPY will fill file holes even without
1337 * PROT_WRITE. This check enforces that if this is a
1338 * MAP_SHARED, the process has write permission to the backing
1339 * file. If VM_MAYWRITE is set it also enforces that on a
1340 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1341 * F_WRITE_SEAL can be taken until the vma is destroyed.
1344 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1348 * If this vma contains ending address, and huge pages
1351 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1352 end > cur->vm_start) {
1353 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1357 if (end & (vma_hpagesize - 1))
1360 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1364 * Check that this vma isn't already owned by a
1365 * different userfaultfd. We can't allow more than one
1366 * userfaultfd to own a single vma simultaneously or we
1367 * wouldn't know which one to deliver the userfaults to.
1370 if (cur->vm_userfaultfd_ctx.ctx &&
1371 cur->vm_userfaultfd_ctx.ctx != ctx)
1375 * Note vmas containing huge pages
1377 if (is_vm_hugetlb_page(cur))
1378 basic_ioctls = true;
1384 if (vma->vm_start < start)
1391 BUG_ON(!vma_can_userfault(vma, vm_flags));
1392 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1393 vma->vm_userfaultfd_ctx.ctx != ctx);
1394 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1397 * Nothing to do: this vma is already registered into this
1398 * userfaultfd and with the right tracking mode too.
1400 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1401 (vma->vm_flags & vm_flags) == vm_flags)
1404 if (vma->vm_start > start)
1405 start = vma->vm_start;
1406 vma_end = min(end, vma->vm_end);
1408 new_flags = (vma->vm_flags &
1409 ~(VM_UFFD_MISSING|VM_UFFD_WP)) | vm_flags;
1410 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1411 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1413 ((struct vm_userfaultfd_ctx){ ctx }));
1418 if (vma->vm_start < start) {
1419 ret = split_vma(mm, vma, start, 1);
1423 if (vma->vm_end > end) {
1424 ret = split_vma(mm, vma, end, 0);
1430 * In the vma_merge() successful mprotect-like case 8:
1431 * the next vma was merged into the current one and
1432 * the current one has not been updated yet.
1434 vma->vm_flags = new_flags;
1435 vma->vm_userfaultfd_ctx.ctx = ctx;
1439 start = vma->vm_end;
1441 } while (vma && vma->vm_start < end);
1443 mmap_write_unlock(mm);
1448 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1449 UFFD_API_RANGE_IOCTLS;
1452 * Declare the WP ioctl only if the WP mode is
1453 * specified and all checks passed with the range
1455 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1456 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1459 * Now that we scanned all vmas we can already tell
1460 * userland which ioctls methods are guaranteed to
1461 * succeed on this range.
1463 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1470 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1473 struct mm_struct *mm = ctx->mm;
1474 struct vm_area_struct *vma, *prev, *cur;
1476 struct uffdio_range uffdio_unregister;
1477 unsigned long new_flags;
1479 unsigned long start, end, vma_end;
1480 const void __user *buf = (void __user *)arg;
1483 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1486 ret = validate_range(mm, uffdio_unregister.start,
1487 uffdio_unregister.len);
1491 start = uffdio_unregister.start;
1492 end = start + uffdio_unregister.len;
1495 if (!mmget_not_zero(mm))
1498 mmap_write_lock(mm);
1499 vma = find_vma_prev(mm, start, &prev);
1503 /* check that there's at least one vma in the range */
1505 if (vma->vm_start >= end)
1509 * If the first vma contains huge pages, make sure start address
1510 * is aligned to huge page size.
1512 if (is_vm_hugetlb_page(vma)) {
1513 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1515 if (start & (vma_hpagesize - 1))
1520 * Search for not compatible vmas.
1524 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1527 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1528 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1531 * Check not compatible vmas, not strictly required
1532 * here as not compatible vmas cannot have an
1533 * userfaultfd_ctx registered on them, but this
1534 * provides for more strict behavior to notice
1535 * unregistration errors.
1537 if (!vma_can_userfault(cur, cur->vm_flags))
1544 if (vma->vm_start < start)
1551 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1554 * Nothing to do: this vma is already registered into this
1555 * userfaultfd and with the right tracking mode too.
1557 if (!vma->vm_userfaultfd_ctx.ctx)
1560 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1562 if (vma->vm_start > start)
1563 start = vma->vm_start;
1564 vma_end = min(end, vma->vm_end);
1566 if (userfaultfd_missing(vma)) {
1568 * Wake any concurrent pending userfault while
1569 * we unregister, so they will not hang
1570 * permanently and it avoids userland to call
1571 * UFFDIO_WAKE explicitly.
1573 struct userfaultfd_wake_range range;
1574 range.start = start;
1575 range.len = vma_end - start;
1576 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1579 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1580 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1581 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1588 if (vma->vm_start < start) {
1589 ret = split_vma(mm, vma, start, 1);
1593 if (vma->vm_end > end) {
1594 ret = split_vma(mm, vma, end, 0);
1600 * In the vma_merge() successful mprotect-like case 8:
1601 * the next vma was merged into the current one and
1602 * the current one has not been updated yet.
1604 vma->vm_flags = new_flags;
1605 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1609 start = vma->vm_end;
1611 } while (vma && vma->vm_start < end);
1613 mmap_write_unlock(mm);
1620 * userfaultfd_wake may be used in combination with the
1621 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1623 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1627 struct uffdio_range uffdio_wake;
1628 struct userfaultfd_wake_range range;
1629 const void __user *buf = (void __user *)arg;
1632 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1635 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1639 range.start = uffdio_wake.start;
1640 range.len = uffdio_wake.len;
1643 * len == 0 means wake all and we don't want to wake all here,
1644 * so check it again to be sure.
1646 VM_BUG_ON(!range.len);
1648 wake_userfault(ctx, &range);
1655 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1659 struct uffdio_copy uffdio_copy;
1660 struct uffdio_copy __user *user_uffdio_copy;
1661 struct userfaultfd_wake_range range;
1663 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1666 if (READ_ONCE(ctx->mmap_changing))
1670 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1671 /* don't copy "copy" last field */
1672 sizeof(uffdio_copy)-sizeof(__s64)))
1675 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1679 * double check for wraparound just in case. copy_from_user()
1680 * will later check uffdio_copy.src + uffdio_copy.len to fit
1681 * in the userland range.
1684 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1686 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1688 if (mmget_not_zero(ctx->mm)) {
1689 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1690 uffdio_copy.len, &ctx->mmap_changing,
1696 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1701 /* len == 0 would wake all */
1703 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1704 range.start = uffdio_copy.dst;
1705 wake_userfault(ctx, &range);
1707 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1712 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1716 struct uffdio_zeropage uffdio_zeropage;
1717 struct uffdio_zeropage __user *user_uffdio_zeropage;
1718 struct userfaultfd_wake_range range;
1720 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1723 if (READ_ONCE(ctx->mmap_changing))
1727 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1728 /* don't copy "zeropage" last field */
1729 sizeof(uffdio_zeropage)-sizeof(__s64)))
1732 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1733 uffdio_zeropage.range.len);
1737 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1740 if (mmget_not_zero(ctx->mm)) {
1741 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1742 uffdio_zeropage.range.len,
1743 &ctx->mmap_changing);
1748 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1752 /* len == 0 would wake all */
1755 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1756 range.start = uffdio_zeropage.range.start;
1757 wake_userfault(ctx, &range);
1759 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1764 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1768 struct uffdio_writeprotect uffdio_wp;
1769 struct uffdio_writeprotect __user *user_uffdio_wp;
1770 struct userfaultfd_wake_range range;
1771 bool mode_wp, mode_dontwake;
1773 if (READ_ONCE(ctx->mmap_changing))
1776 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1778 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1779 sizeof(struct uffdio_writeprotect)))
1782 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1783 uffdio_wp.range.len);
1787 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1788 UFFDIO_WRITEPROTECT_MODE_WP))
1791 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1792 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1794 if (mode_wp && mode_dontwake)
1797 if (mmget_not_zero(ctx->mm)) {
1798 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1799 uffdio_wp.range.len, mode_wp,
1800 &ctx->mmap_changing);
1809 if (!mode_wp && !mode_dontwake) {
1810 range.start = uffdio_wp.range.start;
1811 range.len = uffdio_wp.range.len;
1812 wake_userfault(ctx, &range);
1817 static inline unsigned int uffd_ctx_features(__u64 user_features)
1820 * For the current set of features the bits just coincide. Set
1821 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1823 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1827 * userland asks for a certain API version and we return which bits
1828 * and ioctl commands are implemented in this kernel for such API
1829 * version or -EINVAL if unknown.
1831 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1834 struct uffdio_api uffdio_api;
1835 void __user *buf = (void __user *)arg;
1836 unsigned int ctx_features;
1841 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1843 features = uffdio_api.features;
1845 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
1848 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1850 /* report all available features and ioctls to userland */
1851 uffdio_api.features = UFFD_API_FEATURES;
1852 uffdio_api.ioctls = UFFD_API_IOCTLS;
1854 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1857 /* only enable the requested features for this uffd context */
1858 ctx_features = uffd_ctx_features(features);
1860 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1867 memset(&uffdio_api, 0, sizeof(uffdio_api));
1868 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1873 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1877 struct userfaultfd_ctx *ctx = file->private_data;
1879 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
1884 ret = userfaultfd_api(ctx, arg);
1886 case UFFDIO_REGISTER:
1887 ret = userfaultfd_register(ctx, arg);
1889 case UFFDIO_UNREGISTER:
1890 ret = userfaultfd_unregister(ctx, arg);
1893 ret = userfaultfd_wake(ctx, arg);
1896 ret = userfaultfd_copy(ctx, arg);
1898 case UFFDIO_ZEROPAGE:
1899 ret = userfaultfd_zeropage(ctx, arg);
1901 case UFFDIO_WRITEPROTECT:
1902 ret = userfaultfd_writeprotect(ctx, arg);
1908 #ifdef CONFIG_PROC_FS
1909 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1911 struct userfaultfd_ctx *ctx = f->private_data;
1912 wait_queue_entry_t *wq;
1913 unsigned long pending = 0, total = 0;
1915 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1916 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
1920 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
1923 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1926 * If more protocols will be added, there will be all shown
1927 * separated by a space. Like this:
1928 * protocols: aa:... bb:...
1930 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1931 pending, total, UFFD_API, ctx->features,
1932 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1936 static const struct file_operations userfaultfd_fops = {
1937 #ifdef CONFIG_PROC_FS
1938 .show_fdinfo = userfaultfd_show_fdinfo,
1940 .release = userfaultfd_release,
1941 .poll = userfaultfd_poll,
1942 .read = userfaultfd_read,
1943 .unlocked_ioctl = userfaultfd_ioctl,
1944 .compat_ioctl = compat_ptr_ioctl,
1945 .llseek = noop_llseek,
1948 static void init_once_userfaultfd_ctx(void *mem)
1950 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1952 init_waitqueue_head(&ctx->fault_pending_wqh);
1953 init_waitqueue_head(&ctx->fault_wqh);
1954 init_waitqueue_head(&ctx->event_wqh);
1955 init_waitqueue_head(&ctx->fd_wqh);
1956 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
1959 SYSCALL_DEFINE1(userfaultfd, int, flags)
1961 struct userfaultfd_ctx *ctx;
1964 if (!sysctl_unprivileged_userfaultfd && !capable(CAP_SYS_PTRACE))
1967 BUG_ON(!current->mm);
1969 /* Check the UFFD_* constants for consistency. */
1970 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1971 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1973 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1976 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1980 refcount_set(&ctx->refcount, 1);
1983 ctx->released = false;
1984 ctx->mmap_changing = false;
1985 ctx->mm = current->mm;
1986 /* prevent the mm struct to be freed */
1989 fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, ctx,
1990 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1993 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1998 static int __init userfaultfd_init(void)
2000 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2001 sizeof(struct userfaultfd_ctx),
2003 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2004 init_once_userfaultfd_ctx);
2007 __initcall(userfaultfd_init);