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