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