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