userfaultfd: non-cooperative: add ability to report non-PF events from uffd descriptor
[linux-2.6-microblaze.git] / fs / userfaultfd.c
1 /*
2  *  fs/userfaultfd.c
3  *
4  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
5  *  Copyright (C) 2008-2009 Red Hat, Inc.
6  *  Copyright (C) 2015  Red Hat, Inc.
7  *
8  *  This work is licensed under the terms of the GNU GPL, version 2. See
9  *  the COPYING file in the top-level directory.
10  *
11  *  Some part derived from fs/eventfd.c (anon inode setup) and
12  *  mm/ksm.c (mm hashing).
13  */
14
15 #include <linux/list.h>
16 #include <linux/hashtable.h>
17 #include <linux/sched.h>
18 #include <linux/mm.h>
19 #include <linux/poll.h>
20 #include <linux/slab.h>
21 #include <linux/seq_file.h>
22 #include <linux/file.h>
23 #include <linux/bug.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/syscalls.h>
26 #include <linux/userfaultfd_k.h>
27 #include <linux/mempolicy.h>
28 #include <linux/ioctl.h>
29 #include <linux/security.h>
30
31 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
32
33 enum userfaultfd_state {
34         UFFD_STATE_WAIT_API,
35         UFFD_STATE_RUNNING,
36 };
37
38 /*
39  * Start with fault_pending_wqh and fault_wqh so they're more likely
40  * to be in the same cacheline.
41  */
42 struct userfaultfd_ctx {
43         /* waitqueue head for the pending (i.e. not read) userfaults */
44         wait_queue_head_t fault_pending_wqh;
45         /* waitqueue head for the userfaults */
46         wait_queue_head_t fault_wqh;
47         /* waitqueue head for the pseudo fd to wakeup poll/read */
48         wait_queue_head_t fd_wqh;
49         /* waitqueue head for events */
50         wait_queue_head_t event_wqh;
51         /* a refile sequence protected by fault_pending_wqh lock */
52         struct seqcount refile_seq;
53         /* pseudo fd refcounting */
54         atomic_t refcount;
55         /* userfaultfd syscall flags */
56         unsigned int flags;
57         /* features requested from the userspace */
58         unsigned int features;
59         /* state machine */
60         enum userfaultfd_state state;
61         /* released */
62         bool released;
63         /* mm with one ore more vmas attached to this userfaultfd_ctx */
64         struct mm_struct *mm;
65 };
66
67 struct userfaultfd_wait_queue {
68         struct uffd_msg msg;
69         wait_queue_t wq;
70         struct userfaultfd_ctx *ctx;
71         bool waken;
72 };
73
74 struct userfaultfd_wake_range {
75         unsigned long start;
76         unsigned long len;
77 };
78
79 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
80                                      int wake_flags, void *key)
81 {
82         struct userfaultfd_wake_range *range = key;
83         int ret;
84         struct userfaultfd_wait_queue *uwq;
85         unsigned long start, len;
86
87         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
88         ret = 0;
89         /* len == 0 means wake all */
90         start = range->start;
91         len = range->len;
92         if (len && (start > uwq->msg.arg.pagefault.address ||
93                     start + len <= uwq->msg.arg.pagefault.address))
94                 goto out;
95         WRITE_ONCE(uwq->waken, true);
96         /*
97          * The implicit smp_mb__before_spinlock in try_to_wake_up()
98          * renders uwq->waken visible to other CPUs before the task is
99          * waken.
100          */
101         ret = wake_up_state(wq->private, mode);
102         if (ret)
103                 /*
104                  * Wake only once, autoremove behavior.
105                  *
106                  * After the effect of list_del_init is visible to the
107                  * other CPUs, the waitqueue may disappear from under
108                  * us, see the !list_empty_careful() in
109                  * handle_userfault(). try_to_wake_up() has an
110                  * implicit smp_mb__before_spinlock, and the
111                  * wq->private is read before calling the extern
112                  * function "wake_up_state" (which in turns calls
113                  * try_to_wake_up). While the spin_lock;spin_unlock;
114                  * wouldn't be enough, the smp_mb__before_spinlock is
115                  * enough to avoid an explicit smp_mb() here.
116                  */
117                 list_del_init(&wq->task_list);
118 out:
119         return ret;
120 }
121
122 /**
123  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
124  * context.
125  * @ctx: [in] Pointer to the userfaultfd context.
126  *
127  * Returns: In case of success, returns not zero.
128  */
129 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
130 {
131         if (!atomic_inc_not_zero(&ctx->refcount))
132                 BUG();
133 }
134
135 /**
136  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
137  * context.
138  * @ctx: [in] Pointer to userfaultfd context.
139  *
140  * The userfaultfd context reference must have been previously acquired either
141  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
142  */
143 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
144 {
145         if (atomic_dec_and_test(&ctx->refcount)) {
146                 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
147                 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
148                 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
149                 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
150                 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
151                 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
152                 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
153                 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
154                 mmdrop(ctx->mm);
155                 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
156         }
157 }
158
159 static inline void msg_init(struct uffd_msg *msg)
160 {
161         BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
162         /*
163          * Must use memset to zero out the paddings or kernel data is
164          * leaked to userland.
165          */
166         memset(msg, 0, sizeof(struct uffd_msg));
167 }
168
169 static inline struct uffd_msg userfault_msg(unsigned long address,
170                                             unsigned int flags,
171                                             unsigned long reason)
172 {
173         struct uffd_msg msg;
174         msg_init(&msg);
175         msg.event = UFFD_EVENT_PAGEFAULT;
176         msg.arg.pagefault.address = address;
177         if (flags & FAULT_FLAG_WRITE)
178                 /*
179                  * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
180                  * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
181                  * was not set in a UFFD_EVENT_PAGEFAULT, it means it
182                  * was a read fault, otherwise if set it means it's
183                  * a write fault.
184                  */
185                 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
186         if (reason & VM_UFFD_WP)
187                 /*
188                  * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
189                  * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
190                  * not set in a UFFD_EVENT_PAGEFAULT, it means it was
191                  * a missing fault, otherwise if set it means it's a
192                  * write protect fault.
193                  */
194                 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
195         return msg;
196 }
197
198 /*
199  * Verify the pagetables are still not ok after having reigstered into
200  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
201  * userfault that has already been resolved, if userfaultfd_read and
202  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
203  * threads.
204  */
205 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
206                                          unsigned long address,
207                                          unsigned long flags,
208                                          unsigned long reason)
209 {
210         struct mm_struct *mm = ctx->mm;
211         pgd_t *pgd;
212         pud_t *pud;
213         pmd_t *pmd, _pmd;
214         pte_t *pte;
215         bool ret = true;
216
217         VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
218
219         pgd = pgd_offset(mm, address);
220         if (!pgd_present(*pgd))
221                 goto out;
222         pud = pud_offset(pgd, address);
223         if (!pud_present(*pud))
224                 goto out;
225         pmd = pmd_offset(pud, address);
226         /*
227          * READ_ONCE must function as a barrier with narrower scope
228          * and it must be equivalent to:
229          *      _pmd = *pmd; barrier();
230          *
231          * This is to deal with the instability (as in
232          * pmd_trans_unstable) of the pmd.
233          */
234         _pmd = READ_ONCE(*pmd);
235         if (!pmd_present(_pmd))
236                 goto out;
237
238         ret = false;
239         if (pmd_trans_huge(_pmd))
240                 goto out;
241
242         /*
243          * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
244          * and use the standard pte_offset_map() instead of parsing _pmd.
245          */
246         pte = pte_offset_map(pmd, address);
247         /*
248          * Lockless access: we're in a wait_event so it's ok if it
249          * changes under us.
250          */
251         if (pte_none(*pte))
252                 ret = true;
253         pte_unmap(pte);
254
255 out:
256         return ret;
257 }
258
259 /*
260  * The locking rules involved in returning VM_FAULT_RETRY depending on
261  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
262  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
263  * recommendation in __lock_page_or_retry is not an understatement.
264  *
265  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
266  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
267  * not set.
268  *
269  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
270  * set, VM_FAULT_RETRY can still be returned if and only if there are
271  * fatal_signal_pending()s, and the mmap_sem must be released before
272  * returning it.
273  */
274 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
275 {
276         struct mm_struct *mm = vmf->vma->vm_mm;
277         struct userfaultfd_ctx *ctx;
278         struct userfaultfd_wait_queue uwq;
279         int ret;
280         bool must_wait, return_to_userland;
281         long blocking_state;
282
283         BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
284
285         ret = VM_FAULT_SIGBUS;
286         ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
287         if (!ctx)
288                 goto out;
289
290         BUG_ON(ctx->mm != mm);
291
292         VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
293         VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
294
295         /*
296          * If it's already released don't get it. This avoids to loop
297          * in __get_user_pages if userfaultfd_release waits on the
298          * caller of handle_userfault to release the mmap_sem.
299          */
300         if (unlikely(ACCESS_ONCE(ctx->released)))
301                 goto out;
302
303         /*
304          * We don't do userfault handling for the final child pid update.
305          */
306         if (current->flags & PF_EXITING)
307                 goto out;
308
309         /*
310          * Check that we can return VM_FAULT_RETRY.
311          *
312          * NOTE: it should become possible to return VM_FAULT_RETRY
313          * even if FAULT_FLAG_TRIED is set without leading to gup()
314          * -EBUSY failures, if the userfaultfd is to be extended for
315          * VM_UFFD_WP tracking and we intend to arm the userfault
316          * without first stopping userland access to the memory. For
317          * VM_UFFD_MISSING userfaults this is enough for now.
318          */
319         if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
320                 /*
321                  * Validate the invariant that nowait must allow retry
322                  * to be sure not to return SIGBUS erroneously on
323                  * nowait invocations.
324                  */
325                 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
326 #ifdef CONFIG_DEBUG_VM
327                 if (printk_ratelimit()) {
328                         printk(KERN_WARNING
329                                "FAULT_FLAG_ALLOW_RETRY missing %x\n",
330                                vmf->flags);
331                         dump_stack();
332                 }
333 #endif
334                 goto out;
335         }
336
337         /*
338          * Handle nowait, not much to do other than tell it to retry
339          * and wait.
340          */
341         ret = VM_FAULT_RETRY;
342         if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
343                 goto out;
344
345         /* take the reference before dropping the mmap_sem */
346         userfaultfd_ctx_get(ctx);
347
348         init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
349         uwq.wq.private = current;
350         uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
351         uwq.ctx = ctx;
352         uwq.waken = false;
353
354         return_to_userland =
355                 (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
356                 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
357         blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
358                          TASK_KILLABLE;
359
360         spin_lock(&ctx->fault_pending_wqh.lock);
361         /*
362          * After the __add_wait_queue the uwq is visible to userland
363          * through poll/read().
364          */
365         __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
366         /*
367          * The smp_mb() after __set_current_state prevents the reads
368          * following the spin_unlock to happen before the list_add in
369          * __add_wait_queue.
370          */
371         set_current_state(blocking_state);
372         spin_unlock(&ctx->fault_pending_wqh.lock);
373
374         must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
375                                           reason);
376         up_read(&mm->mmap_sem);
377
378         if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
379                    (return_to_userland ? !signal_pending(current) :
380                     !fatal_signal_pending(current)))) {
381                 wake_up_poll(&ctx->fd_wqh, POLLIN);
382                 schedule();
383                 ret |= VM_FAULT_MAJOR;
384
385                 /*
386                  * False wakeups can orginate even from rwsem before
387                  * up_read() however userfaults will wait either for a
388                  * targeted wakeup on the specific uwq waitqueue from
389                  * wake_userfault() or for signals or for uffd
390                  * release.
391                  */
392                 while (!READ_ONCE(uwq.waken)) {
393                         /*
394                          * This needs the full smp_store_mb()
395                          * guarantee as the state write must be
396                          * visible to other CPUs before reading
397                          * uwq.waken from other CPUs.
398                          */
399                         set_current_state(blocking_state);
400                         if (READ_ONCE(uwq.waken) ||
401                             READ_ONCE(ctx->released) ||
402                             (return_to_userland ? signal_pending(current) :
403                              fatal_signal_pending(current)))
404                                 break;
405                         schedule();
406                 }
407         }
408
409         __set_current_state(TASK_RUNNING);
410
411         if (return_to_userland) {
412                 if (signal_pending(current) &&
413                     !fatal_signal_pending(current)) {
414                         /*
415                          * If we got a SIGSTOP or SIGCONT and this is
416                          * a normal userland page fault, just let
417                          * userland return so the signal will be
418                          * handled and gdb debugging works.  The page
419                          * fault code immediately after we return from
420                          * this function is going to release the
421                          * mmap_sem and it's not depending on it
422                          * (unlike gup would if we were not to return
423                          * VM_FAULT_RETRY).
424                          *
425                          * If a fatal signal is pending we still take
426                          * the streamlined VM_FAULT_RETRY failure path
427                          * and there's no need to retake the mmap_sem
428                          * in such case.
429                          */
430                         down_read(&mm->mmap_sem);
431                         ret = 0;
432                 }
433         }
434
435         /*
436          * Here we race with the list_del; list_add in
437          * userfaultfd_ctx_read(), however because we don't ever run
438          * list_del_init() to refile across the two lists, the prev
439          * and next pointers will never point to self. list_add also
440          * would never let any of the two pointers to point to
441          * self. So list_empty_careful won't risk to see both pointers
442          * pointing to self at any time during the list refile. The
443          * only case where list_del_init() is called is the full
444          * removal in the wake function and there we don't re-list_add
445          * and it's fine not to block on the spinlock. The uwq on this
446          * kernel stack can be released after the list_del_init.
447          */
448         if (!list_empty_careful(&uwq.wq.task_list)) {
449                 spin_lock(&ctx->fault_pending_wqh.lock);
450                 /*
451                  * No need of list_del_init(), the uwq on the stack
452                  * will be freed shortly anyway.
453                  */
454                 list_del(&uwq.wq.task_list);
455                 spin_unlock(&ctx->fault_pending_wqh.lock);
456         }
457
458         /*
459          * ctx may go away after this if the userfault pseudo fd is
460          * already released.
461          */
462         userfaultfd_ctx_put(ctx);
463
464 out:
465         return ret;
466 }
467
468 static int __maybe_unused userfaultfd_event_wait_completion(
469                 struct userfaultfd_ctx *ctx,
470                 struct userfaultfd_wait_queue *ewq)
471 {
472         int ret = 0;
473
474         ewq->ctx = ctx;
475         init_waitqueue_entry(&ewq->wq, current);
476
477         spin_lock(&ctx->event_wqh.lock);
478         /*
479          * After the __add_wait_queue the uwq is visible to userland
480          * through poll/read().
481          */
482         __add_wait_queue(&ctx->event_wqh, &ewq->wq);
483         for (;;) {
484                 set_current_state(TASK_KILLABLE);
485                 if (ewq->msg.event == 0)
486                         break;
487                 if (ACCESS_ONCE(ctx->released) ||
488                     fatal_signal_pending(current)) {
489                         ret = -1;
490                         __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
491                         break;
492                 }
493
494                 spin_unlock(&ctx->event_wqh.lock);
495
496                 wake_up_poll(&ctx->fd_wqh, POLLIN);
497                 schedule();
498
499                 spin_lock(&ctx->event_wqh.lock);
500         }
501         __set_current_state(TASK_RUNNING);
502         spin_unlock(&ctx->event_wqh.lock);
503
504         /*
505          * ctx may go away after this if the userfault pseudo fd is
506          * already released.
507          */
508
509         userfaultfd_ctx_put(ctx);
510         return ret;
511 }
512
513 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
514                                        struct userfaultfd_wait_queue *ewq)
515 {
516         ewq->msg.event = 0;
517         wake_up_locked(&ctx->event_wqh);
518         __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
519 }
520
521 static int userfaultfd_release(struct inode *inode, struct file *file)
522 {
523         struct userfaultfd_ctx *ctx = file->private_data;
524         struct mm_struct *mm = ctx->mm;
525         struct vm_area_struct *vma, *prev;
526         /* len == 0 means wake all */
527         struct userfaultfd_wake_range range = { .len = 0, };
528         unsigned long new_flags;
529
530         ACCESS_ONCE(ctx->released) = true;
531
532         if (!mmget_not_zero(mm))
533                 goto wakeup;
534
535         /*
536          * Flush page faults out of all CPUs. NOTE: all page faults
537          * must be retried without returning VM_FAULT_SIGBUS if
538          * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
539          * changes while handle_userfault released the mmap_sem. So
540          * it's critical that released is set to true (above), before
541          * taking the mmap_sem for writing.
542          */
543         down_write(&mm->mmap_sem);
544         prev = NULL;
545         for (vma = mm->mmap; vma; vma = vma->vm_next) {
546                 cond_resched();
547                 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
548                        !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
549                 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
550                         prev = vma;
551                         continue;
552                 }
553                 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
554                 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
555                                  new_flags, vma->anon_vma,
556                                  vma->vm_file, vma->vm_pgoff,
557                                  vma_policy(vma),
558                                  NULL_VM_UFFD_CTX);
559                 if (prev)
560                         vma = prev;
561                 else
562                         prev = vma;
563                 vma->vm_flags = new_flags;
564                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
565         }
566         up_write(&mm->mmap_sem);
567         mmput(mm);
568 wakeup:
569         /*
570          * After no new page faults can wait on this fault_*wqh, flush
571          * the last page faults that may have been already waiting on
572          * the fault_*wqh.
573          */
574         spin_lock(&ctx->fault_pending_wqh.lock);
575         __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
576         __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
577         spin_unlock(&ctx->fault_pending_wqh.lock);
578
579         wake_up_poll(&ctx->fd_wqh, POLLHUP);
580         userfaultfd_ctx_put(ctx);
581         return 0;
582 }
583
584 /* fault_pending_wqh.lock must be hold by the caller */
585 static inline struct userfaultfd_wait_queue *find_userfault_in(
586                 wait_queue_head_t *wqh)
587 {
588         wait_queue_t *wq;
589         struct userfaultfd_wait_queue *uwq;
590
591         VM_BUG_ON(!spin_is_locked(&wqh->lock));
592
593         uwq = NULL;
594         if (!waitqueue_active(wqh))
595                 goto out;
596         /* walk in reverse to provide FIFO behavior to read userfaults */
597         wq = list_last_entry(&wqh->task_list, typeof(*wq), task_list);
598         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
599 out:
600         return uwq;
601 }
602
603 static inline struct userfaultfd_wait_queue *find_userfault(
604                 struct userfaultfd_ctx *ctx)
605 {
606         return find_userfault_in(&ctx->fault_pending_wqh);
607 }
608
609 static inline struct userfaultfd_wait_queue *find_userfault_evt(
610                 struct userfaultfd_ctx *ctx)
611 {
612         return find_userfault_in(&ctx->event_wqh);
613 }
614
615 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
616 {
617         struct userfaultfd_ctx *ctx = file->private_data;
618         unsigned int ret;
619
620         poll_wait(file, &ctx->fd_wqh, wait);
621
622         switch (ctx->state) {
623         case UFFD_STATE_WAIT_API:
624                 return POLLERR;
625         case UFFD_STATE_RUNNING:
626                 /*
627                  * poll() never guarantees that read won't block.
628                  * userfaults can be waken before they're read().
629                  */
630                 if (unlikely(!(file->f_flags & O_NONBLOCK)))
631                         return POLLERR;
632                 /*
633                  * lockless access to see if there are pending faults
634                  * __pollwait last action is the add_wait_queue but
635                  * the spin_unlock would allow the waitqueue_active to
636                  * pass above the actual list_add inside
637                  * add_wait_queue critical section. So use a full
638                  * memory barrier to serialize the list_add write of
639                  * add_wait_queue() with the waitqueue_active read
640                  * below.
641                  */
642                 ret = 0;
643                 smp_mb();
644                 if (waitqueue_active(&ctx->fault_pending_wqh))
645                         ret = POLLIN;
646                 else if (waitqueue_active(&ctx->event_wqh))
647                         ret = POLLIN;
648
649                 return ret;
650         default:
651                 WARN_ON_ONCE(1);
652                 return POLLERR;
653         }
654 }
655
656 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
657                                     struct uffd_msg *msg)
658 {
659         ssize_t ret;
660         DECLARE_WAITQUEUE(wait, current);
661         struct userfaultfd_wait_queue *uwq;
662
663         /* always take the fd_wqh lock before the fault_pending_wqh lock */
664         spin_lock(&ctx->fd_wqh.lock);
665         __add_wait_queue(&ctx->fd_wqh, &wait);
666         for (;;) {
667                 set_current_state(TASK_INTERRUPTIBLE);
668                 spin_lock(&ctx->fault_pending_wqh.lock);
669                 uwq = find_userfault(ctx);
670                 if (uwq) {
671                         /*
672                          * Use a seqcount to repeat the lockless check
673                          * in wake_userfault() to avoid missing
674                          * wakeups because during the refile both
675                          * waitqueue could become empty if this is the
676                          * only userfault.
677                          */
678                         write_seqcount_begin(&ctx->refile_seq);
679
680                         /*
681                          * The fault_pending_wqh.lock prevents the uwq
682                          * to disappear from under us.
683                          *
684                          * Refile this userfault from
685                          * fault_pending_wqh to fault_wqh, it's not
686                          * pending anymore after we read it.
687                          *
688                          * Use list_del() by hand (as
689                          * userfaultfd_wake_function also uses
690                          * list_del_init() by hand) to be sure nobody
691                          * changes __remove_wait_queue() to use
692                          * list_del_init() in turn breaking the
693                          * !list_empty_careful() check in
694                          * handle_userfault(). The uwq->wq.task_list
695                          * must never be empty at any time during the
696                          * refile, or the waitqueue could disappear
697                          * from under us. The "wait_queue_head_t"
698                          * parameter of __remove_wait_queue() is unused
699                          * anyway.
700                          */
701                         list_del(&uwq->wq.task_list);
702                         __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
703
704                         write_seqcount_end(&ctx->refile_seq);
705
706                         /* careful to always initialize msg if ret == 0 */
707                         *msg = uwq->msg;
708                         spin_unlock(&ctx->fault_pending_wqh.lock);
709                         ret = 0;
710                         break;
711                 }
712                 spin_unlock(&ctx->fault_pending_wqh.lock);
713
714                 spin_lock(&ctx->event_wqh.lock);
715                 uwq = find_userfault_evt(ctx);
716                 if (uwq) {
717                         *msg = uwq->msg;
718
719                         userfaultfd_event_complete(ctx, uwq);
720                         spin_unlock(&ctx->event_wqh.lock);
721                         ret = 0;
722                         break;
723                 }
724                 spin_unlock(&ctx->event_wqh.lock);
725
726                 if (signal_pending(current)) {
727                         ret = -ERESTARTSYS;
728                         break;
729                 }
730                 if (no_wait) {
731                         ret = -EAGAIN;
732                         break;
733                 }
734                 spin_unlock(&ctx->fd_wqh.lock);
735                 schedule();
736                 spin_lock(&ctx->fd_wqh.lock);
737         }
738         __remove_wait_queue(&ctx->fd_wqh, &wait);
739         __set_current_state(TASK_RUNNING);
740         spin_unlock(&ctx->fd_wqh.lock);
741
742         return ret;
743 }
744
745 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
746                                 size_t count, loff_t *ppos)
747 {
748         struct userfaultfd_ctx *ctx = file->private_data;
749         ssize_t _ret, ret = 0;
750         struct uffd_msg msg;
751         int no_wait = file->f_flags & O_NONBLOCK;
752
753         if (ctx->state == UFFD_STATE_WAIT_API)
754                 return -EINVAL;
755
756         for (;;) {
757                 if (count < sizeof(msg))
758                         return ret ? ret : -EINVAL;
759                 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
760                 if (_ret < 0)
761                         return ret ? ret : _ret;
762                 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
763                         return ret ? ret : -EFAULT;
764                 ret += sizeof(msg);
765                 buf += sizeof(msg);
766                 count -= sizeof(msg);
767                 /*
768                  * Allow to read more than one fault at time but only
769                  * block if waiting for the very first one.
770                  */
771                 no_wait = O_NONBLOCK;
772         }
773 }
774
775 static void __wake_userfault(struct userfaultfd_ctx *ctx,
776                              struct userfaultfd_wake_range *range)
777 {
778         unsigned long start, end;
779
780         start = range->start;
781         end = range->start + range->len;
782
783         spin_lock(&ctx->fault_pending_wqh.lock);
784         /* wake all in the range and autoremove */
785         if (waitqueue_active(&ctx->fault_pending_wqh))
786                 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
787                                      range);
788         if (waitqueue_active(&ctx->fault_wqh))
789                 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
790         spin_unlock(&ctx->fault_pending_wqh.lock);
791 }
792
793 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
794                                            struct userfaultfd_wake_range *range)
795 {
796         unsigned seq;
797         bool need_wakeup;
798
799         /*
800          * To be sure waitqueue_active() is not reordered by the CPU
801          * before the pagetable update, use an explicit SMP memory
802          * barrier here. PT lock release or up_read(mmap_sem) still
803          * have release semantics that can allow the
804          * waitqueue_active() to be reordered before the pte update.
805          */
806         smp_mb();
807
808         /*
809          * Use waitqueue_active because it's very frequent to
810          * change the address space atomically even if there are no
811          * userfaults yet. So we take the spinlock only when we're
812          * sure we've userfaults to wake.
813          */
814         do {
815                 seq = read_seqcount_begin(&ctx->refile_seq);
816                 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
817                         waitqueue_active(&ctx->fault_wqh);
818                 cond_resched();
819         } while (read_seqcount_retry(&ctx->refile_seq, seq));
820         if (need_wakeup)
821                 __wake_userfault(ctx, range);
822 }
823
824 static __always_inline int validate_range(struct mm_struct *mm,
825                                           __u64 start, __u64 len)
826 {
827         __u64 task_size = mm->task_size;
828
829         if (start & ~PAGE_MASK)
830                 return -EINVAL;
831         if (len & ~PAGE_MASK)
832                 return -EINVAL;
833         if (!len)
834                 return -EINVAL;
835         if (start < mmap_min_addr)
836                 return -EINVAL;
837         if (start >= task_size)
838                 return -EINVAL;
839         if (len > task_size - start)
840                 return -EINVAL;
841         return 0;
842 }
843
844 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
845                                 unsigned long arg)
846 {
847         struct mm_struct *mm = ctx->mm;
848         struct vm_area_struct *vma, *prev, *cur;
849         int ret;
850         struct uffdio_register uffdio_register;
851         struct uffdio_register __user *user_uffdio_register;
852         unsigned long vm_flags, new_flags;
853         bool found;
854         unsigned long start, end, vma_end;
855
856         user_uffdio_register = (struct uffdio_register __user *) arg;
857
858         ret = -EFAULT;
859         if (copy_from_user(&uffdio_register, user_uffdio_register,
860                            sizeof(uffdio_register)-sizeof(__u64)))
861                 goto out;
862
863         ret = -EINVAL;
864         if (!uffdio_register.mode)
865                 goto out;
866         if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
867                                      UFFDIO_REGISTER_MODE_WP))
868                 goto out;
869         vm_flags = 0;
870         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
871                 vm_flags |= VM_UFFD_MISSING;
872         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
873                 vm_flags |= VM_UFFD_WP;
874                 /*
875                  * FIXME: remove the below error constraint by
876                  * implementing the wprotect tracking mode.
877                  */
878                 ret = -EINVAL;
879                 goto out;
880         }
881
882         ret = validate_range(mm, uffdio_register.range.start,
883                              uffdio_register.range.len);
884         if (ret)
885                 goto out;
886
887         start = uffdio_register.range.start;
888         end = start + uffdio_register.range.len;
889
890         ret = -ENOMEM;
891         if (!mmget_not_zero(mm))
892                 goto out;
893
894         down_write(&mm->mmap_sem);
895         vma = find_vma_prev(mm, start, &prev);
896         if (!vma)
897                 goto out_unlock;
898
899         /* check that there's at least one vma in the range */
900         ret = -EINVAL;
901         if (vma->vm_start >= end)
902                 goto out_unlock;
903
904         /*
905          * Search for not compatible vmas.
906          *
907          * FIXME: this shall be relaxed later so that it doesn't fail
908          * on tmpfs backed vmas (in addition to the current allowance
909          * on anonymous vmas).
910          */
911         found = false;
912         for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
913                 cond_resched();
914
915                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
916                        !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
917
918                 /* check not compatible vmas */
919                 ret = -EINVAL;
920                 if (!vma_is_anonymous(cur))
921                         goto out_unlock;
922
923                 /*
924                  * Check that this vma isn't already owned by a
925                  * different userfaultfd. We can't allow more than one
926                  * userfaultfd to own a single vma simultaneously or we
927                  * wouldn't know which one to deliver the userfaults to.
928                  */
929                 ret = -EBUSY;
930                 if (cur->vm_userfaultfd_ctx.ctx &&
931                     cur->vm_userfaultfd_ctx.ctx != ctx)
932                         goto out_unlock;
933
934                 found = true;
935         }
936         BUG_ON(!found);
937
938         if (vma->vm_start < start)
939                 prev = vma;
940
941         ret = 0;
942         do {
943                 cond_resched();
944
945                 BUG_ON(!vma_is_anonymous(vma));
946                 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
947                        vma->vm_userfaultfd_ctx.ctx != ctx);
948
949                 /*
950                  * Nothing to do: this vma is already registered into this
951                  * userfaultfd and with the right tracking mode too.
952                  */
953                 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
954                     (vma->vm_flags & vm_flags) == vm_flags)
955                         goto skip;
956
957                 if (vma->vm_start > start)
958                         start = vma->vm_start;
959                 vma_end = min(end, vma->vm_end);
960
961                 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
962                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
963                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
964                                  vma_policy(vma),
965                                  ((struct vm_userfaultfd_ctx){ ctx }));
966                 if (prev) {
967                         vma = prev;
968                         goto next;
969                 }
970                 if (vma->vm_start < start) {
971                         ret = split_vma(mm, vma, start, 1);
972                         if (ret)
973                                 break;
974                 }
975                 if (vma->vm_end > end) {
976                         ret = split_vma(mm, vma, end, 0);
977                         if (ret)
978                                 break;
979                 }
980         next:
981                 /*
982                  * In the vma_merge() successful mprotect-like case 8:
983                  * the next vma was merged into the current one and
984                  * the current one has not been updated yet.
985                  */
986                 vma->vm_flags = new_flags;
987                 vma->vm_userfaultfd_ctx.ctx = ctx;
988
989         skip:
990                 prev = vma;
991                 start = vma->vm_end;
992                 vma = vma->vm_next;
993         } while (vma && vma->vm_start < end);
994 out_unlock:
995         up_write(&mm->mmap_sem);
996         mmput(mm);
997         if (!ret) {
998                 /*
999                  * Now that we scanned all vmas we can already tell
1000                  * userland which ioctls methods are guaranteed to
1001                  * succeed on this range.
1002                  */
1003                 if (put_user(UFFD_API_RANGE_IOCTLS,
1004                              &user_uffdio_register->ioctls))
1005                         ret = -EFAULT;
1006         }
1007 out:
1008         return ret;
1009 }
1010
1011 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1012                                   unsigned long arg)
1013 {
1014         struct mm_struct *mm = ctx->mm;
1015         struct vm_area_struct *vma, *prev, *cur;
1016         int ret;
1017         struct uffdio_range uffdio_unregister;
1018         unsigned long new_flags;
1019         bool found;
1020         unsigned long start, end, vma_end;
1021         const void __user *buf = (void __user *)arg;
1022
1023         ret = -EFAULT;
1024         if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1025                 goto out;
1026
1027         ret = validate_range(mm, uffdio_unregister.start,
1028                              uffdio_unregister.len);
1029         if (ret)
1030                 goto out;
1031
1032         start = uffdio_unregister.start;
1033         end = start + uffdio_unregister.len;
1034
1035         ret = -ENOMEM;
1036         if (!mmget_not_zero(mm))
1037                 goto out;
1038
1039         down_write(&mm->mmap_sem);
1040         vma = find_vma_prev(mm, start, &prev);
1041         if (!vma)
1042                 goto out_unlock;
1043
1044         /* check that there's at least one vma in the range */
1045         ret = -EINVAL;
1046         if (vma->vm_start >= end)
1047                 goto out_unlock;
1048
1049         /*
1050          * Search for not compatible vmas.
1051          *
1052          * FIXME: this shall be relaxed later so that it doesn't fail
1053          * on tmpfs backed vmas (in addition to the current allowance
1054          * on anonymous vmas).
1055          */
1056         found = false;
1057         ret = -EINVAL;
1058         for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1059                 cond_resched();
1060
1061                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1062                        !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1063
1064                 /*
1065                  * Check not compatible vmas, not strictly required
1066                  * here as not compatible vmas cannot have an
1067                  * userfaultfd_ctx registered on them, but this
1068                  * provides for more strict behavior to notice
1069                  * unregistration errors.
1070                  */
1071                 if (!vma_is_anonymous(cur))
1072                         goto out_unlock;
1073
1074                 found = true;
1075         }
1076         BUG_ON(!found);
1077
1078         if (vma->vm_start < start)
1079                 prev = vma;
1080
1081         ret = 0;
1082         do {
1083                 cond_resched();
1084
1085                 BUG_ON(!vma_is_anonymous(vma));
1086
1087                 /*
1088                  * Nothing to do: this vma is already registered into this
1089                  * userfaultfd and with the right tracking mode too.
1090                  */
1091                 if (!vma->vm_userfaultfd_ctx.ctx)
1092                         goto skip;
1093
1094                 if (vma->vm_start > start)
1095                         start = vma->vm_start;
1096                 vma_end = min(end, vma->vm_end);
1097
1098                 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1099                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1100                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1101                                  vma_policy(vma),
1102                                  NULL_VM_UFFD_CTX);
1103                 if (prev) {
1104                         vma = prev;
1105                         goto next;
1106                 }
1107                 if (vma->vm_start < start) {
1108                         ret = split_vma(mm, vma, start, 1);
1109                         if (ret)
1110                                 break;
1111                 }
1112                 if (vma->vm_end > end) {
1113                         ret = split_vma(mm, vma, end, 0);
1114                         if (ret)
1115                                 break;
1116                 }
1117         next:
1118                 /*
1119                  * In the vma_merge() successful mprotect-like case 8:
1120                  * the next vma was merged into the current one and
1121                  * the current one has not been updated yet.
1122                  */
1123                 vma->vm_flags = new_flags;
1124                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1125
1126         skip:
1127                 prev = vma;
1128                 start = vma->vm_end;
1129                 vma = vma->vm_next;
1130         } while (vma && vma->vm_start < end);
1131 out_unlock:
1132         up_write(&mm->mmap_sem);
1133         mmput(mm);
1134 out:
1135         return ret;
1136 }
1137
1138 /*
1139  * userfaultfd_wake may be used in combination with the
1140  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1141  */
1142 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1143                             unsigned long arg)
1144 {
1145         int ret;
1146         struct uffdio_range uffdio_wake;
1147         struct userfaultfd_wake_range range;
1148         const void __user *buf = (void __user *)arg;
1149
1150         ret = -EFAULT;
1151         if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1152                 goto out;
1153
1154         ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1155         if (ret)
1156                 goto out;
1157
1158         range.start = uffdio_wake.start;
1159         range.len = uffdio_wake.len;
1160
1161         /*
1162          * len == 0 means wake all and we don't want to wake all here,
1163          * so check it again to be sure.
1164          */
1165         VM_BUG_ON(!range.len);
1166
1167         wake_userfault(ctx, &range);
1168         ret = 0;
1169
1170 out:
1171         return ret;
1172 }
1173
1174 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1175                             unsigned long arg)
1176 {
1177         __s64 ret;
1178         struct uffdio_copy uffdio_copy;
1179         struct uffdio_copy __user *user_uffdio_copy;
1180         struct userfaultfd_wake_range range;
1181
1182         user_uffdio_copy = (struct uffdio_copy __user *) arg;
1183
1184         ret = -EFAULT;
1185         if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1186                            /* don't copy "copy" last field */
1187                            sizeof(uffdio_copy)-sizeof(__s64)))
1188                 goto out;
1189
1190         ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1191         if (ret)
1192                 goto out;
1193         /*
1194          * double check for wraparound just in case. copy_from_user()
1195          * will later check uffdio_copy.src + uffdio_copy.len to fit
1196          * in the userland range.
1197          */
1198         ret = -EINVAL;
1199         if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1200                 goto out;
1201         if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1202                 goto out;
1203         if (mmget_not_zero(ctx->mm)) {
1204                 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1205                                    uffdio_copy.len);
1206                 mmput(ctx->mm);
1207         }
1208         if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1209                 return -EFAULT;
1210         if (ret < 0)
1211                 goto out;
1212         BUG_ON(!ret);
1213         /* len == 0 would wake all */
1214         range.len = ret;
1215         if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1216                 range.start = uffdio_copy.dst;
1217                 wake_userfault(ctx, &range);
1218         }
1219         ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1220 out:
1221         return ret;
1222 }
1223
1224 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1225                                 unsigned long arg)
1226 {
1227         __s64 ret;
1228         struct uffdio_zeropage uffdio_zeropage;
1229         struct uffdio_zeropage __user *user_uffdio_zeropage;
1230         struct userfaultfd_wake_range range;
1231
1232         user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1233
1234         ret = -EFAULT;
1235         if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1236                            /* don't copy "zeropage" last field */
1237                            sizeof(uffdio_zeropage)-sizeof(__s64)))
1238                 goto out;
1239
1240         ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1241                              uffdio_zeropage.range.len);
1242         if (ret)
1243                 goto out;
1244         ret = -EINVAL;
1245         if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1246                 goto out;
1247
1248         if (mmget_not_zero(ctx->mm)) {
1249                 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1250                                      uffdio_zeropage.range.len);
1251                 mmput(ctx->mm);
1252         }
1253         if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1254                 return -EFAULT;
1255         if (ret < 0)
1256                 goto out;
1257         /* len == 0 would wake all */
1258         BUG_ON(!ret);
1259         range.len = ret;
1260         if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1261                 range.start = uffdio_zeropage.range.start;
1262                 wake_userfault(ctx, &range);
1263         }
1264         ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1265 out:
1266         return ret;
1267 }
1268
1269 static inline unsigned int uffd_ctx_features(__u64 user_features)
1270 {
1271         /*
1272          * For the current set of features the bits just coincide
1273          */
1274         return (unsigned int)user_features;
1275 }
1276
1277 /*
1278  * userland asks for a certain API version and we return which bits
1279  * and ioctl commands are implemented in this kernel for such API
1280  * version or -EINVAL if unknown.
1281  */
1282 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1283                            unsigned long arg)
1284 {
1285         struct uffdio_api uffdio_api;
1286         void __user *buf = (void __user *)arg;
1287         int ret;
1288
1289         ret = -EINVAL;
1290         if (ctx->state != UFFD_STATE_WAIT_API)
1291                 goto out;
1292         ret = -EFAULT;
1293         if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1294                 goto out;
1295         if (uffdio_api.api != UFFD_API ||
1296             (uffdio_api.features & ~UFFD_API_FEATURES)) {
1297                 memset(&uffdio_api, 0, sizeof(uffdio_api));
1298                 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1299                         goto out;
1300                 ret = -EINVAL;
1301                 goto out;
1302         }
1303         uffdio_api.features &= UFFD_API_FEATURES;
1304         uffdio_api.ioctls = UFFD_API_IOCTLS;
1305         ret = -EFAULT;
1306         if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1307                 goto out;
1308         ctx->state = UFFD_STATE_RUNNING;
1309         ctx->features = uffd_ctx_features(uffdio_api.features);
1310         ret = 0;
1311 out:
1312         return ret;
1313 }
1314
1315 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1316                               unsigned long arg)
1317 {
1318         int ret = -EINVAL;
1319         struct userfaultfd_ctx *ctx = file->private_data;
1320
1321         if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1322                 return -EINVAL;
1323
1324         switch(cmd) {
1325         case UFFDIO_API:
1326                 ret = userfaultfd_api(ctx, arg);
1327                 break;
1328         case UFFDIO_REGISTER:
1329                 ret = userfaultfd_register(ctx, arg);
1330                 break;
1331         case UFFDIO_UNREGISTER:
1332                 ret = userfaultfd_unregister(ctx, arg);
1333                 break;
1334         case UFFDIO_WAKE:
1335                 ret = userfaultfd_wake(ctx, arg);
1336                 break;
1337         case UFFDIO_COPY:
1338                 ret = userfaultfd_copy(ctx, arg);
1339                 break;
1340         case UFFDIO_ZEROPAGE:
1341                 ret = userfaultfd_zeropage(ctx, arg);
1342                 break;
1343         }
1344         return ret;
1345 }
1346
1347 #ifdef CONFIG_PROC_FS
1348 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1349 {
1350         struct userfaultfd_ctx *ctx = f->private_data;
1351         wait_queue_t *wq;
1352         struct userfaultfd_wait_queue *uwq;
1353         unsigned long pending = 0, total = 0;
1354
1355         spin_lock(&ctx->fault_pending_wqh.lock);
1356         list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1357                 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1358                 pending++;
1359                 total++;
1360         }
1361         list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1362                 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1363                 total++;
1364         }
1365         spin_unlock(&ctx->fault_pending_wqh.lock);
1366
1367         /*
1368          * If more protocols will be added, there will be all shown
1369          * separated by a space. Like this:
1370          *      protocols: aa:... bb:...
1371          */
1372         seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1373                    pending, total, UFFD_API, UFFD_API_FEATURES,
1374                    UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1375 }
1376 #endif
1377
1378 static const struct file_operations userfaultfd_fops = {
1379 #ifdef CONFIG_PROC_FS
1380         .show_fdinfo    = userfaultfd_show_fdinfo,
1381 #endif
1382         .release        = userfaultfd_release,
1383         .poll           = userfaultfd_poll,
1384         .read           = userfaultfd_read,
1385         .unlocked_ioctl = userfaultfd_ioctl,
1386         .compat_ioctl   = userfaultfd_ioctl,
1387         .llseek         = noop_llseek,
1388 };
1389
1390 static void init_once_userfaultfd_ctx(void *mem)
1391 {
1392         struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1393
1394         init_waitqueue_head(&ctx->fault_pending_wqh);
1395         init_waitqueue_head(&ctx->fault_wqh);
1396         init_waitqueue_head(&ctx->event_wqh);
1397         init_waitqueue_head(&ctx->fd_wqh);
1398         seqcount_init(&ctx->refile_seq);
1399 }
1400
1401 /**
1402  * userfaultfd_file_create - Creates an userfaultfd file pointer.
1403  * @flags: Flags for the userfaultfd file.
1404  *
1405  * This function creates an userfaultfd file pointer, w/out installing
1406  * it into the fd table. This is useful when the userfaultfd file is
1407  * used during the initialization of data structures that require
1408  * extra setup after the userfaultfd creation. So the userfaultfd
1409  * creation is split into the file pointer creation phase, and the
1410  * file descriptor installation phase.  In this way races with
1411  * userspace closing the newly installed file descriptor can be
1412  * avoided.  Returns an userfaultfd file pointer, or a proper error
1413  * pointer.
1414  */
1415 static struct file *userfaultfd_file_create(int flags)
1416 {
1417         struct file *file;
1418         struct userfaultfd_ctx *ctx;
1419
1420         BUG_ON(!current->mm);
1421
1422         /* Check the UFFD_* constants for consistency.  */
1423         BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1424         BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1425
1426         file = ERR_PTR(-EINVAL);
1427         if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1428                 goto out;
1429
1430         file = ERR_PTR(-ENOMEM);
1431         ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1432         if (!ctx)
1433                 goto out;
1434
1435         atomic_set(&ctx->refcount, 1);
1436         ctx->flags = flags;
1437         ctx->features = 0;
1438         ctx->state = UFFD_STATE_WAIT_API;
1439         ctx->released = false;
1440         ctx->mm = current->mm;
1441         /* prevent the mm struct to be freed */
1442         atomic_inc(&ctx->mm->mm_count);
1443
1444         file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1445                                   O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1446         if (IS_ERR(file)) {
1447                 mmdrop(ctx->mm);
1448                 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1449         }
1450 out:
1451         return file;
1452 }
1453
1454 SYSCALL_DEFINE1(userfaultfd, int, flags)
1455 {
1456         int fd, error;
1457         struct file *file;
1458
1459         error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1460         if (error < 0)
1461                 return error;
1462         fd = error;
1463
1464         file = userfaultfd_file_create(flags);
1465         if (IS_ERR(file)) {
1466                 error = PTR_ERR(file);
1467                 goto err_put_unused_fd;
1468         }
1469         fd_install(fd, file);
1470
1471         return fd;
1472
1473 err_put_unused_fd:
1474         put_unused_fd(fd);
1475
1476         return error;
1477 }
1478
1479 static int __init userfaultfd_init(void)
1480 {
1481         userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1482                                                 sizeof(struct userfaultfd_ctx),
1483                                                 0,
1484                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1485                                                 init_once_userfaultfd_ctx);
1486         return 0;
1487 }
1488 __initcall(userfaultfd_init);