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