OSDN Git Service

proc: Don't let Google Camera and Settings run in the background
[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         bool still_valid;
435
436         ACCESS_ONCE(ctx->released) = true;
437
438         if (!mmget_not_zero(mm))
439                 goto wakeup;
440
441         /*
442          * Flush page faults out of all CPUs. NOTE: all page faults
443          * must be retried without returning VM_FAULT_SIGBUS if
444          * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
445          * changes while handle_userfault released the mmap_sem. So
446          * it's critical that released is set to true (above), before
447          * taking the mmap_sem for writing.
448          */
449         down_write(&mm->mmap_sem);
450         still_valid = mmget_still_valid(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                 if (still_valid) {
462                         prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
463                                          new_flags, vma->anon_vma,
464                                          vma->vm_file, vma->vm_pgoff,
465                                          vma_policy(vma),
466                                          NULL_VM_UFFD_CTX,
467                                          vma_get_anon_name(vma));
468                         if (prev)
469                                 vma = prev;
470                         else
471                                 prev = vma;
472                 }
473                 vma->vm_flags = new_flags;
474                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
475         }
476         up_write(&mm->mmap_sem);
477         mmput(mm);
478 wakeup:
479         /*
480          * After no new page faults can wait on this fault_*wqh, flush
481          * the last page faults that may have been already waiting on
482          * the fault_*wqh.
483          */
484         spin_lock(&ctx->fault_pending_wqh.lock);
485         __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
486         __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
487         spin_unlock(&ctx->fault_pending_wqh.lock);
488
489         wake_up_poll(&ctx->fd_wqh, POLLHUP);
490         userfaultfd_ctx_put(ctx);
491         return 0;
492 }
493
494 /* fault_pending_wqh.lock must be hold by the caller */
495 static inline struct userfaultfd_wait_queue *find_userfault(
496         struct userfaultfd_ctx *ctx)
497 {
498         wait_queue_t *wq;
499         struct userfaultfd_wait_queue *uwq;
500
501         VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
502
503         uwq = NULL;
504         if (!waitqueue_active(&ctx->fault_pending_wqh))
505                 goto out;
506         /* walk in reverse to provide FIFO behavior to read userfaults */
507         wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
508                              typeof(*wq), task_list);
509         uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
510 out:
511         return uwq;
512 }
513
514 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
515 {
516         struct userfaultfd_ctx *ctx = file->private_data;
517         unsigned int ret;
518
519         poll_wait(file, &ctx->fd_wqh, wait);
520
521         switch (ctx->state) {
522         case UFFD_STATE_WAIT_API:
523                 return POLLERR;
524         case UFFD_STATE_RUNNING:
525                 /*
526                  * poll() never guarantees that read won't block.
527                  * userfaults can be waken before they're read().
528                  */
529                 if (unlikely(!(file->f_flags & O_NONBLOCK)))
530                         return POLLERR;
531                 /*
532                  * lockless access to see if there are pending faults
533                  * __pollwait last action is the add_wait_queue but
534                  * the spin_unlock would allow the waitqueue_active to
535                  * pass above the actual list_add inside
536                  * add_wait_queue critical section. So use a full
537                  * memory barrier to serialize the list_add write of
538                  * add_wait_queue() with the waitqueue_active read
539                  * below.
540                  */
541                 ret = 0;
542                 smp_mb();
543                 if (waitqueue_active(&ctx->fault_pending_wqh))
544                         ret = POLLIN;
545                 return ret;
546         default:
547                 BUG();
548         }
549 }
550
551 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
552                                     struct uffd_msg *msg)
553 {
554         ssize_t ret;
555         DECLARE_WAITQUEUE(wait, current);
556         struct userfaultfd_wait_queue *uwq;
557
558         /* always take the fd_wqh lock before the fault_pending_wqh lock */
559         spin_lock(&ctx->fd_wqh.lock);
560         __add_wait_queue(&ctx->fd_wqh, &wait);
561         for (;;) {
562                 set_current_state(TASK_INTERRUPTIBLE);
563                 spin_lock(&ctx->fault_pending_wqh.lock);
564                 uwq = find_userfault(ctx);
565                 if (uwq) {
566                         /*
567                          * Use a seqcount to repeat the lockless check
568                          * in wake_userfault() to avoid missing
569                          * wakeups because during the refile both
570                          * waitqueue could become empty if this is the
571                          * only userfault.
572                          */
573                         write_seqcount_begin(&ctx->refile_seq);
574
575                         /*
576                          * The fault_pending_wqh.lock prevents the uwq
577                          * to disappear from under us.
578                          *
579                          * Refile this userfault from
580                          * fault_pending_wqh to fault_wqh, it's not
581                          * pending anymore after we read it.
582                          *
583                          * Use list_del() by hand (as
584                          * userfaultfd_wake_function also uses
585                          * list_del_init() by hand) to be sure nobody
586                          * changes __remove_wait_queue() to use
587                          * list_del_init() in turn breaking the
588                          * !list_empty_careful() check in
589                          * handle_userfault(). The uwq->wq.task_list
590                          * must never be empty at any time during the
591                          * refile, or the waitqueue could disappear
592                          * from under us. The "wait_queue_head_t"
593                          * parameter of __remove_wait_queue() is unused
594                          * anyway.
595                          */
596                         list_del(&uwq->wq.task_list);
597                         __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
598
599                         write_seqcount_end(&ctx->refile_seq);
600
601                         /* careful to always initialize msg if ret == 0 */
602                         *msg = uwq->msg;
603                         spin_unlock(&ctx->fault_pending_wqh.lock);
604                         ret = 0;
605                         break;
606                 }
607                 spin_unlock(&ctx->fault_pending_wqh.lock);
608                 if (signal_pending(current)) {
609                         ret = -ERESTARTSYS;
610                         break;
611                 }
612                 if (no_wait) {
613                         ret = -EAGAIN;
614                         break;
615                 }
616                 spin_unlock(&ctx->fd_wqh.lock);
617                 schedule();
618                 spin_lock(&ctx->fd_wqh.lock);
619         }
620         __remove_wait_queue(&ctx->fd_wqh, &wait);
621         __set_current_state(TASK_RUNNING);
622         spin_unlock(&ctx->fd_wqh.lock);
623
624         return ret;
625 }
626
627 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
628                                 size_t count, loff_t *ppos)
629 {
630         struct userfaultfd_ctx *ctx = file->private_data;
631         ssize_t _ret, ret = 0;
632         struct uffd_msg msg;
633         int no_wait = file->f_flags & O_NONBLOCK;
634
635         if (ctx->state == UFFD_STATE_WAIT_API)
636                 return -EINVAL;
637
638         for (;;) {
639                 if (count < sizeof(msg))
640                         return ret ? ret : -EINVAL;
641                 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
642                 if (_ret < 0)
643                         return ret ? ret : _ret;
644                 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
645                         return ret ? ret : -EFAULT;
646                 ret += sizeof(msg);
647                 buf += sizeof(msg);
648                 count -= sizeof(msg);
649                 /*
650                  * Allow to read more than one fault at time but only
651                  * block if waiting for the very first one.
652                  */
653                 no_wait = O_NONBLOCK;
654         }
655 }
656
657 static void __wake_userfault(struct userfaultfd_ctx *ctx,
658                              struct userfaultfd_wake_range *range)
659 {
660         unsigned long start, end;
661
662         start = range->start;
663         end = range->start + range->len;
664
665         spin_lock(&ctx->fault_pending_wqh.lock);
666         /* wake all in the range and autoremove */
667         if (waitqueue_active(&ctx->fault_pending_wqh))
668                 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
669                                      range);
670         if (waitqueue_active(&ctx->fault_wqh))
671                 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
672         spin_unlock(&ctx->fault_pending_wqh.lock);
673 }
674
675 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
676                                            struct userfaultfd_wake_range *range)
677 {
678         unsigned seq;
679         bool need_wakeup;
680
681         /*
682          * To be sure waitqueue_active() is not reordered by the CPU
683          * before the pagetable update, use an explicit SMP memory
684          * barrier here. PT lock release or up_read(mmap_sem) still
685          * have release semantics that can allow the
686          * waitqueue_active() to be reordered before the pte update.
687          */
688         smp_mb();
689
690         /*
691          * Use waitqueue_active because it's very frequent to
692          * change the address space atomically even if there are no
693          * userfaults yet. So we take the spinlock only when we're
694          * sure we've userfaults to wake.
695          */
696         do {
697                 seq = read_seqcount_begin(&ctx->refile_seq);
698                 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
699                         waitqueue_active(&ctx->fault_wqh);
700                 cond_resched();
701         } while (read_seqcount_retry(&ctx->refile_seq, seq));
702         if (need_wakeup)
703                 __wake_userfault(ctx, range);
704 }
705
706 static __always_inline int validate_range(struct mm_struct *mm,
707                                           __u64 start, __u64 len)
708 {
709         __u64 task_size = mm->task_size;
710
711         if (start & ~PAGE_MASK)
712                 return -EINVAL;
713         if (len & ~PAGE_MASK)
714                 return -EINVAL;
715         if (!len)
716                 return -EINVAL;
717         if (start < mmap_min_addr)
718                 return -EINVAL;
719         if (start >= task_size)
720                 return -EINVAL;
721         if (len > task_size - start)
722                 return -EINVAL;
723         return 0;
724 }
725
726 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
727                                 unsigned long arg)
728 {
729         struct mm_struct *mm = ctx->mm;
730         struct vm_area_struct *vma, *prev, *cur;
731         int ret;
732         struct uffdio_register uffdio_register;
733         struct uffdio_register __user *user_uffdio_register;
734         unsigned long vm_flags, new_flags;
735         bool found;
736         unsigned long start, end, vma_end;
737
738         user_uffdio_register = (struct uffdio_register __user *) arg;
739
740         ret = -EFAULT;
741         if (copy_from_user(&uffdio_register, user_uffdio_register,
742                            sizeof(uffdio_register)-sizeof(__u64)))
743                 goto out;
744
745         ret = -EINVAL;
746         if (!uffdio_register.mode)
747                 goto out;
748         if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
749                                      UFFDIO_REGISTER_MODE_WP))
750                 goto out;
751         vm_flags = 0;
752         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
753                 vm_flags |= VM_UFFD_MISSING;
754         if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
755                 vm_flags |= VM_UFFD_WP;
756                 /*
757                  * FIXME: remove the below error constraint by
758                  * implementing the wprotect tracking mode.
759                  */
760                 ret = -EINVAL;
761                 goto out;
762         }
763
764         ret = validate_range(mm, uffdio_register.range.start,
765                              uffdio_register.range.len);
766         if (ret)
767                 goto out;
768
769         start = uffdio_register.range.start;
770         end = start + uffdio_register.range.len;
771
772         ret = -ENOMEM;
773         if (!mmget_not_zero(mm))
774                 goto out;
775
776         down_write(&mm->mmap_sem);
777         if (!mmget_still_valid(mm))
778                 goto out_unlock;
779         vma = find_vma_prev(mm, start, &prev);
780         if (!vma)
781                 goto out_unlock;
782
783         /* check that there's at least one vma in the range */
784         ret = -EINVAL;
785         if (vma->vm_start >= end)
786                 goto out_unlock;
787
788         /*
789          * Search for not compatible vmas.
790          *
791          * FIXME: this shall be relaxed later so that it doesn't fail
792          * on tmpfs backed vmas (in addition to the current allowance
793          * on anonymous vmas).
794          */
795         found = false;
796         for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
797                 cond_resched();
798
799                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
800                        !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
801
802                 /* check not compatible vmas */
803                 ret = -EINVAL;
804                 if (cur->vm_ops)
805                         goto out_unlock;
806
807                 /*
808                  * UFFDIO_COPY will fill file holes even without
809                  * PROT_WRITE. This check enforces that if this is a
810                  * MAP_SHARED, the process has write permission to the backing
811                  * file. If VM_MAYWRITE is set it also enforces that on a
812                  * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
813                  * F_WRITE_SEAL can be taken until the vma is destroyed.
814                  */
815                 ret = -EPERM;
816                 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
817                         goto out_unlock;
818
819                 /*
820                  * Check that this vma isn't already owned by a
821                  * different userfaultfd. We can't allow more than one
822                  * userfaultfd to own a single vma simultaneously or we
823                  * wouldn't know which one to deliver the userfaults to.
824                  */
825                 ret = -EBUSY;
826                 if (cur->vm_userfaultfd_ctx.ctx &&
827                     cur->vm_userfaultfd_ctx.ctx != ctx)
828                         goto out_unlock;
829
830                 found = true;
831         }
832         BUG_ON(!found);
833
834         if (vma->vm_start < start)
835                 prev = vma;
836
837         ret = 0;
838         do {
839                 cond_resched();
840
841                 BUG_ON(vma->vm_ops);
842                 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
843                        vma->vm_userfaultfd_ctx.ctx != ctx);
844                 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
845
846                 /*
847                  * Nothing to do: this vma is already registered into this
848                  * userfaultfd and with the right tracking mode too.
849                  */
850                 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
851                     (vma->vm_flags & vm_flags) == vm_flags)
852                         goto skip;
853
854                 if (vma->vm_start > start)
855                         start = vma->vm_start;
856                 vma_end = min(end, vma->vm_end);
857
858                 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
859                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
860                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
861                                  vma_policy(vma),
862                                  ((struct vm_userfaultfd_ctx){ ctx }),
863                                  vma_get_anon_name(vma));
864                 if (prev) {
865                         vma = prev;
866                         goto next;
867                 }
868                 if (vma->vm_start < start) {
869                         ret = split_vma(mm, vma, start, 1);
870                         if (ret)
871                                 break;
872                 }
873                 if (vma->vm_end > end) {
874                         ret = split_vma(mm, vma, end, 0);
875                         if (ret)
876                                 break;
877                 }
878         next:
879                 /*
880                  * In the vma_merge() successful mprotect-like case 8:
881                  * the next vma was merged into the current one and
882                  * the current one has not been updated yet.
883                  */
884                 vma->vm_flags = new_flags;
885                 vma->vm_userfaultfd_ctx.ctx = ctx;
886
887         skip:
888                 prev = vma;
889                 start = vma->vm_end;
890                 vma = vma->vm_next;
891         } while (vma && vma->vm_start < end);
892 out_unlock:
893         up_write(&mm->mmap_sem);
894         mmput(mm);
895         if (!ret) {
896                 /*
897                  * Now that we scanned all vmas we can already tell
898                  * userland which ioctls methods are guaranteed to
899                  * succeed on this range.
900                  */
901                 if (put_user(UFFD_API_RANGE_IOCTLS,
902                              &user_uffdio_register->ioctls))
903                         ret = -EFAULT;
904         }
905 out:
906         return ret;
907 }
908
909 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
910                                   unsigned long arg)
911 {
912         struct mm_struct *mm = ctx->mm;
913         struct vm_area_struct *vma, *prev, *cur;
914         int ret;
915         struct uffdio_range uffdio_unregister;
916         unsigned long new_flags;
917         bool found;
918         unsigned long start, end, vma_end;
919         const void __user *buf = (void __user *)arg;
920
921         ret = -EFAULT;
922         if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
923                 goto out;
924
925         ret = validate_range(mm, uffdio_unregister.start,
926                              uffdio_unregister.len);
927         if (ret)
928                 goto out;
929
930         start = uffdio_unregister.start;
931         end = start + uffdio_unregister.len;
932
933         ret = -ENOMEM;
934         if (!mmget_not_zero(mm))
935                 goto out;
936
937         down_write(&mm->mmap_sem);
938         if (!mmget_still_valid(mm))
939                 goto out_unlock;
940         vma = find_vma_prev(mm, start, &prev);
941         if (!vma)
942                 goto out_unlock;
943
944         /* check that there's at least one vma in the range */
945         ret = -EINVAL;
946         if (vma->vm_start >= end)
947                 goto out_unlock;
948
949         /*
950          * Search for not compatible vmas.
951          *
952          * FIXME: this shall be relaxed later so that it doesn't fail
953          * on tmpfs backed vmas (in addition to the current allowance
954          * on anonymous vmas).
955          */
956         found = false;
957         ret = -EINVAL;
958         for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
959                 cond_resched();
960
961                 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
962                        !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
963
964                 /*
965                  * Check not compatible vmas, not strictly required
966                  * here as not compatible vmas cannot have an
967                  * userfaultfd_ctx registered on them, but this
968                  * provides for more strict behavior to notice
969                  * unregistration errors.
970                  */
971                 if (cur->vm_ops)
972                         goto out_unlock;
973
974                 found = true;
975         }
976         BUG_ON(!found);
977
978         if (vma->vm_start < start)
979                 prev = vma;
980
981         ret = 0;
982         do {
983                 cond_resched();
984
985                 BUG_ON(vma->vm_ops);
986                 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
987
988                 /*
989                  * Nothing to do: this vma is already registered into this
990                  * userfaultfd and with the right tracking mode too.
991                  */
992                 if (!vma->vm_userfaultfd_ctx.ctx)
993                         goto skip;
994
995                 if (vma->vm_start > start)
996                         start = vma->vm_start;
997                 vma_end = min(end, vma->vm_end);
998
999                 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1000                 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1001                                  vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1002                                  vma_policy(vma),
1003                                  NULL_VM_UFFD_CTX,
1004                                  vma_get_anon_name(vma));
1005                 if (prev) {
1006                         vma = prev;
1007                         goto next;
1008                 }
1009                 if (vma->vm_start < start) {
1010                         ret = split_vma(mm, vma, start, 1);
1011                         if (ret)
1012                                 break;
1013                 }
1014                 if (vma->vm_end > end) {
1015                         ret = split_vma(mm, vma, end, 0);
1016                         if (ret)
1017                                 break;
1018                 }
1019         next:
1020                 /*
1021                  * In the vma_merge() successful mprotect-like case 8:
1022                  * the next vma was merged into the current one and
1023                  * the current one has not been updated yet.
1024                  */
1025                 vma->vm_flags = new_flags;
1026                 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1027
1028         skip:
1029                 prev = vma;
1030                 start = vma->vm_end;
1031                 vma = vma->vm_next;
1032         } while (vma && vma->vm_start < end);
1033 out_unlock:
1034         up_write(&mm->mmap_sem);
1035         mmput(mm);
1036 out:
1037         return ret;
1038 }
1039
1040 /*
1041  * userfaultfd_wake may be used in combination with the
1042  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1043  */
1044 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1045                             unsigned long arg)
1046 {
1047         int ret;
1048         struct uffdio_range uffdio_wake;
1049         struct userfaultfd_wake_range range;
1050         const void __user *buf = (void __user *)arg;
1051
1052         ret = -EFAULT;
1053         if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1054                 goto out;
1055
1056         ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1057         if (ret)
1058                 goto out;
1059
1060         range.start = uffdio_wake.start;
1061         range.len = uffdio_wake.len;
1062
1063         /*
1064          * len == 0 means wake all and we don't want to wake all here,
1065          * so check it again to be sure.
1066          */
1067         VM_BUG_ON(!range.len);
1068
1069         wake_userfault(ctx, &range);
1070         ret = 0;
1071
1072 out:
1073         return ret;
1074 }
1075
1076 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1077                             unsigned long arg)
1078 {
1079         __s64 ret;
1080         struct uffdio_copy uffdio_copy;
1081         struct uffdio_copy __user *user_uffdio_copy;
1082         struct userfaultfd_wake_range range;
1083
1084         user_uffdio_copy = (struct uffdio_copy __user *) arg;
1085
1086         ret = -EFAULT;
1087         if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1088                            /* don't copy "copy" last field */
1089                            sizeof(uffdio_copy)-sizeof(__s64)))
1090                 goto out;
1091
1092         ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1093         if (ret)
1094                 goto out;
1095         /*
1096          * double check for wraparound just in case. copy_from_user()
1097          * will later check uffdio_copy.src + uffdio_copy.len to fit
1098          * in the userland range.
1099          */
1100         ret = -EINVAL;
1101         if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1102                 goto out;
1103         if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1104                 goto out;
1105         if (mmget_not_zero(ctx->mm)) {
1106                 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1107                                    uffdio_copy.len);
1108                 mmput(ctx->mm);
1109         }
1110         if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1111                 return -EFAULT;
1112         if (ret < 0)
1113                 goto out;
1114         BUG_ON(!ret);
1115         /* len == 0 would wake all */
1116         range.len = ret;
1117         if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1118                 range.start = uffdio_copy.dst;
1119                 wake_userfault(ctx, &range);
1120         }
1121         ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1122 out:
1123         return ret;
1124 }
1125
1126 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1127                                 unsigned long arg)
1128 {
1129         __s64 ret;
1130         struct uffdio_zeropage uffdio_zeropage;
1131         struct uffdio_zeropage __user *user_uffdio_zeropage;
1132         struct userfaultfd_wake_range range;
1133
1134         user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1135
1136         ret = -EFAULT;
1137         if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1138                            /* don't copy "zeropage" last field */
1139                            sizeof(uffdio_zeropage)-sizeof(__s64)))
1140                 goto out;
1141
1142         ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1143                              uffdio_zeropage.range.len);
1144         if (ret)
1145                 goto out;
1146         ret = -EINVAL;
1147         if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1148                 goto out;
1149
1150         if (mmget_not_zero(ctx->mm)) {
1151                 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1152                                      uffdio_zeropage.range.len);
1153                 mmput(ctx->mm);
1154         }
1155         if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1156                 return -EFAULT;
1157         if (ret < 0)
1158                 goto out;
1159         /* len == 0 would wake all */
1160         BUG_ON(!ret);
1161         range.len = ret;
1162         if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1163                 range.start = uffdio_zeropage.range.start;
1164                 wake_userfault(ctx, &range);
1165         }
1166         ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1167 out:
1168         return ret;
1169 }
1170
1171 /*
1172  * userland asks for a certain API version and we return which bits
1173  * and ioctl commands are implemented in this kernel for such API
1174  * version or -EINVAL if unknown.
1175  */
1176 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1177                            unsigned long arg)
1178 {
1179         struct uffdio_api uffdio_api;
1180         void __user *buf = (void __user *)arg;
1181         int ret;
1182
1183         ret = -EINVAL;
1184         if (ctx->state != UFFD_STATE_WAIT_API)
1185                 goto out;
1186         ret = -EFAULT;
1187         if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1188                 goto out;
1189         if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1190                 memset(&uffdio_api, 0, sizeof(uffdio_api));
1191                 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1192                         goto out;
1193                 ret = -EINVAL;
1194                 goto out;
1195         }
1196         uffdio_api.features = UFFD_API_FEATURES;
1197         uffdio_api.ioctls = UFFD_API_IOCTLS;
1198         ret = -EFAULT;
1199         if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1200                 goto out;
1201         ctx->state = UFFD_STATE_RUNNING;
1202         ret = 0;
1203 out:
1204         return ret;
1205 }
1206
1207 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1208                               unsigned long arg)
1209 {
1210         int ret = -EINVAL;
1211         struct userfaultfd_ctx *ctx = file->private_data;
1212
1213         if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1214                 return -EINVAL;
1215
1216         switch(cmd) {
1217         case UFFDIO_API:
1218                 ret = userfaultfd_api(ctx, arg);
1219                 break;
1220         case UFFDIO_REGISTER:
1221                 ret = userfaultfd_register(ctx, arg);
1222                 break;
1223         case UFFDIO_UNREGISTER:
1224                 ret = userfaultfd_unregister(ctx, arg);
1225                 break;
1226         case UFFDIO_WAKE:
1227                 ret = userfaultfd_wake(ctx, arg);
1228                 break;
1229         case UFFDIO_COPY:
1230                 ret = userfaultfd_copy(ctx, arg);
1231                 break;
1232         case UFFDIO_ZEROPAGE:
1233                 ret = userfaultfd_zeropage(ctx, arg);
1234                 break;
1235         }
1236         return ret;
1237 }
1238
1239 #ifdef CONFIG_PROC_FS
1240 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1241 {
1242         struct userfaultfd_ctx *ctx = f->private_data;
1243         wait_queue_t *wq;
1244         struct userfaultfd_wait_queue *uwq;
1245         unsigned long pending = 0, total = 0;
1246
1247         spin_lock(&ctx->fault_pending_wqh.lock);
1248         list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1249                 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1250                 pending++;
1251                 total++;
1252         }
1253         list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1254                 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1255                 total++;
1256         }
1257         spin_unlock(&ctx->fault_pending_wqh.lock);
1258
1259         /*
1260          * If more protocols will be added, there will be all shown
1261          * separated by a space. Like this:
1262          *      protocols: aa:... bb:...
1263          */
1264         seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1265                    pending, total, UFFD_API, UFFD_API_FEATURES,
1266                    UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1267 }
1268 #endif
1269
1270 static const struct file_operations userfaultfd_fops = {
1271 #ifdef CONFIG_PROC_FS
1272         .show_fdinfo    = userfaultfd_show_fdinfo,
1273 #endif
1274         .release        = userfaultfd_release,
1275         .poll           = userfaultfd_poll,
1276         .read           = userfaultfd_read,
1277         .unlocked_ioctl = userfaultfd_ioctl,
1278         .compat_ioctl   = userfaultfd_ioctl,
1279         .llseek         = noop_llseek,
1280 };
1281
1282 static void init_once_userfaultfd_ctx(void *mem)
1283 {
1284         struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1285
1286         init_waitqueue_head(&ctx->fault_pending_wqh);
1287         init_waitqueue_head(&ctx->fault_wqh);
1288         init_waitqueue_head(&ctx->fd_wqh);
1289         seqcount_init(&ctx->refile_seq);
1290 }
1291
1292 /**
1293  * userfaultfd_file_create - Creates an userfaultfd file pointer.
1294  * @flags: Flags for the userfaultfd file.
1295  *
1296  * This function creates an userfaultfd file pointer, w/out installing
1297  * it into the fd table. This is useful when the userfaultfd file is
1298  * used during the initialization of data structures that require
1299  * extra setup after the userfaultfd creation. So the userfaultfd
1300  * creation is split into the file pointer creation phase, and the
1301  * file descriptor installation phase.  In this way races with
1302  * userspace closing the newly installed file descriptor can be
1303  * avoided.  Returns an userfaultfd file pointer, or a proper error
1304  * pointer.
1305  */
1306 static struct file *userfaultfd_file_create(int flags)
1307 {
1308         struct file *file;
1309         struct userfaultfd_ctx *ctx;
1310
1311         BUG_ON(!current->mm);
1312
1313         /* Check the UFFD_* constants for consistency.  */
1314         BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1315         BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1316
1317         file = ERR_PTR(-EINVAL);
1318         if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1319                 goto out;
1320
1321         file = ERR_PTR(-ENOMEM);
1322         ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1323         if (!ctx)
1324                 goto out;
1325
1326         atomic_set(&ctx->refcount, 1);
1327         ctx->flags = flags;
1328         ctx->state = UFFD_STATE_WAIT_API;
1329         ctx->released = false;
1330         ctx->mm = current->mm;
1331         /* prevent the mm struct to be freed */
1332         atomic_inc(&ctx->mm->mm_count);
1333
1334         file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1335                                   O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1336         if (IS_ERR(file)) {
1337                 mmdrop(ctx->mm);
1338                 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1339         }
1340 out:
1341         return file;
1342 }
1343
1344 SYSCALL_DEFINE1(userfaultfd, int, flags)
1345 {
1346         int fd, error;
1347         struct file *file;
1348
1349         error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1350         if (error < 0)
1351                 return error;
1352         fd = error;
1353
1354         file = userfaultfd_file_create(flags);
1355         if (IS_ERR(file)) {
1356                 error = PTR_ERR(file);
1357                 goto err_put_unused_fd;
1358         }
1359         fd_install(fd, file);
1360
1361         return fd;
1362
1363 err_put_unused_fd:
1364         put_unused_fd(fd);
1365
1366         return error;
1367 }
1368
1369 static int __init userfaultfd_init(void)
1370 {
1371         userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1372                                                 sizeof(struct userfaultfd_ctx),
1373                                                 0,
1374                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1375                                                 init_once_userfaultfd_ctx);
1376         return 0;
1377 }
1378 __initcall(userfaultfd_init);