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