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