1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * fs/userfaultfd.c
4 *
5 * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
6 * Copyright (C) 2008-2009 Red Hat, Inc.
7 * Copyright (C) 2015 Red Hat, Inc.
8 *
9 * Some part derived from fs/eventfd.c (anon inode setup) and
10 * mm/ksm.c (mm hashing).
11 */
12
13 #include <linux/list.h>
14 #include <linux/hashtable.h>
15 #include <linux/sched/signal.h>
16 #include <linux/sched/mm.h>
17 #include <linux/mm.h>
18 #include <linux/mm_inline.h>
19 #include <linux/mmu_notifier.h>
20 #include <linux/poll.h>
21 #include <linux/page_size_compat.h>
22 #include <linux/slab.h>
23 #include <linux/seq_file.h>
24 #include <linux/file.h>
25 #include <linux/bug.h>
26 #include <linux/anon_inodes.h>
27 #include <linux/syscalls.h>
28 #include <linux/userfaultfd_k.h>
29 #include <linux/mempolicy.h>
30 #include <linux/ioctl.h>
31 #include <linux/security.h>
32 #include <linux/hugetlb.h>
33 #include <linux/swapops.h>
34 #include <linux/miscdevice.h>
35 #include <linux/uio.h>
36
37 static int sysctl_unprivileged_userfaultfd __read_mostly;
38
39 #ifdef CONFIG_SYSCTL
40 static struct ctl_table vm_userfaultfd_table[] = {
41 {
42 .procname = "unprivileged_userfaultfd",
43 .data = &sysctl_unprivileged_userfaultfd,
44 .maxlen = sizeof(sysctl_unprivileged_userfaultfd),
45 .mode = 0644,
46 .proc_handler = proc_dointvec_minmax,
47 .extra1 = SYSCTL_ZERO,
48 .extra2 = SYSCTL_ONE,
49 },
50 };
51 #endif
52
53 static struct kmem_cache *userfaultfd_ctx_cachep __ro_after_init;
54
55 struct userfaultfd_fork_ctx {
56 struct userfaultfd_ctx *orig;
57 struct userfaultfd_ctx *new;
58 struct list_head list;
59 };
60
61 struct userfaultfd_unmap_ctx {
62 struct userfaultfd_ctx *ctx;
63 unsigned long start;
64 unsigned long end;
65 struct list_head list;
66 };
67
68 struct userfaultfd_wait_queue {
69 struct uffd_msg msg;
70 wait_queue_entry_t wq;
71 struct userfaultfd_ctx *ctx;
72 bool waken;
73 };
74
75 struct userfaultfd_wake_range {
76 unsigned long start;
77 unsigned long len;
78 };
79
80 /* internal indication that UFFD_API ioctl was successfully executed */
81 #define UFFD_FEATURE_INITIALIZED (1u << 31)
82
userfaultfd_is_initialized(struct userfaultfd_ctx * ctx)83 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
84 {
85 return ctx->features & UFFD_FEATURE_INITIALIZED;
86 }
87
userfaultfd_wp_async_ctx(struct userfaultfd_ctx * ctx)88 static bool userfaultfd_wp_async_ctx(struct userfaultfd_ctx *ctx)
89 {
90 return ctx && (ctx->features & UFFD_FEATURE_WP_ASYNC);
91 }
92
93 /*
94 * Whether WP_UNPOPULATED is enabled on the uffd context. It is only
95 * meaningful when userfaultfd_wp()==true on the vma and when it's
96 * anonymous.
97 */
userfaultfd_wp_unpopulated(struct vm_area_struct * vma)98 bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma)
99 {
100 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
101
102 if (!ctx)
103 return false;
104
105 return ctx->features & UFFD_FEATURE_WP_UNPOPULATED;
106 }
107
userfaultfd_wake_function(wait_queue_entry_t * wq,unsigned mode,int wake_flags,void * key)108 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
109 int wake_flags, void *key)
110 {
111 struct userfaultfd_wake_range *range = key;
112 int ret;
113 struct userfaultfd_wait_queue *uwq;
114 unsigned long start, len;
115
116 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
117 ret = 0;
118 /* len == 0 means wake all */
119 start = range->start;
120 len = range->len;
121 if (len && (start > uwq->msg.arg.pagefault.address ||
122 start + len <= uwq->msg.arg.pagefault.address))
123 goto out;
124 WRITE_ONCE(uwq->waken, true);
125 /*
126 * The Program-Order guarantees provided by the scheduler
127 * ensure uwq->waken is visible before the task is woken.
128 */
129 ret = wake_up_state(wq->private, mode);
130 if (ret) {
131 /*
132 * Wake only once, autoremove behavior.
133 *
134 * After the effect of list_del_init is visible to the other
135 * CPUs, the waitqueue may disappear from under us, see the
136 * !list_empty_careful() in handle_userfault().
137 *
138 * try_to_wake_up() has an implicit smp_mb(), and the
139 * wq->private is read before calling the extern function
140 * "wake_up_state" (which in turns calls try_to_wake_up).
141 */
142 list_del_init(&wq->entry);
143 }
144 out:
145 return ret;
146 }
147
148 /**
149 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
150 * context.
151 * @ctx: [in] Pointer to the userfaultfd context.
152 */
userfaultfd_ctx_get(struct userfaultfd_ctx * ctx)153 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
154 {
155 refcount_inc(&ctx->refcount);
156 }
157
158 /**
159 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
160 * context.
161 * @ctx: [in] Pointer to userfaultfd context.
162 *
163 * The userfaultfd context reference must have been previously acquired either
164 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
165 */
userfaultfd_ctx_put(struct userfaultfd_ctx * ctx)166 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
167 {
168 if (refcount_dec_and_test(&ctx->refcount)) {
169 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
170 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
171 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
172 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
173 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
174 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
175 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
176 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
177 mmdrop(ctx->mm);
178 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
179 }
180 }
181
msg_init(struct uffd_msg * msg)182 static inline void msg_init(struct uffd_msg *msg)
183 {
184 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
185 /*
186 * Must use memset to zero out the paddings or kernel data is
187 * leaked to userland.
188 */
189 memset(msg, 0, sizeof(struct uffd_msg));
190 }
191
userfault_msg(unsigned long address,unsigned long real_address,unsigned int flags,unsigned long reason,unsigned int features)192 static inline struct uffd_msg userfault_msg(unsigned long address,
193 unsigned long real_address,
194 unsigned int flags,
195 unsigned long reason,
196 unsigned int features)
197 {
198 struct uffd_msg msg;
199
200 msg_init(&msg);
201 msg.event = UFFD_EVENT_PAGEFAULT;
202
203 msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
204 real_address : address;
205
206 /*
207 * These flags indicate why the userfault occurred:
208 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
209 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
210 * - Neither of these flags being set indicates a MISSING fault.
211 *
212 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
213 * fault. Otherwise, it was a read fault.
214 */
215 if (flags & FAULT_FLAG_WRITE)
216 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
217 if (reason & VM_UFFD_WP)
218 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
219 if (reason & VM_UFFD_MINOR)
220 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
221 if (features & UFFD_FEATURE_THREAD_ID)
222 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
223 return msg;
224 }
225
226 #ifdef CONFIG_HUGETLB_PAGE
227 /*
228 * Same functionality as userfaultfd_must_wait below with modifications for
229 * hugepmd ranges.
230 */
userfaultfd_huge_must_wait(struct userfaultfd_ctx * ctx,struct vm_fault * vmf,unsigned long reason)231 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
232 struct vm_fault *vmf,
233 unsigned long reason)
234 {
235 struct vm_area_struct *vma = vmf->vma;
236 pte_t *ptep, pte;
237 bool ret = true;
238
239 assert_fault_locked(vmf);
240
241 ptep = hugetlb_walk(vma, vmf->address, vma_mmu_pagesize(vma));
242 if (!ptep)
243 goto out;
244
245 ret = false;
246 pte = huge_ptep_get(vma->vm_mm, vmf->address, ptep);
247
248 /*
249 * Lockless access: we're in a wait_event so it's ok if it
250 * changes under us. PTE markers should be handled the same as none
251 * ptes here.
252 */
253 if (huge_pte_none_mostly(pte))
254 ret = true;
255 if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
256 ret = true;
257 out:
258 return ret;
259 }
260 #else
userfaultfd_huge_must_wait(struct userfaultfd_ctx * ctx,struct vm_fault * vmf,unsigned long reason)261 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
262 struct vm_fault *vmf,
263 unsigned long reason)
264 {
265 return false; /* should never get here */
266 }
267 #endif /* CONFIG_HUGETLB_PAGE */
268
269 /*
270 * Verify the pagetables are still not ok after having reigstered into
271 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
272 * userfault that has already been resolved, if userfaultfd_read_iter and
273 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
274 * threads.
275 */
userfaultfd_must_wait(struct userfaultfd_ctx * ctx,struct vm_fault * vmf,unsigned long reason)276 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
277 struct vm_fault *vmf,
278 unsigned long reason)
279 {
280 struct mm_struct *mm = ctx->mm;
281 unsigned long address = vmf->address;
282 pgd_t *pgd;
283 p4d_t *p4d;
284 pud_t *pud;
285 pmd_t *pmd, _pmd;
286 pte_t *pte;
287 pte_t ptent;
288 bool ret = true;
289
290 assert_fault_locked(vmf);
291
292 pgd = pgd_offset(mm, address);
293 if (!pgd_present(*pgd))
294 goto out;
295 p4d = p4d_offset(pgd, address);
296 if (!p4d_present(*p4d))
297 goto out;
298 pud = pud_offset(p4d, address);
299 if (!pud_present(*pud))
300 goto out;
301 pmd = pmd_offset(pud, address);
302 again:
303 _pmd = pmdp_get_lockless(pmd);
304 if (pmd_none(_pmd))
305 goto out;
306
307 ret = false;
308 if (!pmd_present(_pmd) || pmd_devmap(_pmd))
309 goto out;
310
311 if (pmd_trans_huge(_pmd)) {
312 if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
313 ret = true;
314 goto out;
315 }
316
317 pte = pte_offset_map(pmd, address);
318 if (!pte) {
319 ret = true;
320 goto again;
321 }
322 /*
323 * Lockless access: we're in a wait_event so it's ok if it
324 * changes under us. PTE markers should be handled the same as none
325 * ptes here.
326 */
327 ptent = ptep_get(pte);
328 if (pte_none_mostly(ptent))
329 ret = true;
330 if (!pte_write(ptent) && (reason & VM_UFFD_WP))
331 ret = true;
332 pte_unmap(pte);
333
334 out:
335 return ret;
336 }
337
userfaultfd_get_blocking_state(unsigned int flags)338 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
339 {
340 if (flags & FAULT_FLAG_INTERRUPTIBLE)
341 return TASK_INTERRUPTIBLE;
342
343 if (flags & FAULT_FLAG_KILLABLE)
344 return TASK_KILLABLE;
345
346 return TASK_UNINTERRUPTIBLE;
347 }
348
349 /*
350 * The locking rules involved in returning VM_FAULT_RETRY depending on
351 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
352 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
353 * recommendation in __lock_page_or_retry is not an understatement.
354 *
355 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
356 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
357 * not set.
358 *
359 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
360 * set, VM_FAULT_RETRY can still be returned if and only if there are
361 * fatal_signal_pending()s, and the mmap_lock must be released before
362 * returning it.
363 */
handle_userfault(struct vm_fault * vmf,unsigned long reason)364 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
365 {
366 struct vm_area_struct *vma = vmf->vma;
367 struct mm_struct *mm = vma->vm_mm;
368 struct userfaultfd_ctx *ctx;
369 struct userfaultfd_wait_queue uwq;
370 vm_fault_t ret = VM_FAULT_SIGBUS;
371 bool must_wait;
372 unsigned int blocking_state;
373
374 /*
375 * We don't do userfault handling for the final child pid update
376 * and when coredumping (faults triggered by get_dump_page()).
377 */
378 if (current->flags & (PF_EXITING|PF_DUMPCORE))
379 goto out;
380
381 assert_fault_locked(vmf);
382
383 ctx = vma->vm_userfaultfd_ctx.ctx;
384 if (!ctx)
385 goto out;
386
387 BUG_ON(ctx->mm != mm);
388
389 /* Any unrecognized flag is a bug. */
390 VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
391 /* 0 or > 1 flags set is a bug; we expect exactly 1. */
392 VM_BUG_ON(!reason || (reason & (reason - 1)));
393
394 if (ctx->features & UFFD_FEATURE_SIGBUS)
395 goto out;
396 if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
397 goto out;
398
399 /*
400 * Check that we can return VM_FAULT_RETRY.
401 *
402 * NOTE: it should become possible to return VM_FAULT_RETRY
403 * even if FAULT_FLAG_TRIED is set without leading to gup()
404 * -EBUSY failures, if the userfaultfd is to be extended for
405 * VM_UFFD_WP tracking and we intend to arm the userfault
406 * without first stopping userland access to the memory. For
407 * VM_UFFD_MISSING userfaults this is enough for now.
408 */
409 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
410 /*
411 * Validate the invariant that nowait must allow retry
412 * to be sure not to return SIGBUS erroneously on
413 * nowait invocations.
414 */
415 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
416 #ifdef CONFIG_DEBUG_VM
417 if (printk_ratelimit()) {
418 printk(KERN_WARNING
419 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
420 vmf->flags);
421 dump_stack();
422 }
423 #endif
424 goto out;
425 }
426
427 /*
428 * Handle nowait, not much to do other than tell it to retry
429 * and wait.
430 */
431 ret = VM_FAULT_RETRY;
432 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
433 goto out;
434
435 if (unlikely(READ_ONCE(ctx->released))) {
436 /*
437 * If a concurrent release is detected, do not return
438 * VM_FAULT_SIGBUS or VM_FAULT_NOPAGE, but instead always
439 * return VM_FAULT_RETRY with lock released proactively.
440 *
441 * If we were to return VM_FAULT_SIGBUS here, the non
442 * cooperative manager would be instead forced to
443 * always call UFFDIO_UNREGISTER before it can safely
444 * close the uffd, to avoid involuntary SIGBUS triggered.
445 *
446 * If we were to return VM_FAULT_NOPAGE, it would work for
447 * the fault path, in which the lock will be released
448 * later. However for GUP, faultin_page() does nothing
449 * special on NOPAGE, so GUP would spin retrying without
450 * releasing the mmap read lock, causing possible livelock.
451 *
452 * Here only VM_FAULT_RETRY would make sure the mmap lock
453 * be released immediately, so that the thread concurrently
454 * releasing the userfault would always make progress.
455 */
456 release_fault_lock(vmf);
457 goto out;
458 }
459
460 /* take the reference before dropping the mmap_lock */
461 userfaultfd_ctx_get(ctx);
462
463 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
464 uwq.wq.private = current;
465 uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
466 reason, ctx->features);
467 uwq.ctx = ctx;
468 uwq.waken = false;
469
470 blocking_state = userfaultfd_get_blocking_state(vmf->flags);
471
472 /*
473 * Take the vma lock now, in order to safely call
474 * userfaultfd_huge_must_wait() later. Since acquiring the
475 * (sleepable) vma lock can modify the current task state, that
476 * must be before explicitly calling set_current_state().
477 */
478 if (is_vm_hugetlb_page(vma))
479 hugetlb_vma_lock_read(vma);
480
481 spin_lock_irq(&ctx->fault_pending_wqh.lock);
482 /*
483 * After the __add_wait_queue the uwq is visible to userland
484 * through poll/read().
485 */
486 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
487 /*
488 * The smp_mb() after __set_current_state prevents the reads
489 * following the spin_unlock to happen before the list_add in
490 * __add_wait_queue.
491 */
492 set_current_state(blocking_state);
493 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
494
495 if (!is_vm_hugetlb_page(vma))
496 must_wait = userfaultfd_must_wait(ctx, vmf, reason);
497 else
498 must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);
499 if (is_vm_hugetlb_page(vma))
500 hugetlb_vma_unlock_read(vma);
501 release_fault_lock(vmf);
502
503 if (likely(must_wait && !READ_ONCE(ctx->released))) {
504 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
505 schedule();
506 }
507
508 __set_current_state(TASK_RUNNING);
509
510 /*
511 * Here we race with the list_del; list_add in
512 * userfaultfd_ctx_read(), however because we don't ever run
513 * list_del_init() to refile across the two lists, the prev
514 * and next pointers will never point to self. list_add also
515 * would never let any of the two pointers to point to
516 * self. So list_empty_careful won't risk to see both pointers
517 * pointing to self at any time during the list refile. The
518 * only case where list_del_init() is called is the full
519 * removal in the wake function and there we don't re-list_add
520 * and it's fine not to block on the spinlock. The uwq on this
521 * kernel stack can be released after the list_del_init.
522 */
523 if (!list_empty_careful(&uwq.wq.entry)) {
524 spin_lock_irq(&ctx->fault_pending_wqh.lock);
525 /*
526 * No need of list_del_init(), the uwq on the stack
527 * will be freed shortly anyway.
528 */
529 list_del(&uwq.wq.entry);
530 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
531 }
532
533 /*
534 * ctx may go away after this if the userfault pseudo fd is
535 * already released.
536 */
537 userfaultfd_ctx_put(ctx);
538
539 out:
540 return ret;
541 }
542
userfaultfd_event_wait_completion(struct userfaultfd_ctx * ctx,struct userfaultfd_wait_queue * ewq)543 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
544 struct userfaultfd_wait_queue *ewq)
545 {
546 struct userfaultfd_ctx *release_new_ctx;
547
548 if (WARN_ON_ONCE(current->flags & PF_EXITING))
549 goto out;
550
551 ewq->ctx = ctx;
552 init_waitqueue_entry(&ewq->wq, current);
553 release_new_ctx = NULL;
554
555 spin_lock_irq(&ctx->event_wqh.lock);
556 /*
557 * After the __add_wait_queue the uwq is visible to userland
558 * through poll/read().
559 */
560 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
561 for (;;) {
562 set_current_state(TASK_KILLABLE);
563 if (ewq->msg.event == 0)
564 break;
565 if (READ_ONCE(ctx->released) ||
566 fatal_signal_pending(current)) {
567 /*
568 * &ewq->wq may be queued in fork_event, but
569 * __remove_wait_queue ignores the head
570 * parameter. It would be a problem if it
571 * didn't.
572 */
573 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
574 if (ewq->msg.event == UFFD_EVENT_FORK) {
575 struct userfaultfd_ctx *new;
576
577 new = (struct userfaultfd_ctx *)
578 (unsigned long)
579 ewq->msg.arg.reserved.reserved1;
580 release_new_ctx = new;
581 }
582 break;
583 }
584
585 spin_unlock_irq(&ctx->event_wqh.lock);
586
587 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
588 schedule();
589
590 spin_lock_irq(&ctx->event_wqh.lock);
591 }
592 __set_current_state(TASK_RUNNING);
593 spin_unlock_irq(&ctx->event_wqh.lock);
594
595 if (release_new_ctx) {
596 userfaultfd_release_new(release_new_ctx);
597 userfaultfd_ctx_put(release_new_ctx);
598 }
599
600 /*
601 * ctx may go away after this if the userfault pseudo fd is
602 * already released.
603 */
604 out:
605 atomic_dec(&ctx->mmap_changing);
606 VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
607 userfaultfd_ctx_put(ctx);
608 }
609
userfaultfd_event_complete(struct userfaultfd_ctx * ctx,struct userfaultfd_wait_queue * ewq)610 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
611 struct userfaultfd_wait_queue *ewq)
612 {
613 ewq->msg.event = 0;
614 wake_up_locked(&ctx->event_wqh);
615 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
616 }
617
dup_userfaultfd(struct vm_area_struct * vma,struct list_head * fcs)618 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
619 {
620 struct userfaultfd_ctx *ctx = NULL, *octx;
621 struct userfaultfd_fork_ctx *fctx;
622
623 octx = vma->vm_userfaultfd_ctx.ctx;
624 if (!octx)
625 return 0;
626
627 if (!(octx->features & UFFD_FEATURE_EVENT_FORK)) {
628 userfaultfd_reset_ctx(vma);
629 return 0;
630 }
631
632 list_for_each_entry(fctx, fcs, list)
633 if (fctx->orig == octx) {
634 ctx = fctx->new;
635 break;
636 }
637
638 if (!ctx) {
639 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
640 if (!fctx)
641 return -ENOMEM;
642
643 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
644 if (!ctx) {
645 kfree(fctx);
646 return -ENOMEM;
647 }
648
649 refcount_set(&ctx->refcount, 1);
650 ctx->flags = octx->flags;
651 ctx->features = octx->features;
652 ctx->released = false;
653 init_rwsem(&ctx->map_changing_lock);
654 atomic_set(&ctx->mmap_changing, 0);
655 ctx->mm = vma->vm_mm;
656 mmgrab(ctx->mm);
657
658 userfaultfd_ctx_get(octx);
659 down_write(&octx->map_changing_lock);
660 atomic_inc(&octx->mmap_changing);
661 up_write(&octx->map_changing_lock);
662 fctx->orig = octx;
663 fctx->new = ctx;
664 list_add_tail(&fctx->list, fcs);
665 }
666
667 vma->vm_userfaultfd_ctx.ctx = ctx;
668 return 0;
669 }
670
dup_fctx(struct userfaultfd_fork_ctx * fctx)671 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
672 {
673 struct userfaultfd_ctx *ctx = fctx->orig;
674 struct userfaultfd_wait_queue ewq;
675
676 msg_init(&ewq.msg);
677
678 ewq.msg.event = UFFD_EVENT_FORK;
679 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
680
681 userfaultfd_event_wait_completion(ctx, &ewq);
682 }
683
dup_userfaultfd_complete(struct list_head * fcs)684 void dup_userfaultfd_complete(struct list_head *fcs)
685 {
686 struct userfaultfd_fork_ctx *fctx, *n;
687
688 list_for_each_entry_safe(fctx, n, fcs, list) {
689 dup_fctx(fctx);
690 list_del(&fctx->list);
691 kfree(fctx);
692 }
693 }
694
dup_userfaultfd_fail(struct list_head * fcs)695 void dup_userfaultfd_fail(struct list_head *fcs)
696 {
697 struct userfaultfd_fork_ctx *fctx, *n;
698
699 /*
700 * An error has occurred on fork, we will tear memory down, but have
701 * allocated memory for fctx's and raised reference counts for both the
702 * original and child contexts (and on the mm for each as a result).
703 *
704 * These would ordinarily be taken care of by a user handling the event,
705 * but we are no longer doing so, so manually clean up here.
706 *
707 * mm tear down will take care of cleaning up VMA contexts.
708 */
709 list_for_each_entry_safe(fctx, n, fcs, list) {
710 struct userfaultfd_ctx *octx = fctx->orig;
711 struct userfaultfd_ctx *ctx = fctx->new;
712
713 atomic_dec(&octx->mmap_changing);
714 VM_BUG_ON(atomic_read(&octx->mmap_changing) < 0);
715 userfaultfd_ctx_put(octx);
716 userfaultfd_ctx_put(ctx);
717
718 list_del(&fctx->list);
719 kfree(fctx);
720 }
721 }
722
mremap_userfaultfd_prep(struct vm_area_struct * vma,struct vm_userfaultfd_ctx * vm_ctx)723 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
724 struct vm_userfaultfd_ctx *vm_ctx)
725 {
726 struct userfaultfd_ctx *ctx;
727
728 ctx = vma->vm_userfaultfd_ctx.ctx;
729
730 if (!ctx)
731 return;
732
733 if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
734 vm_ctx->ctx = ctx;
735 userfaultfd_ctx_get(ctx);
736 down_write(&ctx->map_changing_lock);
737 atomic_inc(&ctx->mmap_changing);
738 up_write(&ctx->map_changing_lock);
739 } else {
740 /* Drop uffd context if remap feature not enabled */
741 userfaultfd_reset_ctx(vma);
742 }
743 }
744
mremap_userfaultfd_complete(struct vm_userfaultfd_ctx * vm_ctx,unsigned long from,unsigned long to,unsigned long len)745 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
746 unsigned long from, unsigned long to,
747 unsigned long len)
748 {
749 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
750 struct userfaultfd_wait_queue ewq;
751
752 if (!ctx)
753 return;
754
755 if (to & ~PAGE_MASK) {
756 userfaultfd_ctx_put(ctx);
757 return;
758 }
759
760 msg_init(&ewq.msg);
761
762 ewq.msg.event = UFFD_EVENT_REMAP;
763 ewq.msg.arg.remap.from = from;
764 ewq.msg.arg.remap.to = to;
765 ewq.msg.arg.remap.len = len;
766
767 userfaultfd_event_wait_completion(ctx, &ewq);
768 }
769
userfaultfd_remove(struct vm_area_struct * vma,unsigned long start,unsigned long end)770 bool userfaultfd_remove(struct vm_area_struct *vma,
771 unsigned long start, unsigned long end)
772 {
773 struct mm_struct *mm = vma->vm_mm;
774 struct userfaultfd_ctx *ctx;
775 struct userfaultfd_wait_queue ewq;
776
777 ctx = vma->vm_userfaultfd_ctx.ctx;
778 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
779 return true;
780
781 userfaultfd_ctx_get(ctx);
782 down_write(&ctx->map_changing_lock);
783 atomic_inc(&ctx->mmap_changing);
784 up_write(&ctx->map_changing_lock);
785 mmap_read_unlock(mm);
786
787 msg_init(&ewq.msg);
788
789 ewq.msg.event = UFFD_EVENT_REMOVE;
790 ewq.msg.arg.remove.start = start;
791 ewq.msg.arg.remove.end = end;
792
793 userfaultfd_event_wait_completion(ctx, &ewq);
794
795 return false;
796 }
797
has_unmap_ctx(struct userfaultfd_ctx * ctx,struct list_head * unmaps,unsigned long start,unsigned long end)798 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
799 unsigned long start, unsigned long end)
800 {
801 struct userfaultfd_unmap_ctx *unmap_ctx;
802
803 list_for_each_entry(unmap_ctx, unmaps, list)
804 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
805 unmap_ctx->end == end)
806 return true;
807
808 return false;
809 }
810
userfaultfd_unmap_prep(struct vm_area_struct * vma,unsigned long start,unsigned long end,struct list_head * unmaps)811 int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start,
812 unsigned long end, struct list_head *unmaps)
813 {
814 struct userfaultfd_unmap_ctx *unmap_ctx;
815 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
816
817 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
818 has_unmap_ctx(ctx, unmaps, start, end))
819 return 0;
820
821 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
822 if (!unmap_ctx)
823 return -ENOMEM;
824
825 userfaultfd_ctx_get(ctx);
826 down_write(&ctx->map_changing_lock);
827 atomic_inc(&ctx->mmap_changing);
828 up_write(&ctx->map_changing_lock);
829 unmap_ctx->ctx = ctx;
830 unmap_ctx->start = start;
831 unmap_ctx->end = end;
832 list_add_tail(&unmap_ctx->list, unmaps);
833
834 return 0;
835 }
836
userfaultfd_unmap_complete(struct mm_struct * mm,struct list_head * uf)837 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
838 {
839 struct userfaultfd_unmap_ctx *ctx, *n;
840 struct userfaultfd_wait_queue ewq;
841
842 list_for_each_entry_safe(ctx, n, uf, list) {
843 msg_init(&ewq.msg);
844
845 ewq.msg.event = UFFD_EVENT_UNMAP;
846 ewq.msg.arg.remove.start = ctx->start;
847 ewq.msg.arg.remove.end = ctx->end;
848
849 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
850
851 list_del(&ctx->list);
852 kfree(ctx);
853 }
854 }
855
userfaultfd_release(struct inode * inode,struct file * file)856 static int userfaultfd_release(struct inode *inode, struct file *file)
857 {
858 struct userfaultfd_ctx *ctx = file->private_data;
859 struct mm_struct *mm = ctx->mm;
860 /* len == 0 means wake all */
861 struct userfaultfd_wake_range range = { .len = 0, };
862
863 WRITE_ONCE(ctx->released, true);
864
865 userfaultfd_release_all(mm, ctx);
866
867 /*
868 * After no new page faults can wait on this fault_*wqh, flush
869 * the last page faults that may have been already waiting on
870 * the fault_*wqh.
871 */
872 spin_lock_irq(&ctx->fault_pending_wqh.lock);
873 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
874 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
875 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
876
877 /* Flush pending events that may still wait on event_wqh */
878 wake_up_all(&ctx->event_wqh);
879
880 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
881 userfaultfd_ctx_put(ctx);
882 return 0;
883 }
884
885 /* fault_pending_wqh.lock must be hold by the caller */
find_userfault_in(wait_queue_head_t * wqh)886 static inline struct userfaultfd_wait_queue *find_userfault_in(
887 wait_queue_head_t *wqh)
888 {
889 wait_queue_entry_t *wq;
890 struct userfaultfd_wait_queue *uwq;
891
892 lockdep_assert_held(&wqh->lock);
893
894 uwq = NULL;
895 if (!waitqueue_active(wqh))
896 goto out;
897 /* walk in reverse to provide FIFO behavior to read userfaults */
898 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
899 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
900 out:
901 return uwq;
902 }
903
find_userfault(struct userfaultfd_ctx * ctx)904 static inline struct userfaultfd_wait_queue *find_userfault(
905 struct userfaultfd_ctx *ctx)
906 {
907 return find_userfault_in(&ctx->fault_pending_wqh);
908 }
909
find_userfault_evt(struct userfaultfd_ctx * ctx)910 static inline struct userfaultfd_wait_queue *find_userfault_evt(
911 struct userfaultfd_ctx *ctx)
912 {
913 return find_userfault_in(&ctx->event_wqh);
914 }
915
userfaultfd_poll(struct file * file,poll_table * wait)916 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
917 {
918 struct userfaultfd_ctx *ctx = file->private_data;
919 __poll_t ret;
920
921 poll_wait(file, &ctx->fd_wqh, wait);
922
923 if (!userfaultfd_is_initialized(ctx))
924 return EPOLLERR;
925
926 /*
927 * poll() never guarantees that read won't block.
928 * userfaults can be waken before they're read().
929 */
930 if (unlikely(!(file->f_flags & O_NONBLOCK)))
931 return EPOLLERR;
932 /*
933 * lockless access to see if there are pending faults
934 * __pollwait last action is the add_wait_queue but
935 * the spin_unlock would allow the waitqueue_active to
936 * pass above the actual list_add inside
937 * add_wait_queue critical section. So use a full
938 * memory barrier to serialize the list_add write of
939 * add_wait_queue() with the waitqueue_active read
940 * below.
941 */
942 ret = 0;
943 smp_mb();
944 if (waitqueue_active(&ctx->fault_pending_wqh))
945 ret = EPOLLIN;
946 else if (waitqueue_active(&ctx->event_wqh))
947 ret = EPOLLIN;
948
949 return ret;
950 }
951
952 static const struct file_operations userfaultfd_fops;
953
resolve_userfault_fork(struct userfaultfd_ctx * new,struct inode * inode,struct uffd_msg * msg)954 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
955 struct inode *inode,
956 struct uffd_msg *msg)
957 {
958 int fd;
959
960 fd = anon_inode_create_getfd("[userfaultfd]", &userfaultfd_fops, new,
961 O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
962 if (fd < 0)
963 return fd;
964
965 msg->arg.reserved.reserved1 = 0;
966 msg->arg.fork.ufd = fd;
967 return 0;
968 }
969
userfaultfd_ctx_read(struct userfaultfd_ctx * ctx,int no_wait,struct uffd_msg * msg,struct inode * inode)970 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
971 struct uffd_msg *msg, struct inode *inode)
972 {
973 ssize_t ret;
974 DECLARE_WAITQUEUE(wait, current);
975 struct userfaultfd_wait_queue *uwq;
976 /*
977 * Handling fork event requires sleeping operations, so
978 * we drop the event_wqh lock, then do these ops, then
979 * lock it back and wake up the waiter. While the lock is
980 * dropped the ewq may go away so we keep track of it
981 * carefully.
982 */
983 LIST_HEAD(fork_event);
984 struct userfaultfd_ctx *fork_nctx = NULL;
985
986 /* always take the fd_wqh lock before the fault_pending_wqh lock */
987 spin_lock_irq(&ctx->fd_wqh.lock);
988 __add_wait_queue(&ctx->fd_wqh, &wait);
989 for (;;) {
990 set_current_state(TASK_INTERRUPTIBLE);
991 spin_lock(&ctx->fault_pending_wqh.lock);
992 uwq = find_userfault(ctx);
993 if (uwq) {
994 /*
995 * Use a seqcount to repeat the lockless check
996 * in wake_userfault() to avoid missing
997 * wakeups because during the refile both
998 * waitqueue could become empty if this is the
999 * only userfault.
1000 */
1001 write_seqcount_begin(&ctx->refile_seq);
1002
1003 /*
1004 * The fault_pending_wqh.lock prevents the uwq
1005 * to disappear from under us.
1006 *
1007 * Refile this userfault from
1008 * fault_pending_wqh to fault_wqh, it's not
1009 * pending anymore after we read it.
1010 *
1011 * Use list_del() by hand (as
1012 * userfaultfd_wake_function also uses
1013 * list_del_init() by hand) to be sure nobody
1014 * changes __remove_wait_queue() to use
1015 * list_del_init() in turn breaking the
1016 * !list_empty_careful() check in
1017 * handle_userfault(). The uwq->wq.head list
1018 * must never be empty at any time during the
1019 * refile, or the waitqueue could disappear
1020 * from under us. The "wait_queue_head_t"
1021 * parameter of __remove_wait_queue() is unused
1022 * anyway.
1023 */
1024 list_del(&uwq->wq.entry);
1025 add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1026
1027 write_seqcount_end(&ctx->refile_seq);
1028
1029 /* careful to always initialize msg if ret == 0 */
1030 *msg = uwq->msg;
1031 spin_unlock(&ctx->fault_pending_wqh.lock);
1032 ret = 0;
1033 break;
1034 }
1035 spin_unlock(&ctx->fault_pending_wqh.lock);
1036
1037 spin_lock(&ctx->event_wqh.lock);
1038 uwq = find_userfault_evt(ctx);
1039 if (uwq) {
1040 *msg = uwq->msg;
1041
1042 if (uwq->msg.event == UFFD_EVENT_FORK) {
1043 fork_nctx = (struct userfaultfd_ctx *)
1044 (unsigned long)
1045 uwq->msg.arg.reserved.reserved1;
1046 list_move(&uwq->wq.entry, &fork_event);
1047 /*
1048 * fork_nctx can be freed as soon as
1049 * we drop the lock, unless we take a
1050 * reference on it.
1051 */
1052 userfaultfd_ctx_get(fork_nctx);
1053 spin_unlock(&ctx->event_wqh.lock);
1054 ret = 0;
1055 break;
1056 }
1057
1058 userfaultfd_event_complete(ctx, uwq);
1059 spin_unlock(&ctx->event_wqh.lock);
1060 ret = 0;
1061 break;
1062 }
1063 spin_unlock(&ctx->event_wqh.lock);
1064
1065 if (signal_pending(current)) {
1066 ret = -ERESTARTSYS;
1067 break;
1068 }
1069 if (no_wait) {
1070 ret = -EAGAIN;
1071 break;
1072 }
1073 spin_unlock_irq(&ctx->fd_wqh.lock);
1074 schedule();
1075 spin_lock_irq(&ctx->fd_wqh.lock);
1076 }
1077 __remove_wait_queue(&ctx->fd_wqh, &wait);
1078 __set_current_state(TASK_RUNNING);
1079 spin_unlock_irq(&ctx->fd_wqh.lock);
1080
1081 if (!ret && msg->event == UFFD_EVENT_FORK) {
1082 ret = resolve_userfault_fork(fork_nctx, inode, msg);
1083 spin_lock_irq(&ctx->event_wqh.lock);
1084 if (!list_empty(&fork_event)) {
1085 /*
1086 * The fork thread didn't abort, so we can
1087 * drop the temporary refcount.
1088 */
1089 userfaultfd_ctx_put(fork_nctx);
1090
1091 uwq = list_first_entry(&fork_event,
1092 typeof(*uwq),
1093 wq.entry);
1094 /*
1095 * If fork_event list wasn't empty and in turn
1096 * the event wasn't already released by fork
1097 * (the event is allocated on fork kernel
1098 * stack), put the event back to its place in
1099 * the event_wq. fork_event head will be freed
1100 * as soon as we return so the event cannot
1101 * stay queued there no matter the current
1102 * "ret" value.
1103 */
1104 list_del(&uwq->wq.entry);
1105 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1106
1107 /*
1108 * Leave the event in the waitqueue and report
1109 * error to userland if we failed to resolve
1110 * the userfault fork.
1111 */
1112 if (likely(!ret))
1113 userfaultfd_event_complete(ctx, uwq);
1114 } else {
1115 /*
1116 * Here the fork thread aborted and the
1117 * refcount from the fork thread on fork_nctx
1118 * has already been released. We still hold
1119 * the reference we took before releasing the
1120 * lock above. If resolve_userfault_fork
1121 * failed we've to drop it because the
1122 * fork_nctx has to be freed in such case. If
1123 * it succeeded we'll hold it because the new
1124 * uffd references it.
1125 */
1126 if (ret)
1127 userfaultfd_ctx_put(fork_nctx);
1128 }
1129 spin_unlock_irq(&ctx->event_wqh.lock);
1130 }
1131
1132 return ret;
1133 }
1134
userfaultfd_read_iter(struct kiocb * iocb,struct iov_iter * to)1135 static ssize_t userfaultfd_read_iter(struct kiocb *iocb, struct iov_iter *to)
1136 {
1137 struct file *file = iocb->ki_filp;
1138 struct userfaultfd_ctx *ctx = file->private_data;
1139 ssize_t _ret, ret = 0;
1140 struct uffd_msg msg;
1141 struct inode *inode = file_inode(file);
1142 bool no_wait;
1143
1144 if (!userfaultfd_is_initialized(ctx))
1145 return -EINVAL;
1146
1147 no_wait = file->f_flags & O_NONBLOCK || iocb->ki_flags & IOCB_NOWAIT;
1148 for (;;) {
1149 if (iov_iter_count(to) < sizeof(msg))
1150 return ret ? ret : -EINVAL;
1151 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1152 if (_ret < 0)
1153 return ret ? ret : _ret;
1154 _ret = !copy_to_iter_full(&msg, sizeof(msg), to);
1155 if (_ret)
1156 return ret ? ret : -EFAULT;
1157 ret += sizeof(msg);
1158 /*
1159 * Allow to read more than one fault at time but only
1160 * block if waiting for the very first one.
1161 */
1162 no_wait = true;
1163 }
1164 }
1165
__wake_userfault(struct userfaultfd_ctx * ctx,struct userfaultfd_wake_range * range)1166 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1167 struct userfaultfd_wake_range *range)
1168 {
1169 spin_lock_irq(&ctx->fault_pending_wqh.lock);
1170 /* wake all in the range and autoremove */
1171 if (waitqueue_active(&ctx->fault_pending_wqh))
1172 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1173 range);
1174 if (waitqueue_active(&ctx->fault_wqh))
1175 __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1176 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1177 }
1178
wake_userfault(struct userfaultfd_ctx * ctx,struct userfaultfd_wake_range * range)1179 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1180 struct userfaultfd_wake_range *range)
1181 {
1182 unsigned seq;
1183 bool need_wakeup;
1184
1185 /*
1186 * To be sure waitqueue_active() is not reordered by the CPU
1187 * before the pagetable update, use an explicit SMP memory
1188 * barrier here. PT lock release or mmap_read_unlock(mm) still
1189 * have release semantics that can allow the
1190 * waitqueue_active() to be reordered before the pte update.
1191 */
1192 smp_mb();
1193
1194 /*
1195 * Use waitqueue_active because it's very frequent to
1196 * change the address space atomically even if there are no
1197 * userfaults yet. So we take the spinlock only when we're
1198 * sure we've userfaults to wake.
1199 */
1200 do {
1201 seq = read_seqcount_begin(&ctx->refile_seq);
1202 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1203 waitqueue_active(&ctx->fault_wqh);
1204 cond_resched();
1205 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1206 if (need_wakeup)
1207 __wake_userfault(ctx, range);
1208 }
1209
validate_unaligned_range(struct mm_struct * mm,__u64 start,__u64 len)1210 static __always_inline int validate_unaligned_range(
1211 struct mm_struct *mm, __u64 start, __u64 len)
1212 {
1213 __u64 task_size = mm->task_size;
1214
1215 if (len & ~PAGE_MASK)
1216 return -EINVAL;
1217 if (!len)
1218 return -EINVAL;
1219 if (start < mmap_min_addr)
1220 return -EINVAL;
1221 if (start >= task_size)
1222 return -EINVAL;
1223 if (len > task_size - start)
1224 return -EINVAL;
1225 if (start + len <= start)
1226 return -EINVAL;
1227 return 0;
1228 }
1229
validate_range(struct mm_struct * mm,__u64 start,__u64 len)1230 static __always_inline int validate_range(struct mm_struct *mm,
1231 __u64 start, __u64 len)
1232 {
1233 if (start & ~PAGE_MASK)
1234 return -EINVAL;
1235
1236 return validate_unaligned_range(mm, start, len);
1237 }
1238
userfaultfd_register(struct userfaultfd_ctx * ctx,unsigned long arg)1239 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1240 unsigned long arg)
1241 {
1242 struct mm_struct *mm = ctx->mm;
1243 struct vm_area_struct *vma, *cur;
1244 int ret;
1245 struct uffdio_register uffdio_register;
1246 struct uffdio_register __user *user_uffdio_register;
1247 unsigned long vm_flags;
1248 bool found;
1249 bool basic_ioctls;
1250 unsigned long start, end;
1251 struct vma_iterator vmi;
1252 bool wp_async = userfaultfd_wp_async_ctx(ctx);
1253
1254 user_uffdio_register = (struct uffdio_register __user *) arg;
1255
1256 ret = -EFAULT;
1257 if (copy_from_user(&uffdio_register, user_uffdio_register,
1258 sizeof(uffdio_register)-sizeof(__u64)))
1259 goto out;
1260
1261 ret = -EINVAL;
1262 if (!uffdio_register.mode)
1263 goto out;
1264 if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1265 goto out;
1266 vm_flags = 0;
1267 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1268 vm_flags |= VM_UFFD_MISSING;
1269 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1270 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1271 goto out;
1272 #endif
1273 vm_flags |= VM_UFFD_WP;
1274 }
1275 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1276 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1277 goto out;
1278 #endif
1279 vm_flags |= VM_UFFD_MINOR;
1280 }
1281
1282 ret = validate_range(mm, uffdio_register.range.start,
1283 uffdio_register.range.len);
1284 if (ret)
1285 goto out;
1286
1287 start = uffdio_register.range.start;
1288 end = start + uffdio_register.range.len;
1289
1290 ret = -ENOMEM;
1291 if (!mmget_not_zero(mm))
1292 goto out;
1293
1294 ret = -EINVAL;
1295 mmap_write_lock(mm);
1296 vma_iter_init(&vmi, mm, start);
1297 vma = vma_find(&vmi, end);
1298 if (!vma)
1299 goto out_unlock;
1300
1301 /*
1302 * If the first vma contains huge pages, make sure start address
1303 * is aligned to huge page size.
1304 */
1305 if (is_vm_hugetlb_page(vma)) {
1306 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1307
1308 if (start & (vma_hpagesize - 1))
1309 goto out_unlock;
1310 }
1311
1312 /*
1313 * Search for not compatible vmas.
1314 */
1315 found = false;
1316 basic_ioctls = false;
1317 cur = vma;
1318 do {
1319 cond_resched();
1320
1321 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1322 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1323
1324 /* check not compatible vmas */
1325 ret = -EINVAL;
1326 if (!vma_can_userfault(cur, vm_flags, wp_async))
1327 goto out_unlock;
1328
1329 /*
1330 * UFFDIO_COPY will fill file holes even without
1331 * PROT_WRITE. This check enforces that if this is a
1332 * MAP_SHARED, the process has write permission to the backing
1333 * file. If VM_MAYWRITE is set it also enforces that on a
1334 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1335 * F_WRITE_SEAL can be taken until the vma is destroyed.
1336 */
1337 ret = -EPERM;
1338 if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1339 goto out_unlock;
1340
1341 /*
1342 * If this vma contains ending address, and huge pages
1343 * check alignment.
1344 */
1345 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1346 end > cur->vm_start) {
1347 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1348
1349 ret = -EINVAL;
1350
1351 if (end & (vma_hpagesize - 1))
1352 goto out_unlock;
1353 }
1354 if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1355 goto out_unlock;
1356
1357 /*
1358 * Check that this vma isn't already owned by a
1359 * different userfaultfd. We can't allow more than one
1360 * userfaultfd to own a single vma simultaneously or we
1361 * wouldn't know which one to deliver the userfaults to.
1362 */
1363 ret = -EBUSY;
1364 if (cur->vm_userfaultfd_ctx.ctx &&
1365 cur->vm_userfaultfd_ctx.ctx != ctx)
1366 goto out_unlock;
1367
1368 /*
1369 * Note vmas containing huge pages
1370 */
1371 if (is_vm_hugetlb_page(cur))
1372 basic_ioctls = true;
1373
1374 found = true;
1375 } for_each_vma_range(vmi, cur, end);
1376 BUG_ON(!found);
1377
1378 ret = userfaultfd_register_range(ctx, vma, vm_flags, start, end,
1379 wp_async);
1380
1381 out_unlock:
1382 mmap_write_unlock(mm);
1383 mmput(mm);
1384 if (!ret) {
1385 __u64 ioctls_out;
1386
1387 ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1388 UFFD_API_RANGE_IOCTLS;
1389
1390 /*
1391 * Declare the WP ioctl only if the WP mode is
1392 * specified and all checks passed with the range
1393 */
1394 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1395 ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1396
1397 /* CONTINUE ioctl is only supported for MINOR ranges. */
1398 if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1399 ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1400
1401 /*
1402 * Now that we scanned all vmas we can already tell
1403 * userland which ioctls methods are guaranteed to
1404 * succeed on this range.
1405 */
1406 if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1407 ret = -EFAULT;
1408 }
1409 out:
1410 return ret;
1411 }
1412
userfaultfd_unregister(struct userfaultfd_ctx * ctx,unsigned long arg)1413 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1414 unsigned long arg)
1415 {
1416 struct mm_struct *mm = ctx->mm;
1417 struct vm_area_struct *vma, *prev, *cur;
1418 int ret;
1419 struct uffdio_range uffdio_unregister;
1420 bool found;
1421 unsigned long start, end, vma_end;
1422 const void __user *buf = (void __user *)arg;
1423 struct vma_iterator vmi;
1424 bool wp_async = userfaultfd_wp_async_ctx(ctx);
1425
1426 ret = -EFAULT;
1427 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1428 goto out;
1429
1430 ret = validate_range(mm, uffdio_unregister.start,
1431 uffdio_unregister.len);
1432 if (ret)
1433 goto out;
1434
1435 start = uffdio_unregister.start;
1436 end = start + uffdio_unregister.len;
1437
1438 ret = -ENOMEM;
1439 if (!mmget_not_zero(mm))
1440 goto out;
1441
1442 mmap_write_lock(mm);
1443 ret = -EINVAL;
1444 vma_iter_init(&vmi, mm, start);
1445 vma = vma_find(&vmi, end);
1446 if (!vma)
1447 goto out_unlock;
1448
1449 /*
1450 * If the first vma contains huge pages, make sure start address
1451 * is aligned to huge page size.
1452 */
1453 if (is_vm_hugetlb_page(vma)) {
1454 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1455
1456 if (start & (vma_hpagesize - 1))
1457 goto out_unlock;
1458 }
1459
1460 /*
1461 * Search for not compatible vmas.
1462 */
1463 found = false;
1464 cur = vma;
1465 do {
1466 cond_resched();
1467
1468 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1469 !!(cur->vm_flags & __VM_UFFD_FLAGS));
1470
1471 /*
1472 * Check not compatible vmas, not strictly required
1473 * here as not compatible vmas cannot have an
1474 * userfaultfd_ctx registered on them, but this
1475 * provides for more strict behavior to notice
1476 * unregistration errors.
1477 */
1478 if (!vma_can_userfault(cur, cur->vm_flags, wp_async))
1479 goto out_unlock;
1480
1481 found = true;
1482 } for_each_vma_range(vmi, cur, end);
1483 BUG_ON(!found);
1484
1485 vma_iter_set(&vmi, start);
1486 prev = vma_prev(&vmi);
1487 if (vma->vm_start < start)
1488 prev = vma;
1489
1490 ret = 0;
1491 for_each_vma_range(vmi, vma, end) {
1492 cond_resched();
1493
1494 BUG_ON(!vma_can_userfault(vma, vma->vm_flags, wp_async));
1495
1496 /*
1497 * Nothing to do: this vma is already registered into this
1498 * userfaultfd and with the right tracking mode too.
1499 */
1500 if (!vma->vm_userfaultfd_ctx.ctx)
1501 goto skip;
1502
1503 WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
1504
1505 if (vma->vm_start > start)
1506 start = vma->vm_start;
1507 vma_end = min(end, vma->vm_end);
1508
1509 if (userfaultfd_missing(vma)) {
1510 /*
1511 * Wake any concurrent pending userfault while
1512 * we unregister, so they will not hang
1513 * permanently and it avoids userland to call
1514 * UFFDIO_WAKE explicitly.
1515 */
1516 struct userfaultfd_wake_range range;
1517 range.start = start;
1518 range.len = vma_end - start;
1519 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1520 }
1521
1522 vma = userfaultfd_clear_vma(&vmi, prev, vma,
1523 start, vma_end);
1524 if (IS_ERR(vma)) {
1525 ret = PTR_ERR(vma);
1526 break;
1527 }
1528
1529 skip:
1530 prev = vma;
1531 start = vma->vm_end;
1532 }
1533
1534 out_unlock:
1535 mmap_write_unlock(mm);
1536 mmput(mm);
1537 out:
1538 return ret;
1539 }
1540
1541 /*
1542 * userfaultfd_wake may be used in combination with the
1543 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1544 */
userfaultfd_wake(struct userfaultfd_ctx * ctx,unsigned long arg)1545 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1546 unsigned long arg)
1547 {
1548 int ret;
1549 struct uffdio_range uffdio_wake;
1550 struct userfaultfd_wake_range range;
1551 const void __user *buf = (void __user *)arg;
1552
1553 ret = -EFAULT;
1554 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1555 goto out;
1556
1557 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1558 if (ret)
1559 goto out;
1560
1561 range.start = uffdio_wake.start;
1562 range.len = uffdio_wake.len;
1563
1564 /*
1565 * len == 0 means wake all and we don't want to wake all here,
1566 * so check it again to be sure.
1567 */
1568 VM_BUG_ON(!range.len);
1569
1570 wake_userfault(ctx, &range);
1571 ret = 0;
1572
1573 out:
1574 return ret;
1575 }
1576
userfaultfd_copy(struct userfaultfd_ctx * ctx,unsigned long arg)1577 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1578 unsigned long arg)
1579 {
1580 __s64 ret;
1581 struct uffdio_copy uffdio_copy;
1582 struct uffdio_copy __user *user_uffdio_copy;
1583 struct userfaultfd_wake_range range;
1584 uffd_flags_t flags = 0;
1585
1586 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1587
1588 ret = -EAGAIN;
1589 if (unlikely(atomic_read(&ctx->mmap_changing))) {
1590 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1591 return -EFAULT;
1592 goto out;
1593 }
1594
1595 ret = -EFAULT;
1596 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1597 /* don't copy "copy" last field */
1598 sizeof(uffdio_copy)-sizeof(__s64)))
1599 goto out;
1600
1601 ret = validate_unaligned_range(ctx->mm, uffdio_copy.src,
1602 uffdio_copy.len);
1603 if (ret)
1604 goto out;
1605 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1606 if (ret)
1607 goto out;
1608
1609 ret = -EINVAL;
1610 if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1611 goto out;
1612 if (uffdio_copy.mode & UFFDIO_COPY_MODE_WP)
1613 flags |= MFILL_ATOMIC_WP;
1614 if (mmget_not_zero(ctx->mm)) {
1615 ret = mfill_atomic_copy(ctx, uffdio_copy.dst, uffdio_copy.src,
1616 uffdio_copy.len, flags);
1617 mmput(ctx->mm);
1618 } else {
1619 return -ESRCH;
1620 }
1621 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1622 return -EFAULT;
1623 if (ret < 0)
1624 goto out;
1625 BUG_ON(!ret);
1626 /* len == 0 would wake all */
1627 range.len = ret;
1628 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1629 range.start = uffdio_copy.dst;
1630 wake_userfault(ctx, &range);
1631 }
1632 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1633 out:
1634 return ret;
1635 }
1636
userfaultfd_zeropage(struct userfaultfd_ctx * ctx,unsigned long arg)1637 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1638 unsigned long arg)
1639 {
1640 __s64 ret;
1641 struct uffdio_zeropage uffdio_zeropage;
1642 struct uffdio_zeropage __user *user_uffdio_zeropage;
1643 struct userfaultfd_wake_range range;
1644
1645 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1646
1647 ret = -EAGAIN;
1648 if (unlikely(atomic_read(&ctx->mmap_changing))) {
1649 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1650 return -EFAULT;
1651 goto out;
1652 }
1653
1654 ret = -EFAULT;
1655 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1656 /* don't copy "zeropage" last field */
1657 sizeof(uffdio_zeropage)-sizeof(__s64)))
1658 goto out;
1659
1660 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1661 uffdio_zeropage.range.len);
1662 if (ret)
1663 goto out;
1664 ret = -EINVAL;
1665 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1666 goto out;
1667
1668 if (mmget_not_zero(ctx->mm)) {
1669 ret = mfill_atomic_zeropage(ctx, uffdio_zeropage.range.start,
1670 uffdio_zeropage.range.len);
1671 mmput(ctx->mm);
1672 } else {
1673 return -ESRCH;
1674 }
1675 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1676 return -EFAULT;
1677 if (ret < 0)
1678 goto out;
1679 /* len == 0 would wake all */
1680 BUG_ON(!ret);
1681 range.len = ret;
1682 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1683 range.start = uffdio_zeropage.range.start;
1684 wake_userfault(ctx, &range);
1685 }
1686 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1687 out:
1688 return ret;
1689 }
1690
userfaultfd_writeprotect(struct userfaultfd_ctx * ctx,unsigned long arg)1691 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1692 unsigned long arg)
1693 {
1694 int ret;
1695 struct uffdio_writeprotect uffdio_wp;
1696 struct uffdio_writeprotect __user *user_uffdio_wp;
1697 struct userfaultfd_wake_range range;
1698 bool mode_wp, mode_dontwake;
1699
1700 if (atomic_read(&ctx->mmap_changing))
1701 return -EAGAIN;
1702
1703 user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1704
1705 if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1706 sizeof(struct uffdio_writeprotect)))
1707 return -EFAULT;
1708
1709 ret = validate_range(ctx->mm, uffdio_wp.range.start,
1710 uffdio_wp.range.len);
1711 if (ret)
1712 return ret;
1713
1714 if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1715 UFFDIO_WRITEPROTECT_MODE_WP))
1716 return -EINVAL;
1717
1718 mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1719 mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1720
1721 if (mode_wp && mode_dontwake)
1722 return -EINVAL;
1723
1724 if (mmget_not_zero(ctx->mm)) {
1725 ret = mwriteprotect_range(ctx, uffdio_wp.range.start,
1726 uffdio_wp.range.len, mode_wp);
1727 mmput(ctx->mm);
1728 } else {
1729 return -ESRCH;
1730 }
1731
1732 if (ret)
1733 return ret;
1734
1735 if (!mode_wp && !mode_dontwake) {
1736 range.start = uffdio_wp.range.start;
1737 range.len = uffdio_wp.range.len;
1738 wake_userfault(ctx, &range);
1739 }
1740 return ret;
1741 }
1742
userfaultfd_continue(struct userfaultfd_ctx * ctx,unsigned long arg)1743 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1744 {
1745 __s64 ret;
1746 struct uffdio_continue uffdio_continue;
1747 struct uffdio_continue __user *user_uffdio_continue;
1748 struct userfaultfd_wake_range range;
1749 uffd_flags_t flags = 0;
1750
1751 user_uffdio_continue = (struct uffdio_continue __user *)arg;
1752
1753 ret = -EAGAIN;
1754 if (unlikely(atomic_read(&ctx->mmap_changing))) {
1755 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1756 return -EFAULT;
1757 goto out;
1758 }
1759
1760 ret = -EFAULT;
1761 if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1762 /* don't copy the output fields */
1763 sizeof(uffdio_continue) - (sizeof(__s64))))
1764 goto out;
1765
1766 ret = validate_range(ctx->mm, uffdio_continue.range.start,
1767 uffdio_continue.range.len);
1768 if (ret)
1769 goto out;
1770
1771 ret = -EINVAL;
1772 if (uffdio_continue.mode & ~(UFFDIO_CONTINUE_MODE_DONTWAKE |
1773 UFFDIO_CONTINUE_MODE_WP))
1774 goto out;
1775 if (uffdio_continue.mode & UFFDIO_CONTINUE_MODE_WP)
1776 flags |= MFILL_ATOMIC_WP;
1777
1778 if (mmget_not_zero(ctx->mm)) {
1779 ret = mfill_atomic_continue(ctx, uffdio_continue.range.start,
1780 uffdio_continue.range.len, flags);
1781 mmput(ctx->mm);
1782 } else {
1783 return -ESRCH;
1784 }
1785
1786 if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1787 return -EFAULT;
1788 if (ret < 0)
1789 goto out;
1790
1791 /* len == 0 would wake all */
1792 BUG_ON(!ret);
1793 range.len = ret;
1794 if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1795 range.start = uffdio_continue.range.start;
1796 wake_userfault(ctx, &range);
1797 }
1798 ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1799
1800 out:
1801 return ret;
1802 }
1803
userfaultfd_poison(struct userfaultfd_ctx * ctx,unsigned long arg)1804 static inline int userfaultfd_poison(struct userfaultfd_ctx *ctx, unsigned long arg)
1805 {
1806 __s64 ret;
1807 struct uffdio_poison uffdio_poison;
1808 struct uffdio_poison __user *user_uffdio_poison;
1809 struct userfaultfd_wake_range range;
1810
1811 user_uffdio_poison = (struct uffdio_poison __user *)arg;
1812
1813 ret = -EAGAIN;
1814 if (unlikely(atomic_read(&ctx->mmap_changing))) {
1815 if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
1816 return -EFAULT;
1817 goto out;
1818 }
1819
1820 ret = -EFAULT;
1821 if (copy_from_user(&uffdio_poison, user_uffdio_poison,
1822 /* don't copy the output fields */
1823 sizeof(uffdio_poison) - (sizeof(__s64))))
1824 goto out;
1825
1826 ret = validate_range(ctx->mm, uffdio_poison.range.start,
1827 uffdio_poison.range.len);
1828 if (ret)
1829 goto out;
1830
1831 ret = -EINVAL;
1832 if (uffdio_poison.mode & ~UFFDIO_POISON_MODE_DONTWAKE)
1833 goto out;
1834
1835 if (mmget_not_zero(ctx->mm)) {
1836 ret = mfill_atomic_poison(ctx, uffdio_poison.range.start,
1837 uffdio_poison.range.len, 0);
1838 mmput(ctx->mm);
1839 } else {
1840 return -ESRCH;
1841 }
1842
1843 if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
1844 return -EFAULT;
1845 if (ret < 0)
1846 goto out;
1847
1848 /* len == 0 would wake all */
1849 BUG_ON(!ret);
1850 range.len = ret;
1851 if (!(uffdio_poison.mode & UFFDIO_POISON_MODE_DONTWAKE)) {
1852 range.start = uffdio_poison.range.start;
1853 wake_userfault(ctx, &range);
1854 }
1855 ret = range.len == uffdio_poison.range.len ? 0 : -EAGAIN;
1856
1857 out:
1858 return ret;
1859 }
1860
userfaultfd_wp_async(struct vm_area_struct * vma)1861 bool userfaultfd_wp_async(struct vm_area_struct *vma)
1862 {
1863 return userfaultfd_wp_async_ctx(vma->vm_userfaultfd_ctx.ctx);
1864 }
1865
uffd_ctx_features(__u64 user_features)1866 static inline unsigned int uffd_ctx_features(__u64 user_features)
1867 {
1868 /*
1869 * For the current set of features the bits just coincide. Set
1870 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1871 */
1872 return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1873 }
1874
userfaultfd_move(struct userfaultfd_ctx * ctx,unsigned long arg)1875 static int userfaultfd_move(struct userfaultfd_ctx *ctx,
1876 unsigned long arg)
1877 {
1878 __s64 ret;
1879 struct uffdio_move uffdio_move;
1880 struct uffdio_move __user *user_uffdio_move;
1881 struct userfaultfd_wake_range range;
1882 struct mm_struct *mm = ctx->mm;
1883
1884 user_uffdio_move = (struct uffdio_move __user *) arg;
1885
1886 ret = -EAGAIN;
1887 if (unlikely(atomic_read(&ctx->mmap_changing))) {
1888 if (unlikely(put_user(ret, &user_uffdio_move->move)))
1889 return -EFAULT;
1890 goto out;
1891 }
1892
1893 if (copy_from_user(&uffdio_move, user_uffdio_move,
1894 /* don't copy "move" last field */
1895 sizeof(uffdio_move)-sizeof(__s64)))
1896 return -EFAULT;
1897
1898 /* Do not allow cross-mm moves. */
1899 if (mm != current->mm)
1900 return -EINVAL;
1901
1902 ret = validate_range(mm, uffdio_move.dst, uffdio_move.len);
1903 if (ret)
1904 return ret;
1905
1906 ret = validate_range(mm, uffdio_move.src, uffdio_move.len);
1907 if (ret)
1908 return ret;
1909
1910 if (uffdio_move.mode & ~(UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES|
1911 UFFDIO_MOVE_MODE_DONTWAKE))
1912 return -EINVAL;
1913
1914 if (mmget_not_zero(mm)) {
1915 ret = move_pages(ctx, uffdio_move.dst, uffdio_move.src,
1916 uffdio_move.len, uffdio_move.mode);
1917 mmput(mm);
1918 } else {
1919 return -ESRCH;
1920 }
1921
1922 if (unlikely(put_user(ret, &user_uffdio_move->move)))
1923 return -EFAULT;
1924 if (ret < 0)
1925 goto out;
1926
1927 /* len == 0 would wake all */
1928 VM_WARN_ON(!ret);
1929 range.len = ret;
1930 if (!(uffdio_move.mode & UFFDIO_MOVE_MODE_DONTWAKE)) {
1931 range.start = uffdio_move.dst;
1932 wake_userfault(ctx, &range);
1933 }
1934 ret = range.len == uffdio_move.len ? 0 : -EAGAIN;
1935
1936 out:
1937 return ret;
1938 }
1939
1940 /*
1941 * userland asks for a certain API version and we return which bits
1942 * and ioctl commands are implemented in this kernel for such API
1943 * version or -EINVAL if unknown.
1944 */
userfaultfd_api(struct userfaultfd_ctx * ctx,unsigned long arg)1945 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1946 unsigned long arg)
1947 {
1948 struct uffdio_api uffdio_api;
1949 void __user *buf = (void __user *)arg;
1950 unsigned int ctx_features;
1951 int ret;
1952 __u64 features;
1953
1954 ret = -EFAULT;
1955 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1956 goto out;
1957 features = uffdio_api.features;
1958 ret = -EINVAL;
1959 if (uffdio_api.api != UFFD_API)
1960 goto err_out;
1961 ret = -EPERM;
1962 if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1963 goto err_out;
1964
1965 /* WP_ASYNC relies on WP_UNPOPULATED, choose it unconditionally */
1966 if (features & UFFD_FEATURE_WP_ASYNC)
1967 features |= UFFD_FEATURE_WP_UNPOPULATED;
1968
1969 /* report all available features and ioctls to userland */
1970 uffdio_api.features = UFFD_API_FEATURES;
1971 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1972 uffdio_api.features &=
1973 ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1974 #endif
1975 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1976 uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1977 #endif
1978 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1979 uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1980 uffdio_api.features &= ~UFFD_FEATURE_WP_UNPOPULATED;
1981 uffdio_api.features &= ~UFFD_FEATURE_WP_ASYNC;
1982 #endif
1983
1984 ret = -EINVAL;
1985 if (features & ~uffdio_api.features)
1986 goto err_out;
1987
1988 uffdio_api.ioctls = UFFD_API_IOCTLS;
1989 ret = -EFAULT;
1990 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1991 goto out;
1992
1993 /* only enable the requested features for this uffd context */
1994 ctx_features = uffd_ctx_features(features);
1995 ret = -EINVAL;
1996 if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
1997 goto err_out;
1998
1999 ret = 0;
2000 out:
2001 return ret;
2002 err_out:
2003 memset(&uffdio_api, 0, sizeof(uffdio_api));
2004 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2005 ret = -EFAULT;
2006 goto out;
2007 }
2008
userfaultfd_ioctl(struct file * file,unsigned cmd,unsigned long arg)2009 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2010 unsigned long arg)
2011 {
2012 int ret = -EINVAL;
2013 struct userfaultfd_ctx *ctx = file->private_data;
2014
2015 if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2016 return -EINVAL;
2017
2018 switch(cmd) {
2019 case UFFDIO_API:
2020 ret = userfaultfd_api(ctx, arg);
2021 break;
2022 case UFFDIO_REGISTER:
2023 ret = userfaultfd_register(ctx, arg);
2024 break;
2025 case UFFDIO_UNREGISTER:
2026 ret = userfaultfd_unregister(ctx, arg);
2027 break;
2028 case UFFDIO_WAKE:
2029 ret = userfaultfd_wake(ctx, arg);
2030 break;
2031 case UFFDIO_COPY:
2032 ret = userfaultfd_copy(ctx, arg);
2033 break;
2034 case UFFDIO_ZEROPAGE:
2035 ret = userfaultfd_zeropage(ctx, arg);
2036 break;
2037 case UFFDIO_MOVE:
2038 ret = userfaultfd_move(ctx, arg);
2039 break;
2040 case UFFDIO_WRITEPROTECT:
2041 ret = userfaultfd_writeprotect(ctx, arg);
2042 break;
2043 case UFFDIO_CONTINUE:
2044 ret = userfaultfd_continue(ctx, arg);
2045 break;
2046 case UFFDIO_POISON:
2047 ret = userfaultfd_poison(ctx, arg);
2048 break;
2049 }
2050 return ret;
2051 }
2052
2053 #ifdef CONFIG_PROC_FS
userfaultfd_show_fdinfo(struct seq_file * m,struct file * f)2054 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2055 {
2056 struct userfaultfd_ctx *ctx = f->private_data;
2057 wait_queue_entry_t *wq;
2058 unsigned long pending = 0, total = 0;
2059
2060 spin_lock_irq(&ctx->fault_pending_wqh.lock);
2061 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2062 pending++;
2063 total++;
2064 }
2065 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2066 total++;
2067 }
2068 spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2069
2070 /*
2071 * If more protocols will be added, there will be all shown
2072 * separated by a space. Like this:
2073 * protocols: aa:... bb:...
2074 */
2075 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2076 pending, total, UFFD_API, ctx->features,
2077 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2078 }
2079 #endif
2080
2081 static const struct file_operations userfaultfd_fops = {
2082 #ifdef CONFIG_PROC_FS
2083 .show_fdinfo = userfaultfd_show_fdinfo,
2084 #endif
2085 .release = userfaultfd_release,
2086 .poll = userfaultfd_poll,
2087 .read_iter = userfaultfd_read_iter,
2088 .unlocked_ioctl = userfaultfd_ioctl,
2089 .compat_ioctl = compat_ptr_ioctl,
2090 .llseek = noop_llseek,
2091 };
2092
init_once_userfaultfd_ctx(void * mem)2093 static void init_once_userfaultfd_ctx(void *mem)
2094 {
2095 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2096
2097 init_waitqueue_head(&ctx->fault_pending_wqh);
2098 init_waitqueue_head(&ctx->fault_wqh);
2099 init_waitqueue_head(&ctx->event_wqh);
2100 init_waitqueue_head(&ctx->fd_wqh);
2101 seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2102 }
2103
new_userfaultfd(int flags)2104 static int new_userfaultfd(int flags)
2105 {
2106 struct userfaultfd_ctx *ctx;
2107 struct file *file;
2108 int fd;
2109
2110 BUG_ON(!current->mm);
2111
2112 /* Check the UFFD_* constants for consistency. */
2113 BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2114 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
2115 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
2116
2117 if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2118 return -EINVAL;
2119
2120 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2121 if (!ctx)
2122 return -ENOMEM;
2123
2124 refcount_set(&ctx->refcount, 1);
2125 ctx->flags = flags;
2126 ctx->features = 0;
2127 ctx->released = false;
2128 init_rwsem(&ctx->map_changing_lock);
2129 atomic_set(&ctx->mmap_changing, 0);
2130 ctx->mm = current->mm;
2131
2132 fd = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
2133 if (fd < 0)
2134 goto err_out;
2135
2136 /* Create a new inode so that the LSM can block the creation. */
2137 file = anon_inode_create_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
2138 O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2139 if (IS_ERR(file)) {
2140 put_unused_fd(fd);
2141 fd = PTR_ERR(file);
2142 goto err_out;
2143 }
2144 /* prevent the mm struct to be freed */
2145 mmgrab(ctx->mm);
2146 file->f_mode |= FMODE_NOWAIT;
2147 fd_install(fd, file);
2148 return fd;
2149 err_out:
2150 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2151 return fd;
2152 }
2153
userfaultfd_syscall_allowed(int flags)2154 static inline bool userfaultfd_syscall_allowed(int flags)
2155 {
2156 /* Userspace-only page faults are always allowed */
2157 if (flags & UFFD_USER_MODE_ONLY)
2158 return true;
2159
2160 /*
2161 * The user is requesting a userfaultfd which can handle kernel faults.
2162 * Privileged users are always allowed to do this.
2163 */
2164 if (capable(CAP_SYS_PTRACE))
2165 return true;
2166
2167 /* Otherwise, access to kernel fault handling is sysctl controlled. */
2168 return sysctl_unprivileged_userfaultfd;
2169 }
2170
SYSCALL_DEFINE1(userfaultfd,int,flags)2171 SYSCALL_DEFINE1(userfaultfd, int, flags)
2172 {
2173 if (__PAGE_SIZE != PAGE_SIZE)
2174 return -EOPNOTSUPP;
2175
2176 if (!userfaultfd_syscall_allowed(flags))
2177 return -EPERM;
2178
2179 return new_userfaultfd(flags);
2180 }
2181
userfaultfd_dev_ioctl(struct file * file,unsigned int cmd,unsigned long flags)2182 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2183 {
2184 if (cmd != USERFAULTFD_IOC_NEW)
2185 return -EINVAL;
2186
2187 return new_userfaultfd(flags);
2188 }
2189
2190 static const struct file_operations userfaultfd_dev_fops = {
2191 .unlocked_ioctl = userfaultfd_dev_ioctl,
2192 .compat_ioctl = userfaultfd_dev_ioctl,
2193 .owner = THIS_MODULE,
2194 .llseek = noop_llseek,
2195 };
2196
2197 static struct miscdevice userfaultfd_misc = {
2198 .minor = MISC_DYNAMIC_MINOR,
2199 .name = "userfaultfd",
2200 .fops = &userfaultfd_dev_fops
2201 };
2202
userfaultfd_init(void)2203 static int __init userfaultfd_init(void)
2204 {
2205 int ret;
2206
2207 if (__PAGE_SIZE != PAGE_SIZE)
2208 return 0;
2209
2210 ret = misc_register(&userfaultfd_misc);
2211 if (ret)
2212 return ret;
2213
2214 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2215 sizeof(struct userfaultfd_ctx),
2216 0,
2217 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2218 init_once_userfaultfd_ctx);
2219 #ifdef CONFIG_SYSCTL
2220 register_sysctl_init("vm", vm_userfaultfd_table);
2221 #endif
2222 return 0;
2223 }
2224 __initcall(userfaultfd_init);
2225