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