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