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