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