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