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