OSDN Git Service

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