Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  *  fs/userfaultfd.c
0004  *
0005  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
0006  *  Copyright (C) 2008-2009 Red Hat, Inc.
0007  *  Copyright (C) 2015  Red Hat, Inc.
0008  *
0009  *  Some part derived from fs/eventfd.c (anon inode setup) and
0010  *  mm/ksm.c (mm hashing).
0011  */
0012 
0013 #include <linux/list.h>
0014 #include <linux/hashtable.h>
0015 #include <linux/sched/signal.h>
0016 #include <linux/sched/mm.h>
0017 #include <linux/mm.h>
0018 #include <linux/mm_inline.h>
0019 #include <linux/mmu_notifier.h>
0020 #include <linux/poll.h>
0021 #include <linux/slab.h>
0022 #include <linux/seq_file.h>
0023 #include <linux/file.h>
0024 #include <linux/bug.h>
0025 #include <linux/anon_inodes.h>
0026 #include <linux/syscalls.h>
0027 #include <linux/userfaultfd_k.h>
0028 #include <linux/mempolicy.h>
0029 #include <linux/ioctl.h>
0030 #include <linux/security.h>
0031 #include <linux/hugetlb.h>
0032 #include <linux/swapops.h>
0033 
0034 int sysctl_unprivileged_userfaultfd __read_mostly;
0035 
0036 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
0037 
0038 /*
0039  * Start with fault_pending_wqh and fault_wqh so they're more likely
0040  * to be in the same cacheline.
0041  *
0042  * Locking order:
0043  *  fd_wqh.lock
0044  *      fault_pending_wqh.lock
0045  *          fault_wqh.lock
0046  *      event_wqh.lock
0047  *
0048  * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
0049  * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
0050  * also taken in IRQ context.
0051  */
0052 struct userfaultfd_ctx {
0053     /* waitqueue head for the pending (i.e. not read) userfaults */
0054     wait_queue_head_t fault_pending_wqh;
0055     /* waitqueue head for the userfaults */
0056     wait_queue_head_t fault_wqh;
0057     /* waitqueue head for the pseudo fd to wakeup poll/read */
0058     wait_queue_head_t fd_wqh;
0059     /* waitqueue head for events */
0060     wait_queue_head_t event_wqh;
0061     /* a refile sequence protected by fault_pending_wqh lock */
0062     seqcount_spinlock_t refile_seq;
0063     /* pseudo fd refcounting */
0064     refcount_t refcount;
0065     /* userfaultfd syscall flags */
0066     unsigned int flags;
0067     /* features requested from the userspace */
0068     unsigned int features;
0069     /* released */
0070     bool released;
0071     /* memory mappings are changing because of non-cooperative event */
0072     atomic_t mmap_changing;
0073     /* mm with one ore more vmas attached to this userfaultfd_ctx */
0074     struct mm_struct *mm;
0075 };
0076 
0077 struct userfaultfd_fork_ctx {
0078     struct userfaultfd_ctx *orig;
0079     struct userfaultfd_ctx *new;
0080     struct list_head list;
0081 };
0082 
0083 struct userfaultfd_unmap_ctx {
0084     struct userfaultfd_ctx *ctx;
0085     unsigned long start;
0086     unsigned long end;
0087     struct list_head list;
0088 };
0089 
0090 struct userfaultfd_wait_queue {
0091     struct uffd_msg msg;
0092     wait_queue_entry_t wq;
0093     struct userfaultfd_ctx *ctx;
0094     bool waken;
0095 };
0096 
0097 struct userfaultfd_wake_range {
0098     unsigned long start;
0099     unsigned long len;
0100 };
0101 
0102 /* internal indication that UFFD_API ioctl was successfully executed */
0103 #define UFFD_FEATURE_INITIALIZED        (1u << 31)
0104 
0105 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
0106 {
0107     return ctx->features & UFFD_FEATURE_INITIALIZED;
0108 }
0109 
0110 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
0111                      int wake_flags, void *key)
0112 {
0113     struct userfaultfd_wake_range *range = key;
0114     int ret;
0115     struct userfaultfd_wait_queue *uwq;
0116     unsigned long start, len;
0117 
0118     uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
0119     ret = 0;
0120     /* len == 0 means wake all */
0121     start = range->start;
0122     len = range->len;
0123     if (len && (start > uwq->msg.arg.pagefault.address ||
0124             start + len <= uwq->msg.arg.pagefault.address))
0125         goto out;
0126     WRITE_ONCE(uwq->waken, true);
0127     /*
0128      * The Program-Order guarantees provided by the scheduler
0129      * ensure uwq->waken is visible before the task is woken.
0130      */
0131     ret = wake_up_state(wq->private, mode);
0132     if (ret) {
0133         /*
0134          * Wake only once, autoremove behavior.
0135          *
0136          * After the effect of list_del_init is visible to the other
0137          * CPUs, the waitqueue may disappear from under us, see the
0138          * !list_empty_careful() in handle_userfault().
0139          *
0140          * try_to_wake_up() has an implicit smp_mb(), and the
0141          * wq->private is read before calling the extern function
0142          * "wake_up_state" (which in turns calls try_to_wake_up).
0143          */
0144         list_del_init(&wq->entry);
0145     }
0146 out:
0147     return ret;
0148 }
0149 
0150 /**
0151  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
0152  * context.
0153  * @ctx: [in] Pointer to the userfaultfd context.
0154  */
0155 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
0156 {
0157     refcount_inc(&ctx->refcount);
0158 }
0159 
0160 /**
0161  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
0162  * context.
0163  * @ctx: [in] Pointer to userfaultfd context.
0164  *
0165  * The userfaultfd context reference must have been previously acquired either
0166  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
0167  */
0168 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
0169 {
0170     if (refcount_dec_and_test(&ctx->refcount)) {
0171         VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
0172         VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
0173         VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
0174         VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
0175         VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
0176         VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
0177         VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
0178         VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
0179         mmdrop(ctx->mm);
0180         kmem_cache_free(userfaultfd_ctx_cachep, ctx);
0181     }
0182 }
0183 
0184 static inline void msg_init(struct uffd_msg *msg)
0185 {
0186     BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
0187     /*
0188      * Must use memset to zero out the paddings or kernel data is
0189      * leaked to userland.
0190      */
0191     memset(msg, 0, sizeof(struct uffd_msg));
0192 }
0193 
0194 static inline struct uffd_msg userfault_msg(unsigned long address,
0195                         unsigned long real_address,
0196                         unsigned int flags,
0197                         unsigned long reason,
0198                         unsigned int features)
0199 {
0200     struct uffd_msg msg;
0201 
0202     msg_init(&msg);
0203     msg.event = UFFD_EVENT_PAGEFAULT;
0204 
0205     msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
0206                     real_address : address;
0207 
0208     /*
0209      * These flags indicate why the userfault occurred:
0210      * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
0211      * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
0212      * - Neither of these flags being set indicates a MISSING fault.
0213      *
0214      * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
0215      * fault. Otherwise, it was a read fault.
0216      */
0217     if (flags & FAULT_FLAG_WRITE)
0218         msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
0219     if (reason & VM_UFFD_WP)
0220         msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
0221     if (reason & VM_UFFD_MINOR)
0222         msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
0223     if (features & UFFD_FEATURE_THREAD_ID)
0224         msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
0225     return msg;
0226 }
0227 
0228 #ifdef CONFIG_HUGETLB_PAGE
0229 /*
0230  * Same functionality as userfaultfd_must_wait below with modifications for
0231  * hugepmd ranges.
0232  */
0233 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
0234                      struct vm_area_struct *vma,
0235                      unsigned long address,
0236                      unsigned long flags,
0237                      unsigned long reason)
0238 {
0239     struct mm_struct *mm = ctx->mm;
0240     pte_t *ptep, pte;
0241     bool ret = true;
0242 
0243     mmap_assert_locked(mm);
0244 
0245     ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
0246 
0247     if (!ptep)
0248         goto out;
0249 
0250     ret = false;
0251     pte = huge_ptep_get(ptep);
0252 
0253     /*
0254      * Lockless access: we're in a wait_event so it's ok if it
0255      * changes under us.  PTE markers should be handled the same as none
0256      * ptes here.
0257      */
0258     if (huge_pte_none_mostly(pte))
0259         ret = true;
0260     if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
0261         ret = true;
0262 out:
0263     return ret;
0264 }
0265 #else
0266 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
0267                      struct vm_area_struct *vma,
0268                      unsigned long address,
0269                      unsigned long flags,
0270                      unsigned long reason)
0271 {
0272     return false;   /* should never get here */
0273 }
0274 #endif /* CONFIG_HUGETLB_PAGE */
0275 
0276 /*
0277  * Verify the pagetables are still not ok after having reigstered into
0278  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
0279  * userfault that has already been resolved, if userfaultfd_read and
0280  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
0281  * threads.
0282  */
0283 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
0284                      unsigned long address,
0285                      unsigned long flags,
0286                      unsigned long reason)
0287 {
0288     struct mm_struct *mm = ctx->mm;
0289     pgd_t *pgd;
0290     p4d_t *p4d;
0291     pud_t *pud;
0292     pmd_t *pmd, _pmd;
0293     pte_t *pte;
0294     bool ret = true;
0295 
0296     mmap_assert_locked(mm);
0297 
0298     pgd = pgd_offset(mm, address);
0299     if (!pgd_present(*pgd))
0300         goto out;
0301     p4d = p4d_offset(pgd, address);
0302     if (!p4d_present(*p4d))
0303         goto out;
0304     pud = pud_offset(p4d, address);
0305     if (!pud_present(*pud))
0306         goto out;
0307     pmd = pmd_offset(pud, address);
0308     /*
0309      * READ_ONCE must function as a barrier with narrower scope
0310      * and it must be equivalent to:
0311      *  _pmd = *pmd; barrier();
0312      *
0313      * This is to deal with the instability (as in
0314      * pmd_trans_unstable) of the pmd.
0315      */
0316     _pmd = READ_ONCE(*pmd);
0317     if (pmd_none(_pmd))
0318         goto out;
0319 
0320     ret = false;
0321     if (!pmd_present(_pmd))
0322         goto out;
0323 
0324     if (pmd_trans_huge(_pmd)) {
0325         if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
0326             ret = true;
0327         goto out;
0328     }
0329 
0330     /*
0331      * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
0332      * and use the standard pte_offset_map() instead of parsing _pmd.
0333      */
0334     pte = pte_offset_map(pmd, address);
0335     /*
0336      * Lockless access: we're in a wait_event so it's ok if it
0337      * changes under us.  PTE markers should be handled the same as none
0338      * ptes here.
0339      */
0340     if (pte_none_mostly(*pte))
0341         ret = true;
0342     if (!pte_write(*pte) && (reason & VM_UFFD_WP))
0343         ret = true;
0344     pte_unmap(pte);
0345 
0346 out:
0347     return ret;
0348 }
0349 
0350 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
0351 {
0352     if (flags & FAULT_FLAG_INTERRUPTIBLE)
0353         return TASK_INTERRUPTIBLE;
0354 
0355     if (flags & FAULT_FLAG_KILLABLE)
0356         return TASK_KILLABLE;
0357 
0358     return TASK_UNINTERRUPTIBLE;
0359 }
0360 
0361 /*
0362  * The locking rules involved in returning VM_FAULT_RETRY depending on
0363  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
0364  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
0365  * recommendation in __lock_page_or_retry is not an understatement.
0366  *
0367  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
0368  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
0369  * not set.
0370  *
0371  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
0372  * set, VM_FAULT_RETRY can still be returned if and only if there are
0373  * fatal_signal_pending()s, and the mmap_lock must be released before
0374  * returning it.
0375  */
0376 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
0377 {
0378     struct mm_struct *mm = vmf->vma->vm_mm;
0379     struct userfaultfd_ctx *ctx;
0380     struct userfaultfd_wait_queue uwq;
0381     vm_fault_t ret = VM_FAULT_SIGBUS;
0382     bool must_wait;
0383     unsigned int blocking_state;
0384 
0385     /*
0386      * We don't do userfault handling for the final child pid update.
0387      *
0388      * We also don't do userfault handling during
0389      * coredumping. hugetlbfs has the special
0390      * follow_hugetlb_page() to skip missing pages in the
0391      * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
0392      * the no_page_table() helper in follow_page_mask(), but the
0393      * shmem_vm_ops->fault method is invoked even during
0394      * coredumping without mmap_lock and it ends up here.
0395      */
0396     if (current->flags & (PF_EXITING|PF_DUMPCORE))
0397         goto out;
0398 
0399     /*
0400      * Coredumping runs without mmap_lock so we can only check that
0401      * the mmap_lock is held, if PF_DUMPCORE was not set.
0402      */
0403     mmap_assert_locked(mm);
0404 
0405     ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
0406     if (!ctx)
0407         goto out;
0408 
0409     BUG_ON(ctx->mm != mm);
0410 
0411     /* Any unrecognized flag is a bug. */
0412     VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
0413     /* 0 or > 1 flags set is a bug; we expect exactly 1. */
0414     VM_BUG_ON(!reason || (reason & (reason - 1)));
0415 
0416     if (ctx->features & UFFD_FEATURE_SIGBUS)
0417         goto out;
0418     if ((vmf->flags & FAULT_FLAG_USER) == 0 &&
0419         ctx->flags & UFFD_USER_MODE_ONLY) {
0420         printk_once(KERN_WARNING "uffd: Set unprivileged_userfaultfd "
0421             "sysctl knob to 1 if kernel faults must be handled "
0422             "without obtaining CAP_SYS_PTRACE capability\n");
0423         goto out;
0424     }
0425 
0426     /*
0427      * If it's already released don't get it. This avoids to loop
0428      * in __get_user_pages if userfaultfd_release waits on the
0429      * caller of handle_userfault to release the mmap_lock.
0430      */
0431     if (unlikely(READ_ONCE(ctx->released))) {
0432         /*
0433          * Don't return VM_FAULT_SIGBUS in this case, so a non
0434          * cooperative manager can close the uffd after the
0435          * last UFFDIO_COPY, without risking to trigger an
0436          * involuntary SIGBUS if the process was starting the
0437          * userfaultfd while the userfaultfd was still armed
0438          * (but after the last UFFDIO_COPY). If the uffd
0439          * wasn't already closed when the userfault reached
0440          * this point, that would normally be solved by
0441          * userfaultfd_must_wait returning 'false'.
0442          *
0443          * If we were to return VM_FAULT_SIGBUS here, the non
0444          * cooperative manager would be instead forced to
0445          * always call UFFDIO_UNREGISTER before it can safely
0446          * close the uffd.
0447          */
0448         ret = VM_FAULT_NOPAGE;
0449         goto out;
0450     }
0451 
0452     /*
0453      * Check that we can return VM_FAULT_RETRY.
0454      *
0455      * NOTE: it should become possible to return VM_FAULT_RETRY
0456      * even if FAULT_FLAG_TRIED is set without leading to gup()
0457      * -EBUSY failures, if the userfaultfd is to be extended for
0458      * VM_UFFD_WP tracking and we intend to arm the userfault
0459      * without first stopping userland access to the memory. For
0460      * VM_UFFD_MISSING userfaults this is enough for now.
0461      */
0462     if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
0463         /*
0464          * Validate the invariant that nowait must allow retry
0465          * to be sure not to return SIGBUS erroneously on
0466          * nowait invocations.
0467          */
0468         BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
0469 #ifdef CONFIG_DEBUG_VM
0470         if (printk_ratelimit()) {
0471             printk(KERN_WARNING
0472                    "FAULT_FLAG_ALLOW_RETRY missing %x\n",
0473                    vmf->flags);
0474             dump_stack();
0475         }
0476 #endif
0477         goto out;
0478     }
0479 
0480     /*
0481      * Handle nowait, not much to do other than tell it to retry
0482      * and wait.
0483      */
0484     ret = VM_FAULT_RETRY;
0485     if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
0486         goto out;
0487 
0488     /* take the reference before dropping the mmap_lock */
0489     userfaultfd_ctx_get(ctx);
0490 
0491     init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
0492     uwq.wq.private = current;
0493     uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
0494                 reason, ctx->features);
0495     uwq.ctx = ctx;
0496     uwq.waken = false;
0497 
0498     blocking_state = userfaultfd_get_blocking_state(vmf->flags);
0499 
0500     spin_lock_irq(&ctx->fault_pending_wqh.lock);
0501     /*
0502      * After the __add_wait_queue the uwq is visible to userland
0503      * through poll/read().
0504      */
0505     __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
0506     /*
0507      * The smp_mb() after __set_current_state prevents the reads
0508      * following the spin_unlock to happen before the list_add in
0509      * __add_wait_queue.
0510      */
0511     set_current_state(blocking_state);
0512     spin_unlock_irq(&ctx->fault_pending_wqh.lock);
0513 
0514     if (!is_vm_hugetlb_page(vmf->vma))
0515         must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
0516                           reason);
0517     else
0518         must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
0519                                vmf->address,
0520                                vmf->flags, reason);
0521     mmap_read_unlock(mm);
0522 
0523     if (likely(must_wait && !READ_ONCE(ctx->released))) {
0524         wake_up_poll(&ctx->fd_wqh, EPOLLIN);
0525         schedule();
0526     }
0527 
0528     __set_current_state(TASK_RUNNING);
0529 
0530     /*
0531      * Here we race with the list_del; list_add in
0532      * userfaultfd_ctx_read(), however because we don't ever run
0533      * list_del_init() to refile across the two lists, the prev
0534      * and next pointers will never point to self. list_add also
0535      * would never let any of the two pointers to point to
0536      * self. So list_empty_careful won't risk to see both pointers
0537      * pointing to self at any time during the list refile. The
0538      * only case where list_del_init() is called is the full
0539      * removal in the wake function and there we don't re-list_add
0540      * and it's fine not to block on the spinlock. The uwq on this
0541      * kernel stack can be released after the list_del_init.
0542      */
0543     if (!list_empty_careful(&uwq.wq.entry)) {
0544         spin_lock_irq(&ctx->fault_pending_wqh.lock);
0545         /*
0546          * No need of list_del_init(), the uwq on the stack
0547          * will be freed shortly anyway.
0548          */
0549         list_del(&uwq.wq.entry);
0550         spin_unlock_irq(&ctx->fault_pending_wqh.lock);
0551     }
0552 
0553     /*
0554      * ctx may go away after this if the userfault pseudo fd is
0555      * already released.
0556      */
0557     userfaultfd_ctx_put(ctx);
0558 
0559 out:
0560     return ret;
0561 }
0562 
0563 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
0564                           struct userfaultfd_wait_queue *ewq)
0565 {
0566     struct userfaultfd_ctx *release_new_ctx;
0567 
0568     if (WARN_ON_ONCE(current->flags & PF_EXITING))
0569         goto out;
0570 
0571     ewq->ctx = ctx;
0572     init_waitqueue_entry(&ewq->wq, current);
0573     release_new_ctx = NULL;
0574 
0575     spin_lock_irq(&ctx->event_wqh.lock);
0576     /*
0577      * After the __add_wait_queue the uwq is visible to userland
0578      * through poll/read().
0579      */
0580     __add_wait_queue(&ctx->event_wqh, &ewq->wq);
0581     for (;;) {
0582         set_current_state(TASK_KILLABLE);
0583         if (ewq->msg.event == 0)
0584             break;
0585         if (READ_ONCE(ctx->released) ||
0586             fatal_signal_pending(current)) {
0587             /*
0588              * &ewq->wq may be queued in fork_event, but
0589              * __remove_wait_queue ignores the head
0590              * parameter. It would be a problem if it
0591              * didn't.
0592              */
0593             __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
0594             if (ewq->msg.event == UFFD_EVENT_FORK) {
0595                 struct userfaultfd_ctx *new;
0596 
0597                 new = (struct userfaultfd_ctx *)
0598                     (unsigned long)
0599                     ewq->msg.arg.reserved.reserved1;
0600                 release_new_ctx = new;
0601             }
0602             break;
0603         }
0604 
0605         spin_unlock_irq(&ctx->event_wqh.lock);
0606 
0607         wake_up_poll(&ctx->fd_wqh, EPOLLIN);
0608         schedule();
0609 
0610         spin_lock_irq(&ctx->event_wqh.lock);
0611     }
0612     __set_current_state(TASK_RUNNING);
0613     spin_unlock_irq(&ctx->event_wqh.lock);
0614 
0615     if (release_new_ctx) {
0616         struct vm_area_struct *vma;
0617         struct mm_struct *mm = release_new_ctx->mm;
0618 
0619         /* the various vma->vm_userfaultfd_ctx still points to it */
0620         mmap_write_lock(mm);
0621         for (vma = mm->mmap; vma; vma = vma->vm_next)
0622             if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
0623                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
0624                 vma->vm_flags &= ~__VM_UFFD_FLAGS;
0625             }
0626         mmap_write_unlock(mm);
0627 
0628         userfaultfd_ctx_put(release_new_ctx);
0629     }
0630 
0631     /*
0632      * ctx may go away after this if the userfault pseudo fd is
0633      * already released.
0634      */
0635 out:
0636     atomic_dec(&ctx->mmap_changing);
0637     VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
0638     userfaultfd_ctx_put(ctx);
0639 }
0640 
0641 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
0642                        struct userfaultfd_wait_queue *ewq)
0643 {
0644     ewq->msg.event = 0;
0645     wake_up_locked(&ctx->event_wqh);
0646     __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
0647 }
0648 
0649 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
0650 {
0651     struct userfaultfd_ctx *ctx = NULL, *octx;
0652     struct userfaultfd_fork_ctx *fctx;
0653 
0654     octx = vma->vm_userfaultfd_ctx.ctx;
0655     if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
0656         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
0657         vma->vm_flags &= ~__VM_UFFD_FLAGS;
0658         return 0;
0659     }
0660 
0661     list_for_each_entry(fctx, fcs, list)
0662         if (fctx->orig == octx) {
0663             ctx = fctx->new;
0664             break;
0665         }
0666 
0667     if (!ctx) {
0668         fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
0669         if (!fctx)
0670             return -ENOMEM;
0671 
0672         ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
0673         if (!ctx) {
0674             kfree(fctx);
0675             return -ENOMEM;
0676         }
0677 
0678         refcount_set(&ctx->refcount, 1);
0679         ctx->flags = octx->flags;
0680         ctx->features = octx->features;
0681         ctx->released = false;
0682         atomic_set(&ctx->mmap_changing, 0);
0683         ctx->mm = vma->vm_mm;
0684         mmgrab(ctx->mm);
0685 
0686         userfaultfd_ctx_get(octx);
0687         atomic_inc(&octx->mmap_changing);
0688         fctx->orig = octx;
0689         fctx->new = ctx;
0690         list_add_tail(&fctx->list, fcs);
0691     }
0692 
0693     vma->vm_userfaultfd_ctx.ctx = ctx;
0694     return 0;
0695 }
0696 
0697 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
0698 {
0699     struct userfaultfd_ctx *ctx = fctx->orig;
0700     struct userfaultfd_wait_queue ewq;
0701 
0702     msg_init(&ewq.msg);
0703 
0704     ewq.msg.event = UFFD_EVENT_FORK;
0705     ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
0706 
0707     userfaultfd_event_wait_completion(ctx, &ewq);
0708 }
0709 
0710 void dup_userfaultfd_complete(struct list_head *fcs)
0711 {
0712     struct userfaultfd_fork_ctx *fctx, *n;
0713 
0714     list_for_each_entry_safe(fctx, n, fcs, list) {
0715         dup_fctx(fctx);
0716         list_del(&fctx->list);
0717         kfree(fctx);
0718     }
0719 }
0720 
0721 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
0722                  struct vm_userfaultfd_ctx *vm_ctx)
0723 {
0724     struct userfaultfd_ctx *ctx;
0725 
0726     ctx = vma->vm_userfaultfd_ctx.ctx;
0727 
0728     if (!ctx)
0729         return;
0730 
0731     if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
0732         vm_ctx->ctx = ctx;
0733         userfaultfd_ctx_get(ctx);
0734         atomic_inc(&ctx->mmap_changing);
0735     } else {
0736         /* Drop uffd context if remap feature not enabled */
0737         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
0738         vma->vm_flags &= ~__VM_UFFD_FLAGS;
0739     }
0740 }
0741 
0742 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
0743                  unsigned long from, unsigned long to,
0744                  unsigned long len)
0745 {
0746     struct userfaultfd_ctx *ctx = vm_ctx->ctx;
0747     struct userfaultfd_wait_queue ewq;
0748 
0749     if (!ctx)
0750         return;
0751 
0752     if (to & ~PAGE_MASK) {
0753         userfaultfd_ctx_put(ctx);
0754         return;
0755     }
0756 
0757     msg_init(&ewq.msg);
0758 
0759     ewq.msg.event = UFFD_EVENT_REMAP;
0760     ewq.msg.arg.remap.from = from;
0761     ewq.msg.arg.remap.to = to;
0762     ewq.msg.arg.remap.len = len;
0763 
0764     userfaultfd_event_wait_completion(ctx, &ewq);
0765 }
0766 
0767 bool userfaultfd_remove(struct vm_area_struct *vma,
0768             unsigned long start, unsigned long end)
0769 {
0770     struct mm_struct *mm = vma->vm_mm;
0771     struct userfaultfd_ctx *ctx;
0772     struct userfaultfd_wait_queue ewq;
0773 
0774     ctx = vma->vm_userfaultfd_ctx.ctx;
0775     if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
0776         return true;
0777 
0778     userfaultfd_ctx_get(ctx);
0779     atomic_inc(&ctx->mmap_changing);
0780     mmap_read_unlock(mm);
0781 
0782     msg_init(&ewq.msg);
0783 
0784     ewq.msg.event = UFFD_EVENT_REMOVE;
0785     ewq.msg.arg.remove.start = start;
0786     ewq.msg.arg.remove.end = end;
0787 
0788     userfaultfd_event_wait_completion(ctx, &ewq);
0789 
0790     return false;
0791 }
0792 
0793 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
0794               unsigned long start, unsigned long end)
0795 {
0796     struct userfaultfd_unmap_ctx *unmap_ctx;
0797 
0798     list_for_each_entry(unmap_ctx, unmaps, list)
0799         if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
0800             unmap_ctx->end == end)
0801             return true;
0802 
0803     return false;
0804 }
0805 
0806 int userfaultfd_unmap_prep(struct vm_area_struct *vma,
0807                unsigned long start, unsigned long end,
0808                struct list_head *unmaps)
0809 {
0810     for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
0811         struct userfaultfd_unmap_ctx *unmap_ctx;
0812         struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
0813 
0814         if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
0815             has_unmap_ctx(ctx, unmaps, start, end))
0816             continue;
0817 
0818         unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
0819         if (!unmap_ctx)
0820             return -ENOMEM;
0821 
0822         userfaultfd_ctx_get(ctx);
0823         atomic_inc(&ctx->mmap_changing);
0824         unmap_ctx->ctx = ctx;
0825         unmap_ctx->start = start;
0826         unmap_ctx->end = end;
0827         list_add_tail(&unmap_ctx->list, unmaps);
0828     }
0829 
0830     return 0;
0831 }
0832 
0833 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
0834 {
0835     struct userfaultfd_unmap_ctx *ctx, *n;
0836     struct userfaultfd_wait_queue ewq;
0837 
0838     list_for_each_entry_safe(ctx, n, uf, list) {
0839         msg_init(&ewq.msg);
0840 
0841         ewq.msg.event = UFFD_EVENT_UNMAP;
0842         ewq.msg.arg.remove.start = ctx->start;
0843         ewq.msg.arg.remove.end = ctx->end;
0844 
0845         userfaultfd_event_wait_completion(ctx->ctx, &ewq);
0846 
0847         list_del(&ctx->list);
0848         kfree(ctx);
0849     }
0850 }
0851 
0852 static int userfaultfd_release(struct inode *inode, struct file *file)
0853 {
0854     struct userfaultfd_ctx *ctx = file->private_data;
0855     struct mm_struct *mm = ctx->mm;
0856     struct vm_area_struct *vma, *prev;
0857     /* len == 0 means wake all */
0858     struct userfaultfd_wake_range range = { .len = 0, };
0859     unsigned long new_flags;
0860 
0861     WRITE_ONCE(ctx->released, true);
0862 
0863     if (!mmget_not_zero(mm))
0864         goto wakeup;
0865 
0866     /*
0867      * Flush page faults out of all CPUs. NOTE: all page faults
0868      * must be retried without returning VM_FAULT_SIGBUS if
0869      * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
0870      * changes while handle_userfault released the mmap_lock. So
0871      * it's critical that released is set to true (above), before
0872      * taking the mmap_lock for writing.
0873      */
0874     mmap_write_lock(mm);
0875     prev = NULL;
0876     for (vma = mm->mmap; vma; vma = vma->vm_next) {
0877         cond_resched();
0878         BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
0879                !!(vma->vm_flags & __VM_UFFD_FLAGS));
0880         if (vma->vm_userfaultfd_ctx.ctx != ctx) {
0881             prev = vma;
0882             continue;
0883         }
0884         new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
0885         prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
0886                  new_flags, vma->anon_vma,
0887                  vma->vm_file, vma->vm_pgoff,
0888                  vma_policy(vma),
0889                  NULL_VM_UFFD_CTX, anon_vma_name(vma));
0890         if (prev)
0891             vma = prev;
0892         else
0893             prev = vma;
0894         vma->vm_flags = new_flags;
0895         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
0896     }
0897     mmap_write_unlock(mm);
0898     mmput(mm);
0899 wakeup:
0900     /*
0901      * After no new page faults can wait on this fault_*wqh, flush
0902      * the last page faults that may have been already waiting on
0903      * the fault_*wqh.
0904      */
0905     spin_lock_irq(&ctx->fault_pending_wqh.lock);
0906     __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
0907     __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
0908     spin_unlock_irq(&ctx->fault_pending_wqh.lock);
0909 
0910     /* Flush pending events that may still wait on event_wqh */
0911     wake_up_all(&ctx->event_wqh);
0912 
0913     wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
0914     userfaultfd_ctx_put(ctx);
0915     return 0;
0916 }
0917 
0918 /* fault_pending_wqh.lock must be hold by the caller */
0919 static inline struct userfaultfd_wait_queue *find_userfault_in(
0920         wait_queue_head_t *wqh)
0921 {
0922     wait_queue_entry_t *wq;
0923     struct userfaultfd_wait_queue *uwq;
0924 
0925     lockdep_assert_held(&wqh->lock);
0926 
0927     uwq = NULL;
0928     if (!waitqueue_active(wqh))
0929         goto out;
0930     /* walk in reverse to provide FIFO behavior to read userfaults */
0931     wq = list_last_entry(&wqh->head, typeof(*wq), entry);
0932     uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
0933 out:
0934     return uwq;
0935 }
0936 
0937 static inline struct userfaultfd_wait_queue *find_userfault(
0938         struct userfaultfd_ctx *ctx)
0939 {
0940     return find_userfault_in(&ctx->fault_pending_wqh);
0941 }
0942 
0943 static inline struct userfaultfd_wait_queue *find_userfault_evt(
0944         struct userfaultfd_ctx *ctx)
0945 {
0946     return find_userfault_in(&ctx->event_wqh);
0947 }
0948 
0949 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
0950 {
0951     struct userfaultfd_ctx *ctx = file->private_data;
0952     __poll_t ret;
0953 
0954     poll_wait(file, &ctx->fd_wqh, wait);
0955 
0956     if (!userfaultfd_is_initialized(ctx))
0957         return EPOLLERR;
0958 
0959     /*
0960      * poll() never guarantees that read won't block.
0961      * userfaults can be waken before they're read().
0962      */
0963     if (unlikely(!(file->f_flags & O_NONBLOCK)))
0964         return EPOLLERR;
0965     /*
0966      * lockless access to see if there are pending faults
0967      * __pollwait last action is the add_wait_queue but
0968      * the spin_unlock would allow the waitqueue_active to
0969      * pass above the actual list_add inside
0970      * add_wait_queue critical section. So use a full
0971      * memory barrier to serialize the list_add write of
0972      * add_wait_queue() with the waitqueue_active read
0973      * below.
0974      */
0975     ret = 0;
0976     smp_mb();
0977     if (waitqueue_active(&ctx->fault_pending_wqh))
0978         ret = EPOLLIN;
0979     else if (waitqueue_active(&ctx->event_wqh))
0980         ret = EPOLLIN;
0981 
0982     return ret;
0983 }
0984 
0985 static const struct file_operations userfaultfd_fops;
0986 
0987 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
0988                   struct inode *inode,
0989                   struct uffd_msg *msg)
0990 {
0991     int fd;
0992 
0993     fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
0994             O_RDWR | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
0995     if (fd < 0)
0996         return fd;
0997 
0998     msg->arg.reserved.reserved1 = 0;
0999     msg->arg.fork.ufd = fd;
1000     return 0;
1001 }
1002 
1003 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1004                     struct uffd_msg *msg, struct inode *inode)
1005 {
1006     ssize_t ret;
1007     DECLARE_WAITQUEUE(wait, current);
1008     struct userfaultfd_wait_queue *uwq;
1009     /*
1010      * Handling fork event requires sleeping operations, so
1011      * we drop the event_wqh lock, then do these ops, then
1012      * lock it back and wake up the waiter. While the lock is
1013      * dropped the ewq may go away so we keep track of it
1014      * carefully.
1015      */
1016     LIST_HEAD(fork_event);
1017     struct userfaultfd_ctx *fork_nctx = NULL;
1018 
1019     /* always take the fd_wqh lock before the fault_pending_wqh lock */
1020     spin_lock_irq(&ctx->fd_wqh.lock);
1021     __add_wait_queue(&ctx->fd_wqh, &wait);
1022     for (;;) {
1023         set_current_state(TASK_INTERRUPTIBLE);
1024         spin_lock(&ctx->fault_pending_wqh.lock);
1025         uwq = find_userfault(ctx);
1026         if (uwq) {
1027             /*
1028              * Use a seqcount to repeat the lockless check
1029              * in wake_userfault() to avoid missing
1030              * wakeups because during the refile both
1031              * waitqueue could become empty if this is the
1032              * only userfault.
1033              */
1034             write_seqcount_begin(&ctx->refile_seq);
1035 
1036             /*
1037              * The fault_pending_wqh.lock prevents the uwq
1038              * to disappear from under us.
1039              *
1040              * Refile this userfault from
1041              * fault_pending_wqh to fault_wqh, it's not
1042              * pending anymore after we read it.
1043              *
1044              * Use list_del() by hand (as
1045              * userfaultfd_wake_function also uses
1046              * list_del_init() by hand) to be sure nobody
1047              * changes __remove_wait_queue() to use
1048              * list_del_init() in turn breaking the
1049              * !list_empty_careful() check in
1050              * handle_userfault(). The uwq->wq.head list
1051              * must never be empty at any time during the
1052              * refile, or the waitqueue could disappear
1053              * from under us. The "wait_queue_head_t"
1054              * parameter of __remove_wait_queue() is unused
1055              * anyway.
1056              */
1057             list_del(&uwq->wq.entry);
1058             add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1059 
1060             write_seqcount_end(&ctx->refile_seq);
1061 
1062             /* careful to always initialize msg if ret == 0 */
1063             *msg = uwq->msg;
1064             spin_unlock(&ctx->fault_pending_wqh.lock);
1065             ret = 0;
1066             break;
1067         }
1068         spin_unlock(&ctx->fault_pending_wqh.lock);
1069 
1070         spin_lock(&ctx->event_wqh.lock);
1071         uwq = find_userfault_evt(ctx);
1072         if (uwq) {
1073             *msg = uwq->msg;
1074 
1075             if (uwq->msg.event == UFFD_EVENT_FORK) {
1076                 fork_nctx = (struct userfaultfd_ctx *)
1077                     (unsigned long)
1078                     uwq->msg.arg.reserved.reserved1;
1079                 list_move(&uwq->wq.entry, &fork_event);
1080                 /*
1081                  * fork_nctx can be freed as soon as
1082                  * we drop the lock, unless we take a
1083                  * reference on it.
1084                  */
1085                 userfaultfd_ctx_get(fork_nctx);
1086                 spin_unlock(&ctx->event_wqh.lock);
1087                 ret = 0;
1088                 break;
1089             }
1090 
1091             userfaultfd_event_complete(ctx, uwq);
1092             spin_unlock(&ctx->event_wqh.lock);
1093             ret = 0;
1094             break;
1095         }
1096         spin_unlock(&ctx->event_wqh.lock);
1097 
1098         if (signal_pending(current)) {
1099             ret = -ERESTARTSYS;
1100             break;
1101         }
1102         if (no_wait) {
1103             ret = -EAGAIN;
1104             break;
1105         }
1106         spin_unlock_irq(&ctx->fd_wqh.lock);
1107         schedule();
1108         spin_lock_irq(&ctx->fd_wqh.lock);
1109     }
1110     __remove_wait_queue(&ctx->fd_wqh, &wait);
1111     __set_current_state(TASK_RUNNING);
1112     spin_unlock_irq(&ctx->fd_wqh.lock);
1113 
1114     if (!ret && msg->event == UFFD_EVENT_FORK) {
1115         ret = resolve_userfault_fork(fork_nctx, inode, msg);
1116         spin_lock_irq(&ctx->event_wqh.lock);
1117         if (!list_empty(&fork_event)) {
1118             /*
1119              * The fork thread didn't abort, so we can
1120              * drop the temporary refcount.
1121              */
1122             userfaultfd_ctx_put(fork_nctx);
1123 
1124             uwq = list_first_entry(&fork_event,
1125                            typeof(*uwq),
1126                            wq.entry);
1127             /*
1128              * If fork_event list wasn't empty and in turn
1129              * the event wasn't already released by fork
1130              * (the event is allocated on fork kernel
1131              * stack), put the event back to its place in
1132              * the event_wq. fork_event head will be freed
1133              * as soon as we return so the event cannot
1134              * stay queued there no matter the current
1135              * "ret" value.
1136              */
1137             list_del(&uwq->wq.entry);
1138             __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1139 
1140             /*
1141              * Leave the event in the waitqueue and report
1142              * error to userland if we failed to resolve
1143              * the userfault fork.
1144              */
1145             if (likely(!ret))
1146                 userfaultfd_event_complete(ctx, uwq);
1147         } else {
1148             /*
1149              * Here the fork thread aborted and the
1150              * refcount from the fork thread on fork_nctx
1151              * has already been released. We still hold
1152              * the reference we took before releasing the
1153              * lock above. If resolve_userfault_fork
1154              * failed we've to drop it because the
1155              * fork_nctx has to be freed in such case. If
1156              * it succeeded we'll hold it because the new
1157              * uffd references it.
1158              */
1159             if (ret)
1160                 userfaultfd_ctx_put(fork_nctx);
1161         }
1162         spin_unlock_irq(&ctx->event_wqh.lock);
1163     }
1164 
1165     return ret;
1166 }
1167 
1168 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1169                 size_t count, loff_t *ppos)
1170 {
1171     struct userfaultfd_ctx *ctx = file->private_data;
1172     ssize_t _ret, ret = 0;
1173     struct uffd_msg msg;
1174     int no_wait = file->f_flags & O_NONBLOCK;
1175     struct inode *inode = file_inode(file);
1176 
1177     if (!userfaultfd_is_initialized(ctx))
1178         return -EINVAL;
1179 
1180     for (;;) {
1181         if (count < sizeof(msg))
1182             return ret ? ret : -EINVAL;
1183         _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1184         if (_ret < 0)
1185             return ret ? ret : _ret;
1186         if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1187             return ret ? ret : -EFAULT;
1188         ret += sizeof(msg);
1189         buf += sizeof(msg);
1190         count -= sizeof(msg);
1191         /*
1192          * Allow to read more than one fault at time but only
1193          * block if waiting for the very first one.
1194          */
1195         no_wait = O_NONBLOCK;
1196     }
1197 }
1198 
1199 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1200                  struct userfaultfd_wake_range *range)
1201 {
1202     spin_lock_irq(&ctx->fault_pending_wqh.lock);
1203     /* wake all in the range and autoremove */
1204     if (waitqueue_active(&ctx->fault_pending_wqh))
1205         __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1206                      range);
1207     if (waitqueue_active(&ctx->fault_wqh))
1208         __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1209     spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1210 }
1211 
1212 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1213                        struct userfaultfd_wake_range *range)
1214 {
1215     unsigned seq;
1216     bool need_wakeup;
1217 
1218     /*
1219      * To be sure waitqueue_active() is not reordered by the CPU
1220      * before the pagetable update, use an explicit SMP memory
1221      * barrier here. PT lock release or mmap_read_unlock(mm) still
1222      * have release semantics that can allow the
1223      * waitqueue_active() to be reordered before the pte update.
1224      */
1225     smp_mb();
1226 
1227     /*
1228      * Use waitqueue_active because it's very frequent to
1229      * change the address space atomically even if there are no
1230      * userfaults yet. So we take the spinlock only when we're
1231      * sure we've userfaults to wake.
1232      */
1233     do {
1234         seq = read_seqcount_begin(&ctx->refile_seq);
1235         need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1236             waitqueue_active(&ctx->fault_wqh);
1237         cond_resched();
1238     } while (read_seqcount_retry(&ctx->refile_seq, seq));
1239     if (need_wakeup)
1240         __wake_userfault(ctx, range);
1241 }
1242 
1243 static __always_inline int validate_range(struct mm_struct *mm,
1244                       __u64 start, __u64 len)
1245 {
1246     __u64 task_size = mm->task_size;
1247 
1248     if (start & ~PAGE_MASK)
1249         return -EINVAL;
1250     if (len & ~PAGE_MASK)
1251         return -EINVAL;
1252     if (!len)
1253         return -EINVAL;
1254     if (start < mmap_min_addr)
1255         return -EINVAL;
1256     if (start >= task_size)
1257         return -EINVAL;
1258     if (len > task_size - start)
1259         return -EINVAL;
1260     return 0;
1261 }
1262 
1263 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1264                 unsigned long arg)
1265 {
1266     struct mm_struct *mm = ctx->mm;
1267     struct vm_area_struct *vma, *prev, *cur;
1268     int ret;
1269     struct uffdio_register uffdio_register;
1270     struct uffdio_register __user *user_uffdio_register;
1271     unsigned long vm_flags, new_flags;
1272     bool found;
1273     bool basic_ioctls;
1274     unsigned long start, end, vma_end;
1275 
1276     user_uffdio_register = (struct uffdio_register __user *) arg;
1277 
1278     ret = -EFAULT;
1279     if (copy_from_user(&uffdio_register, user_uffdio_register,
1280                sizeof(uffdio_register)-sizeof(__u64)))
1281         goto out;
1282 
1283     ret = -EINVAL;
1284     if (!uffdio_register.mode)
1285         goto out;
1286     if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1287         goto out;
1288     vm_flags = 0;
1289     if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1290         vm_flags |= VM_UFFD_MISSING;
1291     if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1292 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1293         goto out;
1294 #endif
1295         vm_flags |= VM_UFFD_WP;
1296     }
1297     if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1298 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1299         goto out;
1300 #endif
1301         vm_flags |= VM_UFFD_MINOR;
1302     }
1303 
1304     ret = validate_range(mm, uffdio_register.range.start,
1305                  uffdio_register.range.len);
1306     if (ret)
1307         goto out;
1308 
1309     start = uffdio_register.range.start;
1310     end = start + uffdio_register.range.len;
1311 
1312     ret = -ENOMEM;
1313     if (!mmget_not_zero(mm))
1314         goto out;
1315 
1316     mmap_write_lock(mm);
1317     vma = find_vma_prev(mm, start, &prev);
1318     if (!vma)
1319         goto out_unlock;
1320 
1321     /* check that there's at least one vma in the range */
1322     ret = -EINVAL;
1323     if (vma->vm_start >= end)
1324         goto out_unlock;
1325 
1326     /*
1327      * If the first vma contains huge pages, make sure start address
1328      * is aligned to huge page size.
1329      */
1330     if (is_vm_hugetlb_page(vma)) {
1331         unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1332 
1333         if (start & (vma_hpagesize - 1))
1334             goto out_unlock;
1335     }
1336 
1337     /*
1338      * Search for not compatible vmas.
1339      */
1340     found = false;
1341     basic_ioctls = false;
1342     for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1343         cond_resched();
1344 
1345         BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1346                !!(cur->vm_flags & __VM_UFFD_FLAGS));
1347 
1348         /* check not compatible vmas */
1349         ret = -EINVAL;
1350         if (!vma_can_userfault(cur, vm_flags))
1351             goto out_unlock;
1352 
1353         /*
1354          * UFFDIO_COPY will fill file holes even without
1355          * PROT_WRITE. This check enforces that if this is a
1356          * MAP_SHARED, the process has write permission to the backing
1357          * file. If VM_MAYWRITE is set it also enforces that on a
1358          * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1359          * F_WRITE_SEAL can be taken until the vma is destroyed.
1360          */
1361         ret = -EPERM;
1362         if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1363             goto out_unlock;
1364 
1365         /*
1366          * If this vma contains ending address, and huge pages
1367          * check alignment.
1368          */
1369         if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1370             end > cur->vm_start) {
1371             unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1372 
1373             ret = -EINVAL;
1374 
1375             if (end & (vma_hpagesize - 1))
1376                 goto out_unlock;
1377         }
1378         if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1379             goto out_unlock;
1380 
1381         /*
1382          * Check that this vma isn't already owned by a
1383          * different userfaultfd. We can't allow more than one
1384          * userfaultfd to own a single vma simultaneously or we
1385          * wouldn't know which one to deliver the userfaults to.
1386          */
1387         ret = -EBUSY;
1388         if (cur->vm_userfaultfd_ctx.ctx &&
1389             cur->vm_userfaultfd_ctx.ctx != ctx)
1390             goto out_unlock;
1391 
1392         /*
1393          * Note vmas containing huge pages
1394          */
1395         if (is_vm_hugetlb_page(cur))
1396             basic_ioctls = true;
1397 
1398         found = true;
1399     }
1400     BUG_ON(!found);
1401 
1402     if (vma->vm_start < start)
1403         prev = vma;
1404 
1405     ret = 0;
1406     do {
1407         cond_resched();
1408 
1409         BUG_ON(!vma_can_userfault(vma, vm_flags));
1410         BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1411                vma->vm_userfaultfd_ctx.ctx != ctx);
1412         WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1413 
1414         /*
1415          * Nothing to do: this vma is already registered into this
1416          * userfaultfd and with the right tracking mode too.
1417          */
1418         if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1419             (vma->vm_flags & vm_flags) == vm_flags)
1420             goto skip;
1421 
1422         if (vma->vm_start > start)
1423             start = vma->vm_start;
1424         vma_end = min(end, vma->vm_end);
1425 
1426         new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1427         prev = vma_merge(mm, prev, start, vma_end, new_flags,
1428                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1429                  vma_policy(vma),
1430                  ((struct vm_userfaultfd_ctx){ ctx }),
1431                  anon_vma_name(vma));
1432         if (prev) {
1433             vma = prev;
1434             goto next;
1435         }
1436         if (vma->vm_start < start) {
1437             ret = split_vma(mm, vma, start, 1);
1438             if (ret)
1439                 break;
1440         }
1441         if (vma->vm_end > end) {
1442             ret = split_vma(mm, vma, end, 0);
1443             if (ret)
1444                 break;
1445         }
1446     next:
1447         /*
1448          * In the vma_merge() successful mprotect-like case 8:
1449          * the next vma was merged into the current one and
1450          * the current one has not been updated yet.
1451          */
1452         vma->vm_flags = new_flags;
1453         vma->vm_userfaultfd_ctx.ctx = ctx;
1454 
1455         if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1456             hugetlb_unshare_all_pmds(vma);
1457 
1458     skip:
1459         prev = vma;
1460         start = vma->vm_end;
1461         vma = vma->vm_next;
1462     } while (vma && vma->vm_start < end);
1463 out_unlock:
1464     mmap_write_unlock(mm);
1465     mmput(mm);
1466     if (!ret) {
1467         __u64 ioctls_out;
1468 
1469         ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1470             UFFD_API_RANGE_IOCTLS;
1471 
1472         /*
1473          * Declare the WP ioctl only if the WP mode is
1474          * specified and all checks passed with the range
1475          */
1476         if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1477             ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1478 
1479         /* CONTINUE ioctl is only supported for MINOR ranges. */
1480         if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1481             ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1482 
1483         /*
1484          * Now that we scanned all vmas we can already tell
1485          * userland which ioctls methods are guaranteed to
1486          * succeed on this range.
1487          */
1488         if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1489             ret = -EFAULT;
1490     }
1491 out:
1492     return ret;
1493 }
1494 
1495 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1496                   unsigned long arg)
1497 {
1498     struct mm_struct *mm = ctx->mm;
1499     struct vm_area_struct *vma, *prev, *cur;
1500     int ret;
1501     struct uffdio_range uffdio_unregister;
1502     unsigned long new_flags;
1503     bool found;
1504     unsigned long start, end, vma_end;
1505     const void __user *buf = (void __user *)arg;
1506 
1507     ret = -EFAULT;
1508     if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1509         goto out;
1510 
1511     ret = validate_range(mm, uffdio_unregister.start,
1512                  uffdio_unregister.len);
1513     if (ret)
1514         goto out;
1515 
1516     start = uffdio_unregister.start;
1517     end = start + uffdio_unregister.len;
1518 
1519     ret = -ENOMEM;
1520     if (!mmget_not_zero(mm))
1521         goto out;
1522 
1523     mmap_write_lock(mm);
1524     vma = find_vma_prev(mm, start, &prev);
1525     if (!vma)
1526         goto out_unlock;
1527 
1528     /* check that there's at least one vma in the range */
1529     ret = -EINVAL;
1530     if (vma->vm_start >= end)
1531         goto out_unlock;
1532 
1533     /*
1534      * If the first vma contains huge pages, make sure start address
1535      * is aligned to huge page size.
1536      */
1537     if (is_vm_hugetlb_page(vma)) {
1538         unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1539 
1540         if (start & (vma_hpagesize - 1))
1541             goto out_unlock;
1542     }
1543 
1544     /*
1545      * Search for not compatible vmas.
1546      */
1547     found = false;
1548     ret = -EINVAL;
1549     for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1550         cond_resched();
1551 
1552         BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1553                !!(cur->vm_flags & __VM_UFFD_FLAGS));
1554 
1555         /*
1556          * Check not compatible vmas, not strictly required
1557          * here as not compatible vmas cannot have an
1558          * userfaultfd_ctx registered on them, but this
1559          * provides for more strict behavior to notice
1560          * unregistration errors.
1561          */
1562         if (!vma_can_userfault(cur, cur->vm_flags))
1563             goto out_unlock;
1564 
1565         found = true;
1566     }
1567     BUG_ON(!found);
1568 
1569     if (vma->vm_start < start)
1570         prev = vma;
1571 
1572     ret = 0;
1573     do {
1574         cond_resched();
1575 
1576         BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1577 
1578         /*
1579          * Nothing to do: this vma is already registered into this
1580          * userfaultfd and with the right tracking mode too.
1581          */
1582         if (!vma->vm_userfaultfd_ctx.ctx)
1583             goto skip;
1584 
1585         WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1586 
1587         if (vma->vm_start > start)
1588             start = vma->vm_start;
1589         vma_end = min(end, vma->vm_end);
1590 
1591         if (userfaultfd_missing(vma)) {
1592             /*
1593              * Wake any concurrent pending userfault while
1594              * we unregister, so they will not hang
1595              * permanently and it avoids userland to call
1596              * UFFDIO_WAKE explicitly.
1597              */
1598             struct userfaultfd_wake_range range;
1599             range.start = start;
1600             range.len = vma_end - start;
1601             wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1602         }
1603 
1604         /* Reset ptes for the whole vma range if wr-protected */
1605         if (userfaultfd_wp(vma))
1606             uffd_wp_range(mm, vma, start, vma_end - start, false);
1607 
1608         new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1609         prev = vma_merge(mm, prev, start, vma_end, new_flags,
1610                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1611                  vma_policy(vma),
1612                  NULL_VM_UFFD_CTX, anon_vma_name(vma));
1613         if (prev) {
1614             vma = prev;
1615             goto next;
1616         }
1617         if (vma->vm_start < start) {
1618             ret = split_vma(mm, vma, start, 1);
1619             if (ret)
1620                 break;
1621         }
1622         if (vma->vm_end > end) {
1623             ret = split_vma(mm, vma, end, 0);
1624             if (ret)
1625                 break;
1626         }
1627     next:
1628         /*
1629          * In the vma_merge() successful mprotect-like case 8:
1630          * the next vma was merged into the current one and
1631          * the current one has not been updated yet.
1632          */
1633         vma->vm_flags = new_flags;
1634         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1635 
1636     skip:
1637         prev = vma;
1638         start = vma->vm_end;
1639         vma = vma->vm_next;
1640     } while (vma && vma->vm_start < end);
1641 out_unlock:
1642     mmap_write_unlock(mm);
1643     mmput(mm);
1644 out:
1645     return ret;
1646 }
1647 
1648 /*
1649  * userfaultfd_wake may be used in combination with the
1650  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1651  */
1652 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1653                 unsigned long arg)
1654 {
1655     int ret;
1656     struct uffdio_range uffdio_wake;
1657     struct userfaultfd_wake_range range;
1658     const void __user *buf = (void __user *)arg;
1659 
1660     ret = -EFAULT;
1661     if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1662         goto out;
1663 
1664     ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1665     if (ret)
1666         goto out;
1667 
1668     range.start = uffdio_wake.start;
1669     range.len = uffdio_wake.len;
1670 
1671     /*
1672      * len == 0 means wake all and we don't want to wake all here,
1673      * so check it again to be sure.
1674      */
1675     VM_BUG_ON(!range.len);
1676 
1677     wake_userfault(ctx, &range);
1678     ret = 0;
1679 
1680 out:
1681     return ret;
1682 }
1683 
1684 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1685                 unsigned long arg)
1686 {
1687     __s64 ret;
1688     struct uffdio_copy uffdio_copy;
1689     struct uffdio_copy __user *user_uffdio_copy;
1690     struct userfaultfd_wake_range range;
1691 
1692     user_uffdio_copy = (struct uffdio_copy __user *) arg;
1693 
1694     ret = -EAGAIN;
1695     if (atomic_read(&ctx->mmap_changing))
1696         goto out;
1697 
1698     ret = -EFAULT;
1699     if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1700                /* don't copy "copy" last field */
1701                sizeof(uffdio_copy)-sizeof(__s64)))
1702         goto out;
1703 
1704     ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1705     if (ret)
1706         goto out;
1707     /*
1708      * double check for wraparound just in case. copy_from_user()
1709      * will later check uffdio_copy.src + uffdio_copy.len to fit
1710      * in the userland range.
1711      */
1712     ret = -EINVAL;
1713     if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1714         goto out;
1715     if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1716         goto out;
1717     if (mmget_not_zero(ctx->mm)) {
1718         ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1719                    uffdio_copy.len, &ctx->mmap_changing,
1720                    uffdio_copy.mode);
1721         mmput(ctx->mm);
1722     } else {
1723         return -ESRCH;
1724     }
1725     if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1726         return -EFAULT;
1727     if (ret < 0)
1728         goto out;
1729     BUG_ON(!ret);
1730     /* len == 0 would wake all */
1731     range.len = ret;
1732     if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1733         range.start = uffdio_copy.dst;
1734         wake_userfault(ctx, &range);
1735     }
1736     ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1737 out:
1738     return ret;
1739 }
1740 
1741 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1742                 unsigned long arg)
1743 {
1744     __s64 ret;
1745     struct uffdio_zeropage uffdio_zeropage;
1746     struct uffdio_zeropage __user *user_uffdio_zeropage;
1747     struct userfaultfd_wake_range range;
1748 
1749     user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1750 
1751     ret = -EAGAIN;
1752     if (atomic_read(&ctx->mmap_changing))
1753         goto out;
1754 
1755     ret = -EFAULT;
1756     if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1757                /* don't copy "zeropage" last field */
1758                sizeof(uffdio_zeropage)-sizeof(__s64)))
1759         goto out;
1760 
1761     ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1762                  uffdio_zeropage.range.len);
1763     if (ret)
1764         goto out;
1765     ret = -EINVAL;
1766     if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1767         goto out;
1768 
1769     if (mmget_not_zero(ctx->mm)) {
1770         ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1771                      uffdio_zeropage.range.len,
1772                      &ctx->mmap_changing);
1773         mmput(ctx->mm);
1774     } else {
1775         return -ESRCH;
1776     }
1777     if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1778         return -EFAULT;
1779     if (ret < 0)
1780         goto out;
1781     /* len == 0 would wake all */
1782     BUG_ON(!ret);
1783     range.len = ret;
1784     if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1785         range.start = uffdio_zeropage.range.start;
1786         wake_userfault(ctx, &range);
1787     }
1788     ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1789 out:
1790     return ret;
1791 }
1792 
1793 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1794                     unsigned long arg)
1795 {
1796     int ret;
1797     struct uffdio_writeprotect uffdio_wp;
1798     struct uffdio_writeprotect __user *user_uffdio_wp;
1799     struct userfaultfd_wake_range range;
1800     bool mode_wp, mode_dontwake;
1801 
1802     if (atomic_read(&ctx->mmap_changing))
1803         return -EAGAIN;
1804 
1805     user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1806 
1807     if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1808                sizeof(struct uffdio_writeprotect)))
1809         return -EFAULT;
1810 
1811     ret = validate_range(ctx->mm, uffdio_wp.range.start,
1812                  uffdio_wp.range.len);
1813     if (ret)
1814         return ret;
1815 
1816     if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1817                    UFFDIO_WRITEPROTECT_MODE_WP))
1818         return -EINVAL;
1819 
1820     mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1821     mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1822 
1823     if (mode_wp && mode_dontwake)
1824         return -EINVAL;
1825 
1826     if (mmget_not_zero(ctx->mm)) {
1827         ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1828                       uffdio_wp.range.len, mode_wp,
1829                       &ctx->mmap_changing);
1830         mmput(ctx->mm);
1831     } else {
1832         return -ESRCH;
1833     }
1834 
1835     if (ret)
1836         return ret;
1837 
1838     if (!mode_wp && !mode_dontwake) {
1839         range.start = uffdio_wp.range.start;
1840         range.len = uffdio_wp.range.len;
1841         wake_userfault(ctx, &range);
1842     }
1843     return ret;
1844 }
1845 
1846 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1847 {
1848     __s64 ret;
1849     struct uffdio_continue uffdio_continue;
1850     struct uffdio_continue __user *user_uffdio_continue;
1851     struct userfaultfd_wake_range range;
1852 
1853     user_uffdio_continue = (struct uffdio_continue __user *)arg;
1854 
1855     ret = -EAGAIN;
1856     if (atomic_read(&ctx->mmap_changing))
1857         goto out;
1858 
1859     ret = -EFAULT;
1860     if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1861                /* don't copy the output fields */
1862                sizeof(uffdio_continue) - (sizeof(__s64))))
1863         goto out;
1864 
1865     ret = validate_range(ctx->mm, uffdio_continue.range.start,
1866                  uffdio_continue.range.len);
1867     if (ret)
1868         goto out;
1869 
1870     ret = -EINVAL;
1871     /* double check for wraparound just in case. */
1872     if (uffdio_continue.range.start + uffdio_continue.range.len <=
1873         uffdio_continue.range.start) {
1874         goto out;
1875     }
1876     if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1877         goto out;
1878 
1879     if (mmget_not_zero(ctx->mm)) {
1880         ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1881                      uffdio_continue.range.len,
1882                      &ctx->mmap_changing);
1883         mmput(ctx->mm);
1884     } else {
1885         return -ESRCH;
1886     }
1887 
1888     if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1889         return -EFAULT;
1890     if (ret < 0)
1891         goto out;
1892 
1893     /* len == 0 would wake all */
1894     BUG_ON(!ret);
1895     range.len = ret;
1896     if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1897         range.start = uffdio_continue.range.start;
1898         wake_userfault(ctx, &range);
1899     }
1900     ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1901 
1902 out:
1903     return ret;
1904 }
1905 
1906 static inline unsigned int uffd_ctx_features(__u64 user_features)
1907 {
1908     /*
1909      * For the current set of features the bits just coincide. Set
1910      * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1911      */
1912     return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1913 }
1914 
1915 /*
1916  * userland asks for a certain API version and we return which bits
1917  * and ioctl commands are implemented in this kernel for such API
1918  * version or -EINVAL if unknown.
1919  */
1920 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1921                unsigned long arg)
1922 {
1923     struct uffdio_api uffdio_api;
1924     void __user *buf = (void __user *)arg;
1925     unsigned int ctx_features;
1926     int ret;
1927     __u64 features;
1928 
1929     ret = -EFAULT;
1930     if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1931         goto out;
1932     /* Ignore unsupported features (userspace built against newer kernel) */
1933     features = uffdio_api.features & UFFD_API_FEATURES;
1934     ret = -EPERM;
1935     if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1936         goto err_out;
1937     /* report all available features and ioctls to userland */
1938     uffdio_api.features = UFFD_API_FEATURES;
1939 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1940     uffdio_api.features &=
1941         ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1942 #endif
1943 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1944     uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1945 #endif
1946 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1947     uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1948 #endif
1949     uffdio_api.ioctls = UFFD_API_IOCTLS;
1950     ret = -EFAULT;
1951     if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1952         goto out;
1953 
1954     /* only enable the requested features for this uffd context */
1955     ctx_features = uffd_ctx_features(features);
1956     ret = -EINVAL;
1957     if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1958         goto err_out;
1959 
1960     ret = 0;
1961 out:
1962     return ret;
1963 err_out:
1964     memset(&uffdio_api, 0, sizeof(uffdio_api));
1965     if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1966         ret = -EFAULT;
1967     goto out;
1968 }
1969 
1970 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1971                   unsigned long arg)
1972 {
1973     int ret = -EINVAL;
1974     struct userfaultfd_ctx *ctx = file->private_data;
1975 
1976     if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
1977         return -EINVAL;
1978 
1979     switch(cmd) {
1980     case UFFDIO_API:
1981         ret = userfaultfd_api(ctx, arg);
1982         break;
1983     case UFFDIO_REGISTER:
1984         ret = userfaultfd_register(ctx, arg);
1985         break;
1986     case UFFDIO_UNREGISTER:
1987         ret = userfaultfd_unregister(ctx, arg);
1988         break;
1989     case UFFDIO_WAKE:
1990         ret = userfaultfd_wake(ctx, arg);
1991         break;
1992     case UFFDIO_COPY:
1993         ret = userfaultfd_copy(ctx, arg);
1994         break;
1995     case UFFDIO_ZEROPAGE:
1996         ret = userfaultfd_zeropage(ctx, arg);
1997         break;
1998     case UFFDIO_WRITEPROTECT:
1999         ret = userfaultfd_writeprotect(ctx, arg);
2000         break;
2001     case UFFDIO_CONTINUE:
2002         ret = userfaultfd_continue(ctx, arg);
2003         break;
2004     }
2005     return ret;
2006 }
2007 
2008 #ifdef CONFIG_PROC_FS
2009 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2010 {
2011     struct userfaultfd_ctx *ctx = f->private_data;
2012     wait_queue_entry_t *wq;
2013     unsigned long pending = 0, total = 0;
2014 
2015     spin_lock_irq(&ctx->fault_pending_wqh.lock);
2016     list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2017         pending++;
2018         total++;
2019     }
2020     list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2021         total++;
2022     }
2023     spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2024 
2025     /*
2026      * If more protocols will be added, there will be all shown
2027      * separated by a space. Like this:
2028      *  protocols: aa:... bb:...
2029      */
2030     seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2031            pending, total, UFFD_API, ctx->features,
2032            UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2033 }
2034 #endif
2035 
2036 static const struct file_operations userfaultfd_fops = {
2037 #ifdef CONFIG_PROC_FS
2038     .show_fdinfo    = userfaultfd_show_fdinfo,
2039 #endif
2040     .release    = userfaultfd_release,
2041     .poll       = userfaultfd_poll,
2042     .read       = userfaultfd_read,
2043     .unlocked_ioctl = userfaultfd_ioctl,
2044     .compat_ioctl   = compat_ptr_ioctl,
2045     .llseek     = noop_llseek,
2046 };
2047 
2048 static void init_once_userfaultfd_ctx(void *mem)
2049 {
2050     struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2051 
2052     init_waitqueue_head(&ctx->fault_pending_wqh);
2053     init_waitqueue_head(&ctx->fault_wqh);
2054     init_waitqueue_head(&ctx->event_wqh);
2055     init_waitqueue_head(&ctx->fd_wqh);
2056     seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2057 }
2058 
2059 SYSCALL_DEFINE1(userfaultfd, int, flags)
2060 {
2061     struct userfaultfd_ctx *ctx;
2062     int fd;
2063 
2064     if (!sysctl_unprivileged_userfaultfd &&
2065         (flags & UFFD_USER_MODE_ONLY) == 0 &&
2066         !capable(CAP_SYS_PTRACE)) {
2067         printk_once(KERN_WARNING "uffd: Set unprivileged_userfaultfd "
2068             "sysctl knob to 1 if kernel faults must be handled "
2069             "without obtaining CAP_SYS_PTRACE capability\n");
2070         return -EPERM;
2071     }
2072 
2073     BUG_ON(!current->mm);
2074 
2075     /* Check the UFFD_* constants for consistency.  */
2076     BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2077     BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2078     BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2079 
2080     if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2081         return -EINVAL;
2082 
2083     ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2084     if (!ctx)
2085         return -ENOMEM;
2086 
2087     refcount_set(&ctx->refcount, 1);
2088     ctx->flags = flags;
2089     ctx->features = 0;
2090     ctx->released = false;
2091     atomic_set(&ctx->mmap_changing, 0);
2092     ctx->mm = current->mm;
2093     /* prevent the mm struct to be freed */
2094     mmgrab(ctx->mm);
2095 
2096     fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2097             O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2098     if (fd < 0) {
2099         mmdrop(ctx->mm);
2100         kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2101     }
2102     return fd;
2103 }
2104 
2105 static int __init userfaultfd_init(void)
2106 {
2107     userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2108                         sizeof(struct userfaultfd_ctx),
2109                         0,
2110                         SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2111                         init_once_userfaultfd_ctx);
2112     return 0;
2113 }
2114 __initcall(userfaultfd_init);