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