io: define stronger ordering for the default writeX() implementation
[linux/fpc-iii.git] / fs / userfaultfd.c
blobcec550c8468f484a3f14d6a6b3e5dcc2a09ea70f
1 /*
2 * fs/userfaultfd.c
4 * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
5 * Copyright (C) 2008-2009 Red Hat, Inc.
6 * Copyright (C) 2015 Red Hat, Inc.
8 * This work is licensed under the terms of the GNU GPL, version 2. See
9 * the COPYING file in the top-level directory.
11 * Some part derived from fs/eventfd.c (anon inode setup) and
12 * mm/ksm.c (mm hashing).
15 #include <linux/list.h>
16 #include <linux/hashtable.h>
17 #include <linux/sched/signal.h>
18 #include <linux/sched/mm.h>
19 #include <linux/mm.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>
33 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
35 enum userfaultfd_state {
36 UFFD_STATE_WAIT_API,
37 UFFD_STATE_RUNNING,
41 * Start with fault_pending_wqh and fault_wqh so they're more likely
42 * to be in the same cacheline.
44 struct userfaultfd_ctx {
45 /* waitqueue head for the pending (i.e. not read) userfaults */
46 wait_queue_head_t fault_pending_wqh;
47 /* waitqueue head for the userfaults */
48 wait_queue_head_t fault_wqh;
49 /* waitqueue head for the pseudo fd to wakeup poll/read */
50 wait_queue_head_t fd_wqh;
51 /* waitqueue head for events */
52 wait_queue_head_t event_wqh;
53 /* a refile sequence protected by fault_pending_wqh lock */
54 struct seqcount refile_seq;
55 /* pseudo fd refcounting */
56 atomic_t refcount;
57 /* userfaultfd syscall flags */
58 unsigned int flags;
59 /* features requested from the userspace */
60 unsigned int features;
61 /* state machine */
62 enum userfaultfd_state state;
63 /* released */
64 bool released;
65 /* mm with one ore more vmas attached to this userfaultfd_ctx */
66 struct mm_struct *mm;
69 struct userfaultfd_fork_ctx {
70 struct userfaultfd_ctx *orig;
71 struct userfaultfd_ctx *new;
72 struct list_head list;
75 struct userfaultfd_unmap_ctx {
76 struct userfaultfd_ctx *ctx;
77 unsigned long start;
78 unsigned long end;
79 struct list_head list;
82 struct userfaultfd_wait_queue {
83 struct uffd_msg msg;
84 wait_queue_entry_t wq;
85 struct userfaultfd_ctx *ctx;
86 bool waken;
89 struct userfaultfd_wake_range {
90 unsigned long start;
91 unsigned long len;
94 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
95 int wake_flags, void *key)
97 struct userfaultfd_wake_range *range = key;
98 int ret;
99 struct userfaultfd_wait_queue *uwq;
100 unsigned long start, len;
102 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
103 ret = 0;
104 /* len == 0 means wake all */
105 start = range->start;
106 len = range->len;
107 if (len && (start > uwq->msg.arg.pagefault.address ||
108 start + len <= uwq->msg.arg.pagefault.address))
109 goto out;
110 WRITE_ONCE(uwq->waken, true);
112 * The Program-Order guarantees provided by the scheduler
113 * ensure uwq->waken is visible before the task is woken.
115 ret = wake_up_state(wq->private, mode);
116 if (ret) {
118 * Wake only once, autoremove behavior.
120 * After the effect of list_del_init is visible to the other
121 * CPUs, the waitqueue may disappear from under us, see the
122 * !list_empty_careful() in handle_userfault().
124 * try_to_wake_up() has an implicit smp_mb(), and the
125 * wq->private is read before calling the extern function
126 * "wake_up_state" (which in turns calls try_to_wake_up).
128 list_del_init(&wq->entry);
130 out:
131 return ret;
135 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
136 * context.
137 * @ctx: [in] Pointer to the userfaultfd context.
139 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
141 if (!atomic_inc_not_zero(&ctx->refcount))
142 BUG();
146 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
147 * context.
148 * @ctx: [in] Pointer to userfaultfd context.
150 * The userfaultfd context reference must have been previously acquired either
151 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
153 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
155 if (atomic_dec_and_test(&ctx->refcount)) {
156 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
157 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
158 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
159 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
160 VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
161 VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
162 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
163 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
164 mmdrop(ctx->mm);
165 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
169 static inline void msg_init(struct uffd_msg *msg)
171 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
173 * Must use memset to zero out the paddings or kernel data is
174 * leaked to userland.
176 memset(msg, 0, sizeof(struct uffd_msg));
179 static inline struct uffd_msg userfault_msg(unsigned long address,
180 unsigned int flags,
181 unsigned long reason,
182 unsigned int features)
184 struct uffd_msg msg;
185 msg_init(&msg);
186 msg.event = UFFD_EVENT_PAGEFAULT;
187 msg.arg.pagefault.address = address;
188 if (flags & FAULT_FLAG_WRITE)
190 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
191 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
192 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
193 * was a read fault, otherwise if set it means it's
194 * a write fault.
196 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
197 if (reason & VM_UFFD_WP)
199 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
200 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
201 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
202 * a missing fault, otherwise if set it means it's a
203 * write protect fault.
205 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
206 if (features & UFFD_FEATURE_THREAD_ID)
207 msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
208 return msg;
211 #ifdef CONFIG_HUGETLB_PAGE
213 * Same functionality as userfaultfd_must_wait below with modifications for
214 * hugepmd ranges.
216 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
217 struct vm_area_struct *vma,
218 unsigned long address,
219 unsigned long flags,
220 unsigned long reason)
222 struct mm_struct *mm = ctx->mm;
223 pte_t *pte;
224 bool ret = true;
226 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
228 pte = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
229 if (!pte)
230 goto out;
232 ret = false;
235 * Lockless access: we're in a wait_event so it's ok if it
236 * changes under us.
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;
245 #else
246 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
247 struct vm_area_struct *vma,
248 unsigned long address,
249 unsigned long flags,
250 unsigned long reason)
252 return false; /* should never get here */
254 #endif /* CONFIG_HUGETLB_PAGE */
257 * Verify the pagetables are still not ok after having reigstered into
258 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
259 * userfault that has already been resolved, if userfaultfd_read and
260 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
261 * threads.
263 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
264 unsigned long address,
265 unsigned long flags,
266 unsigned long reason)
268 struct mm_struct *mm = ctx->mm;
269 pgd_t *pgd;
270 p4d_t *p4d;
271 pud_t *pud;
272 pmd_t *pmd, _pmd;
273 pte_t *pte;
274 bool ret = true;
276 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
278 pgd = pgd_offset(mm, address);
279 if (!pgd_present(*pgd))
280 goto out;
281 p4d = p4d_offset(pgd, address);
282 if (!p4d_present(*p4d))
283 goto out;
284 pud = pud_offset(p4d, address);
285 if (!pud_present(*pud))
286 goto out;
287 pmd = pmd_offset(pud, address);
289 * READ_ONCE must function as a barrier with narrower scope
290 * and it must be equivalent to:
291 * _pmd = *pmd; barrier();
293 * This is to deal with the instability (as in
294 * pmd_trans_unstable) of the pmd.
296 _pmd = READ_ONCE(*pmd);
297 if (pmd_none(_pmd))
298 goto out;
300 ret = false;
301 if (!pmd_present(_pmd))
302 goto out;
304 if (pmd_trans_huge(_pmd))
305 goto out;
308 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
309 * and use the standard pte_offset_map() instead of parsing _pmd.
311 pte = pte_offset_map(pmd, address);
313 * Lockless access: we're in a wait_event so it's ok if it
314 * changes under us.
316 if (pte_none(*pte))
317 ret = true;
318 pte_unmap(pte);
320 out:
321 return ret;
325 * The locking rules involved in returning VM_FAULT_RETRY depending on
326 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
327 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
328 * recommendation in __lock_page_or_retry is not an understatement.
330 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
331 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
332 * not set.
334 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
335 * set, VM_FAULT_RETRY can still be returned if and only if there are
336 * fatal_signal_pending()s, and the mmap_sem must be released before
337 * returning it.
339 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
341 struct mm_struct *mm = vmf->vma->vm_mm;
342 struct userfaultfd_ctx *ctx;
343 struct userfaultfd_wait_queue uwq;
344 int ret;
345 bool must_wait, return_to_userland;
346 long blocking_state;
348 ret = VM_FAULT_SIGBUS;
351 * We don't do userfault handling for the final child pid update.
353 * We also don't do userfault handling during
354 * coredumping. hugetlbfs has the special
355 * follow_hugetlb_page() to skip missing pages in the
356 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
357 * the no_page_table() helper in follow_page_mask(), but the
358 * shmem_vm_ops->fault method is invoked even during
359 * coredumping without mmap_sem and it ends up here.
361 if (current->flags & (PF_EXITING|PF_DUMPCORE))
362 goto out;
365 * Coredumping runs without mmap_sem so we can only check that
366 * the mmap_sem is held, if PF_DUMPCORE was not set.
368 WARN_ON_ONCE(!rwsem_is_locked(&mm->mmap_sem));
370 ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
371 if (!ctx)
372 goto out;
374 BUG_ON(ctx->mm != mm);
376 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
377 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
379 if (ctx->features & UFFD_FEATURE_SIGBUS)
380 goto out;
383 * If it's already released don't get it. This avoids to loop
384 * in __get_user_pages if userfaultfd_release waits on the
385 * caller of handle_userfault to release the mmap_sem.
387 if (unlikely(READ_ONCE(ctx->released))) {
389 * Don't return VM_FAULT_SIGBUS in this case, so a non
390 * cooperative manager can close the uffd after the
391 * last UFFDIO_COPY, without risking to trigger an
392 * involuntary SIGBUS if the process was starting the
393 * userfaultfd while the userfaultfd was still armed
394 * (but after the last UFFDIO_COPY). If the uffd
395 * wasn't already closed when the userfault reached
396 * this point, that would normally be solved by
397 * userfaultfd_must_wait returning 'false'.
399 * If we were to return VM_FAULT_SIGBUS here, the non
400 * cooperative manager would be instead forced to
401 * always call UFFDIO_UNREGISTER before it can safely
402 * close the uffd.
404 ret = VM_FAULT_NOPAGE;
405 goto out;
409 * Check that we can return VM_FAULT_RETRY.
411 * NOTE: it should become possible to return VM_FAULT_RETRY
412 * even if FAULT_FLAG_TRIED is set without leading to gup()
413 * -EBUSY failures, if the userfaultfd is to be extended for
414 * VM_UFFD_WP tracking and we intend to arm the userfault
415 * without first stopping userland access to the memory. For
416 * VM_UFFD_MISSING userfaults this is enough for now.
418 if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
420 * Validate the invariant that nowait must allow retry
421 * to be sure not to return SIGBUS erroneously on
422 * nowait invocations.
424 BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
425 #ifdef CONFIG_DEBUG_VM
426 if (printk_ratelimit()) {
427 printk(KERN_WARNING
428 "FAULT_FLAG_ALLOW_RETRY missing %x\n",
429 vmf->flags);
430 dump_stack();
432 #endif
433 goto out;
437 * Handle nowait, not much to do other than tell it to retry
438 * and wait.
440 ret = VM_FAULT_RETRY;
441 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
442 goto out;
444 /* take the reference before dropping the mmap_sem */
445 userfaultfd_ctx_get(ctx);
447 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
448 uwq.wq.private = current;
449 uwq.msg = userfault_msg(vmf->address, vmf->flags, reason,
450 ctx->features);
451 uwq.ctx = ctx;
452 uwq.waken = false;
454 return_to_userland =
455 (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
456 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
457 blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
458 TASK_KILLABLE;
460 spin_lock(&ctx->fault_pending_wqh.lock);
462 * After the __add_wait_queue the uwq is visible to userland
463 * through poll/read().
465 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
467 * The smp_mb() after __set_current_state prevents the reads
468 * following the spin_unlock to happen before the list_add in
469 * __add_wait_queue.
471 set_current_state(blocking_state);
472 spin_unlock(&ctx->fault_pending_wqh.lock);
474 if (!is_vm_hugetlb_page(vmf->vma))
475 must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
476 reason);
477 else
478 must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
479 vmf->address,
480 vmf->flags, reason);
481 up_read(&mm->mmap_sem);
483 if (likely(must_wait && !READ_ONCE(ctx->released) &&
484 (return_to_userland ? !signal_pending(current) :
485 !fatal_signal_pending(current)))) {
486 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
487 schedule();
488 ret |= VM_FAULT_MAJOR;
491 * False wakeups can orginate even from rwsem before
492 * up_read() however userfaults will wait either for a
493 * targeted wakeup on the specific uwq waitqueue from
494 * wake_userfault() or for signals or for uffd
495 * release.
497 while (!READ_ONCE(uwq.waken)) {
499 * This needs the full smp_store_mb()
500 * guarantee as the state write must be
501 * visible to other CPUs before reading
502 * uwq.waken from other CPUs.
504 set_current_state(blocking_state);
505 if (READ_ONCE(uwq.waken) ||
506 READ_ONCE(ctx->released) ||
507 (return_to_userland ? signal_pending(current) :
508 fatal_signal_pending(current)))
509 break;
510 schedule();
514 __set_current_state(TASK_RUNNING);
516 if (return_to_userland) {
517 if (signal_pending(current) &&
518 !fatal_signal_pending(current)) {
520 * If we got a SIGSTOP or SIGCONT and this is
521 * a normal userland page fault, just let
522 * userland return so the signal will be
523 * handled and gdb debugging works. The page
524 * fault code immediately after we return from
525 * this function is going to release the
526 * mmap_sem and it's not depending on it
527 * (unlike gup would if we were not to return
528 * VM_FAULT_RETRY).
530 * If a fatal signal is pending we still take
531 * the streamlined VM_FAULT_RETRY failure path
532 * and there's no need to retake the mmap_sem
533 * in such case.
535 down_read(&mm->mmap_sem);
536 ret = VM_FAULT_NOPAGE;
541 * Here we race with the list_del; list_add in
542 * userfaultfd_ctx_read(), however because we don't ever run
543 * list_del_init() to refile across the two lists, the prev
544 * and next pointers will never point to self. list_add also
545 * would never let any of the two pointers to point to
546 * self. So list_empty_careful won't risk to see both pointers
547 * pointing to self at any time during the list refile. The
548 * only case where list_del_init() is called is the full
549 * removal in the wake function and there we don't re-list_add
550 * and it's fine not to block on the spinlock. The uwq on this
551 * kernel stack can be released after the list_del_init.
553 if (!list_empty_careful(&uwq.wq.entry)) {
554 spin_lock(&ctx->fault_pending_wqh.lock);
556 * No need of list_del_init(), the uwq on the stack
557 * will be freed shortly anyway.
559 list_del(&uwq.wq.entry);
560 spin_unlock(&ctx->fault_pending_wqh.lock);
564 * ctx may go away after this if the userfault pseudo fd is
565 * already released.
567 userfaultfd_ctx_put(ctx);
569 out:
570 return ret;
573 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
574 struct userfaultfd_wait_queue *ewq)
576 struct userfaultfd_ctx *release_new_ctx;
578 if (WARN_ON_ONCE(current->flags & PF_EXITING))
579 goto out;
581 ewq->ctx = ctx;
582 init_waitqueue_entry(&ewq->wq, current);
583 release_new_ctx = NULL;
585 spin_lock(&ctx->event_wqh.lock);
587 * After the __add_wait_queue the uwq is visible to userland
588 * through poll/read().
590 __add_wait_queue(&ctx->event_wqh, &ewq->wq);
591 for (;;) {
592 set_current_state(TASK_KILLABLE);
593 if (ewq->msg.event == 0)
594 break;
595 if (READ_ONCE(ctx->released) ||
596 fatal_signal_pending(current)) {
598 * &ewq->wq may be queued in fork_event, but
599 * __remove_wait_queue ignores the head
600 * parameter. It would be a problem if it
601 * didn't.
603 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
604 if (ewq->msg.event == UFFD_EVENT_FORK) {
605 struct userfaultfd_ctx *new;
607 new = (struct userfaultfd_ctx *)
608 (unsigned long)
609 ewq->msg.arg.reserved.reserved1;
610 release_new_ctx = new;
612 break;
615 spin_unlock(&ctx->event_wqh.lock);
617 wake_up_poll(&ctx->fd_wqh, EPOLLIN);
618 schedule();
620 spin_lock(&ctx->event_wqh.lock);
622 __set_current_state(TASK_RUNNING);
623 spin_unlock(&ctx->event_wqh.lock);
625 if (release_new_ctx) {
626 struct vm_area_struct *vma;
627 struct mm_struct *mm = release_new_ctx->mm;
629 /* the various vma->vm_userfaultfd_ctx still points to it */
630 down_write(&mm->mmap_sem);
631 for (vma = mm->mmap; vma; vma = vma->vm_next)
632 if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx)
633 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
634 up_write(&mm->mmap_sem);
636 userfaultfd_ctx_put(release_new_ctx);
640 * ctx may go away after this if the userfault pseudo fd is
641 * already released.
643 out:
644 userfaultfd_ctx_put(ctx);
647 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
648 struct userfaultfd_wait_queue *ewq)
650 ewq->msg.event = 0;
651 wake_up_locked(&ctx->event_wqh);
652 __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
655 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
657 struct userfaultfd_ctx *ctx = NULL, *octx;
658 struct userfaultfd_fork_ctx *fctx;
660 octx = vma->vm_userfaultfd_ctx.ctx;
661 if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
662 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
663 vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
664 return 0;
667 list_for_each_entry(fctx, fcs, list)
668 if (fctx->orig == octx) {
669 ctx = fctx->new;
670 break;
673 if (!ctx) {
674 fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
675 if (!fctx)
676 return -ENOMEM;
678 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
679 if (!ctx) {
680 kfree(fctx);
681 return -ENOMEM;
684 atomic_set(&ctx->refcount, 1);
685 ctx->flags = octx->flags;
686 ctx->state = UFFD_STATE_RUNNING;
687 ctx->features = octx->features;
688 ctx->released = false;
689 ctx->mm = vma->vm_mm;
690 mmgrab(ctx->mm);
692 userfaultfd_ctx_get(octx);
693 fctx->orig = octx;
694 fctx->new = ctx;
695 list_add_tail(&fctx->list, fcs);
698 vma->vm_userfaultfd_ctx.ctx = ctx;
699 return 0;
702 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
704 struct userfaultfd_ctx *ctx = fctx->orig;
705 struct userfaultfd_wait_queue ewq;
707 msg_init(&ewq.msg);
709 ewq.msg.event = UFFD_EVENT_FORK;
710 ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
712 userfaultfd_event_wait_completion(ctx, &ewq);
715 void dup_userfaultfd_complete(struct list_head *fcs)
717 struct userfaultfd_fork_ctx *fctx, *n;
719 list_for_each_entry_safe(fctx, n, fcs, list) {
720 dup_fctx(fctx);
721 list_del(&fctx->list);
722 kfree(fctx);
726 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
727 struct vm_userfaultfd_ctx *vm_ctx)
729 struct userfaultfd_ctx *ctx;
731 ctx = vma->vm_userfaultfd_ctx.ctx;
732 if (ctx && (ctx->features & UFFD_FEATURE_EVENT_REMAP)) {
733 vm_ctx->ctx = ctx;
734 userfaultfd_ctx_get(ctx);
738 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
739 unsigned long from, unsigned long to,
740 unsigned long len)
742 struct userfaultfd_ctx *ctx = vm_ctx->ctx;
743 struct userfaultfd_wait_queue ewq;
745 if (!ctx)
746 return;
748 if (to & ~PAGE_MASK) {
749 userfaultfd_ctx_put(ctx);
750 return;
753 msg_init(&ewq.msg);
755 ewq.msg.event = UFFD_EVENT_REMAP;
756 ewq.msg.arg.remap.from = from;
757 ewq.msg.arg.remap.to = to;
758 ewq.msg.arg.remap.len = len;
760 userfaultfd_event_wait_completion(ctx, &ewq);
763 bool userfaultfd_remove(struct vm_area_struct *vma,
764 unsigned long start, unsigned long end)
766 struct mm_struct *mm = vma->vm_mm;
767 struct userfaultfd_ctx *ctx;
768 struct userfaultfd_wait_queue ewq;
770 ctx = vma->vm_userfaultfd_ctx.ctx;
771 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
772 return true;
774 userfaultfd_ctx_get(ctx);
775 up_read(&mm->mmap_sem);
777 msg_init(&ewq.msg);
779 ewq.msg.event = UFFD_EVENT_REMOVE;
780 ewq.msg.arg.remove.start = start;
781 ewq.msg.arg.remove.end = end;
783 userfaultfd_event_wait_completion(ctx, &ewq);
785 return false;
788 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
789 unsigned long start, unsigned long end)
791 struct userfaultfd_unmap_ctx *unmap_ctx;
793 list_for_each_entry(unmap_ctx, unmaps, list)
794 if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
795 unmap_ctx->end == end)
796 return true;
798 return false;
801 int userfaultfd_unmap_prep(struct vm_area_struct *vma,
802 unsigned long start, unsigned long end,
803 struct list_head *unmaps)
805 for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
806 struct userfaultfd_unmap_ctx *unmap_ctx;
807 struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
809 if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
810 has_unmap_ctx(ctx, unmaps, start, end))
811 continue;
813 unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
814 if (!unmap_ctx)
815 return -ENOMEM;
817 userfaultfd_ctx_get(ctx);
818 unmap_ctx->ctx = ctx;
819 unmap_ctx->start = start;
820 unmap_ctx->end = end;
821 list_add_tail(&unmap_ctx->list, unmaps);
824 return 0;
827 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
829 struct userfaultfd_unmap_ctx *ctx, *n;
830 struct userfaultfd_wait_queue ewq;
832 list_for_each_entry_safe(ctx, n, uf, list) {
833 msg_init(&ewq.msg);
835 ewq.msg.event = UFFD_EVENT_UNMAP;
836 ewq.msg.arg.remove.start = ctx->start;
837 ewq.msg.arg.remove.end = ctx->end;
839 userfaultfd_event_wait_completion(ctx->ctx, &ewq);
841 list_del(&ctx->list);
842 kfree(ctx);
846 static int userfaultfd_release(struct inode *inode, struct file *file)
848 struct userfaultfd_ctx *ctx = file->private_data;
849 struct mm_struct *mm = ctx->mm;
850 struct vm_area_struct *vma, *prev;
851 /* len == 0 means wake all */
852 struct userfaultfd_wake_range range = { .len = 0, };
853 unsigned long new_flags;
855 WRITE_ONCE(ctx->released, true);
857 if (!mmget_not_zero(mm))
858 goto wakeup;
861 * Flush page faults out of all CPUs. NOTE: all page faults
862 * must be retried without returning VM_FAULT_SIGBUS if
863 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
864 * changes while handle_userfault released the mmap_sem. So
865 * it's critical that released is set to true (above), before
866 * taking the mmap_sem for writing.
868 down_write(&mm->mmap_sem);
869 prev = NULL;
870 for (vma = mm->mmap; vma; vma = vma->vm_next) {
871 cond_resched();
872 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
873 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
874 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
875 prev = vma;
876 continue;
878 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
879 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
880 new_flags, vma->anon_vma,
881 vma->vm_file, vma->vm_pgoff,
882 vma_policy(vma),
883 NULL_VM_UFFD_CTX);
884 if (prev)
885 vma = prev;
886 else
887 prev = vma;
888 vma->vm_flags = new_flags;
889 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
891 up_write(&mm->mmap_sem);
892 mmput(mm);
893 wakeup:
895 * After no new page faults can wait on this fault_*wqh, flush
896 * the last page faults that may have been already waiting on
897 * the fault_*wqh.
899 spin_lock(&ctx->fault_pending_wqh.lock);
900 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
901 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
902 spin_unlock(&ctx->fault_pending_wqh.lock);
904 /* Flush pending events that may still wait on event_wqh */
905 wake_up_all(&ctx->event_wqh);
907 wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
908 userfaultfd_ctx_put(ctx);
909 return 0;
912 /* fault_pending_wqh.lock must be hold by the caller */
913 static inline struct userfaultfd_wait_queue *find_userfault_in(
914 wait_queue_head_t *wqh)
916 wait_queue_entry_t *wq;
917 struct userfaultfd_wait_queue *uwq;
919 VM_BUG_ON(!spin_is_locked(&wqh->lock));
921 uwq = NULL;
922 if (!waitqueue_active(wqh))
923 goto out;
924 /* walk in reverse to provide FIFO behavior to read userfaults */
925 wq = list_last_entry(&wqh->head, typeof(*wq), entry);
926 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
927 out:
928 return uwq;
931 static inline struct userfaultfd_wait_queue *find_userfault(
932 struct userfaultfd_ctx *ctx)
934 return find_userfault_in(&ctx->fault_pending_wqh);
937 static inline struct userfaultfd_wait_queue *find_userfault_evt(
938 struct userfaultfd_ctx *ctx)
940 return find_userfault_in(&ctx->event_wqh);
943 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
945 struct userfaultfd_ctx *ctx = file->private_data;
946 __poll_t ret;
948 poll_wait(file, &ctx->fd_wqh, wait);
950 switch (ctx->state) {
951 case UFFD_STATE_WAIT_API:
952 return EPOLLERR;
953 case UFFD_STATE_RUNNING:
955 * poll() never guarantees that read won't block.
956 * userfaults can be waken before they're read().
958 if (unlikely(!(file->f_flags & O_NONBLOCK)))
959 return EPOLLERR;
961 * lockless access to see if there are pending faults
962 * __pollwait last action is the add_wait_queue but
963 * the spin_unlock would allow the waitqueue_active to
964 * pass above the actual list_add inside
965 * add_wait_queue critical section. So use a full
966 * memory barrier to serialize the list_add write of
967 * add_wait_queue() with the waitqueue_active read
968 * below.
970 ret = 0;
971 smp_mb();
972 if (waitqueue_active(&ctx->fault_pending_wqh))
973 ret = EPOLLIN;
974 else if (waitqueue_active(&ctx->event_wqh))
975 ret = EPOLLIN;
977 return ret;
978 default:
979 WARN_ON_ONCE(1);
980 return EPOLLERR;
984 static const struct file_operations userfaultfd_fops;
986 static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
987 struct userfaultfd_ctx *new,
988 struct uffd_msg *msg)
990 int fd;
992 fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, new,
993 O_RDWR | (new->flags & UFFD_SHARED_FCNTL_FLAGS));
994 if (fd < 0)
995 return fd;
997 msg->arg.reserved.reserved1 = 0;
998 msg->arg.fork.ufd = fd;
999 return 0;
1002 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1003 struct uffd_msg *msg)
1005 ssize_t ret;
1006 DECLARE_WAITQUEUE(wait, current);
1007 struct userfaultfd_wait_queue *uwq;
1009 * Handling fork event requires sleeping operations, so
1010 * we drop the event_wqh lock, then do these ops, then
1011 * lock it back and wake up the waiter. While the lock is
1012 * dropped the ewq may go away so we keep track of it
1013 * carefully.
1015 LIST_HEAD(fork_event);
1016 struct userfaultfd_ctx *fork_nctx = NULL;
1018 /* always take the fd_wqh lock before the fault_pending_wqh lock */
1019 spin_lock(&ctx->fd_wqh.lock);
1020 __add_wait_queue(&ctx->fd_wqh, &wait);
1021 for (;;) {
1022 set_current_state(TASK_INTERRUPTIBLE);
1023 spin_lock(&ctx->fault_pending_wqh.lock);
1024 uwq = find_userfault(ctx);
1025 if (uwq) {
1027 * Use a seqcount to repeat the lockless check
1028 * in wake_userfault() to avoid missing
1029 * wakeups because during the refile both
1030 * waitqueue could become empty if this is the
1031 * only userfault.
1033 write_seqcount_begin(&ctx->refile_seq);
1036 * The fault_pending_wqh.lock prevents the uwq
1037 * to disappear from under us.
1039 * Refile this userfault from
1040 * fault_pending_wqh to fault_wqh, it's not
1041 * pending anymore after we read it.
1043 * Use list_del() by hand (as
1044 * userfaultfd_wake_function also uses
1045 * list_del_init() by hand) to be sure nobody
1046 * changes __remove_wait_queue() to use
1047 * list_del_init() in turn breaking the
1048 * !list_empty_careful() check in
1049 * handle_userfault(). The uwq->wq.head list
1050 * must never be empty at any time during the
1051 * refile, or the waitqueue could disappear
1052 * from under us. The "wait_queue_head_t"
1053 * parameter of __remove_wait_queue() is unused
1054 * anyway.
1056 list_del(&uwq->wq.entry);
1057 __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1059 write_seqcount_end(&ctx->refile_seq);
1061 /* careful to always initialize msg if ret == 0 */
1062 *msg = uwq->msg;
1063 spin_unlock(&ctx->fault_pending_wqh.lock);
1064 ret = 0;
1065 break;
1067 spin_unlock(&ctx->fault_pending_wqh.lock);
1069 spin_lock(&ctx->event_wqh.lock);
1070 uwq = find_userfault_evt(ctx);
1071 if (uwq) {
1072 *msg = uwq->msg;
1074 if (uwq->msg.event == UFFD_EVENT_FORK) {
1075 fork_nctx = (struct userfaultfd_ctx *)
1076 (unsigned long)
1077 uwq->msg.arg.reserved.reserved1;
1078 list_move(&uwq->wq.entry, &fork_event);
1080 * fork_nctx can be freed as soon as
1081 * we drop the lock, unless we take a
1082 * reference on it.
1084 userfaultfd_ctx_get(fork_nctx);
1085 spin_unlock(&ctx->event_wqh.lock);
1086 ret = 0;
1087 break;
1090 userfaultfd_event_complete(ctx, uwq);
1091 spin_unlock(&ctx->event_wqh.lock);
1092 ret = 0;
1093 break;
1095 spin_unlock(&ctx->event_wqh.lock);
1097 if (signal_pending(current)) {
1098 ret = -ERESTARTSYS;
1099 break;
1101 if (no_wait) {
1102 ret = -EAGAIN;
1103 break;
1105 spin_unlock(&ctx->fd_wqh.lock);
1106 schedule();
1107 spin_lock(&ctx->fd_wqh.lock);
1109 __remove_wait_queue(&ctx->fd_wqh, &wait);
1110 __set_current_state(TASK_RUNNING);
1111 spin_unlock(&ctx->fd_wqh.lock);
1113 if (!ret && msg->event == UFFD_EVENT_FORK) {
1114 ret = resolve_userfault_fork(ctx, fork_nctx, msg);
1115 spin_lock(&ctx->event_wqh.lock);
1116 if (!list_empty(&fork_event)) {
1118 * The fork thread didn't abort, so we can
1119 * drop the temporary refcount.
1121 userfaultfd_ctx_put(fork_nctx);
1123 uwq = list_first_entry(&fork_event,
1124 typeof(*uwq),
1125 wq.entry);
1127 * If fork_event list wasn't empty and in turn
1128 * the event wasn't already released by fork
1129 * (the event is allocated on fork kernel
1130 * stack), put the event back to its place in
1131 * the event_wq. fork_event head will be freed
1132 * as soon as we return so the event cannot
1133 * stay queued there no matter the current
1134 * "ret" value.
1136 list_del(&uwq->wq.entry);
1137 __add_wait_queue(&ctx->event_wqh, &uwq->wq);
1140 * Leave the event in the waitqueue and report
1141 * error to userland if we failed to resolve
1142 * the userfault fork.
1144 if (likely(!ret))
1145 userfaultfd_event_complete(ctx, uwq);
1146 } else {
1148 * Here the fork thread aborted and the
1149 * refcount from the fork thread on fork_nctx
1150 * has already been released. We still hold
1151 * the reference we took before releasing the
1152 * lock above. If resolve_userfault_fork
1153 * failed we've to drop it because the
1154 * fork_nctx has to be freed in such case. If
1155 * it succeeded we'll hold it because the new
1156 * uffd references it.
1158 if (ret)
1159 userfaultfd_ctx_put(fork_nctx);
1161 spin_unlock(&ctx->event_wqh.lock);
1164 return ret;
1167 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
1168 size_t count, loff_t *ppos)
1170 struct userfaultfd_ctx *ctx = file->private_data;
1171 ssize_t _ret, ret = 0;
1172 struct uffd_msg msg;
1173 int no_wait = file->f_flags & O_NONBLOCK;
1175 if (ctx->state == UFFD_STATE_WAIT_API)
1176 return -EINVAL;
1178 for (;;) {
1179 if (count < sizeof(msg))
1180 return ret ? ret : -EINVAL;
1181 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
1182 if (_ret < 0)
1183 return ret ? ret : _ret;
1184 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
1185 return ret ? ret : -EFAULT;
1186 ret += sizeof(msg);
1187 buf += sizeof(msg);
1188 count -= sizeof(msg);
1190 * Allow to read more than one fault at time but only
1191 * block if waiting for the very first one.
1193 no_wait = O_NONBLOCK;
1197 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1198 struct userfaultfd_wake_range *range)
1200 spin_lock(&ctx->fault_pending_wqh.lock);
1201 /* wake all in the range and autoremove */
1202 if (waitqueue_active(&ctx->fault_pending_wqh))
1203 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1204 range);
1205 if (waitqueue_active(&ctx->fault_wqh))
1206 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
1207 spin_unlock(&ctx->fault_pending_wqh.lock);
1210 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1211 struct userfaultfd_wake_range *range)
1213 unsigned seq;
1214 bool need_wakeup;
1217 * To be sure waitqueue_active() is not reordered by the CPU
1218 * before the pagetable update, use an explicit SMP memory
1219 * barrier here. PT lock release or up_read(mmap_sem) still
1220 * have release semantics that can allow the
1221 * waitqueue_active() to be reordered before the pte update.
1223 smp_mb();
1226 * Use waitqueue_active because it's very frequent to
1227 * change the address space atomically even if there are no
1228 * userfaults yet. So we take the spinlock only when we're
1229 * sure we've userfaults to wake.
1231 do {
1232 seq = read_seqcount_begin(&ctx->refile_seq);
1233 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1234 waitqueue_active(&ctx->fault_wqh);
1235 cond_resched();
1236 } while (read_seqcount_retry(&ctx->refile_seq, seq));
1237 if (need_wakeup)
1238 __wake_userfault(ctx, range);
1241 static __always_inline int validate_range(struct mm_struct *mm,
1242 __u64 start, __u64 len)
1244 __u64 task_size = mm->task_size;
1246 if (start & ~PAGE_MASK)
1247 return -EINVAL;
1248 if (len & ~PAGE_MASK)
1249 return -EINVAL;
1250 if (!len)
1251 return -EINVAL;
1252 if (start < mmap_min_addr)
1253 return -EINVAL;
1254 if (start >= task_size)
1255 return -EINVAL;
1256 if (len > task_size - start)
1257 return -EINVAL;
1258 return 0;
1261 static inline bool vma_can_userfault(struct vm_area_struct *vma)
1263 return vma_is_anonymous(vma) || is_vm_hugetlb_page(vma) ||
1264 vma_is_shmem(vma);
1267 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1268 unsigned long arg)
1270 struct mm_struct *mm = ctx->mm;
1271 struct vm_area_struct *vma, *prev, *cur;
1272 int ret;
1273 struct uffdio_register uffdio_register;
1274 struct uffdio_register __user *user_uffdio_register;
1275 unsigned long vm_flags, new_flags;
1276 bool found;
1277 bool basic_ioctls;
1278 unsigned long start, end, vma_end;
1280 user_uffdio_register = (struct uffdio_register __user *) arg;
1282 ret = -EFAULT;
1283 if (copy_from_user(&uffdio_register, user_uffdio_register,
1284 sizeof(uffdio_register)-sizeof(__u64)))
1285 goto out;
1287 ret = -EINVAL;
1288 if (!uffdio_register.mode)
1289 goto out;
1290 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
1291 UFFDIO_REGISTER_MODE_WP))
1292 goto out;
1293 vm_flags = 0;
1294 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1295 vm_flags |= VM_UFFD_MISSING;
1296 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1297 vm_flags |= VM_UFFD_WP;
1299 * FIXME: remove the below error constraint by
1300 * implementing the wprotect tracking mode.
1302 ret = -EINVAL;
1303 goto out;
1306 ret = validate_range(mm, uffdio_register.range.start,
1307 uffdio_register.range.len);
1308 if (ret)
1309 goto out;
1311 start = uffdio_register.range.start;
1312 end = start + uffdio_register.range.len;
1314 ret = -ENOMEM;
1315 if (!mmget_not_zero(mm))
1316 goto out;
1318 down_write(&mm->mmap_sem);
1319 vma = find_vma_prev(mm, start, &prev);
1320 if (!vma)
1321 goto out_unlock;
1323 /* check that there's at least one vma in the range */
1324 ret = -EINVAL;
1325 if (vma->vm_start >= end)
1326 goto out_unlock;
1329 * If the first vma contains huge pages, make sure start address
1330 * is aligned to huge page size.
1332 if (is_vm_hugetlb_page(vma)) {
1333 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1335 if (start & (vma_hpagesize - 1))
1336 goto out_unlock;
1340 * Search for not compatible vmas.
1342 found = false;
1343 basic_ioctls = false;
1344 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1345 cond_resched();
1347 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1348 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1350 /* check not compatible vmas */
1351 ret = -EINVAL;
1352 if (!vma_can_userfault(cur))
1353 goto out_unlock;
1355 * If this vma contains ending address, and huge pages
1356 * check alignment.
1358 if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1359 end > cur->vm_start) {
1360 unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1362 ret = -EINVAL;
1364 if (end & (vma_hpagesize - 1))
1365 goto out_unlock;
1369 * Check that this vma isn't already owned by a
1370 * different userfaultfd. We can't allow more than one
1371 * userfaultfd to own a single vma simultaneously or we
1372 * wouldn't know which one to deliver the userfaults to.
1374 ret = -EBUSY;
1375 if (cur->vm_userfaultfd_ctx.ctx &&
1376 cur->vm_userfaultfd_ctx.ctx != ctx)
1377 goto out_unlock;
1380 * Note vmas containing huge pages
1382 if (is_vm_hugetlb_page(cur))
1383 basic_ioctls = true;
1385 found = true;
1387 BUG_ON(!found);
1389 if (vma->vm_start < start)
1390 prev = vma;
1392 ret = 0;
1393 do {
1394 cond_resched();
1396 BUG_ON(!vma_can_userfault(vma));
1397 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
1398 vma->vm_userfaultfd_ctx.ctx != ctx);
1401 * Nothing to do: this vma is already registered into this
1402 * userfaultfd and with the right tracking mode too.
1404 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
1405 (vma->vm_flags & vm_flags) == vm_flags)
1406 goto skip;
1408 if (vma->vm_start > start)
1409 start = vma->vm_start;
1410 vma_end = min(end, vma->vm_end);
1412 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
1413 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1414 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1415 vma_policy(vma),
1416 ((struct vm_userfaultfd_ctx){ ctx }));
1417 if (prev) {
1418 vma = prev;
1419 goto next;
1421 if (vma->vm_start < start) {
1422 ret = split_vma(mm, vma, start, 1);
1423 if (ret)
1424 break;
1426 if (vma->vm_end > end) {
1427 ret = split_vma(mm, vma, end, 0);
1428 if (ret)
1429 break;
1431 next:
1433 * In the vma_merge() successful mprotect-like case 8:
1434 * the next vma was merged into the current one and
1435 * the current one has not been updated yet.
1437 vma->vm_flags = new_flags;
1438 vma->vm_userfaultfd_ctx.ctx = ctx;
1440 skip:
1441 prev = vma;
1442 start = vma->vm_end;
1443 vma = vma->vm_next;
1444 } while (vma && vma->vm_start < end);
1445 out_unlock:
1446 up_write(&mm->mmap_sem);
1447 mmput(mm);
1448 if (!ret) {
1450 * Now that we scanned all vmas we can already tell
1451 * userland which ioctls methods are guaranteed to
1452 * succeed on this range.
1454 if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1455 UFFD_API_RANGE_IOCTLS,
1456 &user_uffdio_register->ioctls))
1457 ret = -EFAULT;
1459 out:
1460 return ret;
1463 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1464 unsigned long arg)
1466 struct mm_struct *mm = ctx->mm;
1467 struct vm_area_struct *vma, *prev, *cur;
1468 int ret;
1469 struct uffdio_range uffdio_unregister;
1470 unsigned long new_flags;
1471 bool found;
1472 unsigned long start, end, vma_end;
1473 const void __user *buf = (void __user *)arg;
1475 ret = -EFAULT;
1476 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1477 goto out;
1479 ret = validate_range(mm, uffdio_unregister.start,
1480 uffdio_unregister.len);
1481 if (ret)
1482 goto out;
1484 start = uffdio_unregister.start;
1485 end = start + uffdio_unregister.len;
1487 ret = -ENOMEM;
1488 if (!mmget_not_zero(mm))
1489 goto out;
1491 down_write(&mm->mmap_sem);
1492 vma = find_vma_prev(mm, start, &prev);
1493 if (!vma)
1494 goto out_unlock;
1496 /* check that there's at least one vma in the range */
1497 ret = -EINVAL;
1498 if (vma->vm_start >= end)
1499 goto out_unlock;
1502 * If the first vma contains huge pages, make sure start address
1503 * is aligned to huge page size.
1505 if (is_vm_hugetlb_page(vma)) {
1506 unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1508 if (start & (vma_hpagesize - 1))
1509 goto out_unlock;
1513 * Search for not compatible vmas.
1515 found = false;
1516 ret = -EINVAL;
1517 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
1518 cond_resched();
1520 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
1521 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
1524 * Check not compatible vmas, not strictly required
1525 * here as not compatible vmas cannot have an
1526 * userfaultfd_ctx registered on them, but this
1527 * provides for more strict behavior to notice
1528 * unregistration errors.
1530 if (!vma_can_userfault(cur))
1531 goto out_unlock;
1533 found = true;
1535 BUG_ON(!found);
1537 if (vma->vm_start < start)
1538 prev = vma;
1540 ret = 0;
1541 do {
1542 cond_resched();
1544 BUG_ON(!vma_can_userfault(vma));
1547 * Nothing to do: this vma is already registered into this
1548 * userfaultfd and with the right tracking mode too.
1550 if (!vma->vm_userfaultfd_ctx.ctx)
1551 goto skip;
1553 if (vma->vm_start > start)
1554 start = vma->vm_start;
1555 vma_end = min(end, vma->vm_end);
1557 if (userfaultfd_missing(vma)) {
1559 * Wake any concurrent pending userfault while
1560 * we unregister, so they will not hang
1561 * permanently and it avoids userland to call
1562 * UFFDIO_WAKE explicitly.
1564 struct userfaultfd_wake_range range;
1565 range.start = start;
1566 range.len = vma_end - start;
1567 wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1570 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
1571 prev = vma_merge(mm, prev, start, vma_end, new_flags,
1572 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
1573 vma_policy(vma),
1574 NULL_VM_UFFD_CTX);
1575 if (prev) {
1576 vma = prev;
1577 goto next;
1579 if (vma->vm_start < start) {
1580 ret = split_vma(mm, vma, start, 1);
1581 if (ret)
1582 break;
1584 if (vma->vm_end > end) {
1585 ret = split_vma(mm, vma, end, 0);
1586 if (ret)
1587 break;
1589 next:
1591 * In the vma_merge() successful mprotect-like case 8:
1592 * the next vma was merged into the current one and
1593 * the current one has not been updated yet.
1595 vma->vm_flags = new_flags;
1596 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1598 skip:
1599 prev = vma;
1600 start = vma->vm_end;
1601 vma = vma->vm_next;
1602 } while (vma && vma->vm_start < end);
1603 out_unlock:
1604 up_write(&mm->mmap_sem);
1605 mmput(mm);
1606 out:
1607 return ret;
1611 * userfaultfd_wake may be used in combination with the
1612 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1614 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1615 unsigned long arg)
1617 int ret;
1618 struct uffdio_range uffdio_wake;
1619 struct userfaultfd_wake_range range;
1620 const void __user *buf = (void __user *)arg;
1622 ret = -EFAULT;
1623 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1624 goto out;
1626 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1627 if (ret)
1628 goto out;
1630 range.start = uffdio_wake.start;
1631 range.len = uffdio_wake.len;
1634 * len == 0 means wake all and we don't want to wake all here,
1635 * so check it again to be sure.
1637 VM_BUG_ON(!range.len);
1639 wake_userfault(ctx, &range);
1640 ret = 0;
1642 out:
1643 return ret;
1646 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1647 unsigned long arg)
1649 __s64 ret;
1650 struct uffdio_copy uffdio_copy;
1651 struct uffdio_copy __user *user_uffdio_copy;
1652 struct userfaultfd_wake_range range;
1654 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1656 ret = -EFAULT;
1657 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1658 /* don't copy "copy" last field */
1659 sizeof(uffdio_copy)-sizeof(__s64)))
1660 goto out;
1662 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1663 if (ret)
1664 goto out;
1666 * double check for wraparound just in case. copy_from_user()
1667 * will later check uffdio_copy.src + uffdio_copy.len to fit
1668 * in the userland range.
1670 ret = -EINVAL;
1671 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1672 goto out;
1673 if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1674 goto out;
1675 if (mmget_not_zero(ctx->mm)) {
1676 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1677 uffdio_copy.len);
1678 mmput(ctx->mm);
1679 } else {
1680 return -ESRCH;
1682 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1683 return -EFAULT;
1684 if (ret < 0)
1685 goto out;
1686 BUG_ON(!ret);
1687 /* len == 0 would wake all */
1688 range.len = ret;
1689 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1690 range.start = uffdio_copy.dst;
1691 wake_userfault(ctx, &range);
1693 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1694 out:
1695 return ret;
1698 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1699 unsigned long arg)
1701 __s64 ret;
1702 struct uffdio_zeropage uffdio_zeropage;
1703 struct uffdio_zeropage __user *user_uffdio_zeropage;
1704 struct userfaultfd_wake_range range;
1706 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1708 ret = -EFAULT;
1709 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1710 /* don't copy "zeropage" last field */
1711 sizeof(uffdio_zeropage)-sizeof(__s64)))
1712 goto out;
1714 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1715 uffdio_zeropage.range.len);
1716 if (ret)
1717 goto out;
1718 ret = -EINVAL;
1719 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1720 goto out;
1722 if (mmget_not_zero(ctx->mm)) {
1723 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1724 uffdio_zeropage.range.len);
1725 mmput(ctx->mm);
1726 } else {
1727 return -ESRCH;
1729 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1730 return -EFAULT;
1731 if (ret < 0)
1732 goto out;
1733 /* len == 0 would wake all */
1734 BUG_ON(!ret);
1735 range.len = ret;
1736 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1737 range.start = uffdio_zeropage.range.start;
1738 wake_userfault(ctx, &range);
1740 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1741 out:
1742 return ret;
1745 static inline unsigned int uffd_ctx_features(__u64 user_features)
1748 * For the current set of features the bits just coincide
1750 return (unsigned int)user_features;
1754 * userland asks for a certain API version and we return which bits
1755 * and ioctl commands are implemented in this kernel for such API
1756 * version or -EINVAL if unknown.
1758 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1759 unsigned long arg)
1761 struct uffdio_api uffdio_api;
1762 void __user *buf = (void __user *)arg;
1763 int ret;
1764 __u64 features;
1766 ret = -EINVAL;
1767 if (ctx->state != UFFD_STATE_WAIT_API)
1768 goto out;
1769 ret = -EFAULT;
1770 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1771 goto out;
1772 features = uffdio_api.features;
1773 if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES)) {
1774 memset(&uffdio_api, 0, sizeof(uffdio_api));
1775 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1776 goto out;
1777 ret = -EINVAL;
1778 goto out;
1780 /* report all available features and ioctls to userland */
1781 uffdio_api.features = UFFD_API_FEATURES;
1782 uffdio_api.ioctls = UFFD_API_IOCTLS;
1783 ret = -EFAULT;
1784 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1785 goto out;
1786 ctx->state = UFFD_STATE_RUNNING;
1787 /* only enable the requested features for this uffd context */
1788 ctx->features = uffd_ctx_features(features);
1789 ret = 0;
1790 out:
1791 return ret;
1794 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1795 unsigned long arg)
1797 int ret = -EINVAL;
1798 struct userfaultfd_ctx *ctx = file->private_data;
1800 if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1801 return -EINVAL;
1803 switch(cmd) {
1804 case UFFDIO_API:
1805 ret = userfaultfd_api(ctx, arg);
1806 break;
1807 case UFFDIO_REGISTER:
1808 ret = userfaultfd_register(ctx, arg);
1809 break;
1810 case UFFDIO_UNREGISTER:
1811 ret = userfaultfd_unregister(ctx, arg);
1812 break;
1813 case UFFDIO_WAKE:
1814 ret = userfaultfd_wake(ctx, arg);
1815 break;
1816 case UFFDIO_COPY:
1817 ret = userfaultfd_copy(ctx, arg);
1818 break;
1819 case UFFDIO_ZEROPAGE:
1820 ret = userfaultfd_zeropage(ctx, arg);
1821 break;
1823 return ret;
1826 #ifdef CONFIG_PROC_FS
1827 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1829 struct userfaultfd_ctx *ctx = f->private_data;
1830 wait_queue_entry_t *wq;
1831 struct userfaultfd_wait_queue *uwq;
1832 unsigned long pending = 0, total = 0;
1834 spin_lock(&ctx->fault_pending_wqh.lock);
1835 list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
1836 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1837 pending++;
1838 total++;
1840 list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
1841 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1842 total++;
1844 spin_unlock(&ctx->fault_pending_wqh.lock);
1847 * If more protocols will be added, there will be all shown
1848 * separated by a space. Like this:
1849 * protocols: aa:... bb:...
1851 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1852 pending, total, UFFD_API, ctx->features,
1853 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1855 #endif
1857 static const struct file_operations userfaultfd_fops = {
1858 #ifdef CONFIG_PROC_FS
1859 .show_fdinfo = userfaultfd_show_fdinfo,
1860 #endif
1861 .release = userfaultfd_release,
1862 .poll = userfaultfd_poll,
1863 .read = userfaultfd_read,
1864 .unlocked_ioctl = userfaultfd_ioctl,
1865 .compat_ioctl = userfaultfd_ioctl,
1866 .llseek = noop_llseek,
1869 static void init_once_userfaultfd_ctx(void *mem)
1871 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1873 init_waitqueue_head(&ctx->fault_pending_wqh);
1874 init_waitqueue_head(&ctx->fault_wqh);
1875 init_waitqueue_head(&ctx->event_wqh);
1876 init_waitqueue_head(&ctx->fd_wqh);
1877 seqcount_init(&ctx->refile_seq);
1880 SYSCALL_DEFINE1(userfaultfd, int, flags)
1882 struct userfaultfd_ctx *ctx;
1883 int fd;
1885 BUG_ON(!current->mm);
1887 /* Check the UFFD_* constants for consistency. */
1888 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1889 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1891 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1892 return -EINVAL;
1894 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1895 if (!ctx)
1896 return -ENOMEM;
1898 atomic_set(&ctx->refcount, 1);
1899 ctx->flags = flags;
1900 ctx->features = 0;
1901 ctx->state = UFFD_STATE_WAIT_API;
1902 ctx->released = false;
1903 ctx->mm = current->mm;
1904 /* prevent the mm struct to be freed */
1905 mmgrab(ctx->mm);
1907 fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, ctx,
1908 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1909 if (fd < 0) {
1910 mmdrop(ctx->mm);
1911 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1913 return fd;
1916 static int __init userfaultfd_init(void)
1918 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1919 sizeof(struct userfaultfd_ctx),
1921 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1922 init_once_userfaultfd_ctx);
1923 return 0;
1925 __initcall(userfaultfd_init);