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