Merge tag 'devicetree-fixes-for-6.2-2' of git://git.kernel.org/pub/scm/linux/kernel...
[platform/kernel/linux-starfive.git] / fs / userfaultfd.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  fs/userfaultfd.c
4  *
5  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
6  *  Copyright (C) 2008-2009 Red Hat, Inc.
7  *  Copyright (C) 2015  Red Hat, Inc.
8  *
9  *  Some part derived from fs/eventfd.c (anon inode setup) and
10  *  mm/ksm.c (mm hashing).
11  */
12
13 #include <linux/list.h>
14 #include <linux/hashtable.h>
15 #include <linux/sched/signal.h>
16 #include <linux/sched/mm.h>
17 #include <linux/mm.h>
18 #include <linux/mm_inline.h>
19 #include <linux/mmu_notifier.h>
20 #include <linux/poll.h>
21 #include <linux/slab.h>
22 #include <linux/seq_file.h>
23 #include <linux/file.h>
24 #include <linux/bug.h>
25 #include <linux/anon_inodes.h>
26 #include <linux/syscalls.h>
27 #include <linux/userfaultfd_k.h>
28 #include <linux/mempolicy.h>
29 #include <linux/ioctl.h>
30 #include <linux/security.h>
31 #include <linux/hugetlb.h>
32 #include <linux/swapops.h>
33 #include <linux/miscdevice.h>
34
35 int sysctl_unprivileged_userfaultfd __read_mostly;
36
37 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
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  * Locking order:
44  *      fd_wqh.lock
45  *              fault_pending_wqh.lock
46  *                      fault_wqh.lock
47  *              event_wqh.lock
48  *
49  * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
50  * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
51  * also taken in IRQ context.
52  */
53 struct userfaultfd_ctx {
54         /* waitqueue head for the pending (i.e. not read) userfaults */
55         wait_queue_head_t fault_pending_wqh;
56         /* waitqueue head for the userfaults */
57         wait_queue_head_t fault_wqh;
58         /* waitqueue head for the pseudo fd to wakeup poll/read */
59         wait_queue_head_t fd_wqh;
60         /* waitqueue head for events */
61         wait_queue_head_t event_wqh;
62         /* a refile sequence protected by fault_pending_wqh lock */
63         seqcount_spinlock_t refile_seq;
64         /* pseudo fd refcounting */
65         refcount_t refcount;
66         /* userfaultfd syscall flags */
67         unsigned int flags;
68         /* features requested from the userspace */
69         unsigned int features;
70         /* released */
71         bool released;
72         /* memory mappings are changing because of non-cooperative event */
73         atomic_t mmap_changing;
74         /* mm with one ore more vmas attached to this userfaultfd_ctx */
75         struct mm_struct *mm;
76 };
77
78 struct userfaultfd_fork_ctx {
79         struct userfaultfd_ctx *orig;
80         struct userfaultfd_ctx *new;
81         struct list_head list;
82 };
83
84 struct userfaultfd_unmap_ctx {
85         struct userfaultfd_ctx *ctx;
86         unsigned long start;
87         unsigned long end;
88         struct list_head list;
89 };
90
91 struct userfaultfd_wait_queue {
92         struct uffd_msg msg;
93         wait_queue_entry_t wq;
94         struct userfaultfd_ctx *ctx;
95         bool waken;
96 };
97
98 struct userfaultfd_wake_range {
99         unsigned long start;
100         unsigned long len;
101 };
102
103 /* internal indication that UFFD_API ioctl was successfully executed */
104 #define UFFD_FEATURE_INITIALIZED                (1u << 31)
105
106 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
107 {
108         return ctx->features & UFFD_FEATURE_INITIALIZED;
109 }
110
111 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
112                                      vm_flags_t flags)
113 {
114         const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
115
116         vma->vm_flags = flags;
117         /*
118          * For shared mappings, we want to enable writenotify while
119          * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
120          * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
121          */
122         if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
123                 vma_set_page_prot(vma);
124 }
125
126 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
127                                      int wake_flags, void *key)
128 {
129         struct userfaultfd_wake_range *range = key;
130         int ret;
131         struct userfaultfd_wait_queue *uwq;
132         unsigned long start, len;
133
134         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
135         ret = 0;
136         /* len == 0 means wake all */
137         start = range->start;
138         len = range->len;
139         if (len && (start > uwq->msg.arg.pagefault.address ||
140                     start + len <= uwq->msg.arg.pagefault.address))
141                 goto out;
142         WRITE_ONCE(uwq->waken, true);
143         /*
144          * The Program-Order guarantees provided by the scheduler
145          * ensure uwq->waken is visible before the task is woken.
146          */
147         ret = wake_up_state(wq->private, mode);
148         if (ret) {
149                 /*
150                  * Wake only once, autoremove behavior.
151                  *
152                  * After the effect of list_del_init is visible to the other
153                  * CPUs, the waitqueue may disappear from under us, see the
154                  * !list_empty_careful() in handle_userfault().
155                  *
156                  * try_to_wake_up() has an implicit smp_mb(), and the
157                  * wq->private is read before calling the extern function
158                  * "wake_up_state" (which in turns calls try_to_wake_up).
159                  */
160                 list_del_init(&wq->entry);
161         }
162 out:
163         return ret;
164 }
165
166 /**
167  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
168  * context.
169  * @ctx: [in] Pointer to the userfaultfd context.
170  */
171 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
172 {
173         refcount_inc(&ctx->refcount);
174 }
175
176 /**
177  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
178  * context.
179  * @ctx: [in] Pointer to userfaultfd context.
180  *
181  * The userfaultfd context reference must have been previously acquired either
182  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
183  */
184 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
185 {
186         if (refcount_dec_and_test(&ctx->refcount)) {
187                 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
188                 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
189                 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
190                 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
191                 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
192                 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
193                 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
194                 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
195                 mmdrop(ctx->mm);
196                 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
197         }
198 }
199
200 static inline void msg_init(struct uffd_msg *msg)
201 {
202         BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
203         /*
204          * Must use memset to zero out the paddings or kernel data is
205          * leaked to userland.
206          */
207         memset(msg, 0, sizeof(struct uffd_msg));
208 }
209
210 static inline struct uffd_msg userfault_msg(unsigned long address,
211                                             unsigned long real_address,
212                                             unsigned int flags,
213                                             unsigned long reason,
214                                             unsigned int features)
215 {
216         struct uffd_msg msg;
217
218         msg_init(&msg);
219         msg.event = UFFD_EVENT_PAGEFAULT;
220
221         msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
222                                     real_address : address;
223
224         /*
225          * These flags indicate why the userfault occurred:
226          * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
227          * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
228          * - Neither of these flags being set indicates a MISSING fault.
229          *
230          * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
231          * fault. Otherwise, it was a read fault.
232          */
233         if (flags & FAULT_FLAG_WRITE)
234                 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
235         if (reason & VM_UFFD_WP)
236                 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
237         if (reason & VM_UFFD_MINOR)
238                 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
239         if (features & UFFD_FEATURE_THREAD_ID)
240                 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
241         return msg;
242 }
243
244 #ifdef CONFIG_HUGETLB_PAGE
245 /*
246  * Same functionality as userfaultfd_must_wait below with modifications for
247  * hugepmd ranges.
248  */
249 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
250                                          struct vm_area_struct *vma,
251                                          unsigned long address,
252                                          unsigned long flags,
253                                          unsigned long reason)
254 {
255         struct mm_struct *mm = ctx->mm;
256         pte_t *ptep, pte;
257         bool ret = true;
258
259         mmap_assert_locked(mm);
260
261         ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
262
263         if (!ptep)
264                 goto out;
265
266         ret = false;
267         pte = huge_ptep_get(ptep);
268
269         /*
270          * Lockless access: we're in a wait_event so it's ok if it
271          * changes under us.  PTE markers should be handled the same as none
272          * ptes here.
273          */
274         if (huge_pte_none_mostly(pte))
275                 ret = true;
276         if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
277                 ret = true;
278 out:
279         return ret;
280 }
281 #else
282 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
283                                          struct vm_area_struct *vma,
284                                          unsigned long address,
285                                          unsigned long flags,
286                                          unsigned long reason)
287 {
288         return false;   /* should never get here */
289 }
290 #endif /* CONFIG_HUGETLB_PAGE */
291
292 /*
293  * Verify the pagetables are still not ok after having reigstered into
294  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
295  * userfault that has already been resolved, if userfaultfd_read and
296  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
297  * threads.
298  */
299 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
300                                          unsigned long address,
301                                          unsigned long flags,
302                                          unsigned long reason)
303 {
304         struct mm_struct *mm = ctx->mm;
305         pgd_t *pgd;
306         p4d_t *p4d;
307         pud_t *pud;
308         pmd_t *pmd, _pmd;
309         pte_t *pte;
310         bool ret = true;
311
312         mmap_assert_locked(mm);
313
314         pgd = pgd_offset(mm, address);
315         if (!pgd_present(*pgd))
316                 goto out;
317         p4d = p4d_offset(pgd, address);
318         if (!p4d_present(*p4d))
319                 goto out;
320         pud = pud_offset(p4d, address);
321         if (!pud_present(*pud))
322                 goto out;
323         pmd = pmd_offset(pud, address);
324         /*
325          * READ_ONCE must function as a barrier with narrower scope
326          * and it must be equivalent to:
327          *      _pmd = *pmd; barrier();
328          *
329          * This is to deal with the instability (as in
330          * pmd_trans_unstable) of the pmd.
331          */
332         _pmd = READ_ONCE(*pmd);
333         if (pmd_none(_pmd))
334                 goto out;
335
336         ret = false;
337         if (!pmd_present(_pmd))
338                 goto out;
339
340         if (pmd_trans_huge(_pmd)) {
341                 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
342                         ret = true;
343                 goto out;
344         }
345
346         /*
347          * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
348          * and use the standard pte_offset_map() instead of parsing _pmd.
349          */
350         pte = pte_offset_map(pmd, address);
351         /*
352          * Lockless access: we're in a wait_event so it's ok if it
353          * changes under us.  PTE markers should be handled the same as none
354          * ptes here.
355          */
356         if (pte_none_mostly(*pte))
357                 ret = true;
358         if (!pte_write(*pte) && (reason & VM_UFFD_WP))
359                 ret = true;
360         pte_unmap(pte);
361
362 out:
363         return ret;
364 }
365
366 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
367 {
368         if (flags & FAULT_FLAG_INTERRUPTIBLE)
369                 return TASK_INTERRUPTIBLE;
370
371         if (flags & FAULT_FLAG_KILLABLE)
372                 return TASK_KILLABLE;
373
374         return TASK_UNINTERRUPTIBLE;
375 }
376
377 /*
378  * The locking rules involved in returning VM_FAULT_RETRY depending on
379  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
380  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
381  * recommendation in __lock_page_or_retry is not an understatement.
382  *
383  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
384  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
385  * not set.
386  *
387  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
388  * set, VM_FAULT_RETRY can still be returned if and only if there are
389  * fatal_signal_pending()s, and the mmap_lock must be released before
390  * returning it.
391  */
392 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
393 {
394         struct mm_struct *mm = vmf->vma->vm_mm;
395         struct userfaultfd_ctx *ctx;
396         struct userfaultfd_wait_queue uwq;
397         vm_fault_t ret = VM_FAULT_SIGBUS;
398         bool must_wait;
399         unsigned int blocking_state;
400
401         /*
402          * We don't do userfault handling for the final child pid update.
403          *
404          * We also don't do userfault handling during
405          * coredumping. hugetlbfs has the special
406          * follow_hugetlb_page() to skip missing pages in the
407          * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
408          * the no_page_table() helper in follow_page_mask(), but the
409          * shmem_vm_ops->fault method is invoked even during
410          * coredumping without mmap_lock and it ends up here.
411          */
412         if (current->flags & (PF_EXITING|PF_DUMPCORE))
413                 goto out;
414
415         /*
416          * Coredumping runs without mmap_lock so we can only check that
417          * the mmap_lock is held, if PF_DUMPCORE was not set.
418          */
419         mmap_assert_locked(mm);
420
421         ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
422         if (!ctx)
423                 goto out;
424
425         BUG_ON(ctx->mm != mm);
426
427         /* Any unrecognized flag is a bug. */
428         VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
429         /* 0 or > 1 flags set is a bug; we expect exactly 1. */
430         VM_BUG_ON(!reason || (reason & (reason - 1)));
431
432         if (ctx->features & UFFD_FEATURE_SIGBUS)
433                 goto out;
434         if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
435                 goto out;
436
437         /*
438          * If it's already released don't get it. This avoids to loop
439          * in __get_user_pages if userfaultfd_release waits on the
440          * caller of handle_userfault to release the mmap_lock.
441          */
442         if (unlikely(READ_ONCE(ctx->released))) {
443                 /*
444                  * Don't return VM_FAULT_SIGBUS in this case, so a non
445                  * cooperative manager can close the uffd after the
446                  * last UFFDIO_COPY, without risking to trigger an
447                  * involuntary SIGBUS if the process was starting the
448                  * userfaultfd while the userfaultfd was still armed
449                  * (but after the last UFFDIO_COPY). If the uffd
450                  * wasn't already closed when the userfault reached
451                  * this point, that would normally be solved by
452                  * userfaultfd_must_wait returning 'false'.
453                  *
454                  * If we were to return VM_FAULT_SIGBUS here, the non
455                  * cooperative manager would be instead forced to
456                  * always call UFFDIO_UNREGISTER before it can safely
457                  * close the uffd.
458                  */
459                 ret = VM_FAULT_NOPAGE;
460                 goto out;
461         }
462
463         /*
464          * Check that we can return VM_FAULT_RETRY.
465          *
466          * NOTE: it should become possible to return VM_FAULT_RETRY
467          * even if FAULT_FLAG_TRIED is set without leading to gup()
468          * -EBUSY failures, if the userfaultfd is to be extended for
469          * VM_UFFD_WP tracking and we intend to arm the userfault
470          * without first stopping userland access to the memory. For
471          * VM_UFFD_MISSING userfaults this is enough for now.
472          */
473         if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
474                 /*
475                  * Validate the invariant that nowait must allow retry
476                  * to be sure not to return SIGBUS erroneously on
477                  * nowait invocations.
478                  */
479                 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
480 #ifdef CONFIG_DEBUG_VM
481                 if (printk_ratelimit()) {
482                         printk(KERN_WARNING
483                                "FAULT_FLAG_ALLOW_RETRY missing %x\n",
484                                vmf->flags);
485                         dump_stack();
486                 }
487 #endif
488                 goto out;
489         }
490
491         /*
492          * Handle nowait, not much to do other than tell it to retry
493          * and wait.
494          */
495         ret = VM_FAULT_RETRY;
496         if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
497                 goto out;
498
499         /* take the reference before dropping the mmap_lock */
500         userfaultfd_ctx_get(ctx);
501
502         init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
503         uwq.wq.private = current;
504         uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
505                                 reason, ctx->features);
506         uwq.ctx = ctx;
507         uwq.waken = false;
508
509         blocking_state = userfaultfd_get_blocking_state(vmf->flags);
510
511         spin_lock_irq(&ctx->fault_pending_wqh.lock);
512         /*
513          * After the __add_wait_queue the uwq is visible to userland
514          * through poll/read().
515          */
516         __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
517         /*
518          * The smp_mb() after __set_current_state prevents the reads
519          * following the spin_unlock to happen before the list_add in
520          * __add_wait_queue.
521          */
522         set_current_state(blocking_state);
523         spin_unlock_irq(&ctx->fault_pending_wqh.lock);
524
525         if (!is_vm_hugetlb_page(vmf->vma))
526                 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
527                                                   reason);
528         else
529                 must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
530                                                        vmf->address,
531                                                        vmf->flags, reason);
532         mmap_read_unlock(mm);
533
534         if (likely(must_wait && !READ_ONCE(ctx->released))) {
535                 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
536                 schedule();
537         }
538
539         __set_current_state(TASK_RUNNING);
540
541         /*
542          * Here we race with the list_del; list_add in
543          * userfaultfd_ctx_read(), however because we don't ever run
544          * list_del_init() to refile across the two lists, the prev
545          * and next pointers will never point to self. list_add also
546          * would never let any of the two pointers to point to
547          * self. So list_empty_careful won't risk to see both pointers
548          * pointing to self at any time during the list refile. The
549          * only case where list_del_init() is called is the full
550          * removal in the wake function and there we don't re-list_add
551          * and it's fine not to block on the spinlock. The uwq on this
552          * kernel stack can be released after the list_del_init.
553          */
554         if (!list_empty_careful(&uwq.wq.entry)) {
555                 spin_lock_irq(&ctx->fault_pending_wqh.lock);
556                 /*
557                  * No need of list_del_init(), the uwq on the stack
558                  * will be freed shortly anyway.
559                  */
560                 list_del(&uwq.wq.entry);
561                 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
562         }
563
564         /*
565          * ctx may go away after this if the userfault pseudo fd is
566          * already released.
567          */
568         userfaultfd_ctx_put(ctx);
569
570 out:
571         return ret;
572 }
573
574 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
575                                               struct userfaultfd_wait_queue *ewq)
576 {
577         struct userfaultfd_ctx *release_new_ctx;
578
579         if (WARN_ON_ONCE(current->flags & PF_EXITING))
580                 goto out;
581
582         ewq->ctx = ctx;
583         init_waitqueue_entry(&ewq->wq, current);
584         release_new_ctx = NULL;
585
586         spin_lock_irq(&ctx->event_wqh.lock);
587         /*
588          * After the __add_wait_queue the uwq is visible to userland
589          * through poll/read().
590          */
591         __add_wait_queue(&ctx->event_wqh, &ewq->wq);
592         for (;;) {
593                 set_current_state(TASK_KILLABLE);
594                 if (ewq->msg.event == 0)
595                         break;
596                 if (READ_ONCE(ctx->released) ||
597                     fatal_signal_pending(current)) {
598                         /*
599                          * &ewq->wq may be queued in fork_event, but
600                          * __remove_wait_queue ignores the head
601                          * parameter. It would be a problem if it
602                          * didn't.
603                          */
604                         __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
605                         if (ewq->msg.event == UFFD_EVENT_FORK) {
606                                 struct userfaultfd_ctx *new;
607
608                                 new = (struct userfaultfd_ctx *)
609                                         (unsigned long)
610                                         ewq->msg.arg.reserved.reserved1;
611                                 release_new_ctx = new;
612                         }
613                         break;
614                 }
615
616                 spin_unlock_irq(&ctx->event_wqh.lock);
617
618                 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
619                 schedule();
620
621                 spin_lock_irq(&ctx->event_wqh.lock);
622         }
623         __set_current_state(TASK_RUNNING);
624         spin_unlock_irq(&ctx->event_wqh.lock);
625
626         if (release_new_ctx) {
627                 struct vm_area_struct *vma;
628                 struct mm_struct *mm = release_new_ctx->mm;
629                 VMA_ITERATOR(vmi, mm, 0);
630
631                 /* the various vma->vm_userfaultfd_ctx still points to it */
632                 mmap_write_lock(mm);
633                 for_each_vma(vmi, vma) {
634                         if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
635                                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
636                                 userfaultfd_set_vm_flags(vma,
637                                                          vma->vm_flags & ~__VM_UFFD_FLAGS);
638                         }
639                 }
640                 mmap_write_unlock(mm);
641
642                 userfaultfd_ctx_put(release_new_ctx);
643         }
644
645         /*
646          * ctx may go away after this if the userfault pseudo fd is
647          * already released.
648          */
649 out:
650         atomic_dec(&ctx->mmap_changing);
651         VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
652         userfaultfd_ctx_put(ctx);
653 }
654
655 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
656                                        struct userfaultfd_wait_queue *ewq)
657 {
658         ewq->msg.event = 0;
659         wake_up_locked(&ctx->event_wqh);
660         __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
661 }
662
663 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
664 {
665         struct userfaultfd_ctx *ctx = NULL, *octx;
666         struct userfaultfd_fork_ctx *fctx;
667
668         octx = vma->vm_userfaultfd_ctx.ctx;
669         if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
670                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
671                 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
672                 return 0;
673         }
674
675         list_for_each_entry(fctx, fcs, list)
676                 if (fctx->orig == octx) {
677                         ctx = fctx->new;
678                         break;
679                 }
680
681         if (!ctx) {
682                 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
683                 if (!fctx)
684                         return -ENOMEM;
685
686                 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
687                 if (!ctx) {
688                         kfree(fctx);
689                         return -ENOMEM;
690                 }
691
692                 refcount_set(&ctx->refcount, 1);
693                 ctx->flags = octx->flags;
694                 ctx->features = octx->features;
695                 ctx->released = false;
696                 atomic_set(&ctx->mmap_changing, 0);
697                 ctx->mm = vma->vm_mm;
698                 mmgrab(ctx->mm);
699
700                 userfaultfd_ctx_get(octx);
701                 atomic_inc(&octx->mmap_changing);
702                 fctx->orig = octx;
703                 fctx->new = ctx;
704                 list_add_tail(&fctx->list, fcs);
705         }
706
707         vma->vm_userfaultfd_ctx.ctx = ctx;
708         return 0;
709 }
710
711 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
712 {
713         struct userfaultfd_ctx *ctx = fctx->orig;
714         struct userfaultfd_wait_queue ewq;
715
716         msg_init(&ewq.msg);
717
718         ewq.msg.event = UFFD_EVENT_FORK;
719         ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
720
721         userfaultfd_event_wait_completion(ctx, &ewq);
722 }
723
724 void dup_userfaultfd_complete(struct list_head *fcs)
725 {
726         struct userfaultfd_fork_ctx *fctx, *n;
727
728         list_for_each_entry_safe(fctx, n, fcs, list) {
729                 dup_fctx(fctx);
730                 list_del(&fctx->list);
731                 kfree(fctx);
732         }
733 }
734
735 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
736                              struct vm_userfaultfd_ctx *vm_ctx)
737 {
738         struct userfaultfd_ctx *ctx;
739
740         ctx = vma->vm_userfaultfd_ctx.ctx;
741
742         if (!ctx)
743                 return;
744
745         if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
746                 vm_ctx->ctx = ctx;
747                 userfaultfd_ctx_get(ctx);
748                 atomic_inc(&ctx->mmap_changing);
749         } else {
750                 /* Drop uffd context if remap feature not enabled */
751                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
752                 userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
753         }
754 }
755
756 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
757                                  unsigned long from, unsigned long to,
758                                  unsigned long len)
759 {
760         struct userfaultfd_ctx *ctx = vm_ctx->ctx;
761         struct userfaultfd_wait_queue ewq;
762
763         if (!ctx)
764                 return;
765
766         if (to & ~PAGE_MASK) {
767                 userfaultfd_ctx_put(ctx);
768                 return;
769         }
770
771         msg_init(&ewq.msg);
772
773         ewq.msg.event = UFFD_EVENT_REMAP;
774         ewq.msg.arg.remap.from = from;
775         ewq.msg.arg.remap.to = to;
776         ewq.msg.arg.remap.len = len;
777
778         userfaultfd_event_wait_completion(ctx, &ewq);
779 }
780
781 bool userfaultfd_remove(struct vm_area_struct *vma,
782                         unsigned long start, unsigned long end)
783 {
784         struct mm_struct *mm = vma->vm_mm;
785         struct userfaultfd_ctx *ctx;
786         struct userfaultfd_wait_queue ewq;
787
788         ctx = vma->vm_userfaultfd_ctx.ctx;
789         if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
790                 return true;
791
792         userfaultfd_ctx_get(ctx);
793         atomic_inc(&ctx->mmap_changing);
794         mmap_read_unlock(mm);
795
796         msg_init(&ewq.msg);
797
798         ewq.msg.event = UFFD_EVENT_REMOVE;
799         ewq.msg.arg.remove.start = start;
800         ewq.msg.arg.remove.end = end;
801
802         userfaultfd_event_wait_completion(ctx, &ewq);
803
804         return false;
805 }
806
807 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
808                           unsigned long start, unsigned long end)
809 {
810         struct userfaultfd_unmap_ctx *unmap_ctx;
811
812         list_for_each_entry(unmap_ctx, unmaps, list)
813                 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
814                     unmap_ctx->end == end)
815                         return true;
816
817         return false;
818 }
819
820 int userfaultfd_unmap_prep(struct mm_struct *mm, unsigned long start,
821                            unsigned long end, struct list_head *unmaps)
822 {
823         VMA_ITERATOR(vmi, mm, start);
824         struct vm_area_struct *vma;
825
826         for_each_vma_range(vmi, vma, end) {
827                 struct userfaultfd_unmap_ctx *unmap_ctx;
828                 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
829
830                 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
831                     has_unmap_ctx(ctx, unmaps, start, end))
832                         continue;
833
834                 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
835                 if (!unmap_ctx)
836                         return -ENOMEM;
837
838                 userfaultfd_ctx_get(ctx);
839                 atomic_inc(&ctx->mmap_changing);
840                 unmap_ctx->ctx = ctx;
841                 unmap_ctx->start = start;
842                 unmap_ctx->end = end;
843                 list_add_tail(&unmap_ctx->list, unmaps);
844         }
845
846         return 0;
847 }
848
849 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
850 {
851         struct userfaultfd_unmap_ctx *ctx, *n;
852         struct userfaultfd_wait_queue ewq;
853
854         list_for_each_entry_safe(ctx, n, uf, list) {
855                 msg_init(&ewq.msg);
856
857                 ewq.msg.event = UFFD_EVENT_UNMAP;
858                 ewq.msg.arg.remove.start = ctx->start;
859                 ewq.msg.arg.remove.end = ctx->end;
860
861                 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
862
863                 list_del(&ctx->list);
864                 kfree(ctx);
865         }
866 }
867
868 static int userfaultfd_release(struct inode *inode, struct file *file)
869 {
870         struct userfaultfd_ctx *ctx = file->private_data;
871         struct mm_struct *mm = ctx->mm;
872         struct vm_area_struct *vma, *prev;
873         /* len == 0 means wake all */
874         struct userfaultfd_wake_range range = { .len = 0, };
875         unsigned long new_flags;
876         MA_STATE(mas, &mm->mm_mt, 0, 0);
877
878         WRITE_ONCE(ctx->released, true);
879
880         if (!mmget_not_zero(mm))
881                 goto wakeup;
882
883         /*
884          * Flush page faults out of all CPUs. NOTE: all page faults
885          * must be retried without returning VM_FAULT_SIGBUS if
886          * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
887          * changes while handle_userfault released the mmap_lock. So
888          * it's critical that released is set to true (above), before
889          * taking the mmap_lock for writing.
890          */
891         mmap_write_lock(mm);
892         prev = NULL;
893         mas_for_each(&mas, vma, ULONG_MAX) {
894                 cond_resched();
895                 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
896                        !!(vma->vm_flags & __VM_UFFD_FLAGS));
897                 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
898                         prev = vma;
899                         continue;
900                 }
901                 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
902                 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
903                                  new_flags, vma->anon_vma,
904                                  vma->vm_file, vma->vm_pgoff,
905                                  vma_policy(vma),
906                                  NULL_VM_UFFD_CTX, anon_vma_name(vma));
907                 if (prev) {
908                         mas_pause(&mas);
909                         vma = prev;
910                 } else {
911                         prev = vma;
912                 }
913
914                 userfaultfd_set_vm_flags(vma, new_flags);
915                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
916         }
917         mmap_write_unlock(mm);
918         mmput(mm);
919 wakeup:
920         /*
921          * After no new page faults can wait on this fault_*wqh, flush
922          * the last page faults that may have been already waiting on
923          * the fault_*wqh.
924          */
925         spin_lock_irq(&ctx->fault_pending_wqh.lock);
926         __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
927         __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
928         spin_unlock_irq(&ctx->fault_pending_wqh.lock);
929
930         /* Flush pending events that may still wait on event_wqh */
931         wake_up_all(&ctx->event_wqh);
932
933         wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
934         userfaultfd_ctx_put(ctx);
935         return 0;
936 }
937
938 /* fault_pending_wqh.lock must be hold by the caller */
939 static inline struct userfaultfd_wait_queue *find_userfault_in(
940                 wait_queue_head_t *wqh)
941 {
942         wait_queue_entry_t *wq;
943         struct userfaultfd_wait_queue *uwq;
944
945         lockdep_assert_held(&wqh->lock);
946
947         uwq = NULL;
948         if (!waitqueue_active(wqh))
949                 goto out;
950         /* walk in reverse to provide FIFO behavior to read userfaults */
951         wq = list_last_entry(&wqh->head, typeof(*wq), entry);
952         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
953 out:
954         return uwq;
955 }
956
957 static inline struct userfaultfd_wait_queue *find_userfault(
958                 struct userfaultfd_ctx *ctx)
959 {
960         return find_userfault_in(&ctx->fault_pending_wqh);
961 }
962
963 static inline struct userfaultfd_wait_queue *find_userfault_evt(
964                 struct userfaultfd_ctx *ctx)
965 {
966         return find_userfault_in(&ctx->event_wqh);
967 }
968
969 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
970 {
971         struct userfaultfd_ctx *ctx = file->private_data;
972         __poll_t ret;
973
974         poll_wait(file, &ctx->fd_wqh, wait);
975
976         if (!userfaultfd_is_initialized(ctx))
977                 return EPOLLERR;
978
979         /*
980          * poll() never guarantees that read won't block.
981          * userfaults can be waken before they're read().
982          */
983         if (unlikely(!(file->f_flags & O_NONBLOCK)))
984                 return EPOLLERR;
985         /*
986          * lockless access to see if there are pending faults
987          * __pollwait last action is the add_wait_queue but
988          * the spin_unlock would allow the waitqueue_active to
989          * pass above the actual list_add inside
990          * add_wait_queue critical section. So use a full
991          * memory barrier to serialize the list_add write of
992          * add_wait_queue() with the waitqueue_active read
993          * below.
994          */
995         ret = 0;
996         smp_mb();
997         if (waitqueue_active(&ctx->fault_pending_wqh))
998                 ret = EPOLLIN;
999         else if (waitqueue_active(&ctx->event_wqh))
1000                 ret = EPOLLIN;
1001
1002         return ret;
1003 }
1004
1005 static const struct file_operations userfaultfd_fops;
1006
1007 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
1008                                   struct inode *inode,
1009                                   struct uffd_msg *msg)
1010 {
1011         int fd;
1012
1013         fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
1014                         O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
1015         if (fd < 0)
1016                 return fd;
1017
1018         msg->arg.reserved.reserved1 = 0;
1019         msg->arg.fork.ufd = fd;
1020         return 0;
1021 }
1022
1023 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1024                                     struct uffd_msg *msg, struct inode *inode)
1025 {
1026         ssize_t ret;
1027         DECLARE_WAITQUEUE(wait, current);
1028         struct userfaultfd_wait_queue *uwq;
1029         /*
1030          * Handling fork event requires sleeping operations, so
1031          * we drop the event_wqh lock, then do these ops, then
1032          * lock it back and wake up the waiter. While the lock is
1033          * dropped the ewq may go away so we keep track of it
1034          * carefully.
1035          */
1036         LIST_HEAD(fork_event);
1037         struct userfaultfd_ctx *fork_nctx = NULL;
1038
1039         /* always take the fd_wqh lock before the fault_pending_wqh lock */
1040         spin_lock_irq(&ctx->fd_wqh.lock);
1041         __add_wait_queue(&ctx->fd_wqh, &wait);
1042         for (;;) {
1043                 set_current_state(TASK_INTERRUPTIBLE);
1044                 spin_lock(&ctx->fault_pending_wqh.lock);
1045                 uwq = find_userfault(ctx);
1046                 if (uwq) {
1047                         /*
1048                          * Use a seqcount to repeat the lockless check
1049                          * in wake_userfault() to avoid missing
1050                          * wakeups because during the refile both
1051                          * waitqueue could become empty if this is the
1052                          * only userfault.
1053                          */
1054                         write_seqcount_begin(&ctx->refile_seq);
1055
1056                         /*
1057                          * The fault_pending_wqh.lock prevents the uwq
1058                          * to disappear from under us.
1059                          *
1060                          * Refile this userfault from
1061                          * fault_pending_wqh to fault_wqh, it's not
1062                          * pending anymore after we read it.
1063                          *
1064                          * Use list_del() by hand (as
1065                          * userfaultfd_wake_function also uses
1066                          * list_del_init() by hand) to be sure nobody
1067                          * changes __remove_wait_queue() to use
1068                          * list_del_init() in turn breaking the
1069                          * !list_empty_careful() check in
1070                          * handle_userfault(). The uwq->wq.head list
1071                          * must never be empty at any time during the
1072                          * refile, or the waitqueue could disappear
1073                          * from under us. The "wait_queue_head_t"
1074                          * parameter of __remove_wait_queue() is unused
1075                          * anyway.
1076                          */
1077                         list_del(&uwq->wq.entry);
1078                         add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1079
1080                         write_seqcount_end(&ctx->refile_seq);
1081
1082                         /* careful to always initialize msg if ret == 0 */
1083                         *msg = uwq->msg;
1084                         spin_unlock(&ctx->fault_pending_wqh.lock);
1085                         ret = 0;
1086                         break;
1087                 }
1088                 spin_unlock(&ctx->fault_pending_wqh.lock);
1089
1090                 spin_lock(&ctx->event_wqh.lock);
1091                 uwq = find_userfault_evt(ctx);
1092                 if (uwq) {
1093                         *msg = uwq->msg;
1094
1095                         if (uwq->msg.event == UFFD_EVENT_FORK) {
1096                                 fork_nctx = (struct userfaultfd_ctx *)
1097                                         (unsigned long)
1098                                         uwq->msg.arg.reserved.reserved1;
1099                                 list_move(&uwq->wq.entry, &fork_event);
1100                                 /*
1101                                  * fork_nctx can be freed as soon as
1102                                  * we drop the lock, unless we take a
1103                                  * reference on it.
1104                                  */
1105                                 userfaultfd_ctx_get(fork_nctx);
1106                                 spin_unlock(&ctx->event_wqh.lock);
1107                                 ret = 0;
1108                                 break;
1109                         }
1110
1111                         userfaultfd_event_complete(ctx, uwq);
1112                         spin_unlock(&ctx->event_wqh.lock);
1113                         ret = 0;
1114                         break;
1115                 }
1116                 spin_unlock(&ctx->event_wqh.lock);
1117
1118                 if (signal_pending(current)) {
1119                         ret = -ERESTARTSYS;
1120                         break;
1121                 }
1122                 if (no_wait) {
1123                         ret = -EAGAIN;
1124                         break;
1125                 }
1126                 spin_unlock_irq(&ctx->fd_wqh.lock);
1127                 schedule();
1128                 spin_lock_irq(&ctx->fd_wqh.lock);
1129         }
1130         __remove_wait_queue(&ctx->fd_wqh, &wait);
1131         __set_current_state(TASK_RUNNING);
1132         spin_unlock_irq(&ctx->fd_wqh.lock);
1133
1134         if (!ret && msg->event == UFFD_EVENT_FORK) {
1135                 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1136                 spin_lock_irq(&ctx->event_wqh.lock);
1137                 if (!list_empty(&fork_event)) {
1138                         /*
1139                          * The fork thread didn't abort, so we can
1140                          * drop the temporary refcount.
1141                          */
1142                         userfaultfd_ctx_put(fork_nctx);
1143
1144                         uwq = list_first_entry(&fork_event,
1145                                                typeof(*uwq),
1146                                                wq.entry);
1147                         /*
1148                          * If fork_event list wasn't empty and in turn
1149                          * the event wasn't already released by fork
1150                          * (the event is allocated on fork kernel
1151                          * stack), put the event back to its place in
1152                          * the event_wq. fork_event head will be freed
1153                          * as soon as we return so the event cannot
1154                          * stay queued there no matter the current
1155                          * "ret" value.
1156                          */
1157                         list_del(&uwq->wq.entry);
1158                         __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1159
1160                         /*
1161                          * Leave the event in the waitqueue and report
1162                          * error to userland if we failed to resolve
1163                          * the userfault fork.
1164                          */
1165                         if (likely(!ret))
1166                                 userfaultfd_event_complete(ctx, uwq);
1167                 } else {
1168                         /*
1169                          * Here the fork thread aborted and the
1170                          * refcount from the fork thread on fork_nctx
1171                          * has already been released. We still hold
1172                          * the reference we took before releasing the
1173                          * lock above. If resolve_userfault_fork
1174                          * failed we've to drop it because the
1175                          * fork_nctx has to be freed in such case. If
1176                          * it succeeded we'll hold it because the new
1177                          * uffd references it.
1178                          */
1179                         if (ret)
1180                                 userfaultfd_ctx_put(fork_nctx);
1181                 }
1182                 spin_unlock_irq(&ctx->event_wqh.lock);
1183         }
1184
1185         return ret;
1186 }
1187
1188 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1189                                 size_t count, loff_t *ppos)
1190 {
1191         struct userfaultfd_ctx *ctx = file->private_data;
1192         ssize_t _ret, ret = 0;
1193         struct uffd_msg msg;
1194         int no_wait = file->f_flags & O_NONBLOCK;
1195         struct inode *inode = file_inode(file);
1196
1197         if (!userfaultfd_is_initialized(ctx))
1198                 return -EINVAL;
1199
1200         for (;;) {
1201                 if (count < sizeof(msg))
1202                         return ret ? ret : -EINVAL;
1203                 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1204                 if (_ret < 0)
1205                         return ret ? ret : _ret;
1206                 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1207                         return ret ? ret : -EFAULT;
1208                 ret += sizeof(msg);
1209                 buf += sizeof(msg);
1210                 count -= sizeof(msg);
1211                 /*
1212                  * Allow to read more than one fault at time but only
1213                  * block if waiting for the very first one.
1214                  */
1215                 no_wait = O_NONBLOCK;
1216         }
1217 }
1218
1219 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1220                              struct userfaultfd_wake_range *range)
1221 {
1222         spin_lock_irq(&ctx->fault_pending_wqh.lock);
1223         /* wake all in the range and autoremove */
1224         if (waitqueue_active(&ctx->fault_pending_wqh))
1225                 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1226                                      range);
1227         if (waitqueue_active(&ctx->fault_wqh))
1228                 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1229         spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1230 }
1231
1232 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1233                                            struct userfaultfd_wake_range *range)
1234 {
1235         unsigned seq;
1236         bool need_wakeup;
1237
1238         /*
1239          * To be sure waitqueue_active() is not reordered by the CPU
1240          * before the pagetable update, use an explicit SMP memory
1241          * barrier here. PT lock release or mmap_read_unlock(mm) still
1242          * have release semantics that can allow the
1243          * waitqueue_active() to be reordered before the pte update.
1244          */
1245         smp_mb();
1246
1247         /*
1248          * Use waitqueue_active because it's very frequent to
1249          * change the address space atomically even if there are no
1250          * userfaults yet. So we take the spinlock only when we're
1251          * sure we've userfaults to wake.
1252          */
1253         do {
1254                 seq = read_seqcount_begin(&ctx->refile_seq);
1255                 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1256                         waitqueue_active(&ctx->fault_wqh);
1257                 cond_resched();
1258         } while (read_seqcount_retry(&ctx->refile_seq, seq));
1259         if (need_wakeup)
1260                 __wake_userfault(ctx, range);
1261 }
1262
1263 static __always_inline int validate_range(struct mm_struct *mm,
1264                                           __u64 start, __u64 len)
1265 {
1266         __u64 task_size = mm->task_size;
1267
1268         if (start & ~PAGE_MASK)
1269                 return -EINVAL;
1270         if (len & ~PAGE_MASK)
1271                 return -EINVAL;
1272         if (!len)
1273                 return -EINVAL;
1274         if (start < mmap_min_addr)
1275                 return -EINVAL;
1276         if (start >= task_size)
1277                 return -EINVAL;
1278         if (len > task_size - start)
1279                 return -EINVAL;
1280         return 0;
1281 }
1282
1283 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1284                                 unsigned long arg)
1285 {
1286         struct mm_struct *mm = ctx->mm;
1287         struct vm_area_struct *vma, *prev, *cur;
1288         int ret;
1289         struct uffdio_register uffdio_register;
1290         struct uffdio_register __user *user_uffdio_register;
1291         unsigned long vm_flags, new_flags;
1292         bool found;
1293         bool basic_ioctls;
1294         unsigned long start, end, vma_end;
1295         MA_STATE(mas, &mm->mm_mt, 0, 0);
1296
1297         user_uffdio_register = (struct uffdio_register __user *) arg;
1298
1299         ret = -EFAULT;
1300         if (copy_from_user(&uffdio_register, user_uffdio_register,
1301                            sizeof(uffdio_register)-sizeof(__u64)))
1302                 goto out;
1303
1304         ret = -EINVAL;
1305         if (!uffdio_register.mode)
1306                 goto out;
1307         if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1308                 goto out;
1309         vm_flags = 0;
1310         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1311                 vm_flags |= VM_UFFD_MISSING;
1312         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1313 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1314                 goto out;
1315 #endif
1316                 vm_flags |= VM_UFFD_WP;
1317         }
1318         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1319 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1320                 goto out;
1321 #endif
1322                 vm_flags |= VM_UFFD_MINOR;
1323         }
1324
1325         ret = validate_range(mm, uffdio_register.range.start,
1326                              uffdio_register.range.len);
1327         if (ret)
1328                 goto out;
1329
1330         start = uffdio_register.range.start;
1331         end = start + uffdio_register.range.len;
1332
1333         ret = -ENOMEM;
1334         if (!mmget_not_zero(mm))
1335                 goto out;
1336
1337         mmap_write_lock(mm);
1338         mas_set(&mas, start);
1339         vma = mas_find(&mas, ULONG_MAX);
1340         if (!vma)
1341                 goto out_unlock;
1342
1343         /* check that there's at least one vma in the range */
1344         ret = -EINVAL;
1345         if (vma->vm_start >= end)
1346                 goto out_unlock;
1347
1348         /*
1349          * If the first vma contains huge pages, make sure start address
1350          * is aligned to huge page size.
1351          */
1352         if (is_vm_hugetlb_page(vma)) {
1353                 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1354
1355                 if (start & (vma_hpagesize - 1))
1356                         goto out_unlock;
1357         }
1358
1359         /*
1360          * Search for not compatible vmas.
1361          */
1362         found = false;
1363         basic_ioctls = false;
1364         for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
1365                 cond_resched();
1366
1367                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1368                        !!(cur->vm_flags & __VM_UFFD_FLAGS));
1369
1370                 /* check not compatible vmas */
1371                 ret = -EINVAL;
1372                 if (!vma_can_userfault(cur, vm_flags))
1373                         goto out_unlock;
1374
1375                 /*
1376                  * UFFDIO_COPY will fill file holes even without
1377                  * PROT_WRITE. This check enforces that if this is a
1378                  * MAP_SHARED, the process has write permission to the backing
1379                  * file. If VM_MAYWRITE is set it also enforces that on a
1380                  * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1381                  * F_WRITE_SEAL can be taken until the vma is destroyed.
1382                  */
1383                 ret = -EPERM;
1384                 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1385                         goto out_unlock;
1386
1387                 /*
1388                  * If this vma contains ending address, and huge pages
1389                  * check alignment.
1390                  */
1391                 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1392                     end > cur->vm_start) {
1393                         unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1394
1395                         ret = -EINVAL;
1396
1397                         if (end & (vma_hpagesize - 1))
1398                                 goto out_unlock;
1399                 }
1400                 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1401                         goto out_unlock;
1402
1403                 /*
1404                  * Check that this vma isn't already owned by a
1405                  * different userfaultfd. We can't allow more than one
1406                  * userfaultfd to own a single vma simultaneously or we
1407                  * wouldn't know which one to deliver the userfaults to.
1408                  */
1409                 ret = -EBUSY;
1410                 if (cur->vm_userfaultfd_ctx.ctx &&
1411                     cur->vm_userfaultfd_ctx.ctx != ctx)
1412                         goto out_unlock;
1413
1414                 /*
1415                  * Note vmas containing huge pages
1416                  */
1417                 if (is_vm_hugetlb_page(cur))
1418                         basic_ioctls = true;
1419
1420                 found = true;
1421         }
1422         BUG_ON(!found);
1423
1424         mas_set(&mas, start);
1425         prev = mas_prev(&mas, 0);
1426         if (prev != vma)
1427                 mas_next(&mas, ULONG_MAX);
1428
1429         ret = 0;
1430         do {
1431                 cond_resched();
1432
1433                 BUG_ON(!vma_can_userfault(vma, vm_flags));
1434                 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1435                        vma->vm_userfaultfd_ctx.ctx != ctx);
1436                 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1437
1438                 /*
1439                  * Nothing to do: this vma is already registered into this
1440                  * userfaultfd and with the right tracking mode too.
1441                  */
1442                 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1443                     (vma->vm_flags & vm_flags) == vm_flags)
1444                         goto skip;
1445
1446                 if (vma->vm_start > start)
1447                         start = vma->vm_start;
1448                 vma_end = min(end, vma->vm_end);
1449
1450                 new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
1451                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1452                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1453                                  vma_policy(vma),
1454                                  ((struct vm_userfaultfd_ctx){ ctx }),
1455                                  anon_vma_name(vma));
1456                 if (prev) {
1457                         /* vma_merge() invalidated the mas */
1458                         mas_pause(&mas);
1459                         vma = prev;
1460                         goto next;
1461                 }
1462                 if (vma->vm_start < start) {
1463                         ret = split_vma(mm, vma, start, 1);
1464                         if (ret)
1465                                 break;
1466                         /* split_vma() invalidated the mas */
1467                         mas_pause(&mas);
1468                 }
1469                 if (vma->vm_end > end) {
1470                         ret = split_vma(mm, vma, end, 0);
1471                         if (ret)
1472                                 break;
1473                         /* split_vma() invalidated the mas */
1474                         mas_pause(&mas);
1475                 }
1476         next:
1477                 /*
1478                  * In the vma_merge() successful mprotect-like case 8:
1479                  * the next vma was merged into the current one and
1480                  * the current one has not been updated yet.
1481                  */
1482                 userfaultfd_set_vm_flags(vma, new_flags);
1483                 vma->vm_userfaultfd_ctx.ctx = ctx;
1484
1485                 if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
1486                         hugetlb_unshare_all_pmds(vma);
1487
1488         skip:
1489                 prev = vma;
1490                 start = vma->vm_end;
1491                 vma = mas_next(&mas, end - 1);
1492         } while (vma);
1493 out_unlock:
1494         mmap_write_unlock(mm);
1495         mmput(mm);
1496         if (!ret) {
1497                 __u64 ioctls_out;
1498
1499                 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1500                     UFFD_API_RANGE_IOCTLS;
1501
1502                 /*
1503                  * Declare the WP ioctl only if the WP mode is
1504                  * specified and all checks passed with the range
1505                  */
1506                 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1507                         ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1508
1509                 /* CONTINUE ioctl is only supported for MINOR ranges. */
1510                 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1511                         ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1512
1513                 /*
1514                  * Now that we scanned all vmas we can already tell
1515                  * userland which ioctls methods are guaranteed to
1516                  * succeed on this range.
1517                  */
1518                 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1519                         ret = -EFAULT;
1520         }
1521 out:
1522         return ret;
1523 }
1524
1525 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1526                                   unsigned long arg)
1527 {
1528         struct mm_struct *mm = ctx->mm;
1529         struct vm_area_struct *vma, *prev, *cur;
1530         int ret;
1531         struct uffdio_range uffdio_unregister;
1532         unsigned long new_flags;
1533         bool found;
1534         unsigned long start, end, vma_end;
1535         const void __user *buf = (void __user *)arg;
1536         MA_STATE(mas, &mm->mm_mt, 0, 0);
1537
1538         ret = -EFAULT;
1539         if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1540                 goto out;
1541
1542         ret = validate_range(mm, uffdio_unregister.start,
1543                              uffdio_unregister.len);
1544         if (ret)
1545                 goto out;
1546
1547         start = uffdio_unregister.start;
1548         end = start + uffdio_unregister.len;
1549
1550         ret = -ENOMEM;
1551         if (!mmget_not_zero(mm))
1552                 goto out;
1553
1554         mmap_write_lock(mm);
1555         mas_set(&mas, start);
1556         vma = mas_find(&mas, ULONG_MAX);
1557         if (!vma)
1558                 goto out_unlock;
1559
1560         /* check that there's at least one vma in the range */
1561         ret = -EINVAL;
1562         if (vma->vm_start >= end)
1563                 goto out_unlock;
1564
1565         /*
1566          * If the first vma contains huge pages, make sure start address
1567          * is aligned to huge page size.
1568          */
1569         if (is_vm_hugetlb_page(vma)) {
1570                 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1571
1572                 if (start & (vma_hpagesize - 1))
1573                         goto out_unlock;
1574         }
1575
1576         /*
1577          * Search for not compatible vmas.
1578          */
1579         found = false;
1580         ret = -EINVAL;
1581         for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
1582                 cond_resched();
1583
1584                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1585                        !!(cur->vm_flags & __VM_UFFD_FLAGS));
1586
1587                 /*
1588                  * Check not compatible vmas, not strictly required
1589                  * here as not compatible vmas cannot have an
1590                  * userfaultfd_ctx registered on them, but this
1591                  * provides for more strict behavior to notice
1592                  * unregistration errors.
1593                  */
1594                 if (!vma_can_userfault(cur, cur->vm_flags))
1595                         goto out_unlock;
1596
1597                 found = true;
1598         }
1599         BUG_ON(!found);
1600
1601         mas_set(&mas, start);
1602         prev = mas_prev(&mas, 0);
1603         if (prev != vma)
1604                 mas_next(&mas, ULONG_MAX);
1605
1606         ret = 0;
1607         do {
1608                 cond_resched();
1609
1610                 BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
1611
1612                 /*
1613                  * Nothing to do: this vma is already registered into this
1614                  * userfaultfd and with the right tracking mode too.
1615                  */
1616                 if (!vma->vm_userfaultfd_ctx.ctx)
1617                         goto skip;
1618
1619                 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1620
1621                 if (vma->vm_start > start)
1622                         start = vma->vm_start;
1623                 vma_end = min(end, vma->vm_end);
1624
1625                 if (userfaultfd_missing(vma)) {
1626                         /*
1627                          * Wake any concurrent pending userfault while
1628                          * we unregister, so they will not hang
1629                          * permanently and it avoids userland to call
1630                          * UFFDIO_WAKE explicitly.
1631                          */
1632                         struct userfaultfd_wake_range range;
1633                         range.start = start;
1634                         range.len = vma_end - start;
1635                         wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1636                 }
1637
1638                 /* Reset ptes for the whole vma range if wr-protected */
1639                 if (userfaultfd_wp(vma))
1640                         uffd_wp_range(mm, vma, start, vma_end - start, false);
1641
1642                 new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
1643                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1644                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1645                                  vma_policy(vma),
1646                                  NULL_VM_UFFD_CTX, anon_vma_name(vma));
1647                 if (prev) {
1648                         vma = prev;
1649                         mas_pause(&mas);
1650                         goto next;
1651                 }
1652                 if (vma->vm_start < start) {
1653                         ret = split_vma(mm, vma, start, 1);
1654                         if (ret)
1655                                 break;
1656                         mas_pause(&mas);
1657                 }
1658                 if (vma->vm_end > end) {
1659                         ret = split_vma(mm, vma, end, 0);
1660                         if (ret)
1661                                 break;
1662                         mas_pause(&mas);
1663                 }
1664         next:
1665                 /*
1666                  * In the vma_merge() successful mprotect-like case 8:
1667                  * the next vma was merged into the current one and
1668                  * the current one has not been updated yet.
1669                  */
1670                 userfaultfd_set_vm_flags(vma, new_flags);
1671                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1672
1673         skip:
1674                 prev = vma;
1675                 start = vma->vm_end;
1676                 vma = mas_next(&mas, end - 1);
1677         } while (vma);
1678 out_unlock:
1679         mmap_write_unlock(mm);
1680         mmput(mm);
1681 out:
1682         return ret;
1683 }
1684
1685 /*
1686  * userfaultfd_wake may be used in combination with the
1687  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1688  */
1689 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1690                             unsigned long arg)
1691 {
1692         int ret;
1693         struct uffdio_range uffdio_wake;
1694         struct userfaultfd_wake_range range;
1695         const void __user *buf = (void __user *)arg;
1696
1697         ret = -EFAULT;
1698         if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1699                 goto out;
1700
1701         ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1702         if (ret)
1703                 goto out;
1704
1705         range.start = uffdio_wake.start;
1706         range.len = uffdio_wake.len;
1707
1708         /*
1709          * len == 0 means wake all and we don't want to wake all here,
1710          * so check it again to be sure.
1711          */
1712         VM_BUG_ON(!range.len);
1713
1714         wake_userfault(ctx, &range);
1715         ret = 0;
1716
1717 out:
1718         return ret;
1719 }
1720
1721 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1722                             unsigned long arg)
1723 {
1724         __s64 ret;
1725         struct uffdio_copy uffdio_copy;
1726         struct uffdio_copy __user *user_uffdio_copy;
1727         struct userfaultfd_wake_range range;
1728
1729         user_uffdio_copy = (struct uffdio_copy __user *) arg;
1730
1731         ret = -EAGAIN;
1732         if (atomic_read(&ctx->mmap_changing))
1733                 goto out;
1734
1735         ret = -EFAULT;
1736         if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1737                            /* don't copy "copy" last field */
1738                            sizeof(uffdio_copy)-sizeof(__s64)))
1739                 goto out;
1740
1741         ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1742         if (ret)
1743                 goto out;
1744         /*
1745          * double check for wraparound just in case. copy_from_user()
1746          * will later check uffdio_copy.src + uffdio_copy.len to fit
1747          * in the userland range.
1748          */
1749         ret = -EINVAL;
1750         if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1751                 goto out;
1752         if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1753                 goto out;
1754         if (mmget_not_zero(ctx->mm)) {
1755                 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1756                                    uffdio_copy.len, &ctx->mmap_changing,
1757                                    uffdio_copy.mode);
1758                 mmput(ctx->mm);
1759         } else {
1760                 return -ESRCH;
1761         }
1762         if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1763                 return -EFAULT;
1764         if (ret < 0)
1765                 goto out;
1766         BUG_ON(!ret);
1767         /* len == 0 would wake all */
1768         range.len = ret;
1769         if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1770                 range.start = uffdio_copy.dst;
1771                 wake_userfault(ctx, &range);
1772         }
1773         ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1774 out:
1775         return ret;
1776 }
1777
1778 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1779                                 unsigned long arg)
1780 {
1781         __s64 ret;
1782         struct uffdio_zeropage uffdio_zeropage;
1783         struct uffdio_zeropage __user *user_uffdio_zeropage;
1784         struct userfaultfd_wake_range range;
1785
1786         user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1787
1788         ret = -EAGAIN;
1789         if (atomic_read(&ctx->mmap_changing))
1790                 goto out;
1791
1792         ret = -EFAULT;
1793         if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1794                            /* don't copy "zeropage" last field */
1795                            sizeof(uffdio_zeropage)-sizeof(__s64)))
1796                 goto out;
1797
1798         ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1799                              uffdio_zeropage.range.len);
1800         if (ret)
1801                 goto out;
1802         ret = -EINVAL;
1803         if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1804                 goto out;
1805
1806         if (mmget_not_zero(ctx->mm)) {
1807                 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1808                                      uffdio_zeropage.range.len,
1809                                      &ctx->mmap_changing);
1810                 mmput(ctx->mm);
1811         } else {
1812                 return -ESRCH;
1813         }
1814         if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1815                 return -EFAULT;
1816         if (ret < 0)
1817                 goto out;
1818         /* len == 0 would wake all */
1819         BUG_ON(!ret);
1820         range.len = ret;
1821         if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1822                 range.start = uffdio_zeropage.range.start;
1823                 wake_userfault(ctx, &range);
1824         }
1825         ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1826 out:
1827         return ret;
1828 }
1829
1830 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1831                                     unsigned long arg)
1832 {
1833         int ret;
1834         struct uffdio_writeprotect uffdio_wp;
1835         struct uffdio_writeprotect __user *user_uffdio_wp;
1836         struct userfaultfd_wake_range range;
1837         bool mode_wp, mode_dontwake;
1838
1839         if (atomic_read(&ctx->mmap_changing))
1840                 return -EAGAIN;
1841
1842         user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1843
1844         if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1845                            sizeof(struct uffdio_writeprotect)))
1846                 return -EFAULT;
1847
1848         ret = validate_range(ctx->mm, uffdio_wp.range.start,
1849                              uffdio_wp.range.len);
1850         if (ret)
1851                 return ret;
1852
1853         if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1854                                UFFDIO_WRITEPROTECT_MODE_WP))
1855                 return -EINVAL;
1856
1857         mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1858         mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1859
1860         if (mode_wp && mode_dontwake)
1861                 return -EINVAL;
1862
1863         if (mmget_not_zero(ctx->mm)) {
1864                 ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
1865                                           uffdio_wp.range.len, mode_wp,
1866                                           &ctx->mmap_changing);
1867                 mmput(ctx->mm);
1868         } else {
1869                 return -ESRCH;
1870         }
1871
1872         if (ret)
1873                 return ret;
1874
1875         if (!mode_wp && !mode_dontwake) {
1876                 range.start = uffdio_wp.range.start;
1877                 range.len = uffdio_wp.range.len;
1878                 wake_userfault(ctx, &range);
1879         }
1880         return ret;
1881 }
1882
1883 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1884 {
1885         __s64 ret;
1886         struct uffdio_continue uffdio_continue;
1887         struct uffdio_continue __user *user_uffdio_continue;
1888         struct userfaultfd_wake_range range;
1889
1890         user_uffdio_continue = (struct uffdio_continue __user *)arg;
1891
1892         ret = -EAGAIN;
1893         if (atomic_read(&ctx->mmap_changing))
1894                 goto out;
1895
1896         ret = -EFAULT;
1897         if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1898                            /* don't copy the output fields */
1899                            sizeof(uffdio_continue) - (sizeof(__s64))))
1900                 goto out;
1901
1902         ret = validate_range(ctx->mm, uffdio_continue.range.start,
1903                              uffdio_continue.range.len);
1904         if (ret)
1905                 goto out;
1906
1907         ret = -EINVAL;
1908         /* double check for wraparound just in case. */
1909         if (uffdio_continue.range.start + uffdio_continue.range.len <=
1910             uffdio_continue.range.start) {
1911                 goto out;
1912         }
1913         if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1914                 goto out;
1915
1916         if (mmget_not_zero(ctx->mm)) {
1917                 ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1918                                      uffdio_continue.range.len,
1919                                      &ctx->mmap_changing);
1920                 mmput(ctx->mm);
1921         } else {
1922                 return -ESRCH;
1923         }
1924
1925         if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1926                 return -EFAULT;
1927         if (ret < 0)
1928                 goto out;
1929
1930         /* len == 0 would wake all */
1931         BUG_ON(!ret);
1932         range.len = ret;
1933         if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1934                 range.start = uffdio_continue.range.start;
1935                 wake_userfault(ctx, &range);
1936         }
1937         ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1938
1939 out:
1940         return ret;
1941 }
1942
1943 static inline unsigned int uffd_ctx_features(__u64 user_features)
1944 {
1945         /*
1946          * For the current set of features the bits just coincide. Set
1947          * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1948          */
1949         return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1950 }
1951
1952 /*
1953  * userland asks for a certain API version and we return which bits
1954  * and ioctl commands are implemented in this kernel for such API
1955  * version or -EINVAL if unknown.
1956  */
1957 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1958                            unsigned long arg)
1959 {
1960         struct uffdio_api uffdio_api;
1961         void __user *buf = (void __user *)arg;
1962         unsigned int ctx_features;
1963         int ret;
1964         __u64 features;
1965
1966         ret = -EFAULT;
1967         if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1968                 goto out;
1969         /* Ignore unsupported features (userspace built against newer kernel) */
1970         features = uffdio_api.features & UFFD_API_FEATURES;
1971         ret = -EPERM;
1972         if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1973                 goto err_out;
1974         /* report all available features and ioctls to userland */
1975         uffdio_api.features = UFFD_API_FEATURES;
1976 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1977         uffdio_api.features &=
1978                 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1979 #endif
1980 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1981         uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1982 #endif
1983 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1984         uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1985 #endif
1986         uffdio_api.ioctls = UFFD_API_IOCTLS;
1987         ret = -EFAULT;
1988         if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1989                 goto out;
1990
1991         /* only enable the requested features for this uffd context */
1992         ctx_features = uffd_ctx_features(features);
1993         ret = -EINVAL;
1994         if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1995                 goto err_out;
1996
1997         ret = 0;
1998 out:
1999         return ret;
2000 err_out:
2001         memset(&uffdio_api, 0, sizeof(uffdio_api));
2002         if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2003                 ret = -EFAULT;
2004         goto out;
2005 }
2006
2007 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2008                               unsigned long arg)
2009 {
2010         int ret = -EINVAL;
2011         struct userfaultfd_ctx *ctx = file->private_data;
2012
2013         if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2014                 return -EINVAL;
2015
2016         switch(cmd) {
2017         case UFFDIO_API:
2018                 ret = userfaultfd_api(ctx, arg);
2019                 break;
2020         case UFFDIO_REGISTER:
2021                 ret = userfaultfd_register(ctx, arg);
2022                 break;
2023         case UFFDIO_UNREGISTER:
2024                 ret = userfaultfd_unregister(ctx, arg);
2025                 break;
2026         case UFFDIO_WAKE:
2027                 ret = userfaultfd_wake(ctx, arg);
2028                 break;
2029         case UFFDIO_COPY:
2030                 ret = userfaultfd_copy(ctx, arg);
2031                 break;
2032         case UFFDIO_ZEROPAGE:
2033                 ret = userfaultfd_zeropage(ctx, arg);
2034                 break;
2035         case UFFDIO_WRITEPROTECT:
2036                 ret = userfaultfd_writeprotect(ctx, arg);
2037                 break;
2038         case UFFDIO_CONTINUE:
2039                 ret = userfaultfd_continue(ctx, arg);
2040                 break;
2041         }
2042         return ret;
2043 }
2044
2045 #ifdef CONFIG_PROC_FS
2046 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2047 {
2048         struct userfaultfd_ctx *ctx = f->private_data;
2049         wait_queue_entry_t *wq;
2050         unsigned long pending = 0, total = 0;
2051
2052         spin_lock_irq(&ctx->fault_pending_wqh.lock);
2053         list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2054                 pending++;
2055                 total++;
2056         }
2057         list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2058                 total++;
2059         }
2060         spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2061
2062         /*
2063          * If more protocols will be added, there will be all shown
2064          * separated by a space. Like this:
2065          *      protocols: aa:... bb:...
2066          */
2067         seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2068                    pending, total, UFFD_API, ctx->features,
2069                    UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2070 }
2071 #endif
2072
2073 static const struct file_operations userfaultfd_fops = {
2074 #ifdef CONFIG_PROC_FS
2075         .show_fdinfo    = userfaultfd_show_fdinfo,
2076 #endif
2077         .release        = userfaultfd_release,
2078         .poll           = userfaultfd_poll,
2079         .read           = userfaultfd_read,
2080         .unlocked_ioctl = userfaultfd_ioctl,
2081         .compat_ioctl   = compat_ptr_ioctl,
2082         .llseek         = noop_llseek,
2083 };
2084
2085 static void init_once_userfaultfd_ctx(void *mem)
2086 {
2087         struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2088
2089         init_waitqueue_head(&ctx->fault_pending_wqh);
2090         init_waitqueue_head(&ctx->fault_wqh);
2091         init_waitqueue_head(&ctx->event_wqh);
2092         init_waitqueue_head(&ctx->fd_wqh);
2093         seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2094 }
2095
2096 static int new_userfaultfd(int flags)
2097 {
2098         struct userfaultfd_ctx *ctx;
2099         int fd;
2100
2101         BUG_ON(!current->mm);
2102
2103         /* Check the UFFD_* constants for consistency.  */
2104         BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2105         BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2106         BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2107
2108         if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2109                 return -EINVAL;
2110
2111         ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2112         if (!ctx)
2113                 return -ENOMEM;
2114
2115         refcount_set(&ctx->refcount, 1);
2116         ctx->flags = flags;
2117         ctx->features = 0;
2118         ctx->released = false;
2119         atomic_set(&ctx->mmap_changing, 0);
2120         ctx->mm = current->mm;
2121         /* prevent the mm struct to be freed */
2122         mmgrab(ctx->mm);
2123
2124         fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2125                         O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2126         if (fd < 0) {
2127                 mmdrop(ctx->mm);
2128                 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2129         }
2130         return fd;
2131 }
2132
2133 static inline bool userfaultfd_syscall_allowed(int flags)
2134 {
2135         /* Userspace-only page faults are always allowed */
2136         if (flags & UFFD_USER_MODE_ONLY)
2137                 return true;
2138
2139         /*
2140          * The user is requesting a userfaultfd which can handle kernel faults.
2141          * Privileged users are always allowed to do this.
2142          */
2143         if (capable(CAP_SYS_PTRACE))
2144                 return true;
2145
2146         /* Otherwise, access to kernel fault handling is sysctl controlled. */
2147         return sysctl_unprivileged_userfaultfd;
2148 }
2149
2150 SYSCALL_DEFINE1(userfaultfd, int, flags)
2151 {
2152         if (!userfaultfd_syscall_allowed(flags))
2153                 return -EPERM;
2154
2155         return new_userfaultfd(flags);
2156 }
2157
2158 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2159 {
2160         if (cmd != USERFAULTFD_IOC_NEW)
2161                 return -EINVAL;
2162
2163         return new_userfaultfd(flags);
2164 }
2165
2166 static const struct file_operations userfaultfd_dev_fops = {
2167         .unlocked_ioctl = userfaultfd_dev_ioctl,
2168         .compat_ioctl = userfaultfd_dev_ioctl,
2169         .owner = THIS_MODULE,
2170         .llseek = noop_llseek,
2171 };
2172
2173 static struct miscdevice userfaultfd_misc = {
2174         .minor = MISC_DYNAMIC_MINOR,
2175         .name = "userfaultfd",
2176         .fops = &userfaultfd_dev_fops
2177 };
2178
2179 static int __init userfaultfd_init(void)
2180 {
2181         int ret;
2182
2183         ret = misc_register(&userfaultfd_misc);
2184         if (ret)
2185                 return ret;
2186
2187         userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2188                                                 sizeof(struct userfaultfd_ctx),
2189                                                 0,
2190                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2191                                                 init_once_userfaultfd_ctx);
2192         return 0;
2193 }
2194 __initcall(userfaultfd_init);