platform: fimc: fix bitwise negation of a boolean expression
[GitHub/exynos8895/android_kernel_samsung_universal8895.git] / fs / userfaultfd.c
1 /*
2 * fs/userfaultfd.c
3 *
4 * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
5 * Copyright (C) 2008-2009 Red Hat, Inc.
6 * Copyright (C) 2015 Red Hat, Inc.
7 *
8 * This work is licensed under the terms of the GNU GPL, version 2. See
9 * the COPYING file in the top-level directory.
10 *
11 * Some part derived from fs/eventfd.c (anon inode setup) and
12 * mm/ksm.c (mm hashing).
13 */
14
15 #include <linux/hashtable.h>
16 #include <linux/sched.h>
17 #include <linux/mm.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/seq_file.h>
21 #include <linux/file.h>
22 #include <linux/bug.h>
23 #include <linux/anon_inodes.h>
24 #include <linux/syscalls.h>
25 #include <linux/userfaultfd_k.h>
26 #include <linux/mempolicy.h>
27 #include <linux/ioctl.h>
28 #include <linux/security.h>
29
30 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
31
32 enum userfaultfd_state {
33 UFFD_STATE_WAIT_API,
34 UFFD_STATE_RUNNING,
35 };
36
37 /*
38 * Start with fault_pending_wqh and fault_wqh so they're more likely
39 * to be in the same cacheline.
40 */
41 struct userfaultfd_ctx {
42 /* waitqueue head for the pending (i.e. not read) userfaults */
43 wait_queue_head_t fault_pending_wqh;
44 /* waitqueue head for the userfaults */
45 wait_queue_head_t fault_wqh;
46 /* waitqueue head for the pseudo fd to wakeup poll/read */
47 wait_queue_head_t fd_wqh;
48 /* a refile sequence protected by fault_pending_wqh lock */
49 struct seqcount refile_seq;
50 /* pseudo fd refcounting */
51 atomic_t refcount;
52 /* userfaultfd syscall flags */
53 unsigned int flags;
54 /* state machine */
55 enum userfaultfd_state state;
56 /* released */
57 bool released;
58 /* mm with one ore more vmas attached to this userfaultfd_ctx */
59 struct mm_struct *mm;
60 };
61
62 struct userfaultfd_wait_queue {
63 struct uffd_msg msg;
64 wait_queue_t wq;
65 struct userfaultfd_ctx *ctx;
66 };
67
68 struct userfaultfd_wake_range {
69 unsigned long start;
70 unsigned long len;
71 };
72
73 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
74 int wake_flags, void *key)
75 {
76 struct userfaultfd_wake_range *range = key;
77 int ret;
78 struct userfaultfd_wait_queue *uwq;
79 unsigned long start, len;
80
81 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
82 ret = 0;
83 /* len == 0 means wake all */
84 start = range->start;
85 len = range->len;
86 if (len && (start > uwq->msg.arg.pagefault.address ||
87 start + len <= uwq->msg.arg.pagefault.address))
88 goto out;
89 ret = wake_up_state(wq->private, mode);
90 if (ret)
91 /*
92 * Wake only once, autoremove behavior.
93 *
94 * After the effect of list_del_init is visible to the
95 * other CPUs, the waitqueue may disappear from under
96 * us, see the !list_empty_careful() in
97 * handle_userfault(). try_to_wake_up() has an
98 * implicit smp_mb__before_spinlock, and the
99 * wq->private is read before calling the extern
100 * function "wake_up_state" (which in turns calls
101 * try_to_wake_up). While the spin_lock;spin_unlock;
102 * wouldn't be enough, the smp_mb__before_spinlock is
103 * enough to avoid an explicit smp_mb() here.
104 */
105 list_del_init(&wq->task_list);
106 out:
107 return ret;
108 }
109
110 /**
111 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
112 * context.
113 * @ctx: [in] Pointer to the userfaultfd context.
114 *
115 * Returns: In case of success, returns not zero.
116 */
117 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
118 {
119 if (!atomic_inc_not_zero(&ctx->refcount))
120 BUG();
121 }
122
123 /**
124 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
125 * context.
126 * @ctx: [in] Pointer to userfaultfd context.
127 *
128 * The userfaultfd context reference must have been previously acquired either
129 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
130 */
131 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
132 {
133 if (atomic_dec_and_test(&ctx->refcount)) {
134 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
135 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
136 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
137 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
138 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
139 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
140 mmput(ctx->mm);
141 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
142 }
143 }
144
145 static inline void msg_init(struct uffd_msg *msg)
146 {
147 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
148 /*
149 * Must use memset to zero out the paddings or kernel data is
150 * leaked to userland.
151 */
152 memset(msg, 0, sizeof(struct uffd_msg));
153 }
154
155 static inline struct uffd_msg userfault_msg(unsigned long address,
156 unsigned int flags,
157 unsigned long reason)
158 {
159 struct uffd_msg msg;
160 msg_init(&msg);
161 msg.event = UFFD_EVENT_PAGEFAULT;
162 msg.arg.pagefault.address = address;
163 if (flags & FAULT_FLAG_WRITE)
164 /*
165 * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the
166 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
167 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
168 * was a read fault, otherwise if set it means it's
169 * a write fault.
170 */
171 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
172 if (reason & VM_UFFD_WP)
173 /*
174 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
175 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
176 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
177 * a missing fault, otherwise if set it means it's a
178 * write protect fault.
179 */
180 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
181 return msg;
182 }
183
184 /*
185 * Verify the pagetables are still not ok after having reigstered into
186 * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
187 * userfault that has already been resolved, if userfaultfd_read and
188 * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
189 * threads.
190 */
191 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
192 unsigned long address,
193 unsigned long flags,
194 unsigned long reason)
195 {
196 struct mm_struct *mm = ctx->mm;
197 pgd_t *pgd;
198 pud_t *pud;
199 pmd_t *pmd, _pmd;
200 pte_t *pte;
201 bool ret = true;
202
203 VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
204
205 pgd = pgd_offset(mm, address);
206 if (!pgd_present(*pgd))
207 goto out;
208 pud = pud_offset(pgd, address);
209 if (!pud_present(*pud))
210 goto out;
211 pmd = pmd_offset(pud, address);
212 /*
213 * READ_ONCE must function as a barrier with narrower scope
214 * and it must be equivalent to:
215 * _pmd = *pmd; barrier();
216 *
217 * This is to deal with the instability (as in
218 * pmd_trans_unstable) of the pmd.
219 */
220 _pmd = READ_ONCE(*pmd);
221 if (!pmd_present(_pmd))
222 goto out;
223
224 ret = false;
225 if (pmd_trans_huge(_pmd))
226 goto out;
227
228 /*
229 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
230 * and use the standard pte_offset_map() instead of parsing _pmd.
231 */
232 pte = pte_offset_map(pmd, address);
233 /*
234 * Lockless access: we're in a wait_event so it's ok if it
235 * changes under us.
236 */
237 if (pte_none(*pte))
238 ret = true;
239 pte_unmap(pte);
240
241 out:
242 return ret;
243 }
244
245 /*
246 * The locking rules involved in returning VM_FAULT_RETRY depending on
247 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
248 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
249 * recommendation in __lock_page_or_retry is not an understatement.
250 *
251 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
252 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
253 * not set.
254 *
255 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
256 * set, VM_FAULT_RETRY can still be returned if and only if there are
257 * fatal_signal_pending()s, and the mmap_sem must be released before
258 * returning it.
259 */
260 int handle_userfault(struct vm_area_struct *vma, unsigned long address,
261 unsigned int flags, unsigned long reason)
262 {
263 struct mm_struct *mm = vma->vm_mm;
264 struct userfaultfd_ctx *ctx;
265 struct userfaultfd_wait_queue uwq;
266 int ret;
267 bool must_wait, return_to_userland;
268
269 BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
270
271 ret = VM_FAULT_SIGBUS;
272 ctx = vma->vm_userfaultfd_ctx.ctx;
273 if (!ctx)
274 goto out;
275
276 BUG_ON(ctx->mm != mm);
277
278 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
279 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
280
281 /*
282 * If it's already released don't get it. This avoids to loop
283 * in __get_user_pages if userfaultfd_release waits on the
284 * caller of handle_userfault to release the mmap_sem.
285 */
286 if (unlikely(ACCESS_ONCE(ctx->released)))
287 goto out;
288
289 /*
290 * We don't do userfault handling for the final child pid update.
291 */
292 if (current->flags & PF_EXITING)
293 goto out;
294
295 /*
296 * Check that we can return VM_FAULT_RETRY.
297 *
298 * NOTE: it should become possible to return VM_FAULT_RETRY
299 * even if FAULT_FLAG_TRIED is set without leading to gup()
300 * -EBUSY failures, if the userfaultfd is to be extended for
301 * VM_UFFD_WP tracking and we intend to arm the userfault
302 * without first stopping userland access to the memory. For
303 * VM_UFFD_MISSING userfaults this is enough for now.
304 */
305 if (unlikely(!(flags & FAULT_FLAG_ALLOW_RETRY))) {
306 /*
307 * Validate the invariant that nowait must allow retry
308 * to be sure not to return SIGBUS erroneously on
309 * nowait invocations.
310 */
311 BUG_ON(flags & FAULT_FLAG_RETRY_NOWAIT);
312 #ifdef CONFIG_DEBUG_VM
313 if (printk_ratelimit()) {
314 printk(KERN_WARNING
315 "FAULT_FLAG_ALLOW_RETRY missing %x\n", flags);
316 dump_stack();
317 }
318 #endif
319 goto out;
320 }
321
322 /*
323 * Handle nowait, not much to do other than tell it to retry
324 * and wait.
325 */
326 ret = VM_FAULT_RETRY;
327 if (flags & FAULT_FLAG_RETRY_NOWAIT)
328 goto out;
329
330 /* take the reference before dropping the mmap_sem */
331 userfaultfd_ctx_get(ctx);
332
333 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
334 uwq.wq.private = current;
335 uwq.msg = userfault_msg(address, flags, reason);
336 uwq.ctx = ctx;
337
338 return_to_userland = (flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
339 (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
340
341 spin_lock(&ctx->fault_pending_wqh.lock);
342 /*
343 * After the __add_wait_queue the uwq is visible to userland
344 * through poll/read().
345 */
346 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
347 /*
348 * The smp_mb() after __set_current_state prevents the reads
349 * following the spin_unlock to happen before the list_add in
350 * __add_wait_queue.
351 */
352 set_current_state(return_to_userland ? TASK_INTERRUPTIBLE :
353 TASK_KILLABLE);
354 spin_unlock(&ctx->fault_pending_wqh.lock);
355
356 must_wait = userfaultfd_must_wait(ctx, address, flags, reason);
357 up_read(&mm->mmap_sem);
358
359 if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
360 (return_to_userland ? !signal_pending(current) :
361 !fatal_signal_pending(current)))) {
362 wake_up_poll(&ctx->fd_wqh, POLLIN);
363 schedule();
364 ret |= VM_FAULT_MAJOR;
365 }
366
367 __set_current_state(TASK_RUNNING);
368
369 if (return_to_userland) {
370 if (signal_pending(current) &&
371 !fatal_signal_pending(current)) {
372 /*
373 * If we got a SIGSTOP or SIGCONT and this is
374 * a normal userland page fault, just let
375 * userland return so the signal will be
376 * handled and gdb debugging works. The page
377 * fault code immediately after we return from
378 * this function is going to release the
379 * mmap_sem and it's not depending on it
380 * (unlike gup would if we were not to return
381 * VM_FAULT_RETRY).
382 *
383 * If a fatal signal is pending we still take
384 * the streamlined VM_FAULT_RETRY failure path
385 * and there's no need to retake the mmap_sem
386 * in such case.
387 */
388 down_read(&mm->mmap_sem);
389 ret = VM_FAULT_NOPAGE;
390 }
391 }
392
393 /*
394 * Here we race with the list_del; list_add in
395 * userfaultfd_ctx_read(), however because we don't ever run
396 * list_del_init() to refile across the two lists, the prev
397 * and next pointers will never point to self. list_add also
398 * would never let any of the two pointers to point to
399 * self. So list_empty_careful won't risk to see both pointers
400 * pointing to self at any time during the list refile. The
401 * only case where list_del_init() is called is the full
402 * removal in the wake function and there we don't re-list_add
403 * and it's fine not to block on the spinlock. The uwq on this
404 * kernel stack can be released after the list_del_init.
405 */
406 if (!list_empty_careful(&uwq.wq.task_list)) {
407 spin_lock(&ctx->fault_pending_wqh.lock);
408 /*
409 * No need of list_del_init(), the uwq on the stack
410 * will be freed shortly anyway.
411 */
412 list_del(&uwq.wq.task_list);
413 spin_unlock(&ctx->fault_pending_wqh.lock);
414 }
415
416 /*
417 * ctx may go away after this if the userfault pseudo fd is
418 * already released.
419 */
420 userfaultfd_ctx_put(ctx);
421
422 out:
423 return ret;
424 }
425
426 static int userfaultfd_release(struct inode *inode, struct file *file)
427 {
428 struct userfaultfd_ctx *ctx = file->private_data;
429 struct mm_struct *mm = ctx->mm;
430 struct vm_area_struct *vma, *prev;
431 /* len == 0 means wake all */
432 struct userfaultfd_wake_range range = { .len = 0, };
433 unsigned long new_flags;
434
435 ACCESS_ONCE(ctx->released) = true;
436
437 /*
438 * Flush page faults out of all CPUs. NOTE: all page faults
439 * must be retried without returning VM_FAULT_SIGBUS if
440 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
441 * changes while handle_userfault released the mmap_sem. So
442 * it's critical that released is set to true (above), before
443 * taking the mmap_sem for writing.
444 */
445 down_write(&mm->mmap_sem);
446 prev = NULL;
447 for (vma = mm->mmap; vma; vma = vma->vm_next) {
448 cond_resched();
449 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
450 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
451 if (vma->vm_userfaultfd_ctx.ctx != ctx) {
452 prev = vma;
453 continue;
454 }
455 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
456 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
457 new_flags, vma->anon_vma,
458 vma->vm_file, vma->vm_pgoff,
459 vma_policy(vma),
460 NULL_VM_UFFD_CTX,
461 vma_get_anon_name(vma));
462 if (prev)
463 vma = prev;
464 else
465 prev = vma;
466 vma->vm_flags = new_flags;
467 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
468 }
469 up_write(&mm->mmap_sem);
470
471 /*
472 * After no new page faults can wait on this fault_*wqh, flush
473 * the last page faults that may have been already waiting on
474 * the fault_*wqh.
475 */
476 spin_lock(&ctx->fault_pending_wqh.lock);
477 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
478 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
479 spin_unlock(&ctx->fault_pending_wqh.lock);
480
481 wake_up_poll(&ctx->fd_wqh, POLLHUP);
482 userfaultfd_ctx_put(ctx);
483 return 0;
484 }
485
486 /* fault_pending_wqh.lock must be hold by the caller */
487 static inline struct userfaultfd_wait_queue *find_userfault(
488 struct userfaultfd_ctx *ctx)
489 {
490 wait_queue_t *wq;
491 struct userfaultfd_wait_queue *uwq;
492
493 VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
494
495 uwq = NULL;
496 if (!waitqueue_active(&ctx->fault_pending_wqh))
497 goto out;
498 /* walk in reverse to provide FIFO behavior to read userfaults */
499 wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
500 typeof(*wq), task_list);
501 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
502 out:
503 return uwq;
504 }
505
506 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
507 {
508 struct userfaultfd_ctx *ctx = file->private_data;
509 unsigned int ret;
510
511 poll_wait(file, &ctx->fd_wqh, wait);
512
513 switch (ctx->state) {
514 case UFFD_STATE_WAIT_API:
515 return POLLERR;
516 case UFFD_STATE_RUNNING:
517 /*
518 * poll() never guarantees that read won't block.
519 * userfaults can be waken before they're read().
520 */
521 if (unlikely(!(file->f_flags & O_NONBLOCK)))
522 return POLLERR;
523 /*
524 * lockless access to see if there are pending faults
525 * __pollwait last action is the add_wait_queue but
526 * the spin_unlock would allow the waitqueue_active to
527 * pass above the actual list_add inside
528 * add_wait_queue critical section. So use a full
529 * memory barrier to serialize the list_add write of
530 * add_wait_queue() with the waitqueue_active read
531 * below.
532 */
533 ret = 0;
534 smp_mb();
535 if (waitqueue_active(&ctx->fault_pending_wqh))
536 ret = POLLIN;
537 return ret;
538 default:
539 BUG();
540 }
541 }
542
543 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
544 struct uffd_msg *msg)
545 {
546 ssize_t ret;
547 DECLARE_WAITQUEUE(wait, current);
548 struct userfaultfd_wait_queue *uwq;
549
550 /* always take the fd_wqh lock before the fault_pending_wqh lock */
551 spin_lock(&ctx->fd_wqh.lock);
552 __add_wait_queue(&ctx->fd_wqh, &wait);
553 for (;;) {
554 set_current_state(TASK_INTERRUPTIBLE);
555 spin_lock(&ctx->fault_pending_wqh.lock);
556 uwq = find_userfault(ctx);
557 if (uwq) {
558 /*
559 * Use a seqcount to repeat the lockless check
560 * in wake_userfault() to avoid missing
561 * wakeups because during the refile both
562 * waitqueue could become empty if this is the
563 * only userfault.
564 */
565 write_seqcount_begin(&ctx->refile_seq);
566
567 /*
568 * The fault_pending_wqh.lock prevents the uwq
569 * to disappear from under us.
570 *
571 * Refile this userfault from
572 * fault_pending_wqh to fault_wqh, it's not
573 * pending anymore after we read it.
574 *
575 * Use list_del() by hand (as
576 * userfaultfd_wake_function also uses
577 * list_del_init() by hand) to be sure nobody
578 * changes __remove_wait_queue() to use
579 * list_del_init() in turn breaking the
580 * !list_empty_careful() check in
581 * handle_userfault(). The uwq->wq.task_list
582 * must never be empty at any time during the
583 * refile, or the waitqueue could disappear
584 * from under us. The "wait_queue_head_t"
585 * parameter of __remove_wait_queue() is unused
586 * anyway.
587 */
588 list_del(&uwq->wq.task_list);
589 __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
590
591 write_seqcount_end(&ctx->refile_seq);
592
593 /* careful to always initialize msg if ret == 0 */
594 *msg = uwq->msg;
595 spin_unlock(&ctx->fault_pending_wqh.lock);
596 ret = 0;
597 break;
598 }
599 spin_unlock(&ctx->fault_pending_wqh.lock);
600 if (signal_pending(current)) {
601 ret = -ERESTARTSYS;
602 break;
603 }
604 if (no_wait) {
605 ret = -EAGAIN;
606 break;
607 }
608 spin_unlock(&ctx->fd_wqh.lock);
609 schedule();
610 spin_lock(&ctx->fd_wqh.lock);
611 }
612 __remove_wait_queue(&ctx->fd_wqh, &wait);
613 __set_current_state(TASK_RUNNING);
614 spin_unlock(&ctx->fd_wqh.lock);
615
616 return ret;
617 }
618
619 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
620 size_t count, loff_t *ppos)
621 {
622 struct userfaultfd_ctx *ctx = file->private_data;
623 ssize_t _ret, ret = 0;
624 struct uffd_msg msg;
625 int no_wait = file->f_flags & O_NONBLOCK;
626
627 if (ctx->state == UFFD_STATE_WAIT_API)
628 return -EINVAL;
629
630 for (;;) {
631 if (count < sizeof(msg))
632 return ret ? ret : -EINVAL;
633 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
634 if (_ret < 0)
635 return ret ? ret : _ret;
636 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
637 return ret ? ret : -EFAULT;
638 ret += sizeof(msg);
639 buf += sizeof(msg);
640 count -= sizeof(msg);
641 /*
642 * Allow to read more than one fault at time but only
643 * block if waiting for the very first one.
644 */
645 no_wait = O_NONBLOCK;
646 }
647 }
648
649 static void __wake_userfault(struct userfaultfd_ctx *ctx,
650 struct userfaultfd_wake_range *range)
651 {
652 unsigned long start, end;
653
654 start = range->start;
655 end = range->start + range->len;
656
657 spin_lock(&ctx->fault_pending_wqh.lock);
658 /* wake all in the range and autoremove */
659 if (waitqueue_active(&ctx->fault_pending_wqh))
660 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
661 range);
662 if (waitqueue_active(&ctx->fault_wqh))
663 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
664 spin_unlock(&ctx->fault_pending_wqh.lock);
665 }
666
667 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
668 struct userfaultfd_wake_range *range)
669 {
670 unsigned seq;
671 bool need_wakeup;
672
673 /*
674 * To be sure waitqueue_active() is not reordered by the CPU
675 * before the pagetable update, use an explicit SMP memory
676 * barrier here. PT lock release or up_read(mmap_sem) still
677 * have release semantics that can allow the
678 * waitqueue_active() to be reordered before the pte update.
679 */
680 smp_mb();
681
682 /*
683 * Use waitqueue_active because it's very frequent to
684 * change the address space atomically even if there are no
685 * userfaults yet. So we take the spinlock only when we're
686 * sure we've userfaults to wake.
687 */
688 do {
689 seq = read_seqcount_begin(&ctx->refile_seq);
690 need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
691 waitqueue_active(&ctx->fault_wqh);
692 cond_resched();
693 } while (read_seqcount_retry(&ctx->refile_seq, seq));
694 if (need_wakeup)
695 __wake_userfault(ctx, range);
696 }
697
698 static __always_inline int validate_range(struct mm_struct *mm,
699 __u64 start, __u64 len)
700 {
701 __u64 task_size = mm->task_size;
702
703 if (start & ~PAGE_MASK)
704 return -EINVAL;
705 if (len & ~PAGE_MASK)
706 return -EINVAL;
707 if (!len)
708 return -EINVAL;
709 if (start < mmap_min_addr)
710 return -EINVAL;
711 if (start >= task_size)
712 return -EINVAL;
713 if (len > task_size - start)
714 return -EINVAL;
715 return 0;
716 }
717
718 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
719 unsigned long arg)
720 {
721 struct mm_struct *mm = ctx->mm;
722 struct vm_area_struct *vma, *prev, *cur;
723 int ret;
724 struct uffdio_register uffdio_register;
725 struct uffdio_register __user *user_uffdio_register;
726 unsigned long vm_flags, new_flags;
727 bool found;
728 unsigned long start, end, vma_end;
729
730 user_uffdio_register = (struct uffdio_register __user *) arg;
731
732 ret = -EFAULT;
733 if (copy_from_user(&uffdio_register, user_uffdio_register,
734 sizeof(uffdio_register)-sizeof(__u64)))
735 goto out;
736
737 ret = -EINVAL;
738 if (!uffdio_register.mode)
739 goto out;
740 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
741 UFFDIO_REGISTER_MODE_WP))
742 goto out;
743 vm_flags = 0;
744 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
745 vm_flags |= VM_UFFD_MISSING;
746 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
747 vm_flags |= VM_UFFD_WP;
748 /*
749 * FIXME: remove the below error constraint by
750 * implementing the wprotect tracking mode.
751 */
752 ret = -EINVAL;
753 goto out;
754 }
755
756 ret = validate_range(mm, uffdio_register.range.start,
757 uffdio_register.range.len);
758 if (ret)
759 goto out;
760
761 start = uffdio_register.range.start;
762 end = start + uffdio_register.range.len;
763
764 down_write(&mm->mmap_sem);
765 vma = find_vma_prev(mm, start, &prev);
766
767 ret = -ENOMEM;
768 if (!vma)
769 goto out_unlock;
770
771 /* check that there's at least one vma in the range */
772 ret = -EINVAL;
773 if (vma->vm_start >= end)
774 goto out_unlock;
775
776 /*
777 * Search for not compatible vmas.
778 *
779 * FIXME: this shall be relaxed later so that it doesn't fail
780 * on tmpfs backed vmas (in addition to the current allowance
781 * on anonymous vmas).
782 */
783 found = false;
784 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
785 cond_resched();
786
787 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
788 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
789
790 /* check not compatible vmas */
791 ret = -EINVAL;
792 if (cur->vm_ops)
793 goto out_unlock;
794
795 /*
796 * Check that this vma isn't already owned by a
797 * different userfaultfd. We can't allow more than one
798 * userfaultfd to own a single vma simultaneously or we
799 * wouldn't know which one to deliver the userfaults to.
800 */
801 ret = -EBUSY;
802 if (cur->vm_userfaultfd_ctx.ctx &&
803 cur->vm_userfaultfd_ctx.ctx != ctx)
804 goto out_unlock;
805
806 found = true;
807 }
808 BUG_ON(!found);
809
810 if (vma->vm_start < start)
811 prev = vma;
812
813 ret = 0;
814 do {
815 cond_resched();
816
817 BUG_ON(vma->vm_ops);
818 BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
819 vma->vm_userfaultfd_ctx.ctx != ctx);
820
821 /*
822 * Nothing to do: this vma is already registered into this
823 * userfaultfd and with the right tracking mode too.
824 */
825 if (vma->vm_userfaultfd_ctx.ctx == ctx &&
826 (vma->vm_flags & vm_flags) == vm_flags)
827 goto skip;
828
829 if (vma->vm_start > start)
830 start = vma->vm_start;
831 vma_end = min(end, vma->vm_end);
832
833 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
834 prev = vma_merge(mm, prev, start, vma_end, new_flags,
835 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
836 vma_policy(vma),
837 ((struct vm_userfaultfd_ctx){ ctx }),
838 vma_get_anon_name(vma));
839 if (prev) {
840 vma = prev;
841 goto next;
842 }
843 if (vma->vm_start < start) {
844 ret = split_vma(mm, vma, start, 1);
845 if (ret)
846 break;
847 }
848 if (vma->vm_end > end) {
849 ret = split_vma(mm, vma, end, 0);
850 if (ret)
851 break;
852 }
853 next:
854 /*
855 * In the vma_merge() successful mprotect-like case 8:
856 * the next vma was merged into the current one and
857 * the current one has not been updated yet.
858 */
859 vma->vm_flags = new_flags;
860 vma->vm_userfaultfd_ctx.ctx = ctx;
861
862 skip:
863 prev = vma;
864 start = vma->vm_end;
865 vma = vma->vm_next;
866 } while (vma && vma->vm_start < end);
867 out_unlock:
868 up_write(&mm->mmap_sem);
869 if (!ret) {
870 /*
871 * Now that we scanned all vmas we can already tell
872 * userland which ioctls methods are guaranteed to
873 * succeed on this range.
874 */
875 if (put_user(UFFD_API_RANGE_IOCTLS,
876 &user_uffdio_register->ioctls))
877 ret = -EFAULT;
878 }
879 out:
880 return ret;
881 }
882
883 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
884 unsigned long arg)
885 {
886 struct mm_struct *mm = ctx->mm;
887 struct vm_area_struct *vma, *prev, *cur;
888 int ret;
889 struct uffdio_range uffdio_unregister;
890 unsigned long new_flags;
891 bool found;
892 unsigned long start, end, vma_end;
893 const void __user *buf = (void __user *)arg;
894
895 ret = -EFAULT;
896 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
897 goto out;
898
899 ret = validate_range(mm, uffdio_unregister.start,
900 uffdio_unregister.len);
901 if (ret)
902 goto out;
903
904 start = uffdio_unregister.start;
905 end = start + uffdio_unregister.len;
906
907 down_write(&mm->mmap_sem);
908 vma = find_vma_prev(mm, start, &prev);
909
910 ret = -ENOMEM;
911 if (!vma)
912 goto out_unlock;
913
914 /* check that there's at least one vma in the range */
915 ret = -EINVAL;
916 if (vma->vm_start >= end)
917 goto out_unlock;
918
919 /*
920 * Search for not compatible vmas.
921 *
922 * FIXME: this shall be relaxed later so that it doesn't fail
923 * on tmpfs backed vmas (in addition to the current allowance
924 * on anonymous vmas).
925 */
926 found = false;
927 ret = -EINVAL;
928 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
929 cond_resched();
930
931 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
932 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
933
934 /*
935 * Check not compatible vmas, not strictly required
936 * here as not compatible vmas cannot have an
937 * userfaultfd_ctx registered on them, but this
938 * provides for more strict behavior to notice
939 * unregistration errors.
940 */
941 if (cur->vm_ops)
942 goto out_unlock;
943
944 found = true;
945 }
946 BUG_ON(!found);
947
948 if (vma->vm_start < start)
949 prev = vma;
950
951 ret = 0;
952 do {
953 cond_resched();
954
955 BUG_ON(vma->vm_ops);
956
957 /*
958 * Nothing to do: this vma is already registered into this
959 * userfaultfd and with the right tracking mode too.
960 */
961 if (!vma->vm_userfaultfd_ctx.ctx)
962 goto skip;
963
964 if (vma->vm_start > start)
965 start = vma->vm_start;
966 vma_end = min(end, vma->vm_end);
967
968 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
969 prev = vma_merge(mm, prev, start, vma_end, new_flags,
970 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
971 vma_policy(vma),
972 NULL_VM_UFFD_CTX,
973 vma_get_anon_name(vma));
974 if (prev) {
975 vma = prev;
976 goto next;
977 }
978 if (vma->vm_start < start) {
979 ret = split_vma(mm, vma, start, 1);
980 if (ret)
981 break;
982 }
983 if (vma->vm_end > end) {
984 ret = split_vma(mm, vma, end, 0);
985 if (ret)
986 break;
987 }
988 next:
989 /*
990 * In the vma_merge() successful mprotect-like case 8:
991 * the next vma was merged into the current one and
992 * the current one has not been updated yet.
993 */
994 vma->vm_flags = new_flags;
995 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
996
997 skip:
998 prev = vma;
999 start = vma->vm_end;
1000 vma = vma->vm_next;
1001 } while (vma && vma->vm_start < end);
1002 out_unlock:
1003 up_write(&mm->mmap_sem);
1004 out:
1005 return ret;
1006 }
1007
1008 /*
1009 * userfaultfd_wake may be used in combination with the
1010 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1011 */
1012 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1013 unsigned long arg)
1014 {
1015 int ret;
1016 struct uffdio_range uffdio_wake;
1017 struct userfaultfd_wake_range range;
1018 const void __user *buf = (void __user *)arg;
1019
1020 ret = -EFAULT;
1021 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1022 goto out;
1023
1024 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1025 if (ret)
1026 goto out;
1027
1028 range.start = uffdio_wake.start;
1029 range.len = uffdio_wake.len;
1030
1031 /*
1032 * len == 0 means wake all and we don't want to wake all here,
1033 * so check it again to be sure.
1034 */
1035 VM_BUG_ON(!range.len);
1036
1037 wake_userfault(ctx, &range);
1038 ret = 0;
1039
1040 out:
1041 return ret;
1042 }
1043
1044 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1045 unsigned long arg)
1046 {
1047 __s64 ret;
1048 struct uffdio_copy uffdio_copy;
1049 struct uffdio_copy __user *user_uffdio_copy;
1050 struct userfaultfd_wake_range range;
1051
1052 user_uffdio_copy = (struct uffdio_copy __user *) arg;
1053
1054 ret = -EFAULT;
1055 if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1056 /* don't copy "copy" last field */
1057 sizeof(uffdio_copy)-sizeof(__s64)))
1058 goto out;
1059
1060 ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1061 if (ret)
1062 goto out;
1063 /*
1064 * double check for wraparound just in case. copy_from_user()
1065 * will later check uffdio_copy.src + uffdio_copy.len to fit
1066 * in the userland range.
1067 */
1068 ret = -EINVAL;
1069 if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1070 goto out;
1071 if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1072 goto out;
1073
1074 ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1075 uffdio_copy.len);
1076 if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1077 return -EFAULT;
1078 if (ret < 0)
1079 goto out;
1080 BUG_ON(!ret);
1081 /* len == 0 would wake all */
1082 range.len = ret;
1083 if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1084 range.start = uffdio_copy.dst;
1085 wake_userfault(ctx, &range);
1086 }
1087 ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1088 out:
1089 return ret;
1090 }
1091
1092 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1093 unsigned long arg)
1094 {
1095 __s64 ret;
1096 struct uffdio_zeropage uffdio_zeropage;
1097 struct uffdio_zeropage __user *user_uffdio_zeropage;
1098 struct userfaultfd_wake_range range;
1099
1100 user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1101
1102 ret = -EFAULT;
1103 if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1104 /* don't copy "zeropage" last field */
1105 sizeof(uffdio_zeropage)-sizeof(__s64)))
1106 goto out;
1107
1108 ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1109 uffdio_zeropage.range.len);
1110 if (ret)
1111 goto out;
1112 ret = -EINVAL;
1113 if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1114 goto out;
1115
1116 ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1117 uffdio_zeropage.range.len);
1118 if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1119 return -EFAULT;
1120 if (ret < 0)
1121 goto out;
1122 /* len == 0 would wake all */
1123 BUG_ON(!ret);
1124 range.len = ret;
1125 if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1126 range.start = uffdio_zeropage.range.start;
1127 wake_userfault(ctx, &range);
1128 }
1129 ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1130 out:
1131 return ret;
1132 }
1133
1134 /*
1135 * userland asks for a certain API version and we return which bits
1136 * and ioctl commands are implemented in this kernel for such API
1137 * version or -EINVAL if unknown.
1138 */
1139 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1140 unsigned long arg)
1141 {
1142 struct uffdio_api uffdio_api;
1143 void __user *buf = (void __user *)arg;
1144 int ret;
1145
1146 ret = -EINVAL;
1147 if (ctx->state != UFFD_STATE_WAIT_API)
1148 goto out;
1149 ret = -EFAULT;
1150 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1151 goto out;
1152 if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1153 memset(&uffdio_api, 0, sizeof(uffdio_api));
1154 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1155 goto out;
1156 ret = -EINVAL;
1157 goto out;
1158 }
1159 uffdio_api.features = UFFD_API_FEATURES;
1160 uffdio_api.ioctls = UFFD_API_IOCTLS;
1161 ret = -EFAULT;
1162 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1163 goto out;
1164 ctx->state = UFFD_STATE_RUNNING;
1165 ret = 0;
1166 out:
1167 return ret;
1168 }
1169
1170 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1171 unsigned long arg)
1172 {
1173 int ret = -EINVAL;
1174 struct userfaultfd_ctx *ctx = file->private_data;
1175
1176 if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1177 return -EINVAL;
1178
1179 switch(cmd) {
1180 case UFFDIO_API:
1181 ret = userfaultfd_api(ctx, arg);
1182 break;
1183 case UFFDIO_REGISTER:
1184 ret = userfaultfd_register(ctx, arg);
1185 break;
1186 case UFFDIO_UNREGISTER:
1187 ret = userfaultfd_unregister(ctx, arg);
1188 break;
1189 case UFFDIO_WAKE:
1190 ret = userfaultfd_wake(ctx, arg);
1191 break;
1192 case UFFDIO_COPY:
1193 ret = userfaultfd_copy(ctx, arg);
1194 break;
1195 case UFFDIO_ZEROPAGE:
1196 ret = userfaultfd_zeropage(ctx, arg);
1197 break;
1198 }
1199 return ret;
1200 }
1201
1202 #ifdef CONFIG_PROC_FS
1203 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1204 {
1205 struct userfaultfd_ctx *ctx = f->private_data;
1206 wait_queue_t *wq;
1207 struct userfaultfd_wait_queue *uwq;
1208 unsigned long pending = 0, total = 0;
1209
1210 spin_lock(&ctx->fault_pending_wqh.lock);
1211 list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1212 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1213 pending++;
1214 total++;
1215 }
1216 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1217 uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1218 total++;
1219 }
1220 spin_unlock(&ctx->fault_pending_wqh.lock);
1221
1222 /*
1223 * If more protocols will be added, there will be all shown
1224 * separated by a space. Like this:
1225 * protocols: aa:... bb:...
1226 */
1227 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1228 pending, total, UFFD_API, UFFD_API_FEATURES,
1229 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1230 }
1231 #endif
1232
1233 static const struct file_operations userfaultfd_fops = {
1234 #ifdef CONFIG_PROC_FS
1235 .show_fdinfo = userfaultfd_show_fdinfo,
1236 #endif
1237 .release = userfaultfd_release,
1238 .poll = userfaultfd_poll,
1239 .read = userfaultfd_read,
1240 .unlocked_ioctl = userfaultfd_ioctl,
1241 .compat_ioctl = userfaultfd_ioctl,
1242 .llseek = noop_llseek,
1243 };
1244
1245 static void init_once_userfaultfd_ctx(void *mem)
1246 {
1247 struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1248
1249 init_waitqueue_head(&ctx->fault_pending_wqh);
1250 init_waitqueue_head(&ctx->fault_wqh);
1251 init_waitqueue_head(&ctx->fd_wqh);
1252 seqcount_init(&ctx->refile_seq);
1253 }
1254
1255 /**
1256 * userfaultfd_file_create - Creates an userfaultfd file pointer.
1257 * @flags: Flags for the userfaultfd file.
1258 *
1259 * This function creates an userfaultfd file pointer, w/out installing
1260 * it into the fd table. This is useful when the userfaultfd file is
1261 * used during the initialization of data structures that require
1262 * extra setup after the userfaultfd creation. So the userfaultfd
1263 * creation is split into the file pointer creation phase, and the
1264 * file descriptor installation phase. In this way races with
1265 * userspace closing the newly installed file descriptor can be
1266 * avoided. Returns an userfaultfd file pointer, or a proper error
1267 * pointer.
1268 */
1269 static struct file *userfaultfd_file_create(int flags)
1270 {
1271 struct file *file;
1272 struct userfaultfd_ctx *ctx;
1273
1274 BUG_ON(!current->mm);
1275
1276 /* Check the UFFD_* constants for consistency. */
1277 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1278 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1279
1280 file = ERR_PTR(-EINVAL);
1281 if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1282 goto out;
1283
1284 file = ERR_PTR(-ENOMEM);
1285 ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1286 if (!ctx)
1287 goto out;
1288
1289 atomic_set(&ctx->refcount, 1);
1290 ctx->flags = flags;
1291 ctx->state = UFFD_STATE_WAIT_API;
1292 ctx->released = false;
1293 ctx->mm = current->mm;
1294 /* prevent the mm struct to be freed */
1295 atomic_inc(&ctx->mm->mm_users);
1296
1297 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1298 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1299 if (IS_ERR(file)) {
1300 mmput(ctx->mm);
1301 kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1302 }
1303 out:
1304 return file;
1305 }
1306
1307 SYSCALL_DEFINE1(userfaultfd, int, flags)
1308 {
1309 int fd, error;
1310 struct file *file;
1311
1312 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1313 if (error < 0)
1314 return error;
1315 fd = error;
1316
1317 file = userfaultfd_file_create(flags);
1318 if (IS_ERR(file)) {
1319 error = PTR_ERR(file);
1320 goto err_put_unused_fd;
1321 }
1322 fd_install(fd, file);
1323
1324 return fd;
1325
1326 err_put_unused_fd:
1327 put_unused_fd(fd);
1328
1329 return error;
1330 }
1331
1332 static int __init userfaultfd_init(void)
1333 {
1334 userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1335 sizeof(struct userfaultfd_ctx),
1336 0,
1337 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1338 init_once_userfaultfd_ctx);
1339 return 0;
1340 }
1341 __initcall(userfaultfd_init);