OSDN Git Service

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