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