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