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