userfaultfd: wake pending userfaults
[linux-2.6-block.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
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
30enum userfaultfd_state {
31 UFFD_STATE_WAIT_API,
32 UFFD_STATE_RUNNING,
33};
34
35struct userfaultfd_ctx {
36 /* pseudo fd refcounting */
37 atomic_t refcount;
38 /* waitqueue head for the userfaultfd page faults */
39 wait_queue_head_t fault_wqh;
40 /* waitqueue head for the pseudo fd to wakeup poll/read */
41 wait_queue_head_t fd_wqh;
42 /* userfaultfd syscall flags */
43 unsigned int flags;
44 /* state machine */
45 enum userfaultfd_state state;
46 /* released */
47 bool released;
48 /* mm with one ore more vmas attached to this userfaultfd_ctx */
49 struct mm_struct *mm;
50};
51
52struct userfaultfd_wait_queue {
a9b85f94 53 struct uffd_msg msg;
86039bd3 54 wait_queue_t wq;
ba85c702
AA
55 /*
56 * Only relevant when queued in fault_wqh and only used by the
57 * read operation to avoid reading the same userfault twice.
58 */
86039bd3
AA
59 bool pending;
60 struct userfaultfd_ctx *ctx;
61};
62
63struct userfaultfd_wake_range {
64 unsigned long start;
65 unsigned long len;
66};
67
68static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
69 int wake_flags, void *key)
70{
71 struct userfaultfd_wake_range *range = key;
72 int ret;
73 struct userfaultfd_wait_queue *uwq;
74 unsigned long start, len;
75
76 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
77 ret = 0;
86039bd3
AA
78 /* len == 0 means wake all */
79 start = range->start;
80 len = range->len;
a9b85f94
AA
81 if (len && (start > uwq->msg.arg.pagefault.address ||
82 start + len <= uwq->msg.arg.pagefault.address))
86039bd3
AA
83 goto out;
84 ret = wake_up_state(wq->private, mode);
85 if (ret)
86 /*
87 * Wake only once, autoremove behavior.
88 *
89 * After the effect of list_del_init is visible to the
90 * other CPUs, the waitqueue may disappear from under
91 * us, see the !list_empty_careful() in
92 * handle_userfault(). try_to_wake_up() has an
93 * implicit smp_mb__before_spinlock, and the
94 * wq->private is read before calling the extern
95 * function "wake_up_state" (which in turns calls
96 * try_to_wake_up). While the spin_lock;spin_unlock;
97 * wouldn't be enough, the smp_mb__before_spinlock is
98 * enough to avoid an explicit smp_mb() here.
99 */
100 list_del_init(&wq->task_list);
101out:
102 return ret;
103}
104
105/**
106 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
107 * context.
108 * @ctx: [in] Pointer to the userfaultfd context.
109 *
110 * Returns: In case of success, returns not zero.
111 */
112static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
113{
114 if (!atomic_inc_not_zero(&ctx->refcount))
115 BUG();
116}
117
118/**
119 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
120 * context.
121 * @ctx: [in] Pointer to userfaultfd context.
122 *
123 * The userfaultfd context reference must have been previously acquired either
124 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
125 */
126static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
127{
128 if (atomic_dec_and_test(&ctx->refcount)) {
129 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
130 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
131 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
132 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
133 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
134 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
135 mmput(ctx->mm);
136 kfree(ctx);
137 }
138}
139
a9b85f94 140static inline void msg_init(struct uffd_msg *msg)
86039bd3 141{
a9b85f94
AA
142 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
143 /*
144 * Must use memset to zero out the paddings or kernel data is
145 * leaked to userland.
146 */
147 memset(msg, 0, sizeof(struct uffd_msg));
148}
149
150static inline struct uffd_msg userfault_msg(unsigned long address,
151 unsigned int flags,
152 unsigned long reason)
153{
154 struct uffd_msg msg;
155 msg_init(&msg);
156 msg.event = UFFD_EVENT_PAGEFAULT;
157 msg.arg.pagefault.address = address;
86039bd3
AA
158 if (flags & FAULT_FLAG_WRITE)
159 /*
a9b85f94
AA
160 * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the
161 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
162 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
163 * was a read fault, otherwise if set it means it's
164 * a write fault.
86039bd3 165 */
a9b85f94 166 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
86039bd3
AA
167 if (reason & VM_UFFD_WP)
168 /*
a9b85f94
AA
169 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
170 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
171 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
172 * a missing fault, otherwise if set it means it's a
173 * write protect fault.
86039bd3 174 */
a9b85f94
AA
175 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
176 return msg;
86039bd3
AA
177}
178
179/*
180 * The locking rules involved in returning VM_FAULT_RETRY depending on
181 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
182 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
183 * recommendation in __lock_page_or_retry is not an understatement.
184 *
185 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
186 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
187 * not set.
188 *
189 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
190 * set, VM_FAULT_RETRY can still be returned if and only if there are
191 * fatal_signal_pending()s, and the mmap_sem must be released before
192 * returning it.
193 */
194int handle_userfault(struct vm_area_struct *vma, unsigned long address,
195 unsigned int flags, unsigned long reason)
196{
197 struct mm_struct *mm = vma->vm_mm;
198 struct userfaultfd_ctx *ctx;
199 struct userfaultfd_wait_queue uwq;
ba85c702 200 int ret;
86039bd3
AA
201
202 BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
203
ba85c702 204 ret = VM_FAULT_SIGBUS;
86039bd3
AA
205 ctx = vma->vm_userfaultfd_ctx.ctx;
206 if (!ctx)
ba85c702 207 goto out;
86039bd3
AA
208
209 BUG_ON(ctx->mm != mm);
210
211 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
212 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
213
214 /*
215 * If it's already released don't get it. This avoids to loop
216 * in __get_user_pages if userfaultfd_release waits on the
217 * caller of handle_userfault to release the mmap_sem.
218 */
219 if (unlikely(ACCESS_ONCE(ctx->released)))
ba85c702 220 goto out;
86039bd3
AA
221
222 /*
223 * Check that we can return VM_FAULT_RETRY.
224 *
225 * NOTE: it should become possible to return VM_FAULT_RETRY
226 * even if FAULT_FLAG_TRIED is set without leading to gup()
227 * -EBUSY failures, if the userfaultfd is to be extended for
228 * VM_UFFD_WP tracking and we intend to arm the userfault
229 * without first stopping userland access to the memory. For
230 * VM_UFFD_MISSING userfaults this is enough for now.
231 */
232 if (unlikely(!(flags & FAULT_FLAG_ALLOW_RETRY))) {
233 /*
234 * Validate the invariant that nowait must allow retry
235 * to be sure not to return SIGBUS erroneously on
236 * nowait invocations.
237 */
238 BUG_ON(flags & FAULT_FLAG_RETRY_NOWAIT);
239#ifdef CONFIG_DEBUG_VM
240 if (printk_ratelimit()) {
241 printk(KERN_WARNING
242 "FAULT_FLAG_ALLOW_RETRY missing %x\n", flags);
243 dump_stack();
244 }
245#endif
ba85c702 246 goto out;
86039bd3
AA
247 }
248
249 /*
250 * Handle nowait, not much to do other than tell it to retry
251 * and wait.
252 */
ba85c702 253 ret = VM_FAULT_RETRY;
86039bd3 254 if (flags & FAULT_FLAG_RETRY_NOWAIT)
ba85c702 255 goto out;
86039bd3
AA
256
257 /* take the reference before dropping the mmap_sem */
258 userfaultfd_ctx_get(ctx);
259
260 /* be gentle and immediately relinquish the mmap_sem */
261 up_read(&mm->mmap_sem);
262
263 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
264 uwq.wq.private = current;
a9b85f94 265 uwq.msg = userfault_msg(address, flags, reason);
86039bd3
AA
266 uwq.pending = true;
267 uwq.ctx = ctx;
268
269 spin_lock(&ctx->fault_wqh.lock);
270 /*
271 * After the __add_wait_queue the uwq is visible to userland
272 * through poll/read().
273 */
274 __add_wait_queue(&ctx->fault_wqh, &uwq.wq);
ba85c702
AA
275 set_current_state(TASK_KILLABLE);
276 spin_unlock(&ctx->fault_wqh.lock);
86039bd3 277
ba85c702
AA
278 if (likely(!ACCESS_ONCE(ctx->released) &&
279 !fatal_signal_pending(current))) {
86039bd3
AA
280 wake_up_poll(&ctx->fd_wqh, POLLIN);
281 schedule();
ba85c702
AA
282 ret |= VM_FAULT_MAJOR;
283 }
86039bd3 284
ba85c702
AA
285 __set_current_state(TASK_RUNNING);
286 /* see finish_wait() comment for why list_empty_careful() */
287 if (!list_empty_careful(&uwq.wq.task_list)) {
86039bd3 288 spin_lock(&ctx->fault_wqh.lock);
ba85c702
AA
289 list_del_init(&uwq.wq.task_list);
290 spin_unlock(&ctx->fault_wqh.lock);
86039bd3 291 }
86039bd3
AA
292
293 /*
294 * ctx may go away after this if the userfault pseudo fd is
295 * already released.
296 */
297 userfaultfd_ctx_put(ctx);
298
ba85c702
AA
299out:
300 return ret;
86039bd3
AA
301}
302
303static int userfaultfd_release(struct inode *inode, struct file *file)
304{
305 struct userfaultfd_ctx *ctx = file->private_data;
306 struct mm_struct *mm = ctx->mm;
307 struct vm_area_struct *vma, *prev;
308 /* len == 0 means wake all */
309 struct userfaultfd_wake_range range = { .len = 0, };
310 unsigned long new_flags;
311
312 ACCESS_ONCE(ctx->released) = true;
313
314 /*
315 * Flush page faults out of all CPUs. NOTE: all page faults
316 * must be retried without returning VM_FAULT_SIGBUS if
317 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
318 * changes while handle_userfault released the mmap_sem. So
319 * it's critical that released is set to true (above), before
320 * taking the mmap_sem for writing.
321 */
322 down_write(&mm->mmap_sem);
323 prev = NULL;
324 for (vma = mm->mmap; vma; vma = vma->vm_next) {
325 cond_resched();
326 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
327 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
328 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
329 prev = vma;
330 continue;
331 }
332 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
333 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
334 new_flags, vma->anon_vma,
335 vma->vm_file, vma->vm_pgoff,
336 vma_policy(vma),
337 NULL_VM_UFFD_CTX);
338 if (prev)
339 vma = prev;
340 else
341 prev = vma;
342 vma->vm_flags = new_flags;
343 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
344 }
345 up_write(&mm->mmap_sem);
346
347 /*
348 * After no new page faults can wait on this fault_wqh, flush
349 * the last page faults that may have been already waiting on
350 * the fault_wqh.
351 */
352 spin_lock(&ctx->fault_wqh.lock);
353 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, 0, &range);
354 spin_unlock(&ctx->fault_wqh.lock);
355
356 wake_up_poll(&ctx->fd_wqh, POLLHUP);
357 userfaultfd_ctx_put(ctx);
358 return 0;
359}
360
361/* fault_wqh.lock must be hold by the caller */
362static inline unsigned int find_userfault(struct userfaultfd_ctx *ctx,
363 struct userfaultfd_wait_queue **uwq)
364{
365 wait_queue_t *wq;
366 struct userfaultfd_wait_queue *_uwq;
367 unsigned int ret = 0;
368
369 VM_BUG_ON(!spin_is_locked(&ctx->fault_wqh.lock));
370
371 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
372 _uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
373 if (_uwq->pending) {
374 ret = POLLIN;
375 if (!uwq)
376 /*
377 * If there's at least a pending and
378 * we don't care which one it is,
379 * break immediately and leverage the
380 * efficiency of the LIFO walk.
381 */
382 break;
383 /*
384 * If we need to find which one was pending we
385 * keep walking until we find the first not
386 * pending one, so we read() them in FIFO order.
387 */
388 *uwq = _uwq;
389 } else
390 /*
391 * break the loop at the first not pending
392 * one, there cannot be pending userfaults
393 * after the first not pending one, because
394 * all new pending ones are inserted at the
395 * head and we walk it in LIFO.
396 */
397 break;
398 }
399
400 return ret;
401}
402
403static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
404{
405 struct userfaultfd_ctx *ctx = file->private_data;
406 unsigned int ret;
407
408 poll_wait(file, &ctx->fd_wqh, wait);
409
410 switch (ctx->state) {
411 case UFFD_STATE_WAIT_API:
412 return POLLERR;
413 case UFFD_STATE_RUNNING:
ba85c702
AA
414 /*
415 * poll() never guarantees that read won't block.
416 * userfaults can be waken before they're read().
417 */
418 if (unlikely(!(file->f_flags & O_NONBLOCK)))
419 return POLLERR;
86039bd3
AA
420 spin_lock(&ctx->fault_wqh.lock);
421 ret = find_userfault(ctx, NULL);
422 spin_unlock(&ctx->fault_wqh.lock);
423 return ret;
424 default:
425 BUG();
426 }
427}
428
429static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
a9b85f94 430 struct uffd_msg *msg)
86039bd3
AA
431{
432 ssize_t ret;
433 DECLARE_WAITQUEUE(wait, current);
434 struct userfaultfd_wait_queue *uwq = NULL;
435
436 /* always take the fd_wqh lock before the fault_wqh lock */
437 spin_lock(&ctx->fd_wqh.lock);
438 __add_wait_queue(&ctx->fd_wqh, &wait);
439 for (;;) {
440 set_current_state(TASK_INTERRUPTIBLE);
441 spin_lock(&ctx->fault_wqh.lock);
442 if (find_userfault(ctx, &uwq)) {
443 /*
444 * The fault_wqh.lock prevents the uwq to
445 * disappear from under us.
446 */
447 uwq->pending = false;
a9b85f94
AA
448 /* careful to always initialize msg if ret == 0 */
449 *msg = uwq->msg;
86039bd3
AA
450 spin_unlock(&ctx->fault_wqh.lock);
451 ret = 0;
452 break;
453 }
454 spin_unlock(&ctx->fault_wqh.lock);
455 if (signal_pending(current)) {
456 ret = -ERESTARTSYS;
457 break;
458 }
459 if (no_wait) {
460 ret = -EAGAIN;
461 break;
462 }
463 spin_unlock(&ctx->fd_wqh.lock);
464 schedule();
465 spin_lock(&ctx->fd_wqh.lock);
466 }
467 __remove_wait_queue(&ctx->fd_wqh, &wait);
468 __set_current_state(TASK_RUNNING);
469 spin_unlock(&ctx->fd_wqh.lock);
470
471 return ret;
472}
473
474static ssize_t userfaultfd_read(struct file *file, char __user *buf,
475 size_t count, loff_t *ppos)
476{
477 struct userfaultfd_ctx *ctx = file->private_data;
478 ssize_t _ret, ret = 0;
a9b85f94 479 struct uffd_msg msg;
86039bd3
AA
480 int no_wait = file->f_flags & O_NONBLOCK;
481
482 if (ctx->state == UFFD_STATE_WAIT_API)
483 return -EINVAL;
484 BUG_ON(ctx->state != UFFD_STATE_RUNNING);
485
486 for (;;) {
a9b85f94 487 if (count < sizeof(msg))
86039bd3 488 return ret ? ret : -EINVAL;
a9b85f94 489 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
86039bd3
AA
490 if (_ret < 0)
491 return ret ? ret : _ret;
a9b85f94 492 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
86039bd3 493 return ret ? ret : -EFAULT;
a9b85f94
AA
494 ret += sizeof(msg);
495 buf += sizeof(msg);
496 count -= sizeof(msg);
86039bd3
AA
497 /*
498 * Allow to read more than one fault at time but only
499 * block if waiting for the very first one.
500 */
501 no_wait = O_NONBLOCK;
502 }
503}
504
505static void __wake_userfault(struct userfaultfd_ctx *ctx,
506 struct userfaultfd_wake_range *range)
507{
508 unsigned long start, end;
509
510 start = range->start;
511 end = range->start + range->len;
512
513 spin_lock(&ctx->fault_wqh.lock);
514 /* wake all in the range and autoremove */
515 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, 0, range);
516 spin_unlock(&ctx->fault_wqh.lock);
517}
518
519static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
520 struct userfaultfd_wake_range *range)
521{
522 /*
523 * To be sure waitqueue_active() is not reordered by the CPU
524 * before the pagetable update, use an explicit SMP memory
525 * barrier here. PT lock release or up_read(mmap_sem) still
526 * have release semantics that can allow the
527 * waitqueue_active() to be reordered before the pte update.
528 */
529 smp_mb();
530
531 /*
532 * Use waitqueue_active because it's very frequent to
533 * change the address space atomically even if there are no
534 * userfaults yet. So we take the spinlock only when we're
535 * sure we've userfaults to wake.
536 */
537 if (waitqueue_active(&ctx->fault_wqh))
538 __wake_userfault(ctx, range);
539}
540
541static __always_inline int validate_range(struct mm_struct *mm,
542 __u64 start, __u64 len)
543{
544 __u64 task_size = mm->task_size;
545
546 if (start & ~PAGE_MASK)
547 return -EINVAL;
548 if (len & ~PAGE_MASK)
549 return -EINVAL;
550 if (!len)
551 return -EINVAL;
552 if (start < mmap_min_addr)
553 return -EINVAL;
554 if (start >= task_size)
555 return -EINVAL;
556 if (len > task_size - start)
557 return -EINVAL;
558 return 0;
559}
560
561static int userfaultfd_register(struct userfaultfd_ctx *ctx,
562 unsigned long arg)
563{
564 struct mm_struct *mm = ctx->mm;
565 struct vm_area_struct *vma, *prev, *cur;
566 int ret;
567 struct uffdio_register uffdio_register;
568 struct uffdio_register __user *user_uffdio_register;
569 unsigned long vm_flags, new_flags;
570 bool found;
571 unsigned long start, end, vma_end;
572
573 user_uffdio_register = (struct uffdio_register __user *) arg;
574
575 ret = -EFAULT;
576 if (copy_from_user(&uffdio_register, user_uffdio_register,
577 sizeof(uffdio_register)-sizeof(__u64)))
578 goto out;
579
580 ret = -EINVAL;
581 if (!uffdio_register.mode)
582 goto out;
583 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
584 UFFDIO_REGISTER_MODE_WP))
585 goto out;
586 vm_flags = 0;
587 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
588 vm_flags |= VM_UFFD_MISSING;
589 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
590 vm_flags |= VM_UFFD_WP;
591 /*
592 * FIXME: remove the below error constraint by
593 * implementing the wprotect tracking mode.
594 */
595 ret = -EINVAL;
596 goto out;
597 }
598
599 ret = validate_range(mm, uffdio_register.range.start,
600 uffdio_register.range.len);
601 if (ret)
602 goto out;
603
604 start = uffdio_register.range.start;
605 end = start + uffdio_register.range.len;
606
607 down_write(&mm->mmap_sem);
608 vma = find_vma_prev(mm, start, &prev);
609
610 ret = -ENOMEM;
611 if (!vma)
612 goto out_unlock;
613
614 /* check that there's at least one vma in the range */
615 ret = -EINVAL;
616 if (vma->vm_start >= end)
617 goto out_unlock;
618
619 /*
620 * Search for not compatible vmas.
621 *
622 * FIXME: this shall be relaxed later so that it doesn't fail
623 * on tmpfs backed vmas (in addition to the current allowance
624 * on anonymous vmas).
625 */
626 found = false;
627 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
628 cond_resched();
629
630 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
631 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
632
633 /* check not compatible vmas */
634 ret = -EINVAL;
635 if (cur->vm_ops)
636 goto out_unlock;
637
638 /*
639 * Check that this vma isn't already owned by a
640 * different userfaultfd. We can't allow more than one
641 * userfaultfd to own a single vma simultaneously or we
642 * wouldn't know which one to deliver the userfaults to.
643 */
644 ret = -EBUSY;
645 if (cur->vm_userfaultfd_ctx.ctx &&
646 cur->vm_userfaultfd_ctx.ctx != ctx)
647 goto out_unlock;
648
649 found = true;
650 }
651 BUG_ON(!found);
652
653 if (vma->vm_start < start)
654 prev = vma;
655
656 ret = 0;
657 do {
658 cond_resched();
659
660 BUG_ON(vma->vm_ops);
661 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
662 vma->vm_userfaultfd_ctx.ctx != ctx);
663
664 /*
665 * Nothing to do: this vma is already registered into this
666 * userfaultfd and with the right tracking mode too.
667 */
668 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
669 (vma->vm_flags & vm_flags) == vm_flags)
670 goto skip;
671
672 if (vma->vm_start > start)
673 start = vma->vm_start;
674 vma_end = min(end, vma->vm_end);
675
676 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
677 prev = vma_merge(mm, prev, start, vma_end, new_flags,
678 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
679 vma_policy(vma),
680 ((struct vm_userfaultfd_ctx){ ctx }));
681 if (prev) {
682 vma = prev;
683 goto next;
684 }
685 if (vma->vm_start < start) {
686 ret = split_vma(mm, vma, start, 1);
687 if (ret)
688 break;
689 }
690 if (vma->vm_end > end) {
691 ret = split_vma(mm, vma, end, 0);
692 if (ret)
693 break;
694 }
695 next:
696 /*
697 * In the vma_merge() successful mprotect-like case 8:
698 * the next vma was merged into the current one and
699 * the current one has not been updated yet.
700 */
701 vma->vm_flags = new_flags;
702 vma->vm_userfaultfd_ctx.ctx = ctx;
703
704 skip:
705 prev = vma;
706 start = vma->vm_end;
707 vma = vma->vm_next;
708 } while (vma && vma->vm_start < end);
709out_unlock:
710 up_write(&mm->mmap_sem);
711 if (!ret) {
712 /*
713 * Now that we scanned all vmas we can already tell
714 * userland which ioctls methods are guaranteed to
715 * succeed on this range.
716 */
717 if (put_user(UFFD_API_RANGE_IOCTLS,
718 &user_uffdio_register->ioctls))
719 ret = -EFAULT;
720 }
721out:
722 return ret;
723}
724
725static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
726 unsigned long arg)
727{
728 struct mm_struct *mm = ctx->mm;
729 struct vm_area_struct *vma, *prev, *cur;
730 int ret;
731 struct uffdio_range uffdio_unregister;
732 unsigned long new_flags;
733 bool found;
734 unsigned long start, end, vma_end;
735 const void __user *buf = (void __user *)arg;
736
737 ret = -EFAULT;
738 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
739 goto out;
740
741 ret = validate_range(mm, uffdio_unregister.start,
742 uffdio_unregister.len);
743 if (ret)
744 goto out;
745
746 start = uffdio_unregister.start;
747 end = start + uffdio_unregister.len;
748
749 down_write(&mm->mmap_sem);
750 vma = find_vma_prev(mm, start, &prev);
751
752 ret = -ENOMEM;
753 if (!vma)
754 goto out_unlock;
755
756 /* check that there's at least one vma in the range */
757 ret = -EINVAL;
758 if (vma->vm_start >= end)
759 goto out_unlock;
760
761 /*
762 * Search for not compatible vmas.
763 *
764 * FIXME: this shall be relaxed later so that it doesn't fail
765 * on tmpfs backed vmas (in addition to the current allowance
766 * on anonymous vmas).
767 */
768 found = false;
769 ret = -EINVAL;
770 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
771 cond_resched();
772
773 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
774 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
775
776 /*
777 * Check not compatible vmas, not strictly required
778 * here as not compatible vmas cannot have an
779 * userfaultfd_ctx registered on them, but this
780 * provides for more strict behavior to notice
781 * unregistration errors.
782 */
783 if (cur->vm_ops)
784 goto out_unlock;
785
786 found = true;
787 }
788 BUG_ON(!found);
789
790 if (vma->vm_start < start)
791 prev = vma;
792
793 ret = 0;
794 do {
795 cond_resched();
796
797 BUG_ON(vma->vm_ops);
798
799 /*
800 * Nothing to do: this vma is already registered into this
801 * userfaultfd and with the right tracking mode too.
802 */
803 if (!vma->vm_userfaultfd_ctx.ctx)
804 goto skip;
805
806 if (vma->vm_start > start)
807 start = vma->vm_start;
808 vma_end = min(end, vma->vm_end);
809
810 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
811 prev = vma_merge(mm, prev, start, vma_end, new_flags,
812 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
813 vma_policy(vma),
814 NULL_VM_UFFD_CTX);
815 if (prev) {
816 vma = prev;
817 goto next;
818 }
819 if (vma->vm_start < start) {
820 ret = split_vma(mm, vma, start, 1);
821 if (ret)
822 break;
823 }
824 if (vma->vm_end > end) {
825 ret = split_vma(mm, vma, end, 0);
826 if (ret)
827 break;
828 }
829 next:
830 /*
831 * In the vma_merge() successful mprotect-like case 8:
832 * the next vma was merged into the current one and
833 * the current one has not been updated yet.
834 */
835 vma->vm_flags = new_flags;
836 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
837
838 skip:
839 prev = vma;
840 start = vma->vm_end;
841 vma = vma->vm_next;
842 } while (vma && vma->vm_start < end);
843out_unlock:
844 up_write(&mm->mmap_sem);
845out:
846 return ret;
847}
848
849/*
ba85c702
AA
850 * userfaultfd_wake is needed in case an userfault is in flight by the
851 * time a UFFDIO_COPY (or other ioctl variants) completes. The page
852 * may be well get mapped and the page fault if repeated wouldn't lead
853 * to a userfault anymore, but before scheduling in TASK_KILLABLE mode
854 * handle_userfault() doesn't recheck the pagetables and it doesn't
855 * serialize against UFFDO_COPY (or other ioctl variants). Ultimately
856 * the knowledge of which pages are mapped is left to userland who is
857 * responsible for handling the race between read() userfaults and
858 * background UFFDIO_COPY (or other ioctl variants), if done by
859 * separate concurrent threads.
860 *
861 * userfaultfd_wake may be used in combination with the
862 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
86039bd3
AA
863 */
864static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
865 unsigned long arg)
866{
867 int ret;
868 struct uffdio_range uffdio_wake;
869 struct userfaultfd_wake_range range;
870 const void __user *buf = (void __user *)arg;
871
872 ret = -EFAULT;
873 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
874 goto out;
875
876 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
877 if (ret)
878 goto out;
879
880 range.start = uffdio_wake.start;
881 range.len = uffdio_wake.len;
882
883 /*
884 * len == 0 means wake all and we don't want to wake all here,
885 * so check it again to be sure.
886 */
887 VM_BUG_ON(!range.len);
888
889 wake_userfault(ctx, &range);
890 ret = 0;
891
892out:
893 return ret;
894}
895
896/*
897 * userland asks for a certain API version and we return which bits
898 * and ioctl commands are implemented in this kernel for such API
899 * version or -EINVAL if unknown.
900 */
901static int userfaultfd_api(struct userfaultfd_ctx *ctx,
902 unsigned long arg)
903{
904 struct uffdio_api uffdio_api;
905 void __user *buf = (void __user *)arg;
906 int ret;
907
908 ret = -EINVAL;
909 if (ctx->state != UFFD_STATE_WAIT_API)
910 goto out;
911 ret = -EFAULT;
a9b85f94 912 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
86039bd3 913 goto out;
a9b85f94 914 if (uffdio_api.api != UFFD_API || uffdio_api.features) {
86039bd3
AA
915 memset(&uffdio_api, 0, sizeof(uffdio_api));
916 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
917 goto out;
918 ret = -EINVAL;
919 goto out;
920 }
3f602d27 921 uffdio_api.features = UFFD_API_FEATURES;
86039bd3
AA
922 uffdio_api.ioctls = UFFD_API_IOCTLS;
923 ret = -EFAULT;
924 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
925 goto out;
926 ctx->state = UFFD_STATE_RUNNING;
927 ret = 0;
928out:
929 return ret;
930}
931
932static long userfaultfd_ioctl(struct file *file, unsigned cmd,
933 unsigned long arg)
934{
935 int ret = -EINVAL;
936 struct userfaultfd_ctx *ctx = file->private_data;
937
938 switch(cmd) {
939 case UFFDIO_API:
940 ret = userfaultfd_api(ctx, arg);
941 break;
942 case UFFDIO_REGISTER:
943 ret = userfaultfd_register(ctx, arg);
944 break;
945 case UFFDIO_UNREGISTER:
946 ret = userfaultfd_unregister(ctx, arg);
947 break;
948 case UFFDIO_WAKE:
949 ret = userfaultfd_wake(ctx, arg);
950 break;
951 }
952 return ret;
953}
954
955#ifdef CONFIG_PROC_FS
956static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
957{
958 struct userfaultfd_ctx *ctx = f->private_data;
959 wait_queue_t *wq;
960 struct userfaultfd_wait_queue *uwq;
961 unsigned long pending = 0, total = 0;
962
963 spin_lock(&ctx->fault_wqh.lock);
964 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
965 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
966 if (uwq->pending)
967 pending++;
968 total++;
969 }
970 spin_unlock(&ctx->fault_wqh.lock);
971
972 /*
973 * If more protocols will be added, there will be all shown
974 * separated by a space. Like this:
975 * protocols: aa:... bb:...
976 */
977 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
3f602d27 978 pending, total, UFFD_API, UFFD_API_FEATURES,
86039bd3
AA
979 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
980}
981#endif
982
983static const struct file_operations userfaultfd_fops = {
984#ifdef CONFIG_PROC_FS
985 .show_fdinfo = userfaultfd_show_fdinfo,
986#endif
987 .release = userfaultfd_release,
988 .poll = userfaultfd_poll,
989 .read = userfaultfd_read,
990 .unlocked_ioctl = userfaultfd_ioctl,
991 .compat_ioctl = userfaultfd_ioctl,
992 .llseek = noop_llseek,
993};
994
995/**
996 * userfaultfd_file_create - Creates an userfaultfd file pointer.
997 * @flags: Flags for the userfaultfd file.
998 *
999 * This function creates an userfaultfd file pointer, w/out installing
1000 * it into the fd table. This is useful when the userfaultfd file is
1001 * used during the initialization of data structures that require
1002 * extra setup after the userfaultfd creation. So the userfaultfd
1003 * creation is split into the file pointer creation phase, and the
1004 * file descriptor installation phase. In this way races with
1005 * userspace closing the newly installed file descriptor can be
1006 * avoided. Returns an userfaultfd file pointer, or a proper error
1007 * pointer.
1008 */
1009static struct file *userfaultfd_file_create(int flags)
1010{
1011 struct file *file;
1012 struct userfaultfd_ctx *ctx;
1013
1014 BUG_ON(!current->mm);
1015
1016 /* Check the UFFD_* constants for consistency. */
1017 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1018 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1019
1020 file = ERR_PTR(-EINVAL);
1021 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1022 goto out;
1023
1024 file = ERR_PTR(-ENOMEM);
1025 ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
1026 if (!ctx)
1027 goto out;
1028
1029 atomic_set(&ctx->refcount, 1);
1030 init_waitqueue_head(&ctx->fault_wqh);
1031 init_waitqueue_head(&ctx->fd_wqh);
1032 ctx->flags = flags;
1033 ctx->state = UFFD_STATE_WAIT_API;
1034 ctx->released = false;
1035 ctx->mm = current->mm;
1036 /* prevent the mm struct to be freed */
1037 atomic_inc(&ctx->mm->mm_users);
1038
1039 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1040 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1041 if (IS_ERR(file))
1042 kfree(ctx);
1043out:
1044 return file;
1045}
1046
1047SYSCALL_DEFINE1(userfaultfd, int, flags)
1048{
1049 int fd, error;
1050 struct file *file;
1051
1052 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1053 if (error < 0)
1054 return error;
1055 fd = error;
1056
1057 file = userfaultfd_file_create(flags);
1058 if (IS_ERR(file)) {
1059 error = PTR_ERR(file);
1060 goto err_put_unused_fd;
1061 }
1062 fd_install(fd, file);
1063
1064 return fd;
1065
1066err_put_unused_fd:
1067 put_unused_fd(fd);
1068
1069 return error;
1070}