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