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