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