Back to home page

LXR

 
 

    


0001 /*
0002  *  fs/userfaultfd.c
0003  *
0004  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
0005  *  Copyright (C) 2008-2009 Red Hat, Inc.
0006  *  Copyright (C) 2015  Red Hat, Inc.
0007  *
0008  *  This work is licensed under the terms of the GNU GPL, version 2. See
0009  *  the COPYING file in the top-level directory.
0010  *
0011  *  Some part derived from fs/eventfd.c (anon inode setup) and
0012  *  mm/ksm.c (mm hashing).
0013  */
0014 
0015 #include <linux/hashtable.h>
0016 #include <linux/sched.h>
0017 #include <linux/mm.h>
0018 #include <linux/poll.h>
0019 #include <linux/slab.h>
0020 #include <linux/seq_file.h>
0021 #include <linux/file.h>
0022 #include <linux/bug.h>
0023 #include <linux/anon_inodes.h>
0024 #include <linux/syscalls.h>
0025 #include <linux/userfaultfd_k.h>
0026 #include <linux/mempolicy.h>
0027 #include <linux/ioctl.h>
0028 #include <linux/security.h>
0029 
0030 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
0031 
0032 enum userfaultfd_state {
0033     UFFD_STATE_WAIT_API,
0034     UFFD_STATE_RUNNING,
0035 };
0036 
0037 /*
0038  * Start with fault_pending_wqh and fault_wqh so they're more likely
0039  * to be in the same cacheline.
0040  */
0041 struct userfaultfd_ctx {
0042     /* waitqueue head for the pending (i.e. not read) userfaults */
0043     wait_queue_head_t fault_pending_wqh;
0044     /* waitqueue head for the userfaults */
0045     wait_queue_head_t fault_wqh;
0046     /* waitqueue head for the pseudo fd to wakeup poll/read */
0047     wait_queue_head_t fd_wqh;
0048     /* a refile sequence protected by fault_pending_wqh lock */
0049     struct seqcount refile_seq;
0050     /* pseudo fd refcounting */
0051     atomic_t refcount;
0052     /* userfaultfd syscall flags */
0053     unsigned int flags;
0054     /* state machine */
0055     enum userfaultfd_state state;
0056     /* released */
0057     bool released;
0058     /* mm with one ore more vmas attached to this userfaultfd_ctx */
0059     struct mm_struct *mm;
0060 };
0061 
0062 struct userfaultfd_wait_queue {
0063     struct uffd_msg msg;
0064     wait_queue_t wq;
0065     struct userfaultfd_ctx *ctx;
0066     bool waken;
0067 };
0068 
0069 struct userfaultfd_wake_range {
0070     unsigned long start;
0071     unsigned long len;
0072 };
0073 
0074 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
0075                      int wake_flags, void *key)
0076 {
0077     struct userfaultfd_wake_range *range = key;
0078     int ret;
0079     struct userfaultfd_wait_queue *uwq;
0080     unsigned long start, len;
0081 
0082     uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
0083     ret = 0;
0084     /* len == 0 means wake all */
0085     start = range->start;
0086     len = range->len;
0087     if (len && (start > uwq->msg.arg.pagefault.address ||
0088             start + len <= uwq->msg.arg.pagefault.address))
0089         goto out;
0090     WRITE_ONCE(uwq->waken, true);
0091     /*
0092      * The implicit smp_mb__before_spinlock in try_to_wake_up()
0093      * renders uwq->waken visible to other CPUs before the task is
0094      * waken.
0095      */
0096     ret = wake_up_state(wq->private, mode);
0097     if (ret)
0098         /*
0099          * Wake only once, autoremove behavior.
0100          *
0101          * After the effect of list_del_init is visible to the
0102          * other CPUs, the waitqueue may disappear from under
0103          * us, see the !list_empty_careful() in
0104          * handle_userfault(). try_to_wake_up() has an
0105          * implicit smp_mb__before_spinlock, and the
0106          * wq->private is read before calling the extern
0107          * function "wake_up_state" (which in turns calls
0108          * try_to_wake_up). While the spin_lock;spin_unlock;
0109          * wouldn't be enough, the smp_mb__before_spinlock is
0110          * enough to avoid an explicit smp_mb() here.
0111          */
0112         list_del_init(&wq->task_list);
0113 out:
0114     return ret;
0115 }
0116 
0117 /**
0118  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
0119  * context.
0120  * @ctx: [in] Pointer to the userfaultfd context.
0121  *
0122  * Returns: In case of success, returns not zero.
0123  */
0124 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
0125 {
0126     if (!atomic_inc_not_zero(&ctx->refcount))
0127         BUG();
0128 }
0129 
0130 /**
0131  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
0132  * context.
0133  * @ctx: [in] Pointer to userfaultfd context.
0134  *
0135  * The userfaultfd context reference must have been previously acquired either
0136  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
0137  */
0138 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
0139 {
0140     if (atomic_dec_and_test(&ctx->refcount)) {
0141         VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
0142         VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
0143         VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
0144         VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
0145         VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
0146         VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
0147         mmdrop(ctx->mm);
0148         kmem_cache_free(userfaultfd_ctx_cachep, ctx);
0149     }
0150 }
0151 
0152 static inline void msg_init(struct uffd_msg *msg)
0153 {
0154     BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
0155     /*
0156      * Must use memset to zero out the paddings or kernel data is
0157      * leaked to userland.
0158      */
0159     memset(msg, 0, sizeof(struct uffd_msg));
0160 }
0161 
0162 static inline struct uffd_msg userfault_msg(unsigned long address,
0163                         unsigned int flags,
0164                         unsigned long reason)
0165 {
0166     struct uffd_msg msg;
0167     msg_init(&msg);
0168     msg.event = UFFD_EVENT_PAGEFAULT;
0169     msg.arg.pagefault.address = address;
0170     if (flags & FAULT_FLAG_WRITE)
0171         /*
0172          * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the
0173          * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
0174          * was not set in a UFFD_EVENT_PAGEFAULT, it means it
0175          * was a read fault, otherwise if set it means it's
0176          * a write fault.
0177          */
0178         msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
0179     if (reason & VM_UFFD_WP)
0180         /*
0181          * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
0182          * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
0183          * not set in a UFFD_EVENT_PAGEFAULT, it means it was
0184          * a missing fault, otherwise if set it means it's a
0185          * write protect fault.
0186          */
0187         msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
0188     return msg;
0189 }
0190 
0191 /*
0192  * Verify the pagetables are still not ok after having reigstered into
0193  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
0194  * userfault that has already been resolved, if userfaultfd_read and
0195  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
0196  * threads.
0197  */
0198 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
0199                      unsigned long address,
0200                      unsigned long flags,
0201                      unsigned long reason)
0202 {
0203     struct mm_struct *mm = ctx->mm;
0204     pgd_t *pgd;
0205     pud_t *pud;
0206     pmd_t *pmd, _pmd;
0207     pte_t *pte;
0208     bool ret = true;
0209 
0210     VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
0211 
0212     pgd = pgd_offset(mm, address);
0213     if (!pgd_present(*pgd))
0214         goto out;
0215     pud = pud_offset(pgd, address);
0216     if (!pud_present(*pud))
0217         goto out;
0218     pmd = pmd_offset(pud, address);
0219     /*
0220      * READ_ONCE must function as a barrier with narrower scope
0221      * and it must be equivalent to:
0222      *  _pmd = *pmd; barrier();
0223      *
0224      * This is to deal with the instability (as in
0225      * pmd_trans_unstable) of the pmd.
0226      */
0227     _pmd = READ_ONCE(*pmd);
0228     if (!pmd_present(_pmd))
0229         goto out;
0230 
0231     ret = false;
0232     if (pmd_trans_huge(_pmd))
0233         goto out;
0234 
0235     /*
0236      * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
0237      * and use the standard pte_offset_map() instead of parsing _pmd.
0238      */
0239     pte = pte_offset_map(pmd, address);
0240     /*
0241      * Lockless access: we're in a wait_event so it's ok if it
0242      * changes under us.
0243      */
0244     if (pte_none(*pte))
0245         ret = true;
0246     pte_unmap(pte);
0247 
0248 out:
0249     return ret;
0250 }
0251 
0252 /*
0253  * The locking rules involved in returning VM_FAULT_RETRY depending on
0254  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
0255  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
0256  * recommendation in __lock_page_or_retry is not an understatement.
0257  *
0258  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
0259  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
0260  * not set.
0261  *
0262  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
0263  * set, VM_FAULT_RETRY can still be returned if and only if there are
0264  * fatal_signal_pending()s, and the mmap_sem must be released before
0265  * returning it.
0266  */
0267 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
0268 {
0269     struct mm_struct *mm = vmf->vma->vm_mm;
0270     struct userfaultfd_ctx *ctx;
0271     struct userfaultfd_wait_queue uwq;
0272     int ret;
0273     bool must_wait, return_to_userland;
0274     long blocking_state;
0275 
0276     BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
0277 
0278     ret = VM_FAULT_SIGBUS;
0279     ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
0280     if (!ctx)
0281         goto out;
0282 
0283     BUG_ON(ctx->mm != mm);
0284 
0285     VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
0286     VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
0287 
0288     /*
0289      * If it's already released don't get it. This avoids to loop
0290      * in __get_user_pages if userfaultfd_release waits on the
0291      * caller of handle_userfault to release the mmap_sem.
0292      */
0293     if (unlikely(ACCESS_ONCE(ctx->released)))
0294         goto out;
0295 
0296     /*
0297      * We don't do userfault handling for the final child pid update.
0298      */
0299     if (current->flags & PF_EXITING)
0300         goto out;
0301 
0302     /*
0303      * Check that we can return VM_FAULT_RETRY.
0304      *
0305      * NOTE: it should become possible to return VM_FAULT_RETRY
0306      * even if FAULT_FLAG_TRIED is set without leading to gup()
0307      * -EBUSY failures, if the userfaultfd is to be extended for
0308      * VM_UFFD_WP tracking and we intend to arm the userfault
0309      * without first stopping userland access to the memory. For
0310      * VM_UFFD_MISSING userfaults this is enough for now.
0311      */
0312     if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
0313         /*
0314          * Validate the invariant that nowait must allow retry
0315          * to be sure not to return SIGBUS erroneously on
0316          * nowait invocations.
0317          */
0318         BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
0319 #ifdef CONFIG_DEBUG_VM
0320         if (printk_ratelimit()) {
0321             printk(KERN_WARNING
0322                    "FAULT_FLAG_ALLOW_RETRY missing %x\n",
0323                    vmf->flags);
0324             dump_stack();
0325         }
0326 #endif
0327         goto out;
0328     }
0329 
0330     /*
0331      * Handle nowait, not much to do other than tell it to retry
0332      * and wait.
0333      */
0334     ret = VM_FAULT_RETRY;
0335     if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
0336         goto out;
0337 
0338     /* take the reference before dropping the mmap_sem */
0339     userfaultfd_ctx_get(ctx);
0340 
0341     init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
0342     uwq.wq.private = current;
0343     uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
0344     uwq.ctx = ctx;
0345     uwq.waken = false;
0346 
0347     return_to_userland =
0348         (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
0349         (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
0350     blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
0351              TASK_KILLABLE;
0352 
0353     spin_lock(&ctx->fault_pending_wqh.lock);
0354     /*
0355      * After the __add_wait_queue the uwq is visible to userland
0356      * through poll/read().
0357      */
0358     __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
0359     /*
0360      * The smp_mb() after __set_current_state prevents the reads
0361      * following the spin_unlock to happen before the list_add in
0362      * __add_wait_queue.
0363      */
0364     set_current_state(blocking_state);
0365     spin_unlock(&ctx->fault_pending_wqh.lock);
0366 
0367     must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
0368                       reason);
0369     up_read(&mm->mmap_sem);
0370 
0371     if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
0372            (return_to_userland ? !signal_pending(current) :
0373             !fatal_signal_pending(current)))) {
0374         wake_up_poll(&ctx->fd_wqh, POLLIN);
0375         schedule();
0376         ret |= VM_FAULT_MAJOR;
0377 
0378         /*
0379          * False wakeups can orginate even from rwsem before
0380          * up_read() however userfaults will wait either for a
0381          * targeted wakeup on the specific uwq waitqueue from
0382          * wake_userfault() or for signals or for uffd
0383          * release.
0384          */
0385         while (!READ_ONCE(uwq.waken)) {
0386             /*
0387              * This needs the full smp_store_mb()
0388              * guarantee as the state write must be
0389              * visible to other CPUs before reading
0390              * uwq.waken from other CPUs.
0391              */
0392             set_current_state(blocking_state);
0393             if (READ_ONCE(uwq.waken) ||
0394                 READ_ONCE(ctx->released) ||
0395                 (return_to_userland ? signal_pending(current) :
0396                  fatal_signal_pending(current)))
0397                 break;
0398             schedule();
0399         }
0400     }
0401 
0402     __set_current_state(TASK_RUNNING);
0403 
0404     if (return_to_userland) {
0405         if (signal_pending(current) &&
0406             !fatal_signal_pending(current)) {
0407             /*
0408              * If we got a SIGSTOP or SIGCONT and this is
0409              * a normal userland page fault, just let
0410              * userland return so the signal will be
0411              * handled and gdb debugging works.  The page
0412              * fault code immediately after we return from
0413              * this function is going to release the
0414              * mmap_sem and it's not depending on it
0415              * (unlike gup would if we were not to return
0416              * VM_FAULT_RETRY).
0417              *
0418              * If a fatal signal is pending we still take
0419              * the streamlined VM_FAULT_RETRY failure path
0420              * and there's no need to retake the mmap_sem
0421              * in such case.
0422              */
0423             down_read(&mm->mmap_sem);
0424             ret = 0;
0425         }
0426     }
0427 
0428     /*
0429      * Here we race with the list_del; list_add in
0430      * userfaultfd_ctx_read(), however because we don't ever run
0431      * list_del_init() to refile across the two lists, the prev
0432      * and next pointers will never point to self. list_add also
0433      * would never let any of the two pointers to point to
0434      * self. So list_empty_careful won't risk to see both pointers
0435      * pointing to self at any time during the list refile. The
0436      * only case where list_del_init() is called is the full
0437      * removal in the wake function and there we don't re-list_add
0438      * and it's fine not to block on the spinlock. The uwq on this
0439      * kernel stack can be released after the list_del_init.
0440      */
0441     if (!list_empty_careful(&uwq.wq.task_list)) {
0442         spin_lock(&ctx->fault_pending_wqh.lock);
0443         /*
0444          * No need of list_del_init(), the uwq on the stack
0445          * will be freed shortly anyway.
0446          */
0447         list_del(&uwq.wq.task_list);
0448         spin_unlock(&ctx->fault_pending_wqh.lock);
0449     }
0450 
0451     /*
0452      * ctx may go away after this if the userfault pseudo fd is
0453      * already released.
0454      */
0455     userfaultfd_ctx_put(ctx);
0456 
0457 out:
0458     return ret;
0459 }
0460 
0461 static int userfaultfd_release(struct inode *inode, struct file *file)
0462 {
0463     struct userfaultfd_ctx *ctx = file->private_data;
0464     struct mm_struct *mm = ctx->mm;
0465     struct vm_area_struct *vma, *prev;
0466     /* len == 0 means wake all */
0467     struct userfaultfd_wake_range range = { .len = 0, };
0468     unsigned long new_flags;
0469 
0470     ACCESS_ONCE(ctx->released) = true;
0471 
0472     if (!mmget_not_zero(mm))
0473         goto wakeup;
0474 
0475     /*
0476      * Flush page faults out of all CPUs. NOTE: all page faults
0477      * must be retried without returning VM_FAULT_SIGBUS if
0478      * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
0479      * changes while handle_userfault released the mmap_sem. So
0480      * it's critical that released is set to true (above), before
0481      * taking the mmap_sem for writing.
0482      */
0483     down_write(&mm->mmap_sem);
0484     prev = NULL;
0485     for (vma = mm->mmap; vma; vma = vma->vm_next) {
0486         cond_resched();
0487         BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
0488                !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
0489         if (vma->vm_userfaultfd_ctx.ctx != ctx) {
0490             prev = vma;
0491             continue;
0492         }
0493         new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
0494         prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
0495                  new_flags, vma->anon_vma,
0496                  vma->vm_file, vma->vm_pgoff,
0497                  vma_policy(vma),
0498                  NULL_VM_UFFD_CTX);
0499         if (prev)
0500             vma = prev;
0501         else
0502             prev = vma;
0503         vma->vm_flags = new_flags;
0504         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
0505     }
0506     up_write(&mm->mmap_sem);
0507     mmput(mm);
0508 wakeup:
0509     /*
0510      * After no new page faults can wait on this fault_*wqh, flush
0511      * the last page faults that may have been already waiting on
0512      * the fault_*wqh.
0513      */
0514     spin_lock(&ctx->fault_pending_wqh.lock);
0515     __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
0516     __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
0517     spin_unlock(&ctx->fault_pending_wqh.lock);
0518 
0519     wake_up_poll(&ctx->fd_wqh, POLLHUP);
0520     userfaultfd_ctx_put(ctx);
0521     return 0;
0522 }
0523 
0524 /* fault_pending_wqh.lock must be hold by the caller */
0525 static inline struct userfaultfd_wait_queue *find_userfault(
0526     struct userfaultfd_ctx *ctx)
0527 {
0528     wait_queue_t *wq;
0529     struct userfaultfd_wait_queue *uwq;
0530 
0531     VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
0532 
0533     uwq = NULL;
0534     if (!waitqueue_active(&ctx->fault_pending_wqh))
0535         goto out;
0536     /* walk in reverse to provide FIFO behavior to read userfaults */
0537     wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
0538                  typeof(*wq), task_list);
0539     uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
0540 out:
0541     return uwq;
0542 }
0543 
0544 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
0545 {
0546     struct userfaultfd_ctx *ctx = file->private_data;
0547     unsigned int ret;
0548 
0549     poll_wait(file, &ctx->fd_wqh, wait);
0550 
0551     switch (ctx->state) {
0552     case UFFD_STATE_WAIT_API:
0553         return POLLERR;
0554     case UFFD_STATE_RUNNING:
0555         /*
0556          * poll() never guarantees that read won't block.
0557          * userfaults can be waken before they're read().
0558          */
0559         if (unlikely(!(file->f_flags & O_NONBLOCK)))
0560             return POLLERR;
0561         /*
0562          * lockless access to see if there are pending faults
0563          * __pollwait last action is the add_wait_queue but
0564          * the spin_unlock would allow the waitqueue_active to
0565          * pass above the actual list_add inside
0566          * add_wait_queue critical section. So use a full
0567          * memory barrier to serialize the list_add write of
0568          * add_wait_queue() with the waitqueue_active read
0569          * below.
0570          */
0571         ret = 0;
0572         smp_mb();
0573         if (waitqueue_active(&ctx->fault_pending_wqh))
0574             ret = POLLIN;
0575         return ret;
0576     default:
0577         BUG();
0578     }
0579 }
0580 
0581 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
0582                     struct uffd_msg *msg)
0583 {
0584     ssize_t ret;
0585     DECLARE_WAITQUEUE(wait, current);
0586     struct userfaultfd_wait_queue *uwq;
0587 
0588     /* always take the fd_wqh lock before the fault_pending_wqh lock */
0589     spin_lock(&ctx->fd_wqh.lock);
0590     __add_wait_queue(&ctx->fd_wqh, &wait);
0591     for (;;) {
0592         set_current_state(TASK_INTERRUPTIBLE);
0593         spin_lock(&ctx->fault_pending_wqh.lock);
0594         uwq = find_userfault(ctx);
0595         if (uwq) {
0596             /*
0597              * Use a seqcount to repeat the lockless check
0598              * in wake_userfault() to avoid missing
0599              * wakeups because during the refile both
0600              * waitqueue could become empty if this is the
0601              * only userfault.
0602              */
0603             write_seqcount_begin(&ctx->refile_seq);
0604 
0605             /*
0606              * The fault_pending_wqh.lock prevents the uwq
0607              * to disappear from under us.
0608              *
0609              * Refile this userfault from
0610              * fault_pending_wqh to fault_wqh, it's not
0611              * pending anymore after we read it.
0612              *
0613              * Use list_del() by hand (as
0614              * userfaultfd_wake_function also uses
0615              * list_del_init() by hand) to be sure nobody
0616              * changes __remove_wait_queue() to use
0617              * list_del_init() in turn breaking the
0618              * !list_empty_careful() check in
0619              * handle_userfault(). The uwq->wq.task_list
0620              * must never be empty at any time during the
0621              * refile, or the waitqueue could disappear
0622              * from under us. The "wait_queue_head_t"
0623              * parameter of __remove_wait_queue() is unused
0624              * anyway.
0625              */
0626             list_del(&uwq->wq.task_list);
0627             __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
0628 
0629             write_seqcount_end(&ctx->refile_seq);
0630 
0631             /* careful to always initialize msg if ret == 0 */
0632             *msg = uwq->msg;
0633             spin_unlock(&ctx->fault_pending_wqh.lock);
0634             ret = 0;
0635             break;
0636         }
0637         spin_unlock(&ctx->fault_pending_wqh.lock);
0638         if (signal_pending(current)) {
0639             ret = -ERESTARTSYS;
0640             break;
0641         }
0642         if (no_wait) {
0643             ret = -EAGAIN;
0644             break;
0645         }
0646         spin_unlock(&ctx->fd_wqh.lock);
0647         schedule();
0648         spin_lock(&ctx->fd_wqh.lock);
0649     }
0650     __remove_wait_queue(&ctx->fd_wqh, &wait);
0651     __set_current_state(TASK_RUNNING);
0652     spin_unlock(&ctx->fd_wqh.lock);
0653 
0654     return ret;
0655 }
0656 
0657 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
0658                 size_t count, loff_t *ppos)
0659 {
0660     struct userfaultfd_ctx *ctx = file->private_data;
0661     ssize_t _ret, ret = 0;
0662     struct uffd_msg msg;
0663     int no_wait = file->f_flags & O_NONBLOCK;
0664 
0665     if (ctx->state == UFFD_STATE_WAIT_API)
0666         return -EINVAL;
0667 
0668     for (;;) {
0669         if (count < sizeof(msg))
0670             return ret ? ret : -EINVAL;
0671         _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
0672         if (_ret < 0)
0673             return ret ? ret : _ret;
0674         if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
0675             return ret ? ret : -EFAULT;
0676         ret += sizeof(msg);
0677         buf += sizeof(msg);
0678         count -= sizeof(msg);
0679         /*
0680          * Allow to read more than one fault at time but only
0681          * block if waiting for the very first one.
0682          */
0683         no_wait = O_NONBLOCK;
0684     }
0685 }
0686 
0687 static void __wake_userfault(struct userfaultfd_ctx *ctx,
0688                  struct userfaultfd_wake_range *range)
0689 {
0690     unsigned long start, end;
0691 
0692     start = range->start;
0693     end = range->start + range->len;
0694 
0695     spin_lock(&ctx->fault_pending_wqh.lock);
0696     /* wake all in the range and autoremove */
0697     if (waitqueue_active(&ctx->fault_pending_wqh))
0698         __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
0699                      range);
0700     if (waitqueue_active(&ctx->fault_wqh))
0701         __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
0702     spin_unlock(&ctx->fault_pending_wqh.lock);
0703 }
0704 
0705 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
0706                        struct userfaultfd_wake_range *range)
0707 {
0708     unsigned seq;
0709     bool need_wakeup;
0710 
0711     /*
0712      * To be sure waitqueue_active() is not reordered by the CPU
0713      * before the pagetable update, use an explicit SMP memory
0714      * barrier here. PT lock release or up_read(mmap_sem) still
0715      * have release semantics that can allow the
0716      * waitqueue_active() to be reordered before the pte update.
0717      */
0718     smp_mb();
0719 
0720     /*
0721      * Use waitqueue_active because it's very frequent to
0722      * change the address space atomically even if there are no
0723      * userfaults yet. So we take the spinlock only when we're
0724      * sure we've userfaults to wake.
0725      */
0726     do {
0727         seq = read_seqcount_begin(&ctx->refile_seq);
0728         need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
0729             waitqueue_active(&ctx->fault_wqh);
0730         cond_resched();
0731     } while (read_seqcount_retry(&ctx->refile_seq, seq));
0732     if (need_wakeup)
0733         __wake_userfault(ctx, range);
0734 }
0735 
0736 static __always_inline int validate_range(struct mm_struct *mm,
0737                       __u64 start, __u64 len)
0738 {
0739     __u64 task_size = mm->task_size;
0740 
0741     if (start & ~PAGE_MASK)
0742         return -EINVAL;
0743     if (len & ~PAGE_MASK)
0744         return -EINVAL;
0745     if (!len)
0746         return -EINVAL;
0747     if (start < mmap_min_addr)
0748         return -EINVAL;
0749     if (start >= task_size)
0750         return -EINVAL;
0751     if (len > task_size - start)
0752         return -EINVAL;
0753     return 0;
0754 }
0755 
0756 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
0757                 unsigned long arg)
0758 {
0759     struct mm_struct *mm = ctx->mm;
0760     struct vm_area_struct *vma, *prev, *cur;
0761     int ret;
0762     struct uffdio_register uffdio_register;
0763     struct uffdio_register __user *user_uffdio_register;
0764     unsigned long vm_flags, new_flags;
0765     bool found;
0766     unsigned long start, end, vma_end;
0767 
0768     user_uffdio_register = (struct uffdio_register __user *) arg;
0769 
0770     ret = -EFAULT;
0771     if (copy_from_user(&uffdio_register, user_uffdio_register,
0772                sizeof(uffdio_register)-sizeof(__u64)))
0773         goto out;
0774 
0775     ret = -EINVAL;
0776     if (!uffdio_register.mode)
0777         goto out;
0778     if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
0779                      UFFDIO_REGISTER_MODE_WP))
0780         goto out;
0781     vm_flags = 0;
0782     if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
0783         vm_flags |= VM_UFFD_MISSING;
0784     if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
0785         vm_flags |= VM_UFFD_WP;
0786         /*
0787          * FIXME: remove the below error constraint by
0788          * implementing the wprotect tracking mode.
0789          */
0790         ret = -EINVAL;
0791         goto out;
0792     }
0793 
0794     ret = validate_range(mm, uffdio_register.range.start,
0795                  uffdio_register.range.len);
0796     if (ret)
0797         goto out;
0798 
0799     start = uffdio_register.range.start;
0800     end = start + uffdio_register.range.len;
0801 
0802     ret = -ENOMEM;
0803     if (!mmget_not_zero(mm))
0804         goto out;
0805 
0806     down_write(&mm->mmap_sem);
0807     vma = find_vma_prev(mm, start, &prev);
0808     if (!vma)
0809         goto out_unlock;
0810 
0811     /* check that there's at least one vma in the range */
0812     ret = -EINVAL;
0813     if (vma->vm_start >= end)
0814         goto out_unlock;
0815 
0816     /*
0817      * Search for not compatible vmas.
0818      *
0819      * FIXME: this shall be relaxed later so that it doesn't fail
0820      * on tmpfs backed vmas (in addition to the current allowance
0821      * on anonymous vmas).
0822      */
0823     found = false;
0824     for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
0825         cond_resched();
0826 
0827         BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
0828                !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
0829 
0830         /* check not compatible vmas */
0831         ret = -EINVAL;
0832         if (cur->vm_ops)
0833             goto out_unlock;
0834 
0835         /*
0836          * Check that this vma isn't already owned by a
0837          * different userfaultfd. We can't allow more than one
0838          * userfaultfd to own a single vma simultaneously or we
0839          * wouldn't know which one to deliver the userfaults to.
0840          */
0841         ret = -EBUSY;
0842         if (cur->vm_userfaultfd_ctx.ctx &&
0843             cur->vm_userfaultfd_ctx.ctx != ctx)
0844             goto out_unlock;
0845 
0846         found = true;
0847     }
0848     BUG_ON(!found);
0849 
0850     if (vma->vm_start < start)
0851         prev = vma;
0852 
0853     ret = 0;
0854     do {
0855         cond_resched();
0856 
0857         BUG_ON(vma->vm_ops);
0858         BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
0859                vma->vm_userfaultfd_ctx.ctx != ctx);
0860 
0861         /*
0862          * Nothing to do: this vma is already registered into this
0863          * userfaultfd and with the right tracking mode too.
0864          */
0865         if (vma->vm_userfaultfd_ctx.ctx == ctx &&
0866             (vma->vm_flags & vm_flags) == vm_flags)
0867             goto skip;
0868 
0869         if (vma->vm_start > start)
0870             start = vma->vm_start;
0871         vma_end = min(end, vma->vm_end);
0872 
0873         new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
0874         prev = vma_merge(mm, prev, start, vma_end, new_flags,
0875                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
0876                  vma_policy(vma),
0877                  ((struct vm_userfaultfd_ctx){ ctx }));
0878         if (prev) {
0879             vma = prev;
0880             goto next;
0881         }
0882         if (vma->vm_start < start) {
0883             ret = split_vma(mm, vma, start, 1);
0884             if (ret)
0885                 break;
0886         }
0887         if (vma->vm_end > end) {
0888             ret = split_vma(mm, vma, end, 0);
0889             if (ret)
0890                 break;
0891         }
0892     next:
0893         /*
0894          * In the vma_merge() successful mprotect-like case 8:
0895          * the next vma was merged into the current one and
0896          * the current one has not been updated yet.
0897          */
0898         vma->vm_flags = new_flags;
0899         vma->vm_userfaultfd_ctx.ctx = ctx;
0900 
0901     skip:
0902         prev = vma;
0903         start = vma->vm_end;
0904         vma = vma->vm_next;
0905     } while (vma && vma->vm_start < end);
0906 out_unlock:
0907     up_write(&mm->mmap_sem);
0908     mmput(mm);
0909     if (!ret) {
0910         /*
0911          * Now that we scanned all vmas we can already tell
0912          * userland which ioctls methods are guaranteed to
0913          * succeed on this range.
0914          */
0915         if (put_user(UFFD_API_RANGE_IOCTLS,
0916                  &user_uffdio_register->ioctls))
0917             ret = -EFAULT;
0918     }
0919 out:
0920     return ret;
0921 }
0922 
0923 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
0924                   unsigned long arg)
0925 {
0926     struct mm_struct *mm = ctx->mm;
0927     struct vm_area_struct *vma, *prev, *cur;
0928     int ret;
0929     struct uffdio_range uffdio_unregister;
0930     unsigned long new_flags;
0931     bool found;
0932     unsigned long start, end, vma_end;
0933     const void __user *buf = (void __user *)arg;
0934 
0935     ret = -EFAULT;
0936     if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
0937         goto out;
0938 
0939     ret = validate_range(mm, uffdio_unregister.start,
0940                  uffdio_unregister.len);
0941     if (ret)
0942         goto out;
0943 
0944     start = uffdio_unregister.start;
0945     end = start + uffdio_unregister.len;
0946 
0947     ret = -ENOMEM;
0948     if (!mmget_not_zero(mm))
0949         goto out;
0950 
0951     down_write(&mm->mmap_sem);
0952     vma = find_vma_prev(mm, start, &prev);
0953     if (!vma)
0954         goto out_unlock;
0955 
0956     /* check that there's at least one vma in the range */
0957     ret = -EINVAL;
0958     if (vma->vm_start >= end)
0959         goto out_unlock;
0960 
0961     /*
0962      * Search for not compatible vmas.
0963      *
0964      * FIXME: this shall be relaxed later so that it doesn't fail
0965      * on tmpfs backed vmas (in addition to the current allowance
0966      * on anonymous vmas).
0967      */
0968     found = false;
0969     ret = -EINVAL;
0970     for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
0971         cond_resched();
0972 
0973         BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
0974                !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
0975 
0976         /*
0977          * Check not compatible vmas, not strictly required
0978          * here as not compatible vmas cannot have an
0979          * userfaultfd_ctx registered on them, but this
0980          * provides for more strict behavior to notice
0981          * unregistration errors.
0982          */
0983         if (cur->vm_ops)
0984             goto out_unlock;
0985 
0986         found = true;
0987     }
0988     BUG_ON(!found);
0989 
0990     if (vma->vm_start < start)
0991         prev = vma;
0992 
0993     ret = 0;
0994     do {
0995         cond_resched();
0996 
0997         BUG_ON(vma->vm_ops);
0998 
0999         /*
1000          * Nothing to do: this vma is already registered into this
1001          * userfaultfd and with the right tracking mode too.
1002          */
1003         if (!vma->vm_userfaultfd_ctx.ctx)
1004             goto skip;
1005 
1006         if (vma->vm_start > start)
1007             start = vma->vm_start;
1008         vma_end = min(end, vma->vm_end);
1009 
1010         new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1011         prev = vma_merge(mm, prev, start, vma_end, new_flags,
1012                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1013                  vma_policy(vma),
1014                  NULL_VM_UFFD_CTX);
1015         if (prev) {
1016             vma = prev;
1017             goto next;
1018         }
1019         if (vma->vm_start < start) {
1020             ret = split_vma(mm, vma, start, 1);
1021             if (ret)
1022                 break;
1023         }
1024         if (vma->vm_end > end) {
1025             ret = split_vma(mm, vma, end, 0);
1026             if (ret)
1027                 break;
1028         }
1029     next:
1030         /*
1031          * In the vma_merge() successful mprotect-like case 8:
1032          * the next vma was merged into the current one and
1033          * the current one has not been updated yet.
1034          */
1035         vma->vm_flags = new_flags;
1036         vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1037 
1038     skip:
1039         prev = vma;
1040         start = vma->vm_end;
1041         vma = vma->vm_next;
1042     } while (vma && vma->vm_start < end);
1043 out_unlock:
1044     up_write(&mm->mmap_sem);
1045     mmput(mm);
1046 out:
1047     return ret;
1048 }
1049 
1050 /*
1051  * userfaultfd_wake may be used in combination with the
1052  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1053  */
1054 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1055                 unsigned long arg)
1056 {
1057     int ret;
1058     struct uffdio_range uffdio_wake;
1059     struct userfaultfd_wake_range range;
1060     const void __user *buf = (void __user *)arg;
1061 
1062     ret = -EFAULT;
1063     if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1064         goto out;
1065 
1066     ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1067     if (ret)
1068         goto out;
1069 
1070     range.start = uffdio_wake.start;
1071     range.len = uffdio_wake.len;
1072 
1073     /*
1074      * len == 0 means wake all and we don't want to wake all here,
1075      * so check it again to be sure.
1076      */
1077     VM_BUG_ON(!range.len);
1078 
1079     wake_userfault(ctx, &range);
1080     ret = 0;
1081 
1082 out:
1083     return ret;
1084 }
1085 
1086 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1087                 unsigned long arg)
1088 {
1089     __s64 ret;
1090     struct uffdio_copy uffdio_copy;
1091     struct uffdio_copy __user *user_uffdio_copy;
1092     struct userfaultfd_wake_range range;
1093 
1094     user_uffdio_copy = (struct uffdio_copy __user *) arg;
1095 
1096     ret = -EFAULT;
1097     if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1098                /* don't copy "copy" last field */
1099                sizeof(uffdio_copy)-sizeof(__s64)))
1100         goto out;
1101 
1102     ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1103     if (ret)
1104         goto out;
1105     /*
1106      * double check for wraparound just in case. copy_from_user()
1107      * will later check uffdio_copy.src + uffdio_copy.len to fit
1108      * in the userland range.
1109      */
1110     ret = -EINVAL;
1111     if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1112         goto out;
1113     if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1114         goto out;
1115     if (mmget_not_zero(ctx->mm)) {
1116         ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1117                    uffdio_copy.len);
1118         mmput(ctx->mm);
1119     }
1120     if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1121         return -EFAULT;
1122     if (ret < 0)
1123         goto out;
1124     BUG_ON(!ret);
1125     /* len == 0 would wake all */
1126     range.len = ret;
1127     if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1128         range.start = uffdio_copy.dst;
1129         wake_userfault(ctx, &range);
1130     }
1131     ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1132 out:
1133     return ret;
1134 }
1135 
1136 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1137                 unsigned long arg)
1138 {
1139     __s64 ret;
1140     struct uffdio_zeropage uffdio_zeropage;
1141     struct uffdio_zeropage __user *user_uffdio_zeropage;
1142     struct userfaultfd_wake_range range;
1143 
1144     user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1145 
1146     ret = -EFAULT;
1147     if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1148                /* don't copy "zeropage" last field */
1149                sizeof(uffdio_zeropage)-sizeof(__s64)))
1150         goto out;
1151 
1152     ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1153                  uffdio_zeropage.range.len);
1154     if (ret)
1155         goto out;
1156     ret = -EINVAL;
1157     if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1158         goto out;
1159 
1160     if (mmget_not_zero(ctx->mm)) {
1161         ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1162                      uffdio_zeropage.range.len);
1163         mmput(ctx->mm);
1164     }
1165     if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1166         return -EFAULT;
1167     if (ret < 0)
1168         goto out;
1169     /* len == 0 would wake all */
1170     BUG_ON(!ret);
1171     range.len = ret;
1172     if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1173         range.start = uffdio_zeropage.range.start;
1174         wake_userfault(ctx, &range);
1175     }
1176     ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1177 out:
1178     return ret;
1179 }
1180 
1181 /*
1182  * userland asks for a certain API version and we return which bits
1183  * and ioctl commands are implemented in this kernel for such API
1184  * version or -EINVAL if unknown.
1185  */
1186 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1187                unsigned long arg)
1188 {
1189     struct uffdio_api uffdio_api;
1190     void __user *buf = (void __user *)arg;
1191     int ret;
1192 
1193     ret = -EINVAL;
1194     if (ctx->state != UFFD_STATE_WAIT_API)
1195         goto out;
1196     ret = -EFAULT;
1197     if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1198         goto out;
1199     if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1200         memset(&uffdio_api, 0, sizeof(uffdio_api));
1201         if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1202             goto out;
1203         ret = -EINVAL;
1204         goto out;
1205     }
1206     uffdio_api.features = UFFD_API_FEATURES;
1207     uffdio_api.ioctls = UFFD_API_IOCTLS;
1208     ret = -EFAULT;
1209     if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1210         goto out;
1211     ctx->state = UFFD_STATE_RUNNING;
1212     ret = 0;
1213 out:
1214     return ret;
1215 }
1216 
1217 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1218                   unsigned long arg)
1219 {
1220     int ret = -EINVAL;
1221     struct userfaultfd_ctx *ctx = file->private_data;
1222 
1223     if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1224         return -EINVAL;
1225 
1226     switch(cmd) {
1227     case UFFDIO_API:
1228         ret = userfaultfd_api(ctx, arg);
1229         break;
1230     case UFFDIO_REGISTER:
1231         ret = userfaultfd_register(ctx, arg);
1232         break;
1233     case UFFDIO_UNREGISTER:
1234         ret = userfaultfd_unregister(ctx, arg);
1235         break;
1236     case UFFDIO_WAKE:
1237         ret = userfaultfd_wake(ctx, arg);
1238         break;
1239     case UFFDIO_COPY:
1240         ret = userfaultfd_copy(ctx, arg);
1241         break;
1242     case UFFDIO_ZEROPAGE:
1243         ret = userfaultfd_zeropage(ctx, arg);
1244         break;
1245     }
1246     return ret;
1247 }
1248 
1249 #ifdef CONFIG_PROC_FS
1250 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1251 {
1252     struct userfaultfd_ctx *ctx = f->private_data;
1253     wait_queue_t *wq;
1254     struct userfaultfd_wait_queue *uwq;
1255     unsigned long pending = 0, total = 0;
1256 
1257     spin_lock(&ctx->fault_pending_wqh.lock);
1258     list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1259         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1260         pending++;
1261         total++;
1262     }
1263     list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1264         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1265         total++;
1266     }
1267     spin_unlock(&ctx->fault_pending_wqh.lock);
1268 
1269     /*
1270      * If more protocols will be added, there will be all shown
1271      * separated by a space. Like this:
1272      *  protocols: aa:... bb:...
1273      */
1274     seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1275            pending, total, UFFD_API, UFFD_API_FEATURES,
1276            UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1277 }
1278 #endif
1279 
1280 static const struct file_operations userfaultfd_fops = {
1281 #ifdef CONFIG_PROC_FS
1282     .show_fdinfo    = userfaultfd_show_fdinfo,
1283 #endif
1284     .release    = userfaultfd_release,
1285     .poll       = userfaultfd_poll,
1286     .read       = userfaultfd_read,
1287     .unlocked_ioctl = userfaultfd_ioctl,
1288     .compat_ioctl   = userfaultfd_ioctl,
1289     .llseek     = noop_llseek,
1290 };
1291 
1292 static void init_once_userfaultfd_ctx(void *mem)
1293 {
1294     struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1295 
1296     init_waitqueue_head(&ctx->fault_pending_wqh);
1297     init_waitqueue_head(&ctx->fault_wqh);
1298     init_waitqueue_head(&ctx->fd_wqh);
1299     seqcount_init(&ctx->refile_seq);
1300 }
1301 
1302 /**
1303  * userfaultfd_file_create - Creates an userfaultfd file pointer.
1304  * @flags: Flags for the userfaultfd file.
1305  *
1306  * This function creates an userfaultfd file pointer, w/out installing
1307  * it into the fd table. This is useful when the userfaultfd file is
1308  * used during the initialization of data structures that require
1309  * extra setup after the userfaultfd creation. So the userfaultfd
1310  * creation is split into the file pointer creation phase, and the
1311  * file descriptor installation phase.  In this way races with
1312  * userspace closing the newly installed file descriptor can be
1313  * avoided.  Returns an userfaultfd file pointer, or a proper error
1314  * pointer.
1315  */
1316 static struct file *userfaultfd_file_create(int flags)
1317 {
1318     struct file *file;
1319     struct userfaultfd_ctx *ctx;
1320 
1321     BUG_ON(!current->mm);
1322 
1323     /* Check the UFFD_* constants for consistency.  */
1324     BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1325     BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1326 
1327     file = ERR_PTR(-EINVAL);
1328     if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1329         goto out;
1330 
1331     file = ERR_PTR(-ENOMEM);
1332     ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1333     if (!ctx)
1334         goto out;
1335 
1336     atomic_set(&ctx->refcount, 1);
1337     ctx->flags = flags;
1338     ctx->state = UFFD_STATE_WAIT_API;
1339     ctx->released = false;
1340     ctx->mm = current->mm;
1341     /* prevent the mm struct to be freed */
1342     atomic_inc(&ctx->mm->mm_count);
1343 
1344     file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1345                   O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1346     if (IS_ERR(file)) {
1347         mmdrop(ctx->mm);
1348         kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1349     }
1350 out:
1351     return file;
1352 }
1353 
1354 SYSCALL_DEFINE1(userfaultfd, int, flags)
1355 {
1356     int fd, error;
1357     struct file *file;
1358 
1359     error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1360     if (error < 0)
1361         return error;
1362     fd = error;
1363 
1364     file = userfaultfd_file_create(flags);
1365     if (IS_ERR(file)) {
1366         error = PTR_ERR(file);
1367         goto err_put_unused_fd;
1368     }
1369     fd_install(fd, file);
1370 
1371     return fd;
1372 
1373 err_put_unused_fd:
1374     put_unused_fd(fd);
1375 
1376     return error;
1377 }
1378 
1379 static int __init userfaultfd_init(void)
1380 {
1381     userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1382                         sizeof(struct userfaultfd_ctx),
1383                         0,
1384                         SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1385                         init_once_userfaultfd_ctx);
1386     return 0;
1387 }
1388 __initcall(userfaultfd_init);