1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (C) 2009 Red Hat, Inc. 3 * Copyright (C) 2006 Rusty Russell IBM Corporation 4 * 5 * Author: Michael S. Tsirkin <mst@redhat.com> 6 * 7 * Inspiration, some code, and most witty comments come from 8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell 9 * 10 * Generic code for virtio server in host kernel. 11 */ 12 13 #include <linux/eventfd.h> 14 #include <linux/vhost.h> 15 #include <linux/uio.h> 16 #include <linux/mm.h> 17 #include <linux/miscdevice.h> 18 #include <linux/mutex.h> 19 #include <linux/poll.h> 20 #include <linux/file.h> 21 #include <linux/highmem.h> 22 #include <linux/slab.h> 23 #include <linux/vmalloc.h> 24 #include <linux/kthread.h> 25 #include <linux/cgroup.h> 26 #include <linux/module.h> 27 #include <linux/sort.h> 28 #include <linux/sched/mm.h> 29 #include <linux/sched/signal.h> 30 #include <linux/sched/vhost_task.h> 31 #include <linux/interval_tree_generic.h> 32 #include <linux/nospec.h> 33 #include <linux/kcov.h> 34 35 #include "vhost.h" 36 37 static ushort max_mem_regions = 64; 38 module_param(max_mem_regions, ushort, 0444); 39 MODULE_PARM_DESC(max_mem_regions, 40 "Maximum number of memory regions in memory map. (default: 64)"); 41 static int max_iotlb_entries = 2048; 42 module_param(max_iotlb_entries, int, 0444); 43 MODULE_PARM_DESC(max_iotlb_entries, 44 "Maximum number of iotlb entries. (default: 2048)"); 45 static bool fork_from_owner_default = VHOST_FORK_OWNER_TASK; 46 47 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL 48 module_param(fork_from_owner_default, bool, 0444); 49 MODULE_PARM_DESC(fork_from_owner_default, 50 "Set task mode as the default(default: Y)"); 51 #endif 52 53 enum { 54 VHOST_MEMORY_F_LOG = 0x1, 55 }; 56 57 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num]) 58 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num]) 59 60 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY 61 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq) 62 { 63 vq->user_be = !virtio_legacy_is_little_endian(); 64 } 65 66 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq) 67 { 68 vq->user_be = true; 69 } 70 71 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq) 72 { 73 vq->user_be = false; 74 } 75 76 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp) 77 { 78 struct vhost_vring_state s; 79 80 if (vq->private_data) 81 return -EBUSY; 82 83 if (copy_from_user(&s, argp, sizeof(s))) 84 return -EFAULT; 85 86 if (s.num != VHOST_VRING_LITTLE_ENDIAN && 87 s.num != VHOST_VRING_BIG_ENDIAN) 88 return -EINVAL; 89 90 if (s.num == VHOST_VRING_BIG_ENDIAN) 91 vhost_enable_cross_endian_big(vq); 92 else 93 vhost_enable_cross_endian_little(vq); 94 95 return 0; 96 } 97 98 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx, 99 int __user *argp) 100 { 101 struct vhost_vring_state s = { 102 .index = idx, 103 .num = vq->user_be 104 }; 105 106 if (copy_to_user(argp, &s, sizeof(s))) 107 return -EFAULT; 108 109 return 0; 110 } 111 112 static void vhost_init_is_le(struct vhost_virtqueue *vq) 113 { 114 /* Note for legacy virtio: user_be is initialized at reset time 115 * according to the host endianness. If userspace does not set an 116 * explicit endianness, the default behavior is native endian, as 117 * expected by legacy virtio. 118 */ 119 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be; 120 } 121 #else 122 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq) 123 { 124 } 125 126 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp) 127 { 128 return -ENOIOCTLCMD; 129 } 130 131 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx, 132 int __user *argp) 133 { 134 return -ENOIOCTLCMD; 135 } 136 137 static void vhost_init_is_le(struct vhost_virtqueue *vq) 138 { 139 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) 140 || virtio_legacy_is_little_endian(); 141 } 142 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */ 143 144 static void vhost_reset_is_le(struct vhost_virtqueue *vq) 145 { 146 vhost_init_is_le(vq); 147 } 148 149 struct vhost_flush_struct { 150 struct vhost_work work; 151 struct completion wait_event; 152 }; 153 154 static void vhost_flush_work(struct vhost_work *work) 155 { 156 struct vhost_flush_struct *s; 157 158 s = container_of(work, struct vhost_flush_struct, work); 159 complete(&s->wait_event); 160 } 161 162 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh, 163 poll_table *pt) 164 { 165 struct vhost_poll *poll; 166 167 poll = container_of(pt, struct vhost_poll, table); 168 poll->wqh = wqh; 169 add_wait_queue(wqh, &poll->wait); 170 } 171 172 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync, 173 void *key) 174 { 175 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait); 176 struct vhost_work *work = &poll->work; 177 178 if (!(key_to_poll(key) & poll->mask)) 179 return 0; 180 181 if (!poll->dev->use_worker) 182 work->fn(work); 183 else 184 vhost_poll_queue(poll); 185 186 return 0; 187 } 188 189 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn) 190 { 191 clear_bit(VHOST_WORK_QUEUED, &work->flags); 192 work->fn = fn; 193 } 194 EXPORT_SYMBOL_GPL(vhost_work_init); 195 196 /* Init poll structure */ 197 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn, 198 __poll_t mask, struct vhost_dev *dev, 199 struct vhost_virtqueue *vq) 200 { 201 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup); 202 init_poll_funcptr(&poll->table, vhost_poll_func); 203 poll->mask = mask; 204 poll->dev = dev; 205 poll->wqh = NULL; 206 poll->vq = vq; 207 208 vhost_work_init(&poll->work, fn); 209 } 210 EXPORT_SYMBOL_GPL(vhost_poll_init); 211 212 /* Start polling a file. We add ourselves to file's wait queue. The caller must 213 * keep a reference to a file until after vhost_poll_stop is called. */ 214 int vhost_poll_start(struct vhost_poll *poll, struct file *file) 215 { 216 __poll_t mask; 217 218 if (poll->wqh) 219 return 0; 220 221 mask = vfs_poll(file, &poll->table); 222 if (mask) 223 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask)); 224 if (mask & EPOLLERR) { 225 vhost_poll_stop(poll); 226 return -EINVAL; 227 } 228 229 return 0; 230 } 231 EXPORT_SYMBOL_GPL(vhost_poll_start); 232 233 /* Stop polling a file. After this function returns, it becomes safe to drop the 234 * file reference. You must also flush afterwards. */ 235 void vhost_poll_stop(struct vhost_poll *poll) 236 { 237 if (poll->wqh) { 238 remove_wait_queue(poll->wqh, &poll->wait); 239 poll->wqh = NULL; 240 } 241 } 242 EXPORT_SYMBOL_GPL(vhost_poll_stop); 243 244 static void vhost_worker_queue(struct vhost_worker *worker, 245 struct vhost_work *work) 246 { 247 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) { 248 /* We can only add the work to the list after we're 249 * sure it was not in the list. 250 * test_and_set_bit() implies a memory barrier. 251 */ 252 llist_add(&work->node, &worker->work_list); 253 worker->ops->wakeup(worker); 254 } 255 } 256 257 bool vhost_vq_work_queue(struct vhost_virtqueue *vq, struct vhost_work *work) 258 { 259 struct vhost_worker *worker; 260 bool queued = false; 261 262 rcu_read_lock(); 263 worker = rcu_dereference(vq->worker); 264 if (worker) { 265 queued = true; 266 vhost_worker_queue(worker, work); 267 } 268 rcu_read_unlock(); 269 270 return queued; 271 } 272 EXPORT_SYMBOL_GPL(vhost_vq_work_queue); 273 274 /** 275 * __vhost_worker_flush - flush a worker 276 * @worker: worker to flush 277 * 278 * The worker's flush_mutex must be held. 279 */ 280 static void __vhost_worker_flush(struct vhost_worker *worker) 281 { 282 struct vhost_flush_struct flush; 283 284 if (!worker->attachment_cnt || worker->killed) 285 return; 286 287 init_completion(&flush.wait_event); 288 vhost_work_init(&flush.work, vhost_flush_work); 289 290 vhost_worker_queue(worker, &flush.work); 291 /* 292 * Drop mutex in case our worker is killed and it needs to take the 293 * mutex to force cleanup. 294 */ 295 mutex_unlock(&worker->mutex); 296 wait_for_completion(&flush.wait_event); 297 mutex_lock(&worker->mutex); 298 } 299 300 static void vhost_worker_flush(struct vhost_worker *worker) 301 { 302 mutex_lock(&worker->mutex); 303 __vhost_worker_flush(worker); 304 mutex_unlock(&worker->mutex); 305 } 306 307 void vhost_dev_flush(struct vhost_dev *dev) 308 { 309 struct vhost_worker *worker; 310 unsigned long i; 311 312 xa_for_each(&dev->worker_xa, i, worker) 313 vhost_worker_flush(worker); 314 } 315 EXPORT_SYMBOL_GPL(vhost_dev_flush); 316 317 /* A lockless hint for busy polling code to exit the loop */ 318 bool vhost_vq_has_work(struct vhost_virtqueue *vq) 319 { 320 struct vhost_worker *worker; 321 bool has_work = false; 322 323 rcu_read_lock(); 324 worker = rcu_dereference(vq->worker); 325 if (worker && !llist_empty(&worker->work_list)) 326 has_work = true; 327 rcu_read_unlock(); 328 329 return has_work; 330 } 331 EXPORT_SYMBOL_GPL(vhost_vq_has_work); 332 333 void vhost_poll_queue(struct vhost_poll *poll) 334 { 335 vhost_vq_work_queue(poll->vq, &poll->work); 336 } 337 EXPORT_SYMBOL_GPL(vhost_poll_queue); 338 339 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq) 340 { 341 int j; 342 343 for (j = 0; j < VHOST_NUM_ADDRS; j++) 344 vq->meta_iotlb[j] = NULL; 345 } 346 347 static void vhost_vq_meta_reset(struct vhost_dev *d) 348 { 349 int i; 350 351 for (i = 0; i < d->nvqs; ++i) 352 __vhost_vq_meta_reset(d->vqs[i]); 353 } 354 355 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx) 356 { 357 call_ctx->ctx = NULL; 358 memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer)); 359 } 360 361 bool vhost_vq_is_setup(struct vhost_virtqueue *vq) 362 { 363 return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq); 364 } 365 EXPORT_SYMBOL_GPL(vhost_vq_is_setup); 366 367 static void vhost_vq_reset(struct vhost_dev *dev, 368 struct vhost_virtqueue *vq) 369 { 370 vq->num = 1; 371 vq->desc = NULL; 372 vq->avail = NULL; 373 vq->used = NULL; 374 vq->last_avail_idx = 0; 375 vq->next_avail_head = 0; 376 vq->avail_idx = 0; 377 vq->last_used_idx = 0; 378 vq->signalled_used = 0; 379 vq->signalled_used_valid = false; 380 vq->used_flags = 0; 381 vq->log_used = false; 382 vq->log_addr = -1ull; 383 vq->private_data = NULL; 384 virtio_features_zero(vq->acked_features_array); 385 vq->acked_backend_features = 0; 386 vq->log_base = NULL; 387 vq->error_ctx = NULL; 388 vq->kick = NULL; 389 vq->log_ctx = NULL; 390 vhost_disable_cross_endian(vq); 391 vhost_reset_is_le(vq); 392 vq->busyloop_timeout = 0; 393 vq->umem = NULL; 394 vq->iotlb = NULL; 395 rcu_assign_pointer(vq->worker, NULL); 396 vhost_vring_call_reset(&vq->call_ctx); 397 __vhost_vq_meta_reset(vq); 398 } 399 400 static int vhost_run_work_kthread_list(void *data) 401 { 402 struct vhost_worker *worker = data; 403 struct vhost_work *work, *work_next; 404 struct vhost_dev *dev = worker->dev; 405 struct llist_node *node; 406 407 kthread_use_mm(dev->mm); 408 409 for (;;) { 410 /* mb paired w/ kthread_stop */ 411 set_current_state(TASK_INTERRUPTIBLE); 412 413 if (kthread_should_stop()) { 414 __set_current_state(TASK_RUNNING); 415 break; 416 } 417 node = llist_del_all(&worker->work_list); 418 if (!node) 419 schedule(); 420 421 node = llist_reverse_order(node); 422 /* make sure flag is seen after deletion */ 423 smp_wmb(); 424 llist_for_each_entry_safe(work, work_next, node, node) { 425 clear_bit(VHOST_WORK_QUEUED, &work->flags); 426 __set_current_state(TASK_RUNNING); 427 kcov_remote_start_common(worker->kcov_handle); 428 work->fn(work); 429 kcov_remote_stop(); 430 cond_resched(); 431 } 432 } 433 kthread_unuse_mm(dev->mm); 434 435 return 0; 436 } 437 438 static bool vhost_run_work_list(void *data) 439 { 440 struct vhost_worker *worker = data; 441 struct vhost_work *work, *work_next; 442 struct llist_node *node; 443 444 node = llist_del_all(&worker->work_list); 445 if (node) { 446 __set_current_state(TASK_RUNNING); 447 448 node = llist_reverse_order(node); 449 /* make sure flag is seen after deletion */ 450 smp_wmb(); 451 llist_for_each_entry_safe(work, work_next, node, node) { 452 clear_bit(VHOST_WORK_QUEUED, &work->flags); 453 kcov_remote_start_common(worker->kcov_handle); 454 work->fn(work); 455 kcov_remote_stop(); 456 cond_resched(); 457 } 458 } 459 460 return !!node; 461 } 462 463 static void vhost_worker_killed(void *data) 464 { 465 struct vhost_worker *worker = data; 466 struct vhost_dev *dev = worker->dev; 467 struct vhost_virtqueue *vq; 468 int i, attach_cnt = 0; 469 470 mutex_lock(&worker->mutex); 471 worker->killed = true; 472 473 for (i = 0; i < dev->nvqs; i++) { 474 vq = dev->vqs[i]; 475 476 mutex_lock(&vq->mutex); 477 if (worker == 478 rcu_dereference_check(vq->worker, 479 lockdep_is_held(&vq->mutex))) { 480 rcu_assign_pointer(vq->worker, NULL); 481 attach_cnt++; 482 } 483 mutex_unlock(&vq->mutex); 484 } 485 486 worker->attachment_cnt -= attach_cnt; 487 if (attach_cnt) 488 synchronize_rcu(); 489 /* 490 * Finish vhost_worker_flush calls and any other works that snuck in 491 * before the synchronize_rcu. 492 */ 493 vhost_run_work_list(worker); 494 mutex_unlock(&worker->mutex); 495 } 496 497 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq) 498 { 499 kfree(vq->indirect); 500 vq->indirect = NULL; 501 kfree(vq->log); 502 vq->log = NULL; 503 kfree(vq->heads); 504 vq->heads = NULL; 505 kfree(vq->nheads); 506 vq->nheads = NULL; 507 } 508 509 /* Helper to allocate iovec buffers for all vqs. */ 510 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev) 511 { 512 struct vhost_virtqueue *vq; 513 int i; 514 515 for (i = 0; i < dev->nvqs; ++i) { 516 vq = dev->vqs[i]; 517 vq->indirect = kmalloc_objs(*vq->indirect, UIO_MAXIOV); 518 vq->log = kmalloc_objs(*vq->log, dev->iov_limit); 519 vq->heads = kmalloc_objs(*vq->heads, dev->iov_limit); 520 vq->nheads = kmalloc_array(dev->iov_limit, sizeof(*vq->nheads), 521 GFP_KERNEL); 522 if (!vq->indirect || !vq->log || !vq->heads || !vq->nheads) 523 goto err_nomem; 524 } 525 return 0; 526 527 err_nomem: 528 for (; i >= 0; --i) 529 vhost_vq_free_iovecs(dev->vqs[i]); 530 return -ENOMEM; 531 } 532 533 static void vhost_dev_free_iovecs(struct vhost_dev *dev) 534 { 535 int i; 536 537 for (i = 0; i < dev->nvqs; ++i) 538 vhost_vq_free_iovecs(dev->vqs[i]); 539 } 540 541 bool vhost_exceeds_weight(struct vhost_virtqueue *vq, 542 int pkts, int total_len) 543 { 544 struct vhost_dev *dev = vq->dev; 545 546 if ((dev->byte_weight && total_len >= dev->byte_weight) || 547 pkts >= dev->weight) { 548 vhost_poll_queue(&vq->poll); 549 return true; 550 } 551 552 return false; 553 } 554 EXPORT_SYMBOL_GPL(vhost_exceeds_weight); 555 556 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq, 557 unsigned int num) 558 { 559 size_t event __maybe_unused = 560 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0; 561 562 return size_add(struct_size(vq->avail, ring, num), event); 563 } 564 565 static size_t vhost_get_used_size(struct vhost_virtqueue *vq, 566 unsigned int num) 567 { 568 size_t event __maybe_unused = 569 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0; 570 571 return size_add(struct_size(vq->used, ring, num), event); 572 } 573 574 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq, 575 unsigned int num) 576 { 577 return sizeof(*vq->desc) * num; 578 } 579 580 void vhost_dev_init(struct vhost_dev *dev, 581 struct vhost_virtqueue **vqs, int nvqs, 582 int iov_limit, int weight, int byte_weight, 583 bool use_worker, 584 int (*msg_handler)(struct vhost_dev *dev, u32 asid, 585 struct vhost_iotlb_msg *msg)) 586 { 587 struct vhost_virtqueue *vq; 588 int i; 589 590 dev->vqs = vqs; 591 dev->nvqs = nvqs; 592 mutex_init(&dev->mutex); 593 dev->log_ctx = NULL; 594 dev->umem = NULL; 595 dev->iotlb = NULL; 596 dev->mm = NULL; 597 dev->iov_limit = iov_limit; 598 dev->weight = weight; 599 dev->byte_weight = byte_weight; 600 dev->use_worker = use_worker; 601 dev->msg_handler = msg_handler; 602 dev->fork_owner = fork_from_owner_default; 603 init_waitqueue_head(&dev->wait); 604 INIT_LIST_HEAD(&dev->read_list); 605 INIT_LIST_HEAD(&dev->pending_list); 606 spin_lock_init(&dev->iotlb_lock); 607 xa_init_flags(&dev->worker_xa, XA_FLAGS_ALLOC); 608 609 for (i = 0; i < dev->nvqs; ++i) { 610 vq = dev->vqs[i]; 611 vq->log = NULL; 612 vq->indirect = NULL; 613 vq->heads = NULL; 614 vq->nheads = NULL; 615 vq->dev = dev; 616 mutex_init(&vq->mutex); 617 vhost_vq_reset(dev, vq); 618 if (vq->handle_kick) 619 vhost_poll_init(&vq->poll, vq->handle_kick, 620 EPOLLIN, dev, vq); 621 } 622 } 623 EXPORT_SYMBOL_GPL(vhost_dev_init); 624 625 /* Caller should have device mutex */ 626 long vhost_dev_check_owner(struct vhost_dev *dev) 627 { 628 /* Are you the owner? If not, I don't think you mean to do that */ 629 return dev->mm == current->mm ? 0 : -EPERM; 630 } 631 EXPORT_SYMBOL_GPL(vhost_dev_check_owner); 632 633 struct vhost_attach_cgroups_struct { 634 struct vhost_work work; 635 struct task_struct *owner; 636 int ret; 637 }; 638 639 static void vhost_attach_cgroups_work(struct vhost_work *work) 640 { 641 struct vhost_attach_cgroups_struct *s; 642 643 s = container_of(work, struct vhost_attach_cgroups_struct, work); 644 s->ret = cgroup_attach_task_all(s->owner, current); 645 } 646 647 static int vhost_attach_task_to_cgroups(struct vhost_worker *worker) 648 { 649 struct vhost_attach_cgroups_struct attach; 650 int saved_cnt; 651 652 attach.owner = current; 653 654 vhost_work_init(&attach.work, vhost_attach_cgroups_work); 655 vhost_worker_queue(worker, &attach.work); 656 657 mutex_lock(&worker->mutex); 658 659 /* 660 * Bypass attachment_cnt check in __vhost_worker_flush: 661 * Temporarily change it to INT_MAX to bypass the check 662 */ 663 saved_cnt = worker->attachment_cnt; 664 worker->attachment_cnt = INT_MAX; 665 __vhost_worker_flush(worker); 666 worker->attachment_cnt = saved_cnt; 667 668 mutex_unlock(&worker->mutex); 669 670 return attach.ret; 671 } 672 673 /* Caller should have device mutex */ 674 bool vhost_dev_has_owner(struct vhost_dev *dev) 675 { 676 return dev->mm; 677 } 678 EXPORT_SYMBOL_GPL(vhost_dev_has_owner); 679 680 static void vhost_attach_mm(struct vhost_dev *dev) 681 { 682 /* No owner, become one */ 683 if (dev->use_worker) { 684 dev->mm = get_task_mm(current); 685 } else { 686 /* vDPA device does not use worker thread, so there's 687 * no need to hold the address space for mm. This helps 688 * to avoid deadlock in the case of mmap() which may 689 * hold the refcnt of the file and depends on release 690 * method to remove vma. 691 */ 692 dev->mm = current->mm; 693 mmgrab(dev->mm); 694 } 695 } 696 697 static void vhost_detach_mm(struct vhost_dev *dev) 698 { 699 if (!dev->mm) 700 return; 701 702 if (dev->use_worker) 703 mmput(dev->mm); 704 else 705 mmdrop(dev->mm); 706 707 dev->mm = NULL; 708 } 709 710 static void vhost_worker_destroy(struct vhost_dev *dev, 711 struct vhost_worker *worker) 712 { 713 if (!worker) 714 return; 715 716 WARN_ON(!llist_empty(&worker->work_list)); 717 xa_erase(&dev->worker_xa, worker->id); 718 worker->ops->stop(worker); 719 kfree(worker); 720 } 721 722 static void vhost_workers_free(struct vhost_dev *dev) 723 { 724 struct vhost_worker *worker; 725 unsigned long i; 726 727 if (!dev->use_worker) 728 return; 729 730 for (i = 0; i < dev->nvqs; i++) 731 rcu_assign_pointer(dev->vqs[i]->worker, NULL); 732 /* 733 * Free the default worker we created and cleanup workers userspace 734 * created but couldn't clean up (it forgot or crashed). 735 */ 736 xa_for_each(&dev->worker_xa, i, worker) 737 vhost_worker_destroy(dev, worker); 738 xa_destroy(&dev->worker_xa); 739 } 740 741 static void vhost_task_wakeup(struct vhost_worker *worker) 742 { 743 return vhost_task_wake(worker->vtsk); 744 } 745 746 static void vhost_kthread_wakeup(struct vhost_worker *worker) 747 { 748 wake_up_process(worker->kthread_task); 749 } 750 751 static void vhost_task_do_stop(struct vhost_worker *worker) 752 { 753 return vhost_task_stop(worker->vtsk); 754 } 755 756 static void vhost_kthread_do_stop(struct vhost_worker *worker) 757 { 758 kthread_stop(worker->kthread_task); 759 } 760 761 static int vhost_task_worker_create(struct vhost_worker *worker, 762 struct vhost_dev *dev, const char *name) 763 { 764 struct vhost_task *vtsk; 765 u32 id; 766 int ret; 767 768 vtsk = vhost_task_create(vhost_run_work_list, vhost_worker_killed, 769 worker, name); 770 if (IS_ERR(vtsk)) 771 return PTR_ERR(vtsk); 772 773 worker->vtsk = vtsk; 774 vhost_task_start(vtsk); 775 ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL); 776 if (ret < 0) { 777 vhost_task_do_stop(worker); 778 return ret; 779 } 780 worker->id = id; 781 return 0; 782 } 783 784 static int vhost_kthread_worker_create(struct vhost_worker *worker, 785 struct vhost_dev *dev, const char *name) 786 { 787 struct task_struct *task; 788 u32 id; 789 int ret; 790 791 task = kthread_create(vhost_run_work_kthread_list, worker, "%s", name); 792 if (IS_ERR(task)) 793 return PTR_ERR(task); 794 795 worker->kthread_task = task; 796 wake_up_process(task); 797 ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL); 798 if (ret < 0) 799 goto stop_worker; 800 801 ret = vhost_attach_task_to_cgroups(worker); 802 if (ret) 803 goto free_id; 804 805 worker->id = id; 806 return 0; 807 808 free_id: 809 xa_erase(&dev->worker_xa, id); 810 stop_worker: 811 vhost_kthread_do_stop(worker); 812 return ret; 813 } 814 815 static const struct vhost_worker_ops kthread_ops = { 816 .create = vhost_kthread_worker_create, 817 .stop = vhost_kthread_do_stop, 818 .wakeup = vhost_kthread_wakeup, 819 }; 820 821 static const struct vhost_worker_ops vhost_task_ops = { 822 .create = vhost_task_worker_create, 823 .stop = vhost_task_do_stop, 824 .wakeup = vhost_task_wakeup, 825 }; 826 827 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev) 828 { 829 struct vhost_worker *worker; 830 char name[TASK_COMM_LEN]; 831 int ret; 832 const struct vhost_worker_ops *ops = dev->fork_owner ? &vhost_task_ops : 833 &kthread_ops; 834 835 worker = kzalloc_obj(*worker, GFP_KERNEL_ACCOUNT); 836 if (!worker) 837 return NULL; 838 839 worker->dev = dev; 840 worker->ops = ops; 841 snprintf(name, sizeof(name), "vhost-%d", current->pid); 842 843 mutex_init(&worker->mutex); 844 init_llist_head(&worker->work_list); 845 worker->kcov_handle = kcov_common_handle(); 846 ret = ops->create(worker, dev, name); 847 if (ret < 0) 848 goto free_worker; 849 850 return worker; 851 852 free_worker: 853 kfree(worker); 854 return NULL; 855 } 856 857 /* Caller must have device mutex */ 858 static void __vhost_vq_attach_worker(struct vhost_virtqueue *vq, 859 struct vhost_worker *worker) 860 { 861 struct vhost_worker *old_worker; 862 863 mutex_lock(&worker->mutex); 864 if (worker->killed) { 865 mutex_unlock(&worker->mutex); 866 return; 867 } 868 869 mutex_lock(&vq->mutex); 870 871 old_worker = rcu_dereference_check(vq->worker, 872 lockdep_is_held(&vq->mutex)); 873 rcu_assign_pointer(vq->worker, worker); 874 worker->attachment_cnt++; 875 876 if (!old_worker) { 877 mutex_unlock(&vq->mutex); 878 mutex_unlock(&worker->mutex); 879 return; 880 } 881 mutex_unlock(&vq->mutex); 882 mutex_unlock(&worker->mutex); 883 884 /* 885 * Take the worker mutex to make sure we see the work queued from 886 * device wide flushes which doesn't use RCU for execution. 887 */ 888 mutex_lock(&old_worker->mutex); 889 if (old_worker->killed) { 890 mutex_unlock(&old_worker->mutex); 891 return; 892 } 893 894 /* 895 * We don't want to call synchronize_rcu for every vq during setup 896 * because it will slow down VM startup. If we haven't done 897 * VHOST_SET_VRING_KICK and not done the driver specific 898 * SET_ENDPOINT/RUNNING then we can skip the sync since there will 899 * not be any works queued for scsi and net. 900 */ 901 mutex_lock(&vq->mutex); 902 if (!vhost_vq_get_backend(vq) && !vq->kick) { 903 mutex_unlock(&vq->mutex); 904 905 old_worker->attachment_cnt--; 906 mutex_unlock(&old_worker->mutex); 907 /* 908 * vsock can queue anytime after VHOST_VSOCK_SET_GUEST_CID. 909 * Warn if it adds support for multiple workers but forgets to 910 * handle the early queueing case. 911 */ 912 WARN_ON(!old_worker->attachment_cnt && 913 !llist_empty(&old_worker->work_list)); 914 return; 915 } 916 mutex_unlock(&vq->mutex); 917 918 /* Make sure new vq queue/flush/poll calls see the new worker */ 919 synchronize_rcu(); 920 /* Make sure whatever was queued gets run */ 921 __vhost_worker_flush(old_worker); 922 old_worker->attachment_cnt--; 923 mutex_unlock(&old_worker->mutex); 924 } 925 926 /* Caller must have device mutex */ 927 static int vhost_vq_attach_worker(struct vhost_virtqueue *vq, 928 struct vhost_vring_worker *info) 929 { 930 unsigned long index = info->worker_id; 931 struct vhost_dev *dev = vq->dev; 932 struct vhost_worker *worker; 933 934 if (!dev->use_worker) 935 return -EINVAL; 936 937 worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT); 938 if (!worker || worker->id != info->worker_id) 939 return -ENODEV; 940 941 __vhost_vq_attach_worker(vq, worker); 942 return 0; 943 } 944 945 /* Caller must have device mutex */ 946 static int vhost_new_worker(struct vhost_dev *dev, 947 struct vhost_worker_state *info) 948 { 949 struct vhost_worker *worker; 950 951 worker = vhost_worker_create(dev); 952 if (!worker) 953 return -ENOMEM; 954 955 info->worker_id = worker->id; 956 return 0; 957 } 958 959 /* Caller must have device mutex */ 960 static int vhost_free_worker(struct vhost_dev *dev, 961 struct vhost_worker_state *info) 962 { 963 unsigned long index = info->worker_id; 964 struct vhost_worker *worker; 965 966 worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT); 967 if (!worker || worker->id != info->worker_id) 968 return -ENODEV; 969 970 mutex_lock(&worker->mutex); 971 if (worker->attachment_cnt || worker->killed) { 972 mutex_unlock(&worker->mutex); 973 return -EBUSY; 974 } 975 /* 976 * A flush might have raced and snuck in before attachment_cnt was set 977 * to zero. Make sure flushes are flushed from the queue before 978 * freeing. 979 */ 980 __vhost_worker_flush(worker); 981 mutex_unlock(&worker->mutex); 982 983 vhost_worker_destroy(dev, worker); 984 return 0; 985 } 986 987 static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp, 988 struct vhost_virtqueue **vq, u32 *id) 989 { 990 u32 __user *idxp = argp; 991 u32 idx; 992 long r; 993 994 r = get_user(idx, idxp); 995 if (r < 0) 996 return r; 997 998 if (idx >= dev->nvqs) 999 return -ENOBUFS; 1000 1001 idx = array_index_nospec(idx, dev->nvqs); 1002 1003 *vq = dev->vqs[idx]; 1004 *id = idx; 1005 return 0; 1006 } 1007 1008 /* Caller must have device mutex */ 1009 long vhost_worker_ioctl(struct vhost_dev *dev, unsigned int ioctl, 1010 void __user *argp) 1011 { 1012 struct vhost_vring_worker ring_worker; 1013 struct vhost_worker_state state; 1014 struct vhost_worker *worker; 1015 struct vhost_virtqueue *vq; 1016 long ret; 1017 u32 idx; 1018 1019 if (!dev->use_worker) 1020 return -EINVAL; 1021 1022 if (!vhost_dev_has_owner(dev)) 1023 return -EINVAL; 1024 1025 ret = vhost_dev_check_owner(dev); 1026 if (ret) 1027 return ret; 1028 1029 switch (ioctl) { 1030 /* dev worker ioctls */ 1031 case VHOST_NEW_WORKER: 1032 /* 1033 * vhost_tasks will account for worker threads under the parent's 1034 * NPROC value but kthreads do not. To avoid userspace overflowing 1035 * the system with worker threads fork_owner must be true. 1036 */ 1037 if (!dev->fork_owner) 1038 return -EFAULT; 1039 1040 ret = vhost_new_worker(dev, &state); 1041 if (!ret && copy_to_user(argp, &state, sizeof(state))) 1042 ret = -EFAULT; 1043 return ret; 1044 case VHOST_FREE_WORKER: 1045 if (copy_from_user(&state, argp, sizeof(state))) 1046 return -EFAULT; 1047 return vhost_free_worker(dev, &state); 1048 /* vring worker ioctls */ 1049 case VHOST_ATTACH_VRING_WORKER: 1050 case VHOST_GET_VRING_WORKER: 1051 break; 1052 default: 1053 return -ENOIOCTLCMD; 1054 } 1055 1056 ret = vhost_get_vq_from_user(dev, argp, &vq, &idx); 1057 if (ret) 1058 return ret; 1059 1060 switch (ioctl) { 1061 case VHOST_ATTACH_VRING_WORKER: 1062 if (copy_from_user(&ring_worker, argp, sizeof(ring_worker))) { 1063 ret = -EFAULT; 1064 break; 1065 } 1066 1067 ret = vhost_vq_attach_worker(vq, &ring_worker); 1068 break; 1069 case VHOST_GET_VRING_WORKER: 1070 worker = rcu_dereference_check(vq->worker, 1071 lockdep_is_held(&dev->mutex)); 1072 if (!worker) { 1073 ret = -EINVAL; 1074 break; 1075 } 1076 1077 ring_worker.index = idx; 1078 ring_worker.worker_id = worker->id; 1079 1080 if (copy_to_user(argp, &ring_worker, sizeof(ring_worker))) 1081 ret = -EFAULT; 1082 break; 1083 default: 1084 ret = -ENOIOCTLCMD; 1085 break; 1086 } 1087 1088 return ret; 1089 } 1090 EXPORT_SYMBOL_GPL(vhost_worker_ioctl); 1091 1092 /* Caller should have device mutex */ 1093 long vhost_dev_set_owner(struct vhost_dev *dev) 1094 { 1095 struct vhost_worker *worker; 1096 int err, i; 1097 1098 /* Is there an owner already? */ 1099 if (vhost_dev_has_owner(dev)) { 1100 err = -EBUSY; 1101 goto err_mm; 1102 } 1103 1104 vhost_attach_mm(dev); 1105 1106 err = vhost_dev_alloc_iovecs(dev); 1107 if (err) 1108 goto err_iovecs; 1109 1110 if (dev->use_worker) { 1111 /* 1112 * This should be done last, because vsock can queue work 1113 * before VHOST_SET_OWNER so it simplifies the failure path 1114 * below since we don't have to worry about vsock queueing 1115 * while we free the worker. 1116 */ 1117 worker = vhost_worker_create(dev); 1118 if (!worker) { 1119 err = -ENOMEM; 1120 goto err_worker; 1121 } 1122 1123 for (i = 0; i < dev->nvqs; i++) 1124 __vhost_vq_attach_worker(dev->vqs[i], worker); 1125 } 1126 1127 return 0; 1128 1129 err_worker: 1130 vhost_dev_free_iovecs(dev); 1131 err_iovecs: 1132 vhost_detach_mm(dev); 1133 err_mm: 1134 return err; 1135 } 1136 EXPORT_SYMBOL_GPL(vhost_dev_set_owner); 1137 1138 static struct vhost_iotlb *iotlb_alloc(void) 1139 { 1140 if (max_iotlb_entries <= 0) 1141 return NULL; 1142 1143 return vhost_iotlb_alloc(max_iotlb_entries, 1144 VHOST_IOTLB_FLAG_RETIRE); 1145 } 1146 1147 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void) 1148 { 1149 return iotlb_alloc(); 1150 } 1151 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare); 1152 1153 /* Caller should have device mutex */ 1154 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem) 1155 { 1156 int i; 1157 1158 vhost_dev_cleanup(dev); 1159 1160 dev->fork_owner = fork_from_owner_default; 1161 dev->umem = umem; 1162 /* We don't need VQ locks below since vhost_dev_cleanup makes sure 1163 * VQs aren't running. 1164 */ 1165 for (i = 0; i < dev->nvqs; ++i) 1166 dev->vqs[i]->umem = umem; 1167 } 1168 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner); 1169 1170 void vhost_dev_stop(struct vhost_dev *dev) 1171 { 1172 int i; 1173 1174 for (i = 0; i < dev->nvqs; ++i) { 1175 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) 1176 vhost_poll_stop(&dev->vqs[i]->poll); 1177 } 1178 1179 vhost_dev_flush(dev); 1180 } 1181 EXPORT_SYMBOL_GPL(vhost_dev_stop); 1182 1183 void vhost_clear_msg(struct vhost_dev *dev) 1184 { 1185 struct vhost_msg_node *node, *n; 1186 1187 spin_lock(&dev->iotlb_lock); 1188 1189 list_for_each_entry_safe(node, n, &dev->read_list, node) { 1190 list_del(&node->node); 1191 kfree(node); 1192 } 1193 1194 list_for_each_entry_safe(node, n, &dev->pending_list, node) { 1195 list_del(&node->node); 1196 kfree(node); 1197 } 1198 1199 spin_unlock(&dev->iotlb_lock); 1200 } 1201 EXPORT_SYMBOL_GPL(vhost_clear_msg); 1202 1203 void vhost_dev_cleanup(struct vhost_dev *dev) 1204 { 1205 int i; 1206 1207 for (i = 0; i < dev->nvqs; ++i) { 1208 if (dev->vqs[i]->error_ctx) 1209 eventfd_ctx_put(dev->vqs[i]->error_ctx); 1210 if (dev->vqs[i]->kick) 1211 fput(dev->vqs[i]->kick); 1212 if (dev->vqs[i]->call_ctx.ctx) 1213 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx); 1214 vhost_vq_reset(dev, dev->vqs[i]); 1215 } 1216 vhost_dev_free_iovecs(dev); 1217 if (dev->log_ctx) 1218 eventfd_ctx_put(dev->log_ctx); 1219 dev->log_ctx = NULL; 1220 /* No one will access memory at this point */ 1221 vhost_iotlb_free(dev->umem); 1222 dev->umem = NULL; 1223 vhost_iotlb_free(dev->iotlb); 1224 dev->iotlb = NULL; 1225 vhost_clear_msg(dev); 1226 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM); 1227 vhost_workers_free(dev); 1228 vhost_detach_mm(dev); 1229 } 1230 EXPORT_SYMBOL_GPL(vhost_dev_cleanup); 1231 1232 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz) 1233 { 1234 u64 a = addr / VHOST_PAGE_SIZE / 8; 1235 1236 /* Make sure 64 bit math will not overflow. */ 1237 if (a > ULONG_MAX - (unsigned long)log_base || 1238 a + (unsigned long)log_base > ULONG_MAX) 1239 return false; 1240 1241 return access_ok(log_base + a, 1242 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8); 1243 } 1244 1245 /* Make sure 64 bit math will not overflow. */ 1246 static bool vhost_overflow(u64 uaddr, u64 size) 1247 { 1248 if (uaddr > ULONG_MAX || size > ULONG_MAX) 1249 return true; 1250 1251 if (!size) 1252 return false; 1253 1254 return uaddr > ULONG_MAX - size + 1; 1255 } 1256 1257 /* Caller should have vq mutex and device mutex. */ 1258 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem, 1259 int log_all) 1260 { 1261 struct vhost_iotlb_map *map; 1262 1263 if (!umem) 1264 return false; 1265 1266 list_for_each_entry(map, &umem->list, link) { 1267 unsigned long a = map->addr; 1268 1269 if (vhost_overflow(map->addr, map->size)) 1270 return false; 1271 1272 1273 if (!access_ok((void __user *)a, map->size)) 1274 return false; 1275 else if (log_all && !log_access_ok(log_base, 1276 map->start, 1277 map->size)) 1278 return false; 1279 } 1280 return true; 1281 } 1282 1283 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq, 1284 u64 addr, unsigned int size, 1285 int type) 1286 { 1287 const struct vhost_iotlb_map *map = vq->meta_iotlb[type]; 1288 1289 if (!map) 1290 return NULL; 1291 1292 return (void __user *)(uintptr_t)(map->addr + addr - map->start); 1293 } 1294 1295 /* Can we switch to this memory table? */ 1296 /* Caller should have device mutex but not vq mutex */ 1297 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem, 1298 int log_all) 1299 { 1300 int i; 1301 1302 for (i = 0; i < d->nvqs; ++i) { 1303 bool ok; 1304 bool log; 1305 1306 mutex_lock(&d->vqs[i]->mutex); 1307 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL); 1308 /* If ring is inactive, will check when it's enabled. */ 1309 if (d->vqs[i]->private_data) 1310 ok = vq_memory_access_ok(d->vqs[i]->log_base, 1311 umem, log); 1312 else 1313 ok = true; 1314 mutex_unlock(&d->vqs[i]->mutex); 1315 if (!ok) 1316 return false; 1317 } 1318 return true; 1319 } 1320 1321 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len, 1322 struct iovec iov[], int iov_size, int access); 1323 1324 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to, 1325 const void *from, unsigned size) 1326 { 1327 int ret; 1328 1329 if (!vq->iotlb) 1330 return __copy_to_user(to, from, size); 1331 else { 1332 /* This function should be called after iotlb 1333 * prefetch, which means we're sure that all vq 1334 * could be access through iotlb. So -EAGAIN should 1335 * not happen in this case. 1336 */ 1337 struct iov_iter t; 1338 void __user *uaddr = vhost_vq_meta_fetch(vq, 1339 (u64)(uintptr_t)to, size, 1340 VHOST_ADDR_USED); 1341 1342 if (uaddr) 1343 return __copy_to_user(uaddr, from, size); 1344 1345 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov, 1346 ARRAY_SIZE(vq->iotlb_iov), 1347 VHOST_ACCESS_WO); 1348 if (ret < 0) 1349 goto out; 1350 iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size); 1351 ret = copy_to_iter(from, size, &t); 1352 if (ret == size) 1353 ret = 0; 1354 } 1355 out: 1356 return ret; 1357 } 1358 1359 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to, 1360 void __user *from, unsigned size) 1361 { 1362 int ret; 1363 1364 if (!vq->iotlb) 1365 return __copy_from_user(to, from, size); 1366 else { 1367 /* This function should be called after iotlb 1368 * prefetch, which means we're sure that vq 1369 * could be access through iotlb. So -EAGAIN should 1370 * not happen in this case. 1371 */ 1372 void __user *uaddr = vhost_vq_meta_fetch(vq, 1373 (u64)(uintptr_t)from, size, 1374 VHOST_ADDR_DESC); 1375 struct iov_iter f; 1376 1377 if (uaddr) 1378 return __copy_from_user(to, uaddr, size); 1379 1380 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov, 1381 ARRAY_SIZE(vq->iotlb_iov), 1382 VHOST_ACCESS_RO); 1383 if (ret < 0) { 1384 vq_err(vq, "IOTLB translation failure: uaddr " 1385 "%p size 0x%llx\n", from, 1386 (unsigned long long) size); 1387 goto out; 1388 } 1389 iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size); 1390 ret = copy_from_iter(to, size, &f); 1391 if (ret == size) 1392 ret = 0; 1393 } 1394 1395 out: 1396 return ret; 1397 } 1398 1399 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq, 1400 void __user *addr, unsigned int size, 1401 int type) 1402 { 1403 int ret; 1404 1405 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov, 1406 ARRAY_SIZE(vq->iotlb_iov), 1407 VHOST_ACCESS_RO); 1408 if (ret < 0) { 1409 vq_err(vq, "IOTLB translation failure: uaddr " 1410 "%p size 0x%llx\n", addr, 1411 (unsigned long long) size); 1412 return NULL; 1413 } 1414 1415 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) { 1416 vq_err(vq, "Non atomic userspace memory access: uaddr " 1417 "%p size 0x%llx\n", addr, 1418 (unsigned long long) size); 1419 return NULL; 1420 } 1421 1422 return vq->iotlb_iov[0].iov_base; 1423 } 1424 1425 /* This function should be called after iotlb 1426 * prefetch, which means we're sure that vq 1427 * could be access through iotlb. So -EAGAIN should 1428 * not happen in this case. 1429 */ 1430 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq, 1431 void __user *addr, unsigned int size, 1432 int type) 1433 { 1434 void __user *uaddr = vhost_vq_meta_fetch(vq, 1435 (u64)(uintptr_t)addr, size, type); 1436 if (uaddr) 1437 return uaddr; 1438 1439 return __vhost_get_user_slow(vq, addr, size, type); 1440 } 1441 1442 #define vhost_put_user(vq, x, ptr) \ 1443 ({ \ 1444 int ret; \ 1445 if (!vq->iotlb) { \ 1446 ret = put_user(x, ptr); \ 1447 } else { \ 1448 __typeof__(ptr) to = \ 1449 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \ 1450 sizeof(*ptr), VHOST_ADDR_USED); \ 1451 if (to != NULL) \ 1452 ret = put_user(x, to); \ 1453 else \ 1454 ret = -EFAULT; \ 1455 } \ 1456 ret; \ 1457 }) 1458 1459 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq) 1460 { 1461 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx), 1462 vhost_avail_event(vq)); 1463 } 1464 1465 static inline int vhost_put_used(struct vhost_virtqueue *vq, 1466 struct vring_used_elem *head, int idx, 1467 int count) 1468 { 1469 return vhost_copy_to_user(vq, vq->used->ring + idx, head, 1470 count * sizeof(*head)); 1471 } 1472 1473 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq) 1474 1475 { 1476 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags), 1477 &vq->used->flags); 1478 } 1479 1480 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq) 1481 1482 { 1483 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx), 1484 &vq->used->idx); 1485 } 1486 1487 #define vhost_get_user(vq, x, ptr, type) \ 1488 ({ \ 1489 int ret; \ 1490 if (!vq->iotlb) { \ 1491 ret = get_user(x, ptr); \ 1492 } else { \ 1493 __typeof__(ptr) from = \ 1494 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \ 1495 sizeof(*ptr), \ 1496 type); \ 1497 if (from != NULL) \ 1498 ret = get_user(x, from); \ 1499 else \ 1500 ret = -EFAULT; \ 1501 } \ 1502 ret; \ 1503 }) 1504 1505 #define vhost_get_avail(vq, x, ptr) \ 1506 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL) 1507 1508 #define vhost_get_used(vq, x, ptr) \ 1509 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED) 1510 1511 static void vhost_dev_lock_vqs(struct vhost_dev *d) 1512 { 1513 int i = 0; 1514 for (i = 0; i < d->nvqs; ++i) 1515 mutex_lock_nested(&d->vqs[i]->mutex, i); 1516 } 1517 1518 static void vhost_dev_unlock_vqs(struct vhost_dev *d) 1519 { 1520 int i = 0; 1521 for (i = 0; i < d->nvqs; ++i) 1522 mutex_unlock(&d->vqs[i]->mutex); 1523 } 1524 1525 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq) 1526 { 1527 __virtio16 idx; 1528 u16 avail_idx; 1529 int r; 1530 1531 r = vhost_get_avail(vq, idx, &vq->avail->idx); 1532 if (unlikely(r < 0)) { 1533 vq_err(vq, "Failed to access available index at %p (%d)\n", 1534 &vq->avail->idx, r); 1535 return r; 1536 } 1537 1538 /* Check it isn't doing very strange thing with available indexes */ 1539 avail_idx = vhost16_to_cpu(vq, idx); 1540 if (unlikely((u16)(avail_idx - vq->last_avail_idx) > vq->num)) { 1541 vq_err(vq, "Invalid available index change from %u to %u", 1542 vq->last_avail_idx, avail_idx); 1543 return -EINVAL; 1544 } 1545 1546 /* We're done if there is nothing new */ 1547 if (avail_idx == vq->avail_idx) 1548 return 0; 1549 1550 vq->avail_idx = avail_idx; 1551 1552 /* 1553 * We updated vq->avail_idx so we need a memory barrier between 1554 * the index read above and the caller reading avail ring entries. 1555 */ 1556 smp_rmb(); 1557 return 1; 1558 } 1559 1560 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq, 1561 __virtio16 *head, int idx) 1562 { 1563 return vhost_get_avail(vq, *head, 1564 &vq->avail->ring[idx & (vq->num - 1)]); 1565 } 1566 1567 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq, 1568 __virtio16 *flags) 1569 { 1570 return vhost_get_avail(vq, *flags, &vq->avail->flags); 1571 } 1572 1573 static inline int vhost_get_used_event(struct vhost_virtqueue *vq, 1574 __virtio16 *event) 1575 { 1576 return vhost_get_avail(vq, *event, vhost_used_event(vq)); 1577 } 1578 1579 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq, 1580 __virtio16 *idx) 1581 { 1582 return vhost_get_used(vq, *idx, &vq->used->idx); 1583 } 1584 1585 static inline int vhost_get_desc(struct vhost_virtqueue *vq, 1586 struct vring_desc *desc, int idx) 1587 { 1588 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc)); 1589 } 1590 1591 static void vhost_iotlb_notify_vq(struct vhost_dev *d, 1592 struct vhost_iotlb_msg *msg) 1593 { 1594 struct vhost_msg_node *node, *n; 1595 1596 spin_lock(&d->iotlb_lock); 1597 1598 list_for_each_entry_safe(node, n, &d->pending_list, node) { 1599 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb; 1600 if (msg->iova <= vq_msg->iova && 1601 msg->iova + msg->size - 1 >= vq_msg->iova && 1602 vq_msg->type == VHOST_IOTLB_MISS) { 1603 vhost_poll_queue(&node->vq->poll); 1604 list_del(&node->node); 1605 kfree(node); 1606 } 1607 } 1608 1609 spin_unlock(&d->iotlb_lock); 1610 } 1611 1612 static bool umem_access_ok(u64 uaddr, u64 size, int access) 1613 { 1614 unsigned long a = uaddr; 1615 1616 /* Make sure 64 bit math will not overflow. */ 1617 if (vhost_overflow(uaddr, size)) 1618 return false; 1619 1620 if ((access & VHOST_ACCESS_RO) && 1621 !access_ok((void __user *)a, size)) 1622 return false; 1623 if ((access & VHOST_ACCESS_WO) && 1624 !access_ok((void __user *)a, size)) 1625 return false; 1626 return true; 1627 } 1628 1629 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid, 1630 struct vhost_iotlb_msg *msg) 1631 { 1632 int ret = 0; 1633 1634 if (asid != 0) 1635 return -EINVAL; 1636 1637 mutex_lock(&dev->mutex); 1638 vhost_dev_lock_vqs(dev); 1639 switch (msg->type) { 1640 case VHOST_IOTLB_UPDATE: 1641 if (!dev->iotlb) { 1642 ret = -EFAULT; 1643 break; 1644 } 1645 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) { 1646 ret = -EFAULT; 1647 break; 1648 } 1649 vhost_vq_meta_reset(dev); 1650 if (vhost_iotlb_add_range(dev->iotlb, msg->iova, 1651 msg->iova + msg->size - 1, 1652 msg->uaddr, msg->perm)) { 1653 ret = -ENOMEM; 1654 break; 1655 } 1656 vhost_iotlb_notify_vq(dev, msg); 1657 break; 1658 case VHOST_IOTLB_INVALIDATE: 1659 if (!dev->iotlb) { 1660 ret = -EFAULT; 1661 break; 1662 } 1663 vhost_vq_meta_reset(dev); 1664 vhost_iotlb_del_range(dev->iotlb, msg->iova, 1665 msg->iova + msg->size - 1); 1666 break; 1667 default: 1668 ret = -EINVAL; 1669 break; 1670 } 1671 1672 vhost_dev_unlock_vqs(dev); 1673 mutex_unlock(&dev->mutex); 1674 1675 return ret; 1676 } 1677 ssize_t vhost_chr_write_iter(struct vhost_dev *dev, 1678 struct iov_iter *from) 1679 { 1680 struct vhost_iotlb_msg msg; 1681 size_t offset; 1682 int type, ret; 1683 u32 asid = 0; 1684 1685 ret = copy_from_iter(&type, sizeof(type), from); 1686 if (ret != sizeof(type)) { 1687 ret = -EINVAL; 1688 goto done; 1689 } 1690 1691 switch (type) { 1692 case VHOST_IOTLB_MSG: 1693 /* There maybe a hole after type for V1 message type, 1694 * so skip it here. 1695 */ 1696 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int); 1697 break; 1698 case VHOST_IOTLB_MSG_V2: 1699 if (vhost_backend_has_feature(dev->vqs[0], 1700 VHOST_BACKEND_F_IOTLB_ASID)) { 1701 ret = copy_from_iter(&asid, sizeof(asid), from); 1702 if (ret != sizeof(asid)) { 1703 ret = -EINVAL; 1704 goto done; 1705 } 1706 offset = 0; 1707 } else 1708 offset = sizeof(__u32); 1709 break; 1710 default: 1711 ret = -EINVAL; 1712 goto done; 1713 } 1714 1715 iov_iter_advance(from, offset); 1716 ret = copy_from_iter(&msg, sizeof(msg), from); 1717 if (ret != sizeof(msg)) { 1718 ret = -EINVAL; 1719 goto done; 1720 } 1721 1722 if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) { 1723 ret = -EINVAL; 1724 goto done; 1725 } 1726 1727 if (dev->msg_handler) 1728 ret = dev->msg_handler(dev, asid, &msg); 1729 else 1730 ret = vhost_process_iotlb_msg(dev, asid, &msg); 1731 if (ret) { 1732 ret = -EFAULT; 1733 goto done; 1734 } 1735 1736 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) : 1737 sizeof(struct vhost_msg_v2); 1738 done: 1739 return ret; 1740 } 1741 EXPORT_SYMBOL(vhost_chr_write_iter); 1742 1743 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev, 1744 poll_table *wait) 1745 { 1746 __poll_t mask = 0; 1747 1748 poll_wait(file, &dev->wait, wait); 1749 1750 if (!list_empty(&dev->read_list)) 1751 mask |= EPOLLIN | EPOLLRDNORM; 1752 1753 return mask; 1754 } 1755 EXPORT_SYMBOL(vhost_chr_poll); 1756 1757 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to, 1758 int noblock) 1759 { 1760 DEFINE_WAIT(wait); 1761 struct vhost_msg_node *node; 1762 ssize_t ret = 0; 1763 unsigned size = sizeof(struct vhost_msg); 1764 1765 if (iov_iter_count(to) < size) 1766 return 0; 1767 1768 while (1) { 1769 if (!noblock) 1770 prepare_to_wait(&dev->wait, &wait, 1771 TASK_INTERRUPTIBLE); 1772 1773 node = vhost_dequeue_msg(dev, &dev->read_list); 1774 if (node) 1775 break; 1776 if (noblock) { 1777 ret = -EAGAIN; 1778 break; 1779 } 1780 if (signal_pending(current)) { 1781 ret = -ERESTARTSYS; 1782 break; 1783 } 1784 if (!dev->iotlb) { 1785 ret = -EBADFD; 1786 break; 1787 } 1788 1789 schedule(); 1790 } 1791 1792 if (!noblock) 1793 finish_wait(&dev->wait, &wait); 1794 1795 if (node) { 1796 struct vhost_iotlb_msg *msg; 1797 void *start = &node->msg; 1798 1799 switch (node->msg.type) { 1800 case VHOST_IOTLB_MSG: 1801 size = sizeof(node->msg); 1802 msg = &node->msg.iotlb; 1803 break; 1804 case VHOST_IOTLB_MSG_V2: 1805 size = sizeof(node->msg_v2); 1806 msg = &node->msg_v2.iotlb; 1807 break; 1808 default: 1809 BUG(); 1810 break; 1811 } 1812 1813 ret = copy_to_iter(start, size, to); 1814 if (ret != size || msg->type != VHOST_IOTLB_MISS) { 1815 kfree(node); 1816 return ret; 1817 } 1818 vhost_enqueue_msg(dev, &dev->pending_list, node); 1819 } 1820 1821 return ret; 1822 } 1823 EXPORT_SYMBOL_GPL(vhost_chr_read_iter); 1824 1825 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access) 1826 { 1827 struct vhost_dev *dev = vq->dev; 1828 struct vhost_msg_node *node; 1829 struct vhost_iotlb_msg *msg; 1830 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2); 1831 1832 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG); 1833 if (!node) 1834 return -ENOMEM; 1835 1836 if (v2) { 1837 node->msg_v2.type = VHOST_IOTLB_MSG_V2; 1838 msg = &node->msg_v2.iotlb; 1839 } else { 1840 msg = &node->msg.iotlb; 1841 } 1842 1843 msg->type = VHOST_IOTLB_MISS; 1844 msg->iova = iova; 1845 msg->perm = access; 1846 1847 vhost_enqueue_msg(dev, &dev->read_list, node); 1848 1849 return 0; 1850 } 1851 1852 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num, 1853 vring_desc_t __user *desc, 1854 vring_avail_t __user *avail, 1855 vring_used_t __user *used) 1856 1857 { 1858 /* If an IOTLB device is present, the vring addresses are 1859 * GIOVAs. Access validation occurs at prefetch time. */ 1860 if (vq->iotlb) 1861 return true; 1862 1863 return access_ok(desc, vhost_get_desc_size(vq, num)) && 1864 access_ok(avail, vhost_get_avail_size(vq, num)) && 1865 access_ok(used, vhost_get_used_size(vq, num)); 1866 } 1867 1868 static void vhost_vq_meta_update(struct vhost_virtqueue *vq, 1869 const struct vhost_iotlb_map *map, 1870 int type) 1871 { 1872 int access = (type == VHOST_ADDR_USED) ? 1873 VHOST_ACCESS_WO : VHOST_ACCESS_RO; 1874 1875 if (likely(map->perm & access)) 1876 vq->meta_iotlb[type] = map; 1877 } 1878 1879 static bool iotlb_access_ok(struct vhost_virtqueue *vq, 1880 int access, u64 addr, u64 len, int type) 1881 { 1882 const struct vhost_iotlb_map *map; 1883 struct vhost_iotlb *umem = vq->iotlb; 1884 u64 s = 0, size, orig_addr = addr, last = addr + len - 1; 1885 1886 if (vhost_vq_meta_fetch(vq, addr, len, type)) 1887 return true; 1888 1889 while (len > s) { 1890 map = vhost_iotlb_itree_first(umem, addr, last); 1891 if (map == NULL || map->start > addr) { 1892 vhost_iotlb_miss(vq, addr, access); 1893 return false; 1894 } else if (!(map->perm & access)) { 1895 /* Report the possible access violation by 1896 * request another translation from userspace. 1897 */ 1898 return false; 1899 } 1900 1901 size = map->size - addr + map->start; 1902 1903 if (orig_addr == addr && size >= len) 1904 vhost_vq_meta_update(vq, map, type); 1905 1906 s += size; 1907 addr += size; 1908 } 1909 1910 return true; 1911 } 1912 1913 int vq_meta_prefetch(struct vhost_virtqueue *vq) 1914 { 1915 unsigned int num = vq->num; 1916 1917 if (!vq->iotlb) 1918 return 1; 1919 1920 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc, 1921 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) && 1922 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail, 1923 vhost_get_avail_size(vq, num), 1924 VHOST_ADDR_AVAIL) && 1925 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used, 1926 vhost_get_used_size(vq, num), VHOST_ADDR_USED); 1927 } 1928 EXPORT_SYMBOL_GPL(vq_meta_prefetch); 1929 1930 /* Can we log writes? */ 1931 /* Caller should have device mutex but not vq mutex */ 1932 bool vhost_log_access_ok(struct vhost_dev *dev) 1933 { 1934 return memory_access_ok(dev, dev->umem, 1); 1935 } 1936 EXPORT_SYMBOL_GPL(vhost_log_access_ok); 1937 1938 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq, 1939 void __user *log_base, 1940 bool log_used, 1941 u64 log_addr) 1942 { 1943 /* If an IOTLB device is present, log_addr is a GIOVA that 1944 * will never be logged by log_used(). */ 1945 if (vq->iotlb) 1946 return true; 1947 1948 return !log_used || log_access_ok(log_base, log_addr, 1949 vhost_get_used_size(vq, vq->num)); 1950 } 1951 1952 /* Verify access for write logging. */ 1953 /* Caller should have vq mutex and device mutex */ 1954 static bool vq_log_access_ok(struct vhost_virtqueue *vq, 1955 void __user *log_base) 1956 { 1957 return vq_memory_access_ok(log_base, vq->umem, 1958 vhost_has_feature(vq, VHOST_F_LOG_ALL)) && 1959 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr); 1960 } 1961 1962 /* Can we start vq? */ 1963 /* Caller should have vq mutex and device mutex */ 1964 bool vhost_vq_access_ok(struct vhost_virtqueue *vq) 1965 { 1966 if (!vq_log_access_ok(vq, vq->log_base)) 1967 return false; 1968 1969 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used); 1970 } 1971 EXPORT_SYMBOL_GPL(vhost_vq_access_ok); 1972 1973 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m) 1974 { 1975 struct vhost_memory mem, *newmem; 1976 struct vhost_memory_region *region; 1977 struct vhost_iotlb *newumem, *oldumem; 1978 unsigned long size = offsetof(struct vhost_memory, regions); 1979 int i; 1980 1981 if (copy_from_user(&mem, m, size)) 1982 return -EFAULT; 1983 if (mem.padding) 1984 return -EOPNOTSUPP; 1985 if (mem.nregions > max_mem_regions) 1986 return -E2BIG; 1987 if (max_iotlb_entries <= 0) 1988 return -EINVAL; 1989 newmem = kvzalloc_flex(*newmem, regions, mem.nregions); 1990 if (!newmem) 1991 return -ENOMEM; 1992 1993 memcpy(newmem, &mem, size); 1994 if (copy_from_user(newmem->regions, m->regions, 1995 flex_array_size(newmem, regions, mem.nregions))) { 1996 kvfree(newmem); 1997 return -EFAULT; 1998 } 1999 2000 newumem = iotlb_alloc(); 2001 if (!newumem) { 2002 kvfree(newmem); 2003 return -ENOMEM; 2004 } 2005 2006 for (region = newmem->regions; 2007 region < newmem->regions + mem.nregions; 2008 region++) { 2009 if (vhost_iotlb_add_range(newumem, 2010 region->guest_phys_addr, 2011 region->guest_phys_addr + 2012 region->memory_size - 1, 2013 region->userspace_addr, 2014 VHOST_MAP_RW)) 2015 goto err; 2016 } 2017 2018 if (!memory_access_ok(d, newumem, 0)) 2019 goto err; 2020 2021 oldumem = d->umem; 2022 d->umem = newumem; 2023 2024 /* All memory accesses are done under some VQ mutex. */ 2025 for (i = 0; i < d->nvqs; ++i) { 2026 mutex_lock(&d->vqs[i]->mutex); 2027 d->vqs[i]->umem = newumem; 2028 mutex_unlock(&d->vqs[i]->mutex); 2029 } 2030 2031 kvfree(newmem); 2032 vhost_iotlb_free(oldumem); 2033 return 0; 2034 2035 err: 2036 vhost_iotlb_free(newumem); 2037 kvfree(newmem); 2038 return -EFAULT; 2039 } 2040 2041 static long vhost_vring_set_num(struct vhost_dev *d, 2042 struct vhost_virtqueue *vq, 2043 void __user *argp) 2044 { 2045 struct vhost_vring_state s; 2046 2047 /* Resizing ring with an active backend? 2048 * You don't want to do that. */ 2049 if (vq->private_data) 2050 return -EBUSY; 2051 2052 if (copy_from_user(&s, argp, sizeof s)) 2053 return -EFAULT; 2054 2055 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) 2056 return -EINVAL; 2057 vq->num = s.num; 2058 2059 return 0; 2060 } 2061 2062 static long vhost_vring_set_addr(struct vhost_dev *d, 2063 struct vhost_virtqueue *vq, 2064 void __user *argp) 2065 { 2066 struct vhost_vring_addr a; 2067 2068 if (copy_from_user(&a, argp, sizeof a)) 2069 return -EFAULT; 2070 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) 2071 return -EOPNOTSUPP; 2072 2073 /* For 32bit, verify that the top 32bits of the user 2074 data are set to zero. */ 2075 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr || 2076 (u64)(unsigned long)a.used_user_addr != a.used_user_addr || 2077 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) 2078 return -EFAULT; 2079 2080 /* Make sure it's safe to cast pointers to vring types. */ 2081 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE); 2082 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE); 2083 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) || 2084 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) || 2085 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) 2086 return -EINVAL; 2087 2088 /* We only verify access here if backend is configured. 2089 * If it is not, we don't as size might not have been setup. 2090 * We will verify when backend is configured. */ 2091 if (vq->private_data) { 2092 if (!vq_access_ok(vq, vq->num, 2093 (void __user *)(unsigned long)a.desc_user_addr, 2094 (void __user *)(unsigned long)a.avail_user_addr, 2095 (void __user *)(unsigned long)a.used_user_addr)) 2096 return -EINVAL; 2097 2098 /* Also validate log access for used ring if enabled. */ 2099 if (!vq_log_used_access_ok(vq, vq->log_base, 2100 a.flags & (0x1 << VHOST_VRING_F_LOG), 2101 a.log_guest_addr)) 2102 return -EINVAL; 2103 } 2104 2105 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG)); 2106 vq->desc = (void __user *)(unsigned long)a.desc_user_addr; 2107 vq->avail = (void __user *)(unsigned long)a.avail_user_addr; 2108 vq->log_addr = a.log_guest_addr; 2109 vq->used = (void __user *)(unsigned long)a.used_user_addr; 2110 2111 return 0; 2112 } 2113 2114 static long vhost_vring_set_num_addr(struct vhost_dev *d, 2115 struct vhost_virtqueue *vq, 2116 unsigned int ioctl, 2117 void __user *argp) 2118 { 2119 long r; 2120 2121 mutex_lock(&vq->mutex); 2122 2123 switch (ioctl) { 2124 case VHOST_SET_VRING_NUM: 2125 r = vhost_vring_set_num(d, vq, argp); 2126 break; 2127 case VHOST_SET_VRING_ADDR: 2128 r = vhost_vring_set_addr(d, vq, argp); 2129 break; 2130 default: 2131 BUG(); 2132 } 2133 2134 /* 2135 * The metadata cache holds the IOTLB mapping that backed the previous 2136 * desc/avail/used addresses and vring size, both of which are being 2137 * replaced here. iotlb_access_ok() takes a cache hit as proof that the 2138 * region was validated, so the stale entries have to go. 2139 */ 2140 __vhost_vq_meta_reset(vq); 2141 2142 mutex_unlock(&vq->mutex); 2143 2144 return r; 2145 } 2146 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp) 2147 { 2148 struct file *eventfp, *filep = NULL; 2149 bool pollstart = false, pollstop = false; 2150 struct eventfd_ctx *ctx = NULL; 2151 struct vhost_virtqueue *vq; 2152 struct vhost_vring_state s; 2153 struct vhost_vring_file f; 2154 u32 idx; 2155 long r; 2156 2157 r = vhost_get_vq_from_user(d, argp, &vq, &idx); 2158 if (r < 0) 2159 return r; 2160 2161 if (ioctl == VHOST_SET_VRING_NUM || 2162 ioctl == VHOST_SET_VRING_ADDR) { 2163 return vhost_vring_set_num_addr(d, vq, ioctl, argp); 2164 } 2165 2166 mutex_lock(&vq->mutex); 2167 2168 switch (ioctl) { 2169 case VHOST_SET_VRING_BASE: 2170 /* Moving base with an active backend? 2171 * You don't want to do that. */ 2172 if (vq->private_data) { 2173 r = -EBUSY; 2174 break; 2175 } 2176 if (copy_from_user(&s, argp, sizeof s)) { 2177 r = -EFAULT; 2178 break; 2179 } 2180 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) { 2181 vq->next_avail_head = vq->last_avail_idx = 2182 s.num & 0xffff; 2183 vq->last_used_idx = (s.num >> 16) & 0xffff; 2184 } else { 2185 if (s.num > 0xffff) { 2186 r = -EINVAL; 2187 break; 2188 } 2189 vq->next_avail_head = vq->last_avail_idx = s.num; 2190 } 2191 /* Forget the cached index value. */ 2192 vq->avail_idx = vq->last_avail_idx; 2193 break; 2194 case VHOST_GET_VRING_BASE: 2195 s.index = idx; 2196 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) 2197 s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16); 2198 else 2199 s.num = vq->last_avail_idx; 2200 if (copy_to_user(argp, &s, sizeof s)) 2201 r = -EFAULT; 2202 break; 2203 case VHOST_SET_VRING_KICK: 2204 if (copy_from_user(&f, argp, sizeof f)) { 2205 r = -EFAULT; 2206 break; 2207 } 2208 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd); 2209 if (IS_ERR(eventfp)) { 2210 r = PTR_ERR(eventfp); 2211 break; 2212 } 2213 if (eventfp != vq->kick) { 2214 pollstop = (filep = vq->kick) != NULL; 2215 pollstart = (vq->kick = eventfp) != NULL; 2216 } else 2217 filep = eventfp; 2218 break; 2219 case VHOST_SET_VRING_CALL: 2220 if (copy_from_user(&f, argp, sizeof f)) { 2221 r = -EFAULT; 2222 break; 2223 } 2224 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd); 2225 if (IS_ERR(ctx)) { 2226 r = PTR_ERR(ctx); 2227 break; 2228 } 2229 2230 swap(ctx, vq->call_ctx.ctx); 2231 break; 2232 case VHOST_SET_VRING_ERR: 2233 if (copy_from_user(&f, argp, sizeof f)) { 2234 r = -EFAULT; 2235 break; 2236 } 2237 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd); 2238 if (IS_ERR(ctx)) { 2239 r = PTR_ERR(ctx); 2240 break; 2241 } 2242 swap(ctx, vq->error_ctx); 2243 break; 2244 case VHOST_SET_VRING_ENDIAN: 2245 r = vhost_set_vring_endian(vq, argp); 2246 break; 2247 case VHOST_GET_VRING_ENDIAN: 2248 r = vhost_get_vring_endian(vq, idx, argp); 2249 break; 2250 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT: 2251 if (copy_from_user(&s, argp, sizeof(s))) { 2252 r = -EFAULT; 2253 break; 2254 } 2255 vq->busyloop_timeout = s.num; 2256 break; 2257 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT: 2258 s.index = idx; 2259 s.num = vq->busyloop_timeout; 2260 if (copy_to_user(argp, &s, sizeof(s))) 2261 r = -EFAULT; 2262 break; 2263 default: 2264 r = -ENOIOCTLCMD; 2265 } 2266 2267 if (pollstop && vq->handle_kick) 2268 vhost_poll_stop(&vq->poll); 2269 2270 if (!IS_ERR_OR_NULL(ctx)) 2271 eventfd_ctx_put(ctx); 2272 if (filep) 2273 fput(filep); 2274 2275 if (pollstart && vq->handle_kick) 2276 r = vhost_poll_start(&vq->poll, vq->kick); 2277 2278 mutex_unlock(&vq->mutex); 2279 2280 if (pollstop && vq->handle_kick) 2281 vhost_dev_flush(vq->poll.dev); 2282 return r; 2283 } 2284 EXPORT_SYMBOL_GPL(vhost_vring_ioctl); 2285 2286 int vhost_init_device_iotlb(struct vhost_dev *d) 2287 { 2288 struct vhost_iotlb *niotlb, *oiotlb; 2289 int i; 2290 2291 if (max_iotlb_entries <= 0) 2292 return -EINVAL; 2293 2294 niotlb = iotlb_alloc(); 2295 if (!niotlb) 2296 return -ENOMEM; 2297 2298 oiotlb = d->iotlb; 2299 d->iotlb = niotlb; 2300 2301 for (i = 0; i < d->nvqs; ++i) { 2302 struct vhost_virtqueue *vq = d->vqs[i]; 2303 2304 mutex_lock(&vq->mutex); 2305 vq->iotlb = niotlb; 2306 __vhost_vq_meta_reset(vq); 2307 mutex_unlock(&vq->mutex); 2308 } 2309 2310 vhost_iotlb_free(oiotlb); 2311 2312 return 0; 2313 } 2314 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb); 2315 2316 /* Caller must have device mutex */ 2317 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp) 2318 { 2319 struct eventfd_ctx *ctx; 2320 u64 p; 2321 long r; 2322 int i, fd; 2323 2324 /* If you are not the owner, you can become one */ 2325 if (ioctl == VHOST_SET_OWNER) { 2326 r = vhost_dev_set_owner(d); 2327 goto done; 2328 } 2329 2330 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL 2331 if (ioctl == VHOST_SET_FORK_FROM_OWNER) { 2332 /* Only allow modification before owner is set */ 2333 if (vhost_dev_has_owner(d)) { 2334 r = -EBUSY; 2335 goto done; 2336 } 2337 u8 fork_owner_val; 2338 2339 if (get_user(fork_owner_val, (u8 __user *)argp)) { 2340 r = -EFAULT; 2341 goto done; 2342 } 2343 if (fork_owner_val != VHOST_FORK_OWNER_TASK && 2344 fork_owner_val != VHOST_FORK_OWNER_KTHREAD) { 2345 r = -EINVAL; 2346 goto done; 2347 } 2348 d->fork_owner = !!fork_owner_val; 2349 r = 0; 2350 goto done; 2351 } 2352 if (ioctl == VHOST_GET_FORK_FROM_OWNER) { 2353 u8 fork_owner_val = d->fork_owner; 2354 2355 if (fork_owner_val != VHOST_FORK_OWNER_TASK && 2356 fork_owner_val != VHOST_FORK_OWNER_KTHREAD) { 2357 r = -EINVAL; 2358 goto done; 2359 } 2360 if (put_user(fork_owner_val, (u8 __user *)argp)) { 2361 r = -EFAULT; 2362 goto done; 2363 } 2364 r = 0; 2365 goto done; 2366 } 2367 #endif 2368 2369 /* You must be the owner to do anything else */ 2370 r = vhost_dev_check_owner(d); 2371 if (r) 2372 goto done; 2373 2374 switch (ioctl) { 2375 case VHOST_SET_MEM_TABLE: 2376 r = vhost_set_memory(d, argp); 2377 break; 2378 case VHOST_SET_LOG_BASE: 2379 if (copy_from_user(&p, argp, sizeof p)) { 2380 r = -EFAULT; 2381 break; 2382 } 2383 if ((u64)(unsigned long)p != p) { 2384 r = -EFAULT; 2385 break; 2386 } 2387 for (i = 0; i < d->nvqs; ++i) { 2388 struct vhost_virtqueue *vq; 2389 void __user *base = (void __user *)(unsigned long)p; 2390 vq = d->vqs[i]; 2391 mutex_lock(&vq->mutex); 2392 /* If ring is inactive, will check when it's enabled. */ 2393 if (vq->private_data && !vq_log_access_ok(vq, base)) 2394 r = -EFAULT; 2395 else 2396 vq->log_base = base; 2397 mutex_unlock(&vq->mutex); 2398 } 2399 break; 2400 case VHOST_SET_LOG_FD: 2401 r = get_user(fd, (int __user *)argp); 2402 if (r < 0) 2403 break; 2404 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd); 2405 if (IS_ERR(ctx)) { 2406 r = PTR_ERR(ctx); 2407 break; 2408 } 2409 swap(ctx, d->log_ctx); 2410 for (i = 0; i < d->nvqs; ++i) { 2411 mutex_lock(&d->vqs[i]->mutex); 2412 d->vqs[i]->log_ctx = d->log_ctx; 2413 mutex_unlock(&d->vqs[i]->mutex); 2414 } 2415 if (ctx) 2416 eventfd_ctx_put(ctx); 2417 break; 2418 default: 2419 r = -ENOIOCTLCMD; 2420 break; 2421 } 2422 done: 2423 return r; 2424 } 2425 EXPORT_SYMBOL_GPL(vhost_dev_ioctl); 2426 2427 /* TODO: This is really inefficient. We need something like get_user() 2428 * (instruction directly accesses the data, with an exception table entry 2429 * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst. 2430 */ 2431 static int set_bit_to_user(int nr, void __user *addr) 2432 { 2433 unsigned long log = (unsigned long)addr; 2434 struct page *page; 2435 void *base; 2436 int bit = nr + (log % PAGE_SIZE) * 8; 2437 int r; 2438 2439 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page); 2440 if (r < 0) 2441 return r; 2442 BUG_ON(r != 1); 2443 base = kmap_atomic(page); 2444 set_bit(bit, base); 2445 kunmap_atomic(base); 2446 unpin_user_pages_dirty_lock(&page, 1, true); 2447 return 0; 2448 } 2449 2450 static int log_write(void __user *log_base, 2451 u64 write_address, u64 write_length) 2452 { 2453 u64 write_page = write_address / VHOST_PAGE_SIZE; 2454 int r; 2455 2456 if (!write_length) 2457 return 0; 2458 write_length += write_address % VHOST_PAGE_SIZE; 2459 for (;;) { 2460 u64 base = (u64)(unsigned long)log_base; 2461 u64 log = base + write_page / 8; 2462 int bit = write_page % 8; 2463 if ((u64)(unsigned long)log != log) 2464 return -EFAULT; 2465 r = set_bit_to_user(bit, (void __user *)(unsigned long)log); 2466 if (r < 0) 2467 return r; 2468 if (write_length <= VHOST_PAGE_SIZE) 2469 break; 2470 write_length -= VHOST_PAGE_SIZE; 2471 write_page += 1; 2472 } 2473 return r; 2474 } 2475 2476 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len) 2477 { 2478 struct vhost_iotlb *umem = vq->umem; 2479 struct vhost_iotlb_map *u; 2480 u64 start, end, l, min; 2481 int r; 2482 bool hit = false; 2483 2484 while (len) { 2485 min = len; 2486 /* More than one GPAs can be mapped into a single HVA. So 2487 * iterate all possible umems here to be safe. 2488 */ 2489 list_for_each_entry(u, &umem->list, link) { 2490 if (u->addr > hva - 1 + len || 2491 u->addr - 1 + u->size < hva) 2492 continue; 2493 start = max(u->addr, hva); 2494 end = min(u->addr - 1 + u->size, hva - 1 + len); 2495 l = end - start + 1; 2496 r = log_write(vq->log_base, 2497 u->start + start - u->addr, 2498 l); 2499 if (r < 0) 2500 return r; 2501 hit = true; 2502 min = min(l, min); 2503 } 2504 2505 if (!hit) 2506 return -EFAULT; 2507 2508 len -= min; 2509 hva += min; 2510 } 2511 2512 return 0; 2513 } 2514 2515 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len) 2516 { 2517 struct iovec *iov = vq->log_iov; 2518 int i, ret; 2519 2520 if (!vq->iotlb) 2521 return log_write(vq->log_base, vq->log_addr + used_offset, len); 2522 2523 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset, 2524 len, iov, 64, VHOST_ACCESS_WO); 2525 if (ret < 0) 2526 return ret; 2527 2528 for (i = 0; i < ret; i++) { 2529 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base, 2530 iov[i].iov_len); 2531 if (ret) 2532 return ret; 2533 } 2534 2535 return 0; 2536 } 2537 2538 /* 2539 * vhost_log_write() - Log in dirty page bitmap 2540 * @vq: vhost virtqueue. 2541 * @log: Array of dirty memory in GPA. 2542 * @log_num: Size of vhost_log arrary. 2543 * @len: The total length of memory buffer to log in the dirty bitmap. 2544 * Some drivers may only partially use pages shared via the last 2545 * vring descriptor (i.e. vhost-net RX buffer). 2546 * Use (len == U64_MAX) to indicate the driver would log all 2547 * pages of vring descriptors. 2548 * @iov: Array of dirty memory in HVA. 2549 * @count: Size of iovec array. 2550 */ 2551 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log, 2552 unsigned int log_num, u64 len, struct iovec *iov, int count) 2553 { 2554 int i, r; 2555 2556 /* Make sure data written is seen before log. */ 2557 smp_wmb(); 2558 2559 if (vq->iotlb) { 2560 for (i = 0; i < count; i++) { 2561 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base, 2562 iov[i].iov_len); 2563 if (r < 0) 2564 return r; 2565 } 2566 return 0; 2567 } 2568 2569 for (i = 0; i < log_num; ++i) { 2570 u64 l = min(log[i].len, len); 2571 r = log_write(vq->log_base, log[i].addr, l); 2572 if (r < 0) 2573 return r; 2574 2575 if (len != U64_MAX) 2576 len -= l; 2577 } 2578 2579 if (vq->log_ctx) 2580 eventfd_signal(vq->log_ctx); 2581 2582 return 0; 2583 } 2584 EXPORT_SYMBOL_GPL(vhost_log_write); 2585 2586 static int vhost_update_used_flags(struct vhost_virtqueue *vq) 2587 { 2588 void __user *used; 2589 if (vhost_put_used_flags(vq)) 2590 return -EFAULT; 2591 if (unlikely(vq->log_used)) { 2592 /* Make sure the flag is seen before log. */ 2593 smp_wmb(); 2594 /* Log used flag write. */ 2595 used = &vq->used->flags; 2596 log_used(vq, (used - (void __user *)vq->used), 2597 sizeof vq->used->flags); 2598 if (vq->log_ctx) 2599 eventfd_signal(vq->log_ctx); 2600 } 2601 return 0; 2602 } 2603 2604 static int vhost_update_avail_event(struct vhost_virtqueue *vq) 2605 { 2606 if (vhost_put_avail_event(vq)) 2607 return -EFAULT; 2608 if (unlikely(vq->log_used)) { 2609 void __user *used; 2610 /* Make sure the event is seen before log. */ 2611 smp_wmb(); 2612 /* Log avail event write */ 2613 used = vhost_avail_event(vq); 2614 log_used(vq, (used - (void __user *)vq->used), 2615 sizeof *vhost_avail_event(vq)); 2616 if (vq->log_ctx) 2617 eventfd_signal(vq->log_ctx); 2618 } 2619 return 0; 2620 } 2621 2622 int vhost_vq_init_access(struct vhost_virtqueue *vq) 2623 { 2624 __virtio16 last_used_idx; 2625 int r; 2626 bool is_le = vq->is_le; 2627 2628 if (!vq->private_data) 2629 return 0; 2630 2631 vhost_init_is_le(vq); 2632 2633 r = vhost_update_used_flags(vq); 2634 if (r) 2635 goto err; 2636 vq->signalled_used_valid = false; 2637 if (!vq->iotlb && 2638 !access_ok(&vq->used->idx, sizeof vq->used->idx)) { 2639 r = -EFAULT; 2640 goto err; 2641 } 2642 r = vhost_get_used_idx(vq, &last_used_idx); 2643 if (r) { 2644 vq_err(vq, "Can't access used idx at %p\n", 2645 &vq->used->idx); 2646 goto err; 2647 } 2648 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx); 2649 return 0; 2650 2651 err: 2652 vq->is_le = is_le; 2653 return r; 2654 } 2655 EXPORT_SYMBOL_GPL(vhost_vq_init_access); 2656 2657 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len, 2658 struct iovec iov[], int iov_size, int access) 2659 { 2660 const struct vhost_iotlb_map *map; 2661 struct vhost_dev *dev = vq->dev; 2662 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem; 2663 struct iovec *_iov; 2664 u64 s = 0, last = addr + len - 1; 2665 int ret = 0; 2666 2667 while ((u64)len > s) { 2668 u64 size; 2669 if (unlikely(ret >= iov_size)) { 2670 ret = -ENOBUFS; 2671 break; 2672 } 2673 2674 map = vhost_iotlb_itree_first(umem, addr, last); 2675 if (map == NULL || map->start > addr) { 2676 if (umem != dev->iotlb) { 2677 ret = -EFAULT; 2678 break; 2679 } 2680 ret = -EAGAIN; 2681 break; 2682 } else if (!(map->perm & access)) { 2683 ret = -EPERM; 2684 break; 2685 } 2686 2687 _iov = iov + ret; 2688 size = map->size - addr + map->start; 2689 _iov->iov_len = min((u64)len - s, size); 2690 _iov->iov_base = (void __user *)(unsigned long) 2691 (map->addr + addr - map->start); 2692 s += size; 2693 addr += size; 2694 ++ret; 2695 } 2696 2697 if (ret == -EAGAIN) 2698 vhost_iotlb_miss(vq, addr, access); 2699 return ret; 2700 } 2701 2702 /* Each buffer in the virtqueues is actually a chain of descriptors. This 2703 * function returns the next descriptor in the chain, 2704 * or -1U if we're at the end. */ 2705 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc) 2706 { 2707 unsigned int next; 2708 2709 /* If this descriptor says it doesn't chain, we're done. */ 2710 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT))) 2711 return -1U; 2712 2713 /* Check they're not leading us off end of descriptors. */ 2714 next = vhost16_to_cpu(vq, READ_ONCE(desc->next)); 2715 return next; 2716 } 2717 2718 static int get_indirect(struct vhost_virtqueue *vq, 2719 struct iovec iov[], unsigned int iov_size, 2720 unsigned int *out_num, unsigned int *in_num, 2721 struct vhost_log *log, unsigned int *log_num, 2722 struct vring_desc *indirect) 2723 { 2724 struct vring_desc desc; 2725 unsigned int i = 0, count, found = 0; 2726 u32 len = vhost32_to_cpu(vq, indirect->len); 2727 struct iov_iter from; 2728 int ret, access; 2729 2730 /* Sanity check */ 2731 if (unlikely(len % sizeof desc)) { 2732 vq_err(vq, "Invalid length in indirect descriptor: " 2733 "len 0x%llx not multiple of 0x%zx\n", 2734 (unsigned long long)len, 2735 sizeof desc); 2736 return -EINVAL; 2737 } 2738 2739 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect, 2740 UIO_MAXIOV, VHOST_ACCESS_RO); 2741 if (unlikely(ret < 0)) { 2742 if (ret != -EAGAIN) 2743 vq_err(vq, "Translation failure %d in indirect.\n", ret); 2744 return ret; 2745 } 2746 iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len); 2747 count = len / sizeof desc; 2748 /* Buffers are chained via a 16 bit next field, so 2749 * we can have at most 2^16 of these. */ 2750 if (unlikely(count > USHRT_MAX + 1)) { 2751 vq_err(vq, "Indirect buffer length too big: %d\n", 2752 indirect->len); 2753 return -E2BIG; 2754 } 2755 2756 do { 2757 unsigned iov_count = *in_num + *out_num; 2758 if (unlikely(++found > count)) { 2759 vq_err(vq, "Loop detected: last one at %u " 2760 "indirect size %u\n", 2761 i, count); 2762 return -EINVAL; 2763 } 2764 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) { 2765 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n", 2766 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc); 2767 return -EINVAL; 2768 } 2769 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) { 2770 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n", 2771 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc); 2772 return -EINVAL; 2773 } 2774 2775 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) 2776 access = VHOST_ACCESS_WO; 2777 else 2778 access = VHOST_ACCESS_RO; 2779 2780 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr), 2781 vhost32_to_cpu(vq, desc.len), iov + iov_count, 2782 iov_size - iov_count, access); 2783 if (unlikely(ret < 0)) { 2784 if (ret != -EAGAIN) 2785 vq_err(vq, "Translation failure %d indirect idx %d\n", 2786 ret, i); 2787 return ret; 2788 } 2789 /* If this is an input descriptor, increment that count. */ 2790 if (access == VHOST_ACCESS_WO) { 2791 *in_num += ret; 2792 if (unlikely(log && ret)) { 2793 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr); 2794 log[*log_num].len = vhost32_to_cpu(vq, desc.len); 2795 ++*log_num; 2796 } 2797 } else { 2798 /* If it's an output descriptor, they're all supposed 2799 * to come before any input descriptors. */ 2800 if (unlikely(*in_num)) { 2801 vq_err(vq, "Indirect descriptor " 2802 "has out after in: idx %d\n", i); 2803 return -EINVAL; 2804 } 2805 *out_num += ret; 2806 } 2807 } while ((i = next_desc(vq, &desc)) != -1); 2808 return 0; 2809 } 2810 2811 /** 2812 * vhost_get_vq_desc_n - Fetch the next available descriptor chain and build iovecs 2813 * @vq: target virtqueue 2814 * @iov: array that receives the scatter/gather segments 2815 * @iov_size: capacity of @iov in elements 2816 * @out_num: the number of output segments 2817 * @in_num: the number of input segments 2818 * @log: optional array to record addr/len for each writable segment; NULL if unused 2819 * @log_num: optional output; number of entries written to @log when provided 2820 * @ndesc: optional output; number of descriptors consumed from the available ring 2821 * (useful for rollback via vhost_discard_vq_desc) 2822 * 2823 * Extracts one available descriptor chain from @vq and translates guest addresses 2824 * into host iovecs. 2825 * 2826 * On success, advances @vq->last_avail_idx by 1 and @vq->next_avail_head by the 2827 * number of descriptors consumed (also stored via @ndesc when non-NULL). 2828 * 2829 * Return: 2830 * - head index in [0, @vq->num) on success; 2831 * - @vq->num if no descriptor is currently available; 2832 * - negative errno on failure 2833 */ 2834 int vhost_get_vq_desc_n(struct vhost_virtqueue *vq, 2835 struct iovec iov[], unsigned int iov_size, 2836 unsigned int *out_num, unsigned int *in_num, 2837 struct vhost_log *log, unsigned int *log_num, 2838 unsigned int *ndesc) 2839 { 2840 bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER); 2841 struct vring_desc desc; 2842 unsigned int i, head, found = 0; 2843 u16 last_avail_idx = vq->last_avail_idx; 2844 __virtio16 ring_head; 2845 int ret, access, c = 0; 2846 2847 if (vq->avail_idx == vq->last_avail_idx) { 2848 ret = vhost_get_avail_idx(vq); 2849 if (unlikely(ret < 0)) 2850 return ret; 2851 2852 if (!ret) 2853 return vq->num; 2854 } 2855 2856 if (in_order) 2857 head = vq->next_avail_head & (vq->num - 1); 2858 else { 2859 /* Grab the next descriptor number they're 2860 * advertising, and increment the index we've seen. */ 2861 if (unlikely(vhost_get_avail_head(vq, &ring_head, 2862 last_avail_idx))) { 2863 vq_err(vq, "Failed to read head: idx %d address %p\n", 2864 last_avail_idx, 2865 &vq->avail->ring[last_avail_idx % vq->num]); 2866 return -EFAULT; 2867 } 2868 head = vhost16_to_cpu(vq, ring_head); 2869 } 2870 2871 /* If their number is silly, that's an error. */ 2872 if (unlikely(head >= vq->num)) { 2873 vq_err(vq, "Guest says index %u > %u is available", 2874 head, vq->num); 2875 return -EINVAL; 2876 } 2877 2878 /* When we start there are none of either input nor output. */ 2879 *out_num = *in_num = 0; 2880 if (unlikely(log)) 2881 *log_num = 0; 2882 2883 i = head; 2884 do { 2885 unsigned iov_count = *in_num + *out_num; 2886 if (unlikely(i >= vq->num)) { 2887 vq_err(vq, "Desc index is %u > %u, head = %u", 2888 i, vq->num, head); 2889 return -EINVAL; 2890 } 2891 if (unlikely(++found > vq->num)) { 2892 vq_err(vq, "Loop detected: last one at %u " 2893 "vq size %u head %u\n", 2894 i, vq->num, head); 2895 return -EINVAL; 2896 } 2897 ret = vhost_get_desc(vq, &desc, i); 2898 if (unlikely(ret)) { 2899 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n", 2900 i, vq->desc + i); 2901 return -EFAULT; 2902 } 2903 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) { 2904 ret = get_indirect(vq, iov, iov_size, 2905 out_num, in_num, 2906 log, log_num, &desc); 2907 if (unlikely(ret < 0)) { 2908 if (ret != -EAGAIN) 2909 vq_err(vq, "Failure detected " 2910 "in indirect descriptor at idx %d\n", i); 2911 return ret; 2912 } 2913 ++c; 2914 continue; 2915 } 2916 2917 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) 2918 access = VHOST_ACCESS_WO; 2919 else 2920 access = VHOST_ACCESS_RO; 2921 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr), 2922 vhost32_to_cpu(vq, desc.len), iov + iov_count, 2923 iov_size - iov_count, access); 2924 if (unlikely(ret < 0)) { 2925 if (ret != -EAGAIN) 2926 vq_err(vq, "Translation failure %d descriptor idx %d\n", 2927 ret, i); 2928 return ret; 2929 } 2930 if (access == VHOST_ACCESS_WO) { 2931 /* If this is an input descriptor, 2932 * increment that count. */ 2933 *in_num += ret; 2934 if (unlikely(log && ret)) { 2935 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr); 2936 log[*log_num].len = vhost32_to_cpu(vq, desc.len); 2937 ++*log_num; 2938 } 2939 } else { 2940 /* If it's an output descriptor, they're all supposed 2941 * to come before any input descriptors. */ 2942 if (unlikely(*in_num)) { 2943 vq_err(vq, "Descriptor has out after in: " 2944 "idx %d\n", i); 2945 return -EINVAL; 2946 } 2947 *out_num += ret; 2948 } 2949 ++c; 2950 } while ((i = next_desc(vq, &desc)) != -1); 2951 2952 /* On success, increment avail index. */ 2953 vq->last_avail_idx++; 2954 vq->next_avail_head += c; 2955 2956 if (ndesc) 2957 *ndesc = c; 2958 2959 /* Assume notifications from guest are disabled at this point, 2960 * if they aren't we would need to update avail_event index. */ 2961 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY)); 2962 return head; 2963 } 2964 EXPORT_SYMBOL_GPL(vhost_get_vq_desc_n); 2965 2966 /* This looks in the virtqueue and for the first available buffer, and converts 2967 * it to an iovec for convenient access. Since descriptors consist of some 2968 * number of output then some number of input descriptors, it's actually two 2969 * iovecs, but we pack them into one and note how many of each there were. 2970 * 2971 * This function returns the descriptor number found, or vq->num (which is 2972 * never a valid descriptor number) if none was found. A negative code is 2973 * returned on error. 2974 */ 2975 int vhost_get_vq_desc(struct vhost_virtqueue *vq, 2976 struct iovec iov[], unsigned int iov_size, 2977 unsigned int *out_num, unsigned int *in_num, 2978 struct vhost_log *log, unsigned int *log_num) 2979 { 2980 return vhost_get_vq_desc_n(vq, iov, iov_size, out_num, in_num, 2981 log, log_num, NULL); 2982 } 2983 EXPORT_SYMBOL_GPL(vhost_get_vq_desc); 2984 2985 /** 2986 * vhost_discard_vq_desc - Reverse the effect of vhost_get_vq_desc_n() 2987 * @vq: target virtqueue 2988 * @nbufs: number of buffers to roll back 2989 * @ndesc: number of descriptors to roll back 2990 * 2991 * Rewinds the internal consumer cursors after a failed attempt to use buffers 2992 * returned by vhost_get_vq_desc_n(). 2993 */ 2994 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int nbufs, 2995 unsigned int ndesc) 2996 { 2997 vq->next_avail_head -= ndesc; 2998 vq->last_avail_idx -= nbufs; 2999 } 3000 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc); 3001 3002 /* After we've used one of their buffers, we tell them about it. We'll then 3003 * want to notify the guest, using eventfd. */ 3004 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len) 3005 { 3006 struct vring_used_elem heads = { 3007 cpu_to_vhost32(vq, head), 3008 cpu_to_vhost32(vq, len) 3009 }; 3010 u16 nheads = 1; 3011 3012 return vhost_add_used_n(vq, &heads, &nheads, 1); 3013 } 3014 EXPORT_SYMBOL_GPL(vhost_add_used); 3015 3016 static int __vhost_add_used_n(struct vhost_virtqueue *vq, 3017 struct vring_used_elem *heads, 3018 unsigned count) 3019 { 3020 vring_used_elem_t __user *used; 3021 u16 old, new; 3022 int start; 3023 3024 start = vq->last_used_idx & (vq->num - 1); 3025 used = vq->used->ring + start; 3026 if (vhost_put_used(vq, heads, start, count)) { 3027 vq_err(vq, "Failed to write used"); 3028 return -EFAULT; 3029 } 3030 if (unlikely(vq->log_used)) { 3031 /* Make sure data is seen before log. */ 3032 smp_wmb(); 3033 /* Log used ring entry write. */ 3034 log_used(vq, ((void __user *)used - (void __user *)vq->used), 3035 count * sizeof *used); 3036 } 3037 old = vq->last_used_idx; 3038 new = (vq->last_used_idx += count); 3039 /* If the driver never bothers to signal in a very long while, 3040 * used index might wrap around. If that happens, invalidate 3041 * signalled_used index we stored. TODO: make sure driver 3042 * signals at least once in 2^16 and remove this. */ 3043 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old))) 3044 vq->signalled_used_valid = false; 3045 return 0; 3046 } 3047 3048 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq, 3049 struct vring_used_elem *heads, 3050 unsigned count) 3051 { 3052 int start, n, r; 3053 3054 start = vq->last_used_idx & (vq->num - 1); 3055 n = vq->num - start; 3056 if (n < count) { 3057 r = __vhost_add_used_n(vq, heads, n); 3058 if (r < 0) 3059 return r; 3060 heads += n; 3061 count -= n; 3062 } 3063 return __vhost_add_used_n(vq, heads, count); 3064 } 3065 3066 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, 3067 struct vring_used_elem *heads, 3068 const u16 *nheads, 3069 unsigned count) 3070 { 3071 vring_used_elem_t __user *used; 3072 u16 old, new = vq->last_used_idx; 3073 int start, i; 3074 3075 if (!nheads) 3076 return -EINVAL; 3077 3078 start = vq->last_used_idx & (vq->num - 1); 3079 used = vq->used->ring + start; 3080 3081 for (i = 0; i < count; i++) { 3082 if (vhost_put_used(vq, &heads[i], start, 1)) { 3083 vq_err(vq, "Failed to write used"); 3084 return -EFAULT; 3085 } 3086 start += nheads[i]; 3087 new += nheads[i]; 3088 if (start >= vq->num) 3089 start -= vq->num; 3090 } 3091 3092 if (unlikely(vq->log_used)) { 3093 /* Make sure data is seen before log. */ 3094 smp_wmb(); 3095 /* Log used ring entry write. */ 3096 log_used(vq, ((void __user *)used - (void __user *)vq->used), 3097 (vq->num - start) * sizeof *used); 3098 if (start + count > vq->num) 3099 log_used(vq, 0, 3100 (start + count - vq->num) * sizeof *used); 3101 } 3102 3103 old = vq->last_used_idx; 3104 vq->last_used_idx = new; 3105 /* If the driver never bothers to signal in a very long while, 3106 * used index might wrap around. If that happens, invalidate 3107 * signalled_used index we stored. TODO: make sure driver 3108 * signals at least once in 2^16 and remove this. */ 3109 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old))) 3110 vq->signalled_used_valid = false; 3111 return 0; 3112 } 3113 3114 /* After we've used one of their buffers, we tell them about it. We'll then 3115 * want to notify the guest, using eventfd. */ 3116 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads, 3117 u16 *nheads, unsigned count) 3118 { 3119 bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER); 3120 int r; 3121 3122 if (!in_order || !nheads) 3123 r = vhost_add_used_n_ooo(vq, heads, count); 3124 else 3125 r = vhost_add_used_n_in_order(vq, heads, nheads, count); 3126 3127 if (r < 0) 3128 return r; 3129 3130 /* Make sure buffer is written before we update index. */ 3131 smp_wmb(); 3132 if (vhost_put_used_idx(vq)) { 3133 vq_err(vq, "Failed to increment used idx"); 3134 return -EFAULT; 3135 } 3136 if (unlikely(vq->log_used)) { 3137 /* Make sure used idx is seen before log. */ 3138 smp_wmb(); 3139 /* Log used index update. */ 3140 log_used(vq, offsetof(struct vring_used, idx), 3141 sizeof vq->used->idx); 3142 if (vq->log_ctx) 3143 eventfd_signal(vq->log_ctx); 3144 } 3145 return r; 3146 } 3147 EXPORT_SYMBOL_GPL(vhost_add_used_n); 3148 3149 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3150 { 3151 __u16 old, new; 3152 __virtio16 event; 3153 bool v; 3154 /* Flush out used index updates. This is paired 3155 * with the barrier that the Guest executes when enabling 3156 * interrupts. */ 3157 smp_mb(); 3158 3159 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) && 3160 unlikely(vq->avail_idx == vq->last_avail_idx)) 3161 return true; 3162 3163 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3164 __virtio16 flags; 3165 if (vhost_get_avail_flags(vq, &flags)) { 3166 vq_err(vq, "Failed to get flags"); 3167 return true; 3168 } 3169 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT)); 3170 } 3171 old = vq->signalled_used; 3172 v = vq->signalled_used_valid; 3173 new = vq->signalled_used = vq->last_used_idx; 3174 vq->signalled_used_valid = true; 3175 3176 if (unlikely(!v)) 3177 return true; 3178 3179 if (vhost_get_used_event(vq, &event)) { 3180 vq_err(vq, "Failed to get used event idx"); 3181 return true; 3182 } 3183 return vring_need_event(vhost16_to_cpu(vq, event), new, old); 3184 } 3185 3186 /* This actually signals the guest, using eventfd. */ 3187 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3188 { 3189 /* Signal the Guest tell them we used something up. */ 3190 if (vq->call_ctx.ctx && vhost_notify(dev, vq)) 3191 eventfd_signal(vq->call_ctx.ctx); 3192 } 3193 EXPORT_SYMBOL_GPL(vhost_signal); 3194 3195 /* And here's the combo meal deal. Supersize me! */ 3196 void vhost_add_used_and_signal(struct vhost_dev *dev, 3197 struct vhost_virtqueue *vq, 3198 unsigned int head, int len) 3199 { 3200 vhost_add_used(vq, head, len); 3201 vhost_signal(dev, vq); 3202 } 3203 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal); 3204 3205 /* multi-buffer version of vhost_add_used_and_signal */ 3206 void vhost_add_used_and_signal_n(struct vhost_dev *dev, 3207 struct vhost_virtqueue *vq, 3208 struct vring_used_elem *heads, 3209 u16 *nheads, 3210 unsigned count) 3211 { 3212 vhost_add_used_n(vq, heads, nheads, count); 3213 vhost_signal(dev, vq); 3214 } 3215 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n); 3216 3217 /* return true if we're sure that available ring is empty */ 3218 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3219 { 3220 int r; 3221 3222 if (vq->avail_idx != vq->last_avail_idx) 3223 return false; 3224 3225 r = vhost_get_avail_idx(vq); 3226 3227 /* Note: we treat error as non-empty here */ 3228 return r == 0; 3229 } 3230 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty); 3231 3232 /* OK, now we need to know about added descriptors. */ 3233 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3234 { 3235 int r; 3236 3237 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY)) 3238 return false; 3239 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY; 3240 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3241 r = vhost_update_used_flags(vq); 3242 if (r) { 3243 vq_err(vq, "Failed to enable notification at %p: %d\n", 3244 &vq->used->flags, r); 3245 return false; 3246 } 3247 } else { 3248 r = vhost_update_avail_event(vq); 3249 if (r) { 3250 vq_err(vq, "Failed to update avail event index at %p: %d\n", 3251 vhost_avail_event(vq), r); 3252 return false; 3253 } 3254 } 3255 /* They could have slipped one in as we were doing that: make 3256 * sure it's written, then check again. */ 3257 smp_mb(); 3258 3259 r = vhost_get_avail_idx(vq); 3260 /* Note: we treat error as empty here */ 3261 if (unlikely(r < 0)) 3262 return false; 3263 3264 return r; 3265 } 3266 EXPORT_SYMBOL_GPL(vhost_enable_notify); 3267 3268 /* We don't need to be notified again. */ 3269 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3270 { 3271 int r; 3272 3273 if (vq->used_flags & VRING_USED_F_NO_NOTIFY) 3274 return; 3275 vq->used_flags |= VRING_USED_F_NO_NOTIFY; 3276 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3277 r = vhost_update_used_flags(vq); 3278 if (r) 3279 vq_err(vq, "Failed to disable notification at %p: %d\n", 3280 &vq->used->flags, r); 3281 } 3282 } 3283 EXPORT_SYMBOL_GPL(vhost_disable_notify); 3284 3285 /* Create a new message. */ 3286 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type) 3287 { 3288 /* Make sure all padding within the structure is initialized. */ 3289 struct vhost_msg_node *node = kzalloc_obj(*node); 3290 if (!node) 3291 return NULL; 3292 3293 node->vq = vq; 3294 node->msg.type = type; 3295 return node; 3296 } 3297 EXPORT_SYMBOL_GPL(vhost_new_msg); 3298 3299 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head, 3300 struct vhost_msg_node *node) 3301 { 3302 spin_lock(&dev->iotlb_lock); 3303 list_add_tail(&node->node, head); 3304 spin_unlock(&dev->iotlb_lock); 3305 3306 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM); 3307 } 3308 EXPORT_SYMBOL_GPL(vhost_enqueue_msg); 3309 3310 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev, 3311 struct list_head *head) 3312 { 3313 struct vhost_msg_node *node = NULL; 3314 3315 spin_lock(&dev->iotlb_lock); 3316 if (!list_empty(head)) { 3317 node = list_first_entry(head, struct vhost_msg_node, 3318 node); 3319 list_del(&node->node); 3320 } 3321 spin_unlock(&dev->iotlb_lock); 3322 3323 return node; 3324 } 3325 EXPORT_SYMBOL_GPL(vhost_dequeue_msg); 3326 3327 void vhost_set_backend_features(struct vhost_dev *dev, u64 features) 3328 { 3329 struct vhost_virtqueue *vq; 3330 int i; 3331 3332 mutex_lock(&dev->mutex); 3333 for (i = 0; i < dev->nvqs; ++i) { 3334 vq = dev->vqs[i]; 3335 mutex_lock(&vq->mutex); 3336 vq->acked_backend_features = features; 3337 mutex_unlock(&vq->mutex); 3338 } 3339 mutex_unlock(&dev->mutex); 3340 } 3341 EXPORT_SYMBOL_GPL(vhost_set_backend_features); 3342 3343 MODULE_VERSION("0.0.1"); 3344 MODULE_LICENSE("GPL v2"); 3345 MODULE_AUTHOR("Michael S. Tsirkin"); 3346 MODULE_DESCRIPTION("Host kernel accelerator for virtio"); 3347