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 enum userfaultfd_state { 31 UFFD_STATE_WAIT_API, 32 UFFD_STATE_RUNNING, 33 }; 34 35 struct userfaultfd_ctx { 36 /* pseudo fd refcounting */ 37 atomic_t refcount; 38 /* waitqueue head for the pending (i.e. not read) userfaults */ 39 wait_queue_head_t fault_pending_wqh; 40 /* waitqueue head for the userfaults */ 41 wait_queue_head_t fault_wqh; 42 /* waitqueue head for the pseudo fd to wakeup poll/read */ 43 wait_queue_head_t fd_wqh; 44 /* userfaultfd syscall flags */ 45 unsigned int flags; 46 /* state machine */ 47 enum userfaultfd_state state; 48 /* released */ 49 bool released; 50 /* mm with one ore more vmas attached to this userfaultfd_ctx */ 51 struct mm_struct *mm; 52 }; 53 54 struct userfaultfd_wait_queue { 55 struct uffd_msg msg; 56 wait_queue_t wq; 57 struct userfaultfd_ctx *ctx; 58 }; 59 60 struct userfaultfd_wake_range { 61 unsigned long start; 62 unsigned long len; 63 }; 64 65 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode, 66 int wake_flags, void *key) 67 { 68 struct userfaultfd_wake_range *range = key; 69 int ret; 70 struct userfaultfd_wait_queue *uwq; 71 unsigned long start, len; 72 73 uwq = container_of(wq, struct userfaultfd_wait_queue, wq); 74 ret = 0; 75 /* len == 0 means wake all */ 76 start = range->start; 77 len = range->len; 78 if (len && (start > uwq->msg.arg.pagefault.address || 79 start + len <= uwq->msg.arg.pagefault.address)) 80 goto out; 81 ret = wake_up_state(wq->private, mode); 82 if (ret) 83 /* 84 * Wake only once, autoremove behavior. 85 * 86 * After the effect of list_del_init is visible to the 87 * other CPUs, the waitqueue may disappear from under 88 * us, see the !list_empty_careful() in 89 * handle_userfault(). try_to_wake_up() has an 90 * implicit smp_mb__before_spinlock, and the 91 * wq->private is read before calling the extern 92 * function "wake_up_state" (which in turns calls 93 * try_to_wake_up). While the spin_lock;spin_unlock; 94 * wouldn't be enough, the smp_mb__before_spinlock is 95 * enough to avoid an explicit smp_mb() here. 96 */ 97 list_del_init(&wq->task_list); 98 out: 99 return ret; 100 } 101 102 /** 103 * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd 104 * context. 105 * @ctx: [in] Pointer to the userfaultfd context. 106 * 107 * Returns: In case of success, returns not zero. 108 */ 109 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx) 110 { 111 if (!atomic_inc_not_zero(&ctx->refcount)) 112 BUG(); 113 } 114 115 /** 116 * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd 117 * context. 118 * @ctx: [in] Pointer to userfaultfd context. 119 * 120 * The userfaultfd context reference must have been previously acquired either 121 * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget(). 122 */ 123 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx) 124 { 125 if (atomic_dec_and_test(&ctx->refcount)) { 126 VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock)); 127 VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh)); 128 VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock)); 129 VM_BUG_ON(waitqueue_active(&ctx->fault_wqh)); 130 VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock)); 131 VM_BUG_ON(waitqueue_active(&ctx->fd_wqh)); 132 mmput(ctx->mm); 133 kfree(ctx); 134 } 135 } 136 137 static inline void msg_init(struct uffd_msg *msg) 138 { 139 BUILD_BUG_ON(sizeof(struct uffd_msg) != 32); 140 /* 141 * Must use memset to zero out the paddings or kernel data is 142 * leaked to userland. 143 */ 144 memset(msg, 0, sizeof(struct uffd_msg)); 145 } 146 147 static inline struct uffd_msg userfault_msg(unsigned long address, 148 unsigned int flags, 149 unsigned long reason) 150 { 151 struct uffd_msg msg; 152 msg_init(&msg); 153 msg.event = UFFD_EVENT_PAGEFAULT; 154 msg.arg.pagefault.address = address; 155 if (flags & FAULT_FLAG_WRITE) 156 /* 157 * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the 158 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE 159 * was not set in a UFFD_EVENT_PAGEFAULT, it means it 160 * was a read fault, otherwise if set it means it's 161 * a write fault. 162 */ 163 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE; 164 if (reason & VM_UFFD_WP) 165 /* 166 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the 167 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was 168 * not set in a UFFD_EVENT_PAGEFAULT, it means it was 169 * a missing fault, otherwise if set it means it's a 170 * write protect fault. 171 */ 172 msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP; 173 return msg; 174 } 175 176 /* 177 * The locking rules involved in returning VM_FAULT_RETRY depending on 178 * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and 179 * FAULT_FLAG_KILLABLE are not straightforward. The "Caution" 180 * recommendation in __lock_page_or_retry is not an understatement. 181 * 182 * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released 183 * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is 184 * not set. 185 * 186 * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not 187 * set, VM_FAULT_RETRY can still be returned if and only if there are 188 * fatal_signal_pending()s, and the mmap_sem must be released before 189 * returning it. 190 */ 191 int handle_userfault(struct vm_area_struct *vma, unsigned long address, 192 unsigned int flags, unsigned long reason) 193 { 194 struct mm_struct *mm = vma->vm_mm; 195 struct userfaultfd_ctx *ctx; 196 struct userfaultfd_wait_queue uwq; 197 int ret; 198 199 BUG_ON(!rwsem_is_locked(&mm->mmap_sem)); 200 201 ret = VM_FAULT_SIGBUS; 202 ctx = vma->vm_userfaultfd_ctx.ctx; 203 if (!ctx) 204 goto out; 205 206 BUG_ON(ctx->mm != mm); 207 208 VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP)); 209 VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP)); 210 211 /* 212 * If it's already released don't get it. This avoids to loop 213 * in __get_user_pages if userfaultfd_release waits on the 214 * caller of handle_userfault to release the mmap_sem. 215 */ 216 if (unlikely(ACCESS_ONCE(ctx->released))) 217 goto out; 218 219 /* 220 * Check that we can return VM_FAULT_RETRY. 221 * 222 * NOTE: it should become possible to return VM_FAULT_RETRY 223 * even if FAULT_FLAG_TRIED is set without leading to gup() 224 * -EBUSY failures, if the userfaultfd is to be extended for 225 * VM_UFFD_WP tracking and we intend to arm the userfault 226 * without first stopping userland access to the memory. For 227 * VM_UFFD_MISSING userfaults this is enough for now. 228 */ 229 if (unlikely(!(flags & FAULT_FLAG_ALLOW_RETRY))) { 230 /* 231 * Validate the invariant that nowait must allow retry 232 * to be sure not to return SIGBUS erroneously on 233 * nowait invocations. 234 */ 235 BUG_ON(flags & FAULT_FLAG_RETRY_NOWAIT); 236 #ifdef CONFIG_DEBUG_VM 237 if (printk_ratelimit()) { 238 printk(KERN_WARNING 239 "FAULT_FLAG_ALLOW_RETRY missing %x\n", flags); 240 dump_stack(); 241 } 242 #endif 243 goto out; 244 } 245 246 /* 247 * Handle nowait, not much to do other than tell it to retry 248 * and wait. 249 */ 250 ret = VM_FAULT_RETRY; 251 if (flags & FAULT_FLAG_RETRY_NOWAIT) 252 goto out; 253 254 /* take the reference before dropping the mmap_sem */ 255 userfaultfd_ctx_get(ctx); 256 257 /* be gentle and immediately relinquish the mmap_sem */ 258 up_read(&mm->mmap_sem); 259 260 init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function); 261 uwq.wq.private = current; 262 uwq.msg = userfault_msg(address, flags, reason); 263 uwq.ctx = ctx; 264 265 spin_lock(&ctx->fault_pending_wqh.lock); 266 /* 267 * After the __add_wait_queue the uwq is visible to userland 268 * through poll/read(). 269 */ 270 __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq); 271 /* 272 * The smp_mb() after __set_current_state prevents the reads 273 * following the spin_unlock to happen before the list_add in 274 * __add_wait_queue. 275 */ 276 set_current_state(TASK_KILLABLE); 277 spin_unlock(&ctx->fault_pending_wqh.lock); 278 279 if (likely(!ACCESS_ONCE(ctx->released) && 280 !fatal_signal_pending(current))) { 281 wake_up_poll(&ctx->fd_wqh, POLLIN); 282 schedule(); 283 ret |= VM_FAULT_MAJOR; 284 } 285 286 __set_current_state(TASK_RUNNING); 287 288 /* 289 * Here we race with the list_del; list_add in 290 * userfaultfd_ctx_read(), however because we don't ever run 291 * list_del_init() to refile across the two lists, the prev 292 * and next pointers will never point to self. list_add also 293 * would never let any of the two pointers to point to 294 * self. So list_empty_careful won't risk to see both pointers 295 * pointing to self at any time during the list refile. The 296 * only case where list_del_init() is called is the full 297 * removal in the wake function and there we don't re-list_add 298 * and it's fine not to block on the spinlock. The uwq on this 299 * kernel stack can be released after the list_del_init. 300 */ 301 if (!list_empty_careful(&uwq.wq.task_list)) { 302 spin_lock(&ctx->fault_pending_wqh.lock); 303 /* 304 * No need of list_del_init(), the uwq on the stack 305 * will be freed shortly anyway. 306 */ 307 list_del(&uwq.wq.task_list); 308 spin_unlock(&ctx->fault_pending_wqh.lock); 309 } 310 311 /* 312 * ctx may go away after this if the userfault pseudo fd is 313 * already released. 314 */ 315 userfaultfd_ctx_put(ctx); 316 317 out: 318 return ret; 319 } 320 321 static int userfaultfd_release(struct inode *inode, struct file *file) 322 { 323 struct userfaultfd_ctx *ctx = file->private_data; 324 struct mm_struct *mm = ctx->mm; 325 struct vm_area_struct *vma, *prev; 326 /* len == 0 means wake all */ 327 struct userfaultfd_wake_range range = { .len = 0, }; 328 unsigned long new_flags; 329 330 ACCESS_ONCE(ctx->released) = true; 331 332 /* 333 * Flush page faults out of all CPUs. NOTE: all page faults 334 * must be retried without returning VM_FAULT_SIGBUS if 335 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx 336 * changes while handle_userfault released the mmap_sem. So 337 * it's critical that released is set to true (above), before 338 * taking the mmap_sem for writing. 339 */ 340 down_write(&mm->mmap_sem); 341 prev = NULL; 342 for (vma = mm->mmap; vma; vma = vma->vm_next) { 343 cond_resched(); 344 BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^ 345 !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); 346 if (vma->vm_userfaultfd_ctx.ctx != ctx) { 347 prev = vma; 348 continue; 349 } 350 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); 351 prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end, 352 new_flags, vma->anon_vma, 353 vma->vm_file, vma->vm_pgoff, 354 vma_policy(vma), 355 NULL_VM_UFFD_CTX); 356 if (prev) 357 vma = prev; 358 else 359 prev = vma; 360 vma->vm_flags = new_flags; 361 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; 362 } 363 up_write(&mm->mmap_sem); 364 365 /* 366 * After no new page faults can wait on this fault_*wqh, flush 367 * the last page faults that may have been already waiting on 368 * the fault_*wqh. 369 */ 370 spin_lock(&ctx->fault_pending_wqh.lock); 371 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, 0, &range); 372 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, 0, &range); 373 spin_unlock(&ctx->fault_pending_wqh.lock); 374 375 wake_up_poll(&ctx->fd_wqh, POLLHUP); 376 userfaultfd_ctx_put(ctx); 377 return 0; 378 } 379 380 /* fault_pending_wqh.lock must be hold by the caller */ 381 static inline struct userfaultfd_wait_queue *find_userfault( 382 struct userfaultfd_ctx *ctx) 383 { 384 wait_queue_t *wq; 385 struct userfaultfd_wait_queue *uwq; 386 387 VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock)); 388 389 uwq = NULL; 390 if (!waitqueue_active(&ctx->fault_pending_wqh)) 391 goto out; 392 /* walk in reverse to provide FIFO behavior to read userfaults */ 393 wq = list_last_entry(&ctx->fault_pending_wqh.task_list, 394 typeof(*wq), task_list); 395 uwq = container_of(wq, struct userfaultfd_wait_queue, wq); 396 out: 397 return uwq; 398 } 399 400 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait) 401 { 402 struct userfaultfd_ctx *ctx = file->private_data; 403 unsigned int ret; 404 405 poll_wait(file, &ctx->fd_wqh, wait); 406 407 switch (ctx->state) { 408 case UFFD_STATE_WAIT_API: 409 return POLLERR; 410 case UFFD_STATE_RUNNING: 411 /* 412 * poll() never guarantees that read won't block. 413 * userfaults can be waken before they're read(). 414 */ 415 if (unlikely(!(file->f_flags & O_NONBLOCK))) 416 return POLLERR; 417 /* 418 * lockless access to see if there are pending faults 419 * __pollwait last action is the add_wait_queue but 420 * the spin_unlock would allow the waitqueue_active to 421 * pass above the actual list_add inside 422 * add_wait_queue critical section. So use a full 423 * memory barrier to serialize the list_add write of 424 * add_wait_queue() with the waitqueue_active read 425 * below. 426 */ 427 ret = 0; 428 smp_mb(); 429 if (waitqueue_active(&ctx->fault_pending_wqh)) 430 ret = POLLIN; 431 return ret; 432 default: 433 BUG(); 434 } 435 } 436 437 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, 438 struct uffd_msg *msg) 439 { 440 ssize_t ret; 441 DECLARE_WAITQUEUE(wait, current); 442 struct userfaultfd_wait_queue *uwq; 443 444 /* always take the fd_wqh lock before the fault_pending_wqh lock */ 445 spin_lock(&ctx->fd_wqh.lock); 446 __add_wait_queue(&ctx->fd_wqh, &wait); 447 for (;;) { 448 set_current_state(TASK_INTERRUPTIBLE); 449 spin_lock(&ctx->fault_pending_wqh.lock); 450 uwq = find_userfault(ctx); 451 if (uwq) { 452 /* 453 * The fault_pending_wqh.lock prevents the uwq 454 * to disappear from under us. 455 * 456 * Refile this userfault from 457 * fault_pending_wqh to fault_wqh, it's not 458 * pending anymore after we read it. 459 * 460 * Use list_del() by hand (as 461 * userfaultfd_wake_function also uses 462 * list_del_init() by hand) to be sure nobody 463 * changes __remove_wait_queue() to use 464 * list_del_init() in turn breaking the 465 * !list_empty_careful() check in 466 * handle_userfault(). The uwq->wq.task_list 467 * must never be empty at any time during the 468 * refile, or the waitqueue could disappear 469 * from under us. The "wait_queue_head_t" 470 * parameter of __remove_wait_queue() is unused 471 * anyway. 472 */ 473 list_del(&uwq->wq.task_list); 474 __add_wait_queue(&ctx->fault_wqh, &uwq->wq); 475 476 /* careful to always initialize msg if ret == 0 */ 477 *msg = uwq->msg; 478 spin_unlock(&ctx->fault_pending_wqh.lock); 479 ret = 0; 480 break; 481 } 482 spin_unlock(&ctx->fault_pending_wqh.lock); 483 if (signal_pending(current)) { 484 ret = -ERESTARTSYS; 485 break; 486 } 487 if (no_wait) { 488 ret = -EAGAIN; 489 break; 490 } 491 spin_unlock(&ctx->fd_wqh.lock); 492 schedule(); 493 spin_lock(&ctx->fd_wqh.lock); 494 } 495 __remove_wait_queue(&ctx->fd_wqh, &wait); 496 __set_current_state(TASK_RUNNING); 497 spin_unlock(&ctx->fd_wqh.lock); 498 499 return ret; 500 } 501 502 static ssize_t userfaultfd_read(struct file *file, char __user *buf, 503 size_t count, loff_t *ppos) 504 { 505 struct userfaultfd_ctx *ctx = file->private_data; 506 ssize_t _ret, ret = 0; 507 struct uffd_msg msg; 508 int no_wait = file->f_flags & O_NONBLOCK; 509 510 if (ctx->state == UFFD_STATE_WAIT_API) 511 return -EINVAL; 512 BUG_ON(ctx->state != UFFD_STATE_RUNNING); 513 514 for (;;) { 515 if (count < sizeof(msg)) 516 return ret ? ret : -EINVAL; 517 _ret = userfaultfd_ctx_read(ctx, no_wait, &msg); 518 if (_ret < 0) 519 return ret ? ret : _ret; 520 if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg))) 521 return ret ? ret : -EFAULT; 522 ret += sizeof(msg); 523 buf += sizeof(msg); 524 count -= sizeof(msg); 525 /* 526 * Allow to read more than one fault at time but only 527 * block if waiting for the very first one. 528 */ 529 no_wait = O_NONBLOCK; 530 } 531 } 532 533 static void __wake_userfault(struct userfaultfd_ctx *ctx, 534 struct userfaultfd_wake_range *range) 535 { 536 unsigned long start, end; 537 538 start = range->start; 539 end = range->start + range->len; 540 541 spin_lock(&ctx->fault_pending_wqh.lock); 542 /* wake all in the range and autoremove */ 543 if (waitqueue_active(&ctx->fault_pending_wqh)) 544 __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, 0, 545 range); 546 if (waitqueue_active(&ctx->fault_wqh)) 547 __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, 0, range); 548 spin_unlock(&ctx->fault_pending_wqh.lock); 549 } 550 551 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx, 552 struct userfaultfd_wake_range *range) 553 { 554 /* 555 * To be sure waitqueue_active() is not reordered by the CPU 556 * before the pagetable update, use an explicit SMP memory 557 * barrier here. PT lock release or up_read(mmap_sem) still 558 * have release semantics that can allow the 559 * waitqueue_active() to be reordered before the pte update. 560 */ 561 smp_mb(); 562 563 /* 564 * Use waitqueue_active because it's very frequent to 565 * change the address space atomically even if there are no 566 * userfaults yet. So we take the spinlock only when we're 567 * sure we've userfaults to wake. 568 */ 569 if (waitqueue_active(&ctx->fault_pending_wqh) || 570 waitqueue_active(&ctx->fault_wqh)) 571 __wake_userfault(ctx, range); 572 } 573 574 static __always_inline int validate_range(struct mm_struct *mm, 575 __u64 start, __u64 len) 576 { 577 __u64 task_size = mm->task_size; 578 579 if (start & ~PAGE_MASK) 580 return -EINVAL; 581 if (len & ~PAGE_MASK) 582 return -EINVAL; 583 if (!len) 584 return -EINVAL; 585 if (start < mmap_min_addr) 586 return -EINVAL; 587 if (start >= task_size) 588 return -EINVAL; 589 if (len > task_size - start) 590 return -EINVAL; 591 return 0; 592 } 593 594 static int userfaultfd_register(struct userfaultfd_ctx *ctx, 595 unsigned long arg) 596 { 597 struct mm_struct *mm = ctx->mm; 598 struct vm_area_struct *vma, *prev, *cur; 599 int ret; 600 struct uffdio_register uffdio_register; 601 struct uffdio_register __user *user_uffdio_register; 602 unsigned long vm_flags, new_flags; 603 bool found; 604 unsigned long start, end, vma_end; 605 606 user_uffdio_register = (struct uffdio_register __user *) arg; 607 608 ret = -EFAULT; 609 if (copy_from_user(&uffdio_register, user_uffdio_register, 610 sizeof(uffdio_register)-sizeof(__u64))) 611 goto out; 612 613 ret = -EINVAL; 614 if (!uffdio_register.mode) 615 goto out; 616 if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING| 617 UFFDIO_REGISTER_MODE_WP)) 618 goto out; 619 vm_flags = 0; 620 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING) 621 vm_flags |= VM_UFFD_MISSING; 622 if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) { 623 vm_flags |= VM_UFFD_WP; 624 /* 625 * FIXME: remove the below error constraint by 626 * implementing the wprotect tracking mode. 627 */ 628 ret = -EINVAL; 629 goto out; 630 } 631 632 ret = validate_range(mm, uffdio_register.range.start, 633 uffdio_register.range.len); 634 if (ret) 635 goto out; 636 637 start = uffdio_register.range.start; 638 end = start + uffdio_register.range.len; 639 640 down_write(&mm->mmap_sem); 641 vma = find_vma_prev(mm, start, &prev); 642 643 ret = -ENOMEM; 644 if (!vma) 645 goto out_unlock; 646 647 /* check that there's at least one vma in the range */ 648 ret = -EINVAL; 649 if (vma->vm_start >= end) 650 goto out_unlock; 651 652 /* 653 * Search for not compatible vmas. 654 * 655 * FIXME: this shall be relaxed later so that it doesn't fail 656 * on tmpfs backed vmas (in addition to the current allowance 657 * on anonymous vmas). 658 */ 659 found = false; 660 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { 661 cond_resched(); 662 663 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ 664 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); 665 666 /* check not compatible vmas */ 667 ret = -EINVAL; 668 if (cur->vm_ops) 669 goto out_unlock; 670 671 /* 672 * Check that this vma isn't already owned by a 673 * different userfaultfd. We can't allow more than one 674 * userfaultfd to own a single vma simultaneously or we 675 * wouldn't know which one to deliver the userfaults to. 676 */ 677 ret = -EBUSY; 678 if (cur->vm_userfaultfd_ctx.ctx && 679 cur->vm_userfaultfd_ctx.ctx != ctx) 680 goto out_unlock; 681 682 found = true; 683 } 684 BUG_ON(!found); 685 686 if (vma->vm_start < start) 687 prev = vma; 688 689 ret = 0; 690 do { 691 cond_resched(); 692 693 BUG_ON(vma->vm_ops); 694 BUG_ON(vma->vm_userfaultfd_ctx.ctx && 695 vma->vm_userfaultfd_ctx.ctx != ctx); 696 697 /* 698 * Nothing to do: this vma is already registered into this 699 * userfaultfd and with the right tracking mode too. 700 */ 701 if (vma->vm_userfaultfd_ctx.ctx == ctx && 702 (vma->vm_flags & vm_flags) == vm_flags) 703 goto skip; 704 705 if (vma->vm_start > start) 706 start = vma->vm_start; 707 vma_end = min(end, vma->vm_end); 708 709 new_flags = (vma->vm_flags & ~vm_flags) | vm_flags; 710 prev = vma_merge(mm, prev, start, vma_end, new_flags, 711 vma->anon_vma, vma->vm_file, vma->vm_pgoff, 712 vma_policy(vma), 713 ((struct vm_userfaultfd_ctx){ ctx })); 714 if (prev) { 715 vma = prev; 716 goto next; 717 } 718 if (vma->vm_start < start) { 719 ret = split_vma(mm, vma, start, 1); 720 if (ret) 721 break; 722 } 723 if (vma->vm_end > end) { 724 ret = split_vma(mm, vma, end, 0); 725 if (ret) 726 break; 727 } 728 next: 729 /* 730 * In the vma_merge() successful mprotect-like case 8: 731 * the next vma was merged into the current one and 732 * the current one has not been updated yet. 733 */ 734 vma->vm_flags = new_flags; 735 vma->vm_userfaultfd_ctx.ctx = ctx; 736 737 skip: 738 prev = vma; 739 start = vma->vm_end; 740 vma = vma->vm_next; 741 } while (vma && vma->vm_start < end); 742 out_unlock: 743 up_write(&mm->mmap_sem); 744 if (!ret) { 745 /* 746 * Now that we scanned all vmas we can already tell 747 * userland which ioctls methods are guaranteed to 748 * succeed on this range. 749 */ 750 if (put_user(UFFD_API_RANGE_IOCTLS, 751 &user_uffdio_register->ioctls)) 752 ret = -EFAULT; 753 } 754 out: 755 return ret; 756 } 757 758 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, 759 unsigned long arg) 760 { 761 struct mm_struct *mm = ctx->mm; 762 struct vm_area_struct *vma, *prev, *cur; 763 int ret; 764 struct uffdio_range uffdio_unregister; 765 unsigned long new_flags; 766 bool found; 767 unsigned long start, end, vma_end; 768 const void __user *buf = (void __user *)arg; 769 770 ret = -EFAULT; 771 if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister))) 772 goto out; 773 774 ret = validate_range(mm, uffdio_unregister.start, 775 uffdio_unregister.len); 776 if (ret) 777 goto out; 778 779 start = uffdio_unregister.start; 780 end = start + uffdio_unregister.len; 781 782 down_write(&mm->mmap_sem); 783 vma = find_vma_prev(mm, start, &prev); 784 785 ret = -ENOMEM; 786 if (!vma) 787 goto out_unlock; 788 789 /* check that there's at least one vma in the range */ 790 ret = -EINVAL; 791 if (vma->vm_start >= end) 792 goto out_unlock; 793 794 /* 795 * Search for not compatible vmas. 796 * 797 * FIXME: this shall be relaxed later so that it doesn't fail 798 * on tmpfs backed vmas (in addition to the current allowance 799 * on anonymous vmas). 800 */ 801 found = false; 802 ret = -EINVAL; 803 for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { 804 cond_resched(); 805 806 BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ 807 !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); 808 809 /* 810 * Check not compatible vmas, not strictly required 811 * here as not compatible vmas cannot have an 812 * userfaultfd_ctx registered on them, but this 813 * provides for more strict behavior to notice 814 * unregistration errors. 815 */ 816 if (cur->vm_ops) 817 goto out_unlock; 818 819 found = true; 820 } 821 BUG_ON(!found); 822 823 if (vma->vm_start < start) 824 prev = vma; 825 826 ret = 0; 827 do { 828 cond_resched(); 829 830 BUG_ON(vma->vm_ops); 831 832 /* 833 * Nothing to do: this vma is already registered into this 834 * userfaultfd and with the right tracking mode too. 835 */ 836 if (!vma->vm_userfaultfd_ctx.ctx) 837 goto skip; 838 839 if (vma->vm_start > start) 840 start = vma->vm_start; 841 vma_end = min(end, vma->vm_end); 842 843 new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); 844 prev = vma_merge(mm, prev, start, vma_end, new_flags, 845 vma->anon_vma, vma->vm_file, vma->vm_pgoff, 846 vma_policy(vma), 847 NULL_VM_UFFD_CTX); 848 if (prev) { 849 vma = prev; 850 goto next; 851 } 852 if (vma->vm_start < start) { 853 ret = split_vma(mm, vma, start, 1); 854 if (ret) 855 break; 856 } 857 if (vma->vm_end > end) { 858 ret = split_vma(mm, vma, end, 0); 859 if (ret) 860 break; 861 } 862 next: 863 /* 864 * In the vma_merge() successful mprotect-like case 8: 865 * the next vma was merged into the current one and 866 * the current one has not been updated yet. 867 */ 868 vma->vm_flags = new_flags; 869 vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; 870 871 skip: 872 prev = vma; 873 start = vma->vm_end; 874 vma = vma->vm_next; 875 } while (vma && vma->vm_start < end); 876 out_unlock: 877 up_write(&mm->mmap_sem); 878 out: 879 return ret; 880 } 881 882 /* 883 * userfaultfd_wake is needed in case an userfault is in flight by the 884 * time a UFFDIO_COPY (or other ioctl variants) completes. The page 885 * may be well get mapped and the page fault if repeated wouldn't lead 886 * to a userfault anymore, but before scheduling in TASK_KILLABLE mode 887 * handle_userfault() doesn't recheck the pagetables and it doesn't 888 * serialize against UFFDO_COPY (or other ioctl variants). Ultimately 889 * the knowledge of which pages are mapped is left to userland who is 890 * responsible for handling the race between read() userfaults and 891 * background UFFDIO_COPY (or other ioctl variants), if done by 892 * separate concurrent threads. 893 * 894 * userfaultfd_wake may be used in combination with the 895 * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches. 896 */ 897 static int userfaultfd_wake(struct userfaultfd_ctx *ctx, 898 unsigned long arg) 899 { 900 int ret; 901 struct uffdio_range uffdio_wake; 902 struct userfaultfd_wake_range range; 903 const void __user *buf = (void __user *)arg; 904 905 ret = -EFAULT; 906 if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake))) 907 goto out; 908 909 ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len); 910 if (ret) 911 goto out; 912 913 range.start = uffdio_wake.start; 914 range.len = uffdio_wake.len; 915 916 /* 917 * len == 0 means wake all and we don't want to wake all here, 918 * so check it again to be sure. 919 */ 920 VM_BUG_ON(!range.len); 921 922 wake_userfault(ctx, &range); 923 ret = 0; 924 925 out: 926 return ret; 927 } 928 929 /* 930 * userland asks for a certain API version and we return which bits 931 * and ioctl commands are implemented in this kernel for such API 932 * version or -EINVAL if unknown. 933 */ 934 static int userfaultfd_api(struct userfaultfd_ctx *ctx, 935 unsigned long arg) 936 { 937 struct uffdio_api uffdio_api; 938 void __user *buf = (void __user *)arg; 939 int ret; 940 941 ret = -EINVAL; 942 if (ctx->state != UFFD_STATE_WAIT_API) 943 goto out; 944 ret = -EFAULT; 945 if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api))) 946 goto out; 947 if (uffdio_api.api != UFFD_API || uffdio_api.features) { 948 memset(&uffdio_api, 0, sizeof(uffdio_api)); 949 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api))) 950 goto out; 951 ret = -EINVAL; 952 goto out; 953 } 954 uffdio_api.features = UFFD_API_FEATURES; 955 uffdio_api.ioctls = UFFD_API_IOCTLS; 956 ret = -EFAULT; 957 if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api))) 958 goto out; 959 ctx->state = UFFD_STATE_RUNNING; 960 ret = 0; 961 out: 962 return ret; 963 } 964 965 static long userfaultfd_ioctl(struct file *file, unsigned cmd, 966 unsigned long arg) 967 { 968 int ret = -EINVAL; 969 struct userfaultfd_ctx *ctx = file->private_data; 970 971 switch(cmd) { 972 case UFFDIO_API: 973 ret = userfaultfd_api(ctx, arg); 974 break; 975 case UFFDIO_REGISTER: 976 ret = userfaultfd_register(ctx, arg); 977 break; 978 case UFFDIO_UNREGISTER: 979 ret = userfaultfd_unregister(ctx, arg); 980 break; 981 case UFFDIO_WAKE: 982 ret = userfaultfd_wake(ctx, arg); 983 break; 984 } 985 return ret; 986 } 987 988 #ifdef CONFIG_PROC_FS 989 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f) 990 { 991 struct userfaultfd_ctx *ctx = f->private_data; 992 wait_queue_t *wq; 993 struct userfaultfd_wait_queue *uwq; 994 unsigned long pending = 0, total = 0; 995 996 spin_lock(&ctx->fault_pending_wqh.lock); 997 list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) { 998 uwq = container_of(wq, struct userfaultfd_wait_queue, wq); 999 pending++; 1000 total++; 1001 } 1002 list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) { 1003 uwq = container_of(wq, struct userfaultfd_wait_queue, wq); 1004 total++; 1005 } 1006 spin_unlock(&ctx->fault_pending_wqh.lock); 1007 1008 /* 1009 * If more protocols will be added, there will be all shown 1010 * separated by a space. Like this: 1011 * protocols: aa:... bb:... 1012 */ 1013 seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n", 1014 pending, total, UFFD_API, UFFD_API_FEATURES, 1015 UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS); 1016 } 1017 #endif 1018 1019 static const struct file_operations userfaultfd_fops = { 1020 #ifdef CONFIG_PROC_FS 1021 .show_fdinfo = userfaultfd_show_fdinfo, 1022 #endif 1023 .release = userfaultfd_release, 1024 .poll = userfaultfd_poll, 1025 .read = userfaultfd_read, 1026 .unlocked_ioctl = userfaultfd_ioctl, 1027 .compat_ioctl = userfaultfd_ioctl, 1028 .llseek = noop_llseek, 1029 }; 1030 1031 /** 1032 * userfaultfd_file_create - Creates an userfaultfd file pointer. 1033 * @flags: Flags for the userfaultfd file. 1034 * 1035 * This function creates an userfaultfd file pointer, w/out installing 1036 * it into the fd table. This is useful when the userfaultfd file is 1037 * used during the initialization of data structures that require 1038 * extra setup after the userfaultfd creation. So the userfaultfd 1039 * creation is split into the file pointer creation phase, and the 1040 * file descriptor installation phase. In this way races with 1041 * userspace closing the newly installed file descriptor can be 1042 * avoided. Returns an userfaultfd file pointer, or a proper error 1043 * pointer. 1044 */ 1045 static struct file *userfaultfd_file_create(int flags) 1046 { 1047 struct file *file; 1048 struct userfaultfd_ctx *ctx; 1049 1050 BUG_ON(!current->mm); 1051 1052 /* Check the UFFD_* constants for consistency. */ 1053 BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC); 1054 BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK); 1055 1056 file = ERR_PTR(-EINVAL); 1057 if (flags & ~UFFD_SHARED_FCNTL_FLAGS) 1058 goto out; 1059 1060 file = ERR_PTR(-ENOMEM); 1061 ctx = kmalloc(sizeof(*ctx), GFP_KERNEL); 1062 if (!ctx) 1063 goto out; 1064 1065 atomic_set(&ctx->refcount, 1); 1066 init_waitqueue_head(&ctx->fault_pending_wqh); 1067 init_waitqueue_head(&ctx->fault_wqh); 1068 init_waitqueue_head(&ctx->fd_wqh); 1069 ctx->flags = flags; 1070 ctx->state = UFFD_STATE_WAIT_API; 1071 ctx->released = false; 1072 ctx->mm = current->mm; 1073 /* prevent the mm struct to be freed */ 1074 atomic_inc(&ctx->mm->mm_users); 1075 1076 file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx, 1077 O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS)); 1078 if (IS_ERR(file)) 1079 kfree(ctx); 1080 out: 1081 return file; 1082 } 1083 1084 SYSCALL_DEFINE1(userfaultfd, int, flags) 1085 { 1086 int fd, error; 1087 struct file *file; 1088 1089 error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS); 1090 if (error < 0) 1091 return error; 1092 fd = error; 1093 1094 file = userfaultfd_file_create(flags); 1095 if (IS_ERR(file)) { 1096 error = PTR_ERR(file); 1097 goto err_put_unused_fd; 1098 } 1099 fd_install(fd, file); 1100 1101 return fd; 1102 1103 err_put_unused_fd: 1104 put_unused_fd(fd); 1105 1106 return error; 1107 } 1108