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