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 return vhost_iotlb_alloc(max_iotlb_entries, 1141 VHOST_IOTLB_FLAG_RETIRE); 1142 } 1143 1144 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void) 1145 { 1146 return iotlb_alloc(); 1147 } 1148 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare); 1149 1150 /* Caller should have device mutex */ 1151 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem) 1152 { 1153 int i; 1154 1155 vhost_dev_cleanup(dev); 1156 1157 dev->fork_owner = fork_from_owner_default; 1158 dev->umem = umem; 1159 /* We don't need VQ locks below since vhost_dev_cleanup makes sure 1160 * VQs aren't running. 1161 */ 1162 for (i = 0; i < dev->nvqs; ++i) 1163 dev->vqs[i]->umem = umem; 1164 } 1165 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner); 1166 1167 void vhost_dev_stop(struct vhost_dev *dev) 1168 { 1169 int i; 1170 1171 for (i = 0; i < dev->nvqs; ++i) { 1172 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) 1173 vhost_poll_stop(&dev->vqs[i]->poll); 1174 } 1175 1176 vhost_dev_flush(dev); 1177 } 1178 EXPORT_SYMBOL_GPL(vhost_dev_stop); 1179 1180 void vhost_clear_msg(struct vhost_dev *dev) 1181 { 1182 struct vhost_msg_node *node, *n; 1183 1184 spin_lock(&dev->iotlb_lock); 1185 1186 list_for_each_entry_safe(node, n, &dev->read_list, node) { 1187 list_del(&node->node); 1188 kfree(node); 1189 } 1190 1191 list_for_each_entry_safe(node, n, &dev->pending_list, node) { 1192 list_del(&node->node); 1193 kfree(node); 1194 } 1195 1196 spin_unlock(&dev->iotlb_lock); 1197 } 1198 EXPORT_SYMBOL_GPL(vhost_clear_msg); 1199 1200 void vhost_dev_cleanup(struct vhost_dev *dev) 1201 { 1202 int i; 1203 1204 for (i = 0; i < dev->nvqs; ++i) { 1205 if (dev->vqs[i]->error_ctx) 1206 eventfd_ctx_put(dev->vqs[i]->error_ctx); 1207 if (dev->vqs[i]->kick) 1208 fput(dev->vqs[i]->kick); 1209 if (dev->vqs[i]->call_ctx.ctx) 1210 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx); 1211 vhost_vq_reset(dev, dev->vqs[i]); 1212 } 1213 vhost_dev_free_iovecs(dev); 1214 if (dev->log_ctx) 1215 eventfd_ctx_put(dev->log_ctx); 1216 dev->log_ctx = NULL; 1217 /* No one will access memory at this point */ 1218 vhost_iotlb_free(dev->umem); 1219 dev->umem = NULL; 1220 vhost_iotlb_free(dev->iotlb); 1221 dev->iotlb = NULL; 1222 vhost_clear_msg(dev); 1223 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM); 1224 vhost_workers_free(dev); 1225 vhost_detach_mm(dev); 1226 } 1227 EXPORT_SYMBOL_GPL(vhost_dev_cleanup); 1228 1229 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz) 1230 { 1231 u64 a = addr / VHOST_PAGE_SIZE / 8; 1232 1233 /* Make sure 64 bit math will not overflow. */ 1234 if (a > ULONG_MAX - (unsigned long)log_base || 1235 a + (unsigned long)log_base > ULONG_MAX) 1236 return false; 1237 1238 return access_ok(log_base + a, 1239 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8); 1240 } 1241 1242 /* Make sure 64 bit math will not overflow. */ 1243 static bool vhost_overflow(u64 uaddr, u64 size) 1244 { 1245 if (uaddr > ULONG_MAX || size > ULONG_MAX) 1246 return true; 1247 1248 if (!size) 1249 return false; 1250 1251 return uaddr > ULONG_MAX - size + 1; 1252 } 1253 1254 /* Caller should have vq mutex and device mutex. */ 1255 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem, 1256 int log_all) 1257 { 1258 struct vhost_iotlb_map *map; 1259 1260 if (!umem) 1261 return false; 1262 1263 list_for_each_entry(map, &umem->list, link) { 1264 unsigned long a = map->addr; 1265 1266 if (vhost_overflow(map->addr, map->size)) 1267 return false; 1268 1269 1270 if (!access_ok((void __user *)a, map->size)) 1271 return false; 1272 else if (log_all && !log_access_ok(log_base, 1273 map->start, 1274 map->size)) 1275 return false; 1276 } 1277 return true; 1278 } 1279 1280 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq, 1281 u64 addr, unsigned int size, 1282 int type) 1283 { 1284 const struct vhost_iotlb_map *map = vq->meta_iotlb[type]; 1285 1286 if (!map) 1287 return NULL; 1288 1289 return (void __user *)(uintptr_t)(map->addr + addr - map->start); 1290 } 1291 1292 /* Can we switch to this memory table? */ 1293 /* Caller should have device mutex but not vq mutex */ 1294 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem, 1295 int log_all) 1296 { 1297 int i; 1298 1299 for (i = 0; i < d->nvqs; ++i) { 1300 bool ok; 1301 bool log; 1302 1303 mutex_lock(&d->vqs[i]->mutex); 1304 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL); 1305 /* If ring is inactive, will check when it's enabled. */ 1306 if (d->vqs[i]->private_data) 1307 ok = vq_memory_access_ok(d->vqs[i]->log_base, 1308 umem, log); 1309 else 1310 ok = true; 1311 mutex_unlock(&d->vqs[i]->mutex); 1312 if (!ok) 1313 return false; 1314 } 1315 return true; 1316 } 1317 1318 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len, 1319 struct iovec iov[], int iov_size, int access); 1320 1321 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to, 1322 const void *from, unsigned size) 1323 { 1324 int ret; 1325 1326 if (!vq->iotlb) 1327 return __copy_to_user(to, from, size); 1328 else { 1329 /* This function should be called after iotlb 1330 * prefetch, which means we're sure that all vq 1331 * could be access through iotlb. So -EAGAIN should 1332 * not happen in this case. 1333 */ 1334 struct iov_iter t; 1335 void __user *uaddr = vhost_vq_meta_fetch(vq, 1336 (u64)(uintptr_t)to, size, 1337 VHOST_ADDR_USED); 1338 1339 if (uaddr) 1340 return __copy_to_user(uaddr, from, size); 1341 1342 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov, 1343 ARRAY_SIZE(vq->iotlb_iov), 1344 VHOST_ACCESS_WO); 1345 if (ret < 0) 1346 goto out; 1347 iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size); 1348 ret = copy_to_iter(from, size, &t); 1349 if (ret == size) 1350 ret = 0; 1351 } 1352 out: 1353 return ret; 1354 } 1355 1356 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to, 1357 void __user *from, unsigned size) 1358 { 1359 int ret; 1360 1361 if (!vq->iotlb) 1362 return __copy_from_user(to, from, size); 1363 else { 1364 /* This function should be called after iotlb 1365 * prefetch, which means we're sure that vq 1366 * could be access through iotlb. So -EAGAIN should 1367 * not happen in this case. 1368 */ 1369 void __user *uaddr = vhost_vq_meta_fetch(vq, 1370 (u64)(uintptr_t)from, size, 1371 VHOST_ADDR_DESC); 1372 struct iov_iter f; 1373 1374 if (uaddr) 1375 return __copy_from_user(to, uaddr, size); 1376 1377 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov, 1378 ARRAY_SIZE(vq->iotlb_iov), 1379 VHOST_ACCESS_RO); 1380 if (ret < 0) { 1381 vq_err(vq, "IOTLB translation failure: uaddr " 1382 "%p size 0x%llx\n", from, 1383 (unsigned long long) size); 1384 goto out; 1385 } 1386 iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size); 1387 ret = copy_from_iter(to, size, &f); 1388 if (ret == size) 1389 ret = 0; 1390 } 1391 1392 out: 1393 return ret; 1394 } 1395 1396 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq, 1397 void __user *addr, unsigned int size, 1398 int type) 1399 { 1400 int ret; 1401 1402 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov, 1403 ARRAY_SIZE(vq->iotlb_iov), 1404 VHOST_ACCESS_RO); 1405 if (ret < 0) { 1406 vq_err(vq, "IOTLB translation failure: uaddr " 1407 "%p size 0x%llx\n", addr, 1408 (unsigned long long) size); 1409 return NULL; 1410 } 1411 1412 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) { 1413 vq_err(vq, "Non atomic userspace memory access: uaddr " 1414 "%p size 0x%llx\n", addr, 1415 (unsigned long long) size); 1416 return NULL; 1417 } 1418 1419 return vq->iotlb_iov[0].iov_base; 1420 } 1421 1422 /* This function should be called after iotlb 1423 * prefetch, which means we're sure that vq 1424 * could be access through iotlb. So -EAGAIN should 1425 * not happen in this case. 1426 */ 1427 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq, 1428 void __user *addr, unsigned int size, 1429 int type) 1430 { 1431 void __user *uaddr = vhost_vq_meta_fetch(vq, 1432 (u64)(uintptr_t)addr, size, type); 1433 if (uaddr) 1434 return uaddr; 1435 1436 return __vhost_get_user_slow(vq, addr, size, type); 1437 } 1438 1439 #define vhost_put_user(vq, x, ptr) \ 1440 ({ \ 1441 int ret; \ 1442 if (!vq->iotlb) { \ 1443 ret = put_user(x, ptr); \ 1444 } else { \ 1445 __typeof__(ptr) to = \ 1446 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \ 1447 sizeof(*ptr), VHOST_ADDR_USED); \ 1448 if (to != NULL) \ 1449 ret = put_user(x, to); \ 1450 else \ 1451 ret = -EFAULT; \ 1452 } \ 1453 ret; \ 1454 }) 1455 1456 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq) 1457 { 1458 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx), 1459 vhost_avail_event(vq)); 1460 } 1461 1462 static inline int vhost_put_used(struct vhost_virtqueue *vq, 1463 struct vring_used_elem *head, int idx, 1464 int count) 1465 { 1466 return vhost_copy_to_user(vq, vq->used->ring + idx, head, 1467 count * sizeof(*head)); 1468 } 1469 1470 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq) 1471 1472 { 1473 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags), 1474 &vq->used->flags); 1475 } 1476 1477 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq) 1478 1479 { 1480 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx), 1481 &vq->used->idx); 1482 } 1483 1484 #define vhost_get_user(vq, x, ptr, type) \ 1485 ({ \ 1486 int ret; \ 1487 if (!vq->iotlb) { \ 1488 ret = get_user(x, ptr); \ 1489 } else { \ 1490 __typeof__(ptr) from = \ 1491 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \ 1492 sizeof(*ptr), \ 1493 type); \ 1494 if (from != NULL) \ 1495 ret = get_user(x, from); \ 1496 else \ 1497 ret = -EFAULT; \ 1498 } \ 1499 ret; \ 1500 }) 1501 1502 #define vhost_get_avail(vq, x, ptr) \ 1503 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL) 1504 1505 #define vhost_get_used(vq, x, ptr) \ 1506 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED) 1507 1508 static void vhost_dev_lock_vqs(struct vhost_dev *d) 1509 { 1510 int i = 0; 1511 for (i = 0; i < d->nvqs; ++i) 1512 mutex_lock_nested(&d->vqs[i]->mutex, i); 1513 } 1514 1515 static void vhost_dev_unlock_vqs(struct vhost_dev *d) 1516 { 1517 int i = 0; 1518 for (i = 0; i < d->nvqs; ++i) 1519 mutex_unlock(&d->vqs[i]->mutex); 1520 } 1521 1522 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq) 1523 { 1524 __virtio16 idx; 1525 u16 avail_idx; 1526 int r; 1527 1528 r = vhost_get_avail(vq, idx, &vq->avail->idx); 1529 if (unlikely(r < 0)) { 1530 vq_err(vq, "Failed to access available index at %p (%d)\n", 1531 &vq->avail->idx, r); 1532 return r; 1533 } 1534 1535 /* Check it isn't doing very strange thing with available indexes */ 1536 avail_idx = vhost16_to_cpu(vq, idx); 1537 if (unlikely((u16)(avail_idx - vq->last_avail_idx) > vq->num)) { 1538 vq_err(vq, "Invalid available index change from %u to %u", 1539 vq->last_avail_idx, avail_idx); 1540 return -EINVAL; 1541 } 1542 1543 /* We're done if there is nothing new */ 1544 if (avail_idx == vq->avail_idx) 1545 return 0; 1546 1547 vq->avail_idx = avail_idx; 1548 1549 /* 1550 * We updated vq->avail_idx so we need a memory barrier between 1551 * the index read above and the caller reading avail ring entries. 1552 */ 1553 smp_rmb(); 1554 return 1; 1555 } 1556 1557 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq, 1558 __virtio16 *head, int idx) 1559 { 1560 return vhost_get_avail(vq, *head, 1561 &vq->avail->ring[idx & (vq->num - 1)]); 1562 } 1563 1564 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq, 1565 __virtio16 *flags) 1566 { 1567 return vhost_get_avail(vq, *flags, &vq->avail->flags); 1568 } 1569 1570 static inline int vhost_get_used_event(struct vhost_virtqueue *vq, 1571 __virtio16 *event) 1572 { 1573 return vhost_get_avail(vq, *event, vhost_used_event(vq)); 1574 } 1575 1576 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq, 1577 __virtio16 *idx) 1578 { 1579 return vhost_get_used(vq, *idx, &vq->used->idx); 1580 } 1581 1582 static inline int vhost_get_desc(struct vhost_virtqueue *vq, 1583 struct vring_desc *desc, int idx) 1584 { 1585 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc)); 1586 } 1587 1588 static void vhost_iotlb_notify_vq(struct vhost_dev *d, 1589 struct vhost_iotlb_msg *msg) 1590 { 1591 struct vhost_msg_node *node, *n; 1592 1593 spin_lock(&d->iotlb_lock); 1594 1595 list_for_each_entry_safe(node, n, &d->pending_list, node) { 1596 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb; 1597 if (msg->iova <= vq_msg->iova && 1598 msg->iova + msg->size - 1 >= vq_msg->iova && 1599 vq_msg->type == VHOST_IOTLB_MISS) { 1600 vhost_poll_queue(&node->vq->poll); 1601 list_del(&node->node); 1602 kfree(node); 1603 } 1604 } 1605 1606 spin_unlock(&d->iotlb_lock); 1607 } 1608 1609 static bool umem_access_ok(u64 uaddr, u64 size, int access) 1610 { 1611 unsigned long a = uaddr; 1612 1613 /* Make sure 64 bit math will not overflow. */ 1614 if (vhost_overflow(uaddr, size)) 1615 return false; 1616 1617 if ((access & VHOST_ACCESS_RO) && 1618 !access_ok((void __user *)a, size)) 1619 return false; 1620 if ((access & VHOST_ACCESS_WO) && 1621 !access_ok((void __user *)a, size)) 1622 return false; 1623 return true; 1624 } 1625 1626 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid, 1627 struct vhost_iotlb_msg *msg) 1628 { 1629 int ret = 0; 1630 1631 if (asid != 0) 1632 return -EINVAL; 1633 1634 mutex_lock(&dev->mutex); 1635 vhost_dev_lock_vqs(dev); 1636 switch (msg->type) { 1637 case VHOST_IOTLB_UPDATE: 1638 if (!dev->iotlb) { 1639 ret = -EFAULT; 1640 break; 1641 } 1642 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) { 1643 ret = -EFAULT; 1644 break; 1645 } 1646 vhost_vq_meta_reset(dev); 1647 if (vhost_iotlb_add_range(dev->iotlb, msg->iova, 1648 msg->iova + msg->size - 1, 1649 msg->uaddr, msg->perm)) { 1650 ret = -ENOMEM; 1651 break; 1652 } 1653 vhost_iotlb_notify_vq(dev, msg); 1654 break; 1655 case VHOST_IOTLB_INVALIDATE: 1656 if (!dev->iotlb) { 1657 ret = -EFAULT; 1658 break; 1659 } 1660 vhost_vq_meta_reset(dev); 1661 vhost_iotlb_del_range(dev->iotlb, msg->iova, 1662 msg->iova + msg->size - 1); 1663 break; 1664 default: 1665 ret = -EINVAL; 1666 break; 1667 } 1668 1669 vhost_dev_unlock_vqs(dev); 1670 mutex_unlock(&dev->mutex); 1671 1672 return ret; 1673 } 1674 ssize_t vhost_chr_write_iter(struct vhost_dev *dev, 1675 struct iov_iter *from) 1676 { 1677 struct vhost_iotlb_msg msg; 1678 size_t offset; 1679 int type, ret; 1680 u32 asid = 0; 1681 1682 ret = copy_from_iter(&type, sizeof(type), from); 1683 if (ret != sizeof(type)) { 1684 ret = -EINVAL; 1685 goto done; 1686 } 1687 1688 switch (type) { 1689 case VHOST_IOTLB_MSG: 1690 /* There maybe a hole after type for V1 message type, 1691 * so skip it here. 1692 */ 1693 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int); 1694 break; 1695 case VHOST_IOTLB_MSG_V2: 1696 if (vhost_backend_has_feature(dev->vqs[0], 1697 VHOST_BACKEND_F_IOTLB_ASID)) { 1698 ret = copy_from_iter(&asid, sizeof(asid), from); 1699 if (ret != sizeof(asid)) { 1700 ret = -EINVAL; 1701 goto done; 1702 } 1703 offset = 0; 1704 } else 1705 offset = sizeof(__u32); 1706 break; 1707 default: 1708 ret = -EINVAL; 1709 goto done; 1710 } 1711 1712 iov_iter_advance(from, offset); 1713 ret = copy_from_iter(&msg, sizeof(msg), from); 1714 if (ret != sizeof(msg)) { 1715 ret = -EINVAL; 1716 goto done; 1717 } 1718 1719 if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) { 1720 ret = -EINVAL; 1721 goto done; 1722 } 1723 1724 if (dev->msg_handler) 1725 ret = dev->msg_handler(dev, asid, &msg); 1726 else 1727 ret = vhost_process_iotlb_msg(dev, asid, &msg); 1728 if (ret) { 1729 ret = -EFAULT; 1730 goto done; 1731 } 1732 1733 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) : 1734 sizeof(struct vhost_msg_v2); 1735 done: 1736 return ret; 1737 } 1738 EXPORT_SYMBOL(vhost_chr_write_iter); 1739 1740 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev, 1741 poll_table *wait) 1742 { 1743 __poll_t mask = 0; 1744 1745 poll_wait(file, &dev->wait, wait); 1746 1747 if (!list_empty(&dev->read_list)) 1748 mask |= EPOLLIN | EPOLLRDNORM; 1749 1750 return mask; 1751 } 1752 EXPORT_SYMBOL(vhost_chr_poll); 1753 1754 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to, 1755 int noblock) 1756 { 1757 DEFINE_WAIT(wait); 1758 struct vhost_msg_node *node; 1759 ssize_t ret = 0; 1760 unsigned size = sizeof(struct vhost_msg); 1761 1762 if (iov_iter_count(to) < size) 1763 return 0; 1764 1765 while (1) { 1766 if (!noblock) 1767 prepare_to_wait(&dev->wait, &wait, 1768 TASK_INTERRUPTIBLE); 1769 1770 node = vhost_dequeue_msg(dev, &dev->read_list); 1771 if (node) 1772 break; 1773 if (noblock) { 1774 ret = -EAGAIN; 1775 break; 1776 } 1777 if (signal_pending(current)) { 1778 ret = -ERESTARTSYS; 1779 break; 1780 } 1781 if (!dev->iotlb) { 1782 ret = -EBADFD; 1783 break; 1784 } 1785 1786 schedule(); 1787 } 1788 1789 if (!noblock) 1790 finish_wait(&dev->wait, &wait); 1791 1792 if (node) { 1793 struct vhost_iotlb_msg *msg; 1794 void *start = &node->msg; 1795 1796 switch (node->msg.type) { 1797 case VHOST_IOTLB_MSG: 1798 size = sizeof(node->msg); 1799 msg = &node->msg.iotlb; 1800 break; 1801 case VHOST_IOTLB_MSG_V2: 1802 size = sizeof(node->msg_v2); 1803 msg = &node->msg_v2.iotlb; 1804 break; 1805 default: 1806 BUG(); 1807 break; 1808 } 1809 1810 ret = copy_to_iter(start, size, to); 1811 if (ret != size || msg->type != VHOST_IOTLB_MISS) { 1812 kfree(node); 1813 return ret; 1814 } 1815 vhost_enqueue_msg(dev, &dev->pending_list, node); 1816 } 1817 1818 return ret; 1819 } 1820 EXPORT_SYMBOL_GPL(vhost_chr_read_iter); 1821 1822 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access) 1823 { 1824 struct vhost_dev *dev = vq->dev; 1825 struct vhost_msg_node *node; 1826 struct vhost_iotlb_msg *msg; 1827 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2); 1828 1829 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG); 1830 if (!node) 1831 return -ENOMEM; 1832 1833 if (v2) { 1834 node->msg_v2.type = VHOST_IOTLB_MSG_V2; 1835 msg = &node->msg_v2.iotlb; 1836 } else { 1837 msg = &node->msg.iotlb; 1838 } 1839 1840 msg->type = VHOST_IOTLB_MISS; 1841 msg->iova = iova; 1842 msg->perm = access; 1843 1844 vhost_enqueue_msg(dev, &dev->read_list, node); 1845 1846 return 0; 1847 } 1848 1849 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num, 1850 vring_desc_t __user *desc, 1851 vring_avail_t __user *avail, 1852 vring_used_t __user *used) 1853 1854 { 1855 /* If an IOTLB device is present, the vring addresses are 1856 * GIOVAs. Access validation occurs at prefetch time. */ 1857 if (vq->iotlb) 1858 return true; 1859 1860 return access_ok(desc, vhost_get_desc_size(vq, num)) && 1861 access_ok(avail, vhost_get_avail_size(vq, num)) && 1862 access_ok(used, vhost_get_used_size(vq, num)); 1863 } 1864 1865 static void vhost_vq_meta_update(struct vhost_virtqueue *vq, 1866 const struct vhost_iotlb_map *map, 1867 int type) 1868 { 1869 int access = (type == VHOST_ADDR_USED) ? 1870 VHOST_ACCESS_WO : VHOST_ACCESS_RO; 1871 1872 if (likely(map->perm & access)) 1873 vq->meta_iotlb[type] = map; 1874 } 1875 1876 static bool iotlb_access_ok(struct vhost_virtqueue *vq, 1877 int access, u64 addr, u64 len, int type) 1878 { 1879 const struct vhost_iotlb_map *map; 1880 struct vhost_iotlb *umem = vq->iotlb; 1881 u64 s = 0, size, orig_addr = addr, last = addr + len - 1; 1882 1883 if (vhost_vq_meta_fetch(vq, addr, len, type)) 1884 return true; 1885 1886 while (len > s) { 1887 map = vhost_iotlb_itree_first(umem, addr, last); 1888 if (map == NULL || map->start > addr) { 1889 vhost_iotlb_miss(vq, addr, access); 1890 return false; 1891 } else if (!(map->perm & access)) { 1892 /* Report the possible access violation by 1893 * request another translation from userspace. 1894 */ 1895 return false; 1896 } 1897 1898 size = map->size - addr + map->start; 1899 1900 if (orig_addr == addr && size >= len) 1901 vhost_vq_meta_update(vq, map, type); 1902 1903 s += size; 1904 addr += size; 1905 } 1906 1907 return true; 1908 } 1909 1910 int vq_meta_prefetch(struct vhost_virtqueue *vq) 1911 { 1912 unsigned int num = vq->num; 1913 1914 if (!vq->iotlb) 1915 return 1; 1916 1917 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc, 1918 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) && 1919 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail, 1920 vhost_get_avail_size(vq, num), 1921 VHOST_ADDR_AVAIL) && 1922 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used, 1923 vhost_get_used_size(vq, num), VHOST_ADDR_USED); 1924 } 1925 EXPORT_SYMBOL_GPL(vq_meta_prefetch); 1926 1927 /* Can we log writes? */ 1928 /* Caller should have device mutex but not vq mutex */ 1929 bool vhost_log_access_ok(struct vhost_dev *dev) 1930 { 1931 return memory_access_ok(dev, dev->umem, 1); 1932 } 1933 EXPORT_SYMBOL_GPL(vhost_log_access_ok); 1934 1935 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq, 1936 void __user *log_base, 1937 bool log_used, 1938 u64 log_addr) 1939 { 1940 /* If an IOTLB device is present, log_addr is a GIOVA that 1941 * will never be logged by log_used(). */ 1942 if (vq->iotlb) 1943 return true; 1944 1945 return !log_used || log_access_ok(log_base, log_addr, 1946 vhost_get_used_size(vq, vq->num)); 1947 } 1948 1949 /* Verify access for write logging. */ 1950 /* Caller should have vq mutex and device mutex */ 1951 static bool vq_log_access_ok(struct vhost_virtqueue *vq, 1952 void __user *log_base) 1953 { 1954 return vq_memory_access_ok(log_base, vq->umem, 1955 vhost_has_feature(vq, VHOST_F_LOG_ALL)) && 1956 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr); 1957 } 1958 1959 /* Can we start vq? */ 1960 /* Caller should have vq mutex and device mutex */ 1961 bool vhost_vq_access_ok(struct vhost_virtqueue *vq) 1962 { 1963 if (!vq_log_access_ok(vq, vq->log_base)) 1964 return false; 1965 1966 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used); 1967 } 1968 EXPORT_SYMBOL_GPL(vhost_vq_access_ok); 1969 1970 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m) 1971 { 1972 struct vhost_memory mem, *newmem; 1973 struct vhost_memory_region *region; 1974 struct vhost_iotlb *newumem, *oldumem; 1975 unsigned long size = offsetof(struct vhost_memory, regions); 1976 int i; 1977 1978 if (copy_from_user(&mem, m, size)) 1979 return -EFAULT; 1980 if (mem.padding) 1981 return -EOPNOTSUPP; 1982 if (mem.nregions > max_mem_regions) 1983 return -E2BIG; 1984 newmem = kvzalloc_flex(*newmem, regions, mem.nregions); 1985 if (!newmem) 1986 return -ENOMEM; 1987 1988 memcpy(newmem, &mem, size); 1989 if (copy_from_user(newmem->regions, m->regions, 1990 flex_array_size(newmem, regions, mem.nregions))) { 1991 kvfree(newmem); 1992 return -EFAULT; 1993 } 1994 1995 newumem = iotlb_alloc(); 1996 if (!newumem) { 1997 kvfree(newmem); 1998 return -ENOMEM; 1999 } 2000 2001 for (region = newmem->regions; 2002 region < newmem->regions + mem.nregions; 2003 region++) { 2004 if (vhost_iotlb_add_range(newumem, 2005 region->guest_phys_addr, 2006 region->guest_phys_addr + 2007 region->memory_size - 1, 2008 region->userspace_addr, 2009 VHOST_MAP_RW)) 2010 goto err; 2011 } 2012 2013 if (!memory_access_ok(d, newumem, 0)) 2014 goto err; 2015 2016 oldumem = d->umem; 2017 d->umem = newumem; 2018 2019 /* All memory accesses are done under some VQ mutex. */ 2020 for (i = 0; i < d->nvqs; ++i) { 2021 mutex_lock(&d->vqs[i]->mutex); 2022 d->vqs[i]->umem = newumem; 2023 mutex_unlock(&d->vqs[i]->mutex); 2024 } 2025 2026 kvfree(newmem); 2027 vhost_iotlb_free(oldumem); 2028 return 0; 2029 2030 err: 2031 vhost_iotlb_free(newumem); 2032 kvfree(newmem); 2033 return -EFAULT; 2034 } 2035 2036 static long vhost_vring_set_num(struct vhost_dev *d, 2037 struct vhost_virtqueue *vq, 2038 void __user *argp) 2039 { 2040 struct vhost_vring_state s; 2041 2042 /* Resizing ring with an active backend? 2043 * You don't want to do that. */ 2044 if (vq->private_data) 2045 return -EBUSY; 2046 2047 if (copy_from_user(&s, argp, sizeof s)) 2048 return -EFAULT; 2049 2050 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) 2051 return -EINVAL; 2052 vq->num = s.num; 2053 2054 return 0; 2055 } 2056 2057 static long vhost_vring_set_addr(struct vhost_dev *d, 2058 struct vhost_virtqueue *vq, 2059 void __user *argp) 2060 { 2061 struct vhost_vring_addr a; 2062 2063 if (copy_from_user(&a, argp, sizeof a)) 2064 return -EFAULT; 2065 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) 2066 return -EOPNOTSUPP; 2067 2068 /* For 32bit, verify that the top 32bits of the user 2069 data are set to zero. */ 2070 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr || 2071 (u64)(unsigned long)a.used_user_addr != a.used_user_addr || 2072 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) 2073 return -EFAULT; 2074 2075 /* Make sure it's safe to cast pointers to vring types. */ 2076 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE); 2077 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE); 2078 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) || 2079 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) || 2080 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) 2081 return -EINVAL; 2082 2083 /* We only verify access here if backend is configured. 2084 * If it is not, we don't as size might not have been setup. 2085 * We will verify when backend is configured. */ 2086 if (vq->private_data) { 2087 if (!vq_access_ok(vq, vq->num, 2088 (void __user *)(unsigned long)a.desc_user_addr, 2089 (void __user *)(unsigned long)a.avail_user_addr, 2090 (void __user *)(unsigned long)a.used_user_addr)) 2091 return -EINVAL; 2092 2093 /* Also validate log access for used ring if enabled. */ 2094 if (!vq_log_used_access_ok(vq, vq->log_base, 2095 a.flags & (0x1 << VHOST_VRING_F_LOG), 2096 a.log_guest_addr)) 2097 return -EINVAL; 2098 } 2099 2100 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG)); 2101 vq->desc = (void __user *)(unsigned long)a.desc_user_addr; 2102 vq->avail = (void __user *)(unsigned long)a.avail_user_addr; 2103 vq->log_addr = a.log_guest_addr; 2104 vq->used = (void __user *)(unsigned long)a.used_user_addr; 2105 2106 return 0; 2107 } 2108 2109 static long vhost_vring_set_num_addr(struct vhost_dev *d, 2110 struct vhost_virtqueue *vq, 2111 unsigned int ioctl, 2112 void __user *argp) 2113 { 2114 long r; 2115 2116 mutex_lock(&vq->mutex); 2117 2118 switch (ioctl) { 2119 case VHOST_SET_VRING_NUM: 2120 r = vhost_vring_set_num(d, vq, argp); 2121 break; 2122 case VHOST_SET_VRING_ADDR: 2123 r = vhost_vring_set_addr(d, vq, argp); 2124 break; 2125 default: 2126 BUG(); 2127 } 2128 2129 mutex_unlock(&vq->mutex); 2130 2131 return r; 2132 } 2133 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp) 2134 { 2135 struct file *eventfp, *filep = NULL; 2136 bool pollstart = false, pollstop = false; 2137 struct eventfd_ctx *ctx = NULL; 2138 struct vhost_virtqueue *vq; 2139 struct vhost_vring_state s; 2140 struct vhost_vring_file f; 2141 u32 idx; 2142 long r; 2143 2144 r = vhost_get_vq_from_user(d, argp, &vq, &idx); 2145 if (r < 0) 2146 return r; 2147 2148 if (ioctl == VHOST_SET_VRING_NUM || 2149 ioctl == VHOST_SET_VRING_ADDR) { 2150 return vhost_vring_set_num_addr(d, vq, ioctl, argp); 2151 } 2152 2153 mutex_lock(&vq->mutex); 2154 2155 switch (ioctl) { 2156 case VHOST_SET_VRING_BASE: 2157 /* Moving base with an active backend? 2158 * You don't want to do that. */ 2159 if (vq->private_data) { 2160 r = -EBUSY; 2161 break; 2162 } 2163 if (copy_from_user(&s, argp, sizeof s)) { 2164 r = -EFAULT; 2165 break; 2166 } 2167 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) { 2168 vq->next_avail_head = vq->last_avail_idx = 2169 s.num & 0xffff; 2170 vq->last_used_idx = (s.num >> 16) & 0xffff; 2171 } else { 2172 if (s.num > 0xffff) { 2173 r = -EINVAL; 2174 break; 2175 } 2176 vq->next_avail_head = vq->last_avail_idx = s.num; 2177 } 2178 /* Forget the cached index value. */ 2179 vq->avail_idx = vq->last_avail_idx; 2180 break; 2181 case VHOST_GET_VRING_BASE: 2182 s.index = idx; 2183 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) 2184 s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16); 2185 else 2186 s.num = vq->last_avail_idx; 2187 if (copy_to_user(argp, &s, sizeof s)) 2188 r = -EFAULT; 2189 break; 2190 case VHOST_SET_VRING_KICK: 2191 if (copy_from_user(&f, argp, sizeof f)) { 2192 r = -EFAULT; 2193 break; 2194 } 2195 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd); 2196 if (IS_ERR(eventfp)) { 2197 r = PTR_ERR(eventfp); 2198 break; 2199 } 2200 if (eventfp != vq->kick) { 2201 pollstop = (filep = vq->kick) != NULL; 2202 pollstart = (vq->kick = eventfp) != NULL; 2203 } else 2204 filep = eventfp; 2205 break; 2206 case VHOST_SET_VRING_CALL: 2207 if (copy_from_user(&f, argp, sizeof f)) { 2208 r = -EFAULT; 2209 break; 2210 } 2211 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd); 2212 if (IS_ERR(ctx)) { 2213 r = PTR_ERR(ctx); 2214 break; 2215 } 2216 2217 swap(ctx, vq->call_ctx.ctx); 2218 break; 2219 case VHOST_SET_VRING_ERR: 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 swap(ctx, vq->error_ctx); 2230 break; 2231 case VHOST_SET_VRING_ENDIAN: 2232 r = vhost_set_vring_endian(vq, argp); 2233 break; 2234 case VHOST_GET_VRING_ENDIAN: 2235 r = vhost_get_vring_endian(vq, idx, argp); 2236 break; 2237 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT: 2238 if (copy_from_user(&s, argp, sizeof(s))) { 2239 r = -EFAULT; 2240 break; 2241 } 2242 vq->busyloop_timeout = s.num; 2243 break; 2244 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT: 2245 s.index = idx; 2246 s.num = vq->busyloop_timeout; 2247 if (copy_to_user(argp, &s, sizeof(s))) 2248 r = -EFAULT; 2249 break; 2250 default: 2251 r = -ENOIOCTLCMD; 2252 } 2253 2254 if (pollstop && vq->handle_kick) 2255 vhost_poll_stop(&vq->poll); 2256 2257 if (!IS_ERR_OR_NULL(ctx)) 2258 eventfd_ctx_put(ctx); 2259 if (filep) 2260 fput(filep); 2261 2262 if (pollstart && vq->handle_kick) 2263 r = vhost_poll_start(&vq->poll, vq->kick); 2264 2265 mutex_unlock(&vq->mutex); 2266 2267 if (pollstop && vq->handle_kick) 2268 vhost_dev_flush(vq->poll.dev); 2269 return r; 2270 } 2271 EXPORT_SYMBOL_GPL(vhost_vring_ioctl); 2272 2273 int vhost_init_device_iotlb(struct vhost_dev *d) 2274 { 2275 struct vhost_iotlb *niotlb, *oiotlb; 2276 int i; 2277 2278 niotlb = iotlb_alloc(); 2279 if (!niotlb) 2280 return -ENOMEM; 2281 2282 oiotlb = d->iotlb; 2283 d->iotlb = niotlb; 2284 2285 for (i = 0; i < d->nvqs; ++i) { 2286 struct vhost_virtqueue *vq = d->vqs[i]; 2287 2288 mutex_lock(&vq->mutex); 2289 vq->iotlb = niotlb; 2290 __vhost_vq_meta_reset(vq); 2291 mutex_unlock(&vq->mutex); 2292 } 2293 2294 vhost_iotlb_free(oiotlb); 2295 2296 return 0; 2297 } 2298 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb); 2299 2300 /* Caller must have device mutex */ 2301 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp) 2302 { 2303 struct eventfd_ctx *ctx; 2304 u64 p; 2305 long r; 2306 int i, fd; 2307 2308 /* If you are not the owner, you can become one */ 2309 if (ioctl == VHOST_SET_OWNER) { 2310 r = vhost_dev_set_owner(d); 2311 goto done; 2312 } 2313 2314 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL 2315 if (ioctl == VHOST_SET_FORK_FROM_OWNER) { 2316 /* Only allow modification before owner is set */ 2317 if (vhost_dev_has_owner(d)) { 2318 r = -EBUSY; 2319 goto done; 2320 } 2321 u8 fork_owner_val; 2322 2323 if (get_user(fork_owner_val, (u8 __user *)argp)) { 2324 r = -EFAULT; 2325 goto done; 2326 } 2327 if (fork_owner_val != VHOST_FORK_OWNER_TASK && 2328 fork_owner_val != VHOST_FORK_OWNER_KTHREAD) { 2329 r = -EINVAL; 2330 goto done; 2331 } 2332 d->fork_owner = !!fork_owner_val; 2333 r = 0; 2334 goto done; 2335 } 2336 if (ioctl == VHOST_GET_FORK_FROM_OWNER) { 2337 u8 fork_owner_val = d->fork_owner; 2338 2339 if (fork_owner_val != VHOST_FORK_OWNER_TASK && 2340 fork_owner_val != VHOST_FORK_OWNER_KTHREAD) { 2341 r = -EINVAL; 2342 goto done; 2343 } 2344 if (put_user(fork_owner_val, (u8 __user *)argp)) { 2345 r = -EFAULT; 2346 goto done; 2347 } 2348 r = 0; 2349 goto done; 2350 } 2351 #endif 2352 2353 /* You must be the owner to do anything else */ 2354 r = vhost_dev_check_owner(d); 2355 if (r) 2356 goto done; 2357 2358 switch (ioctl) { 2359 case VHOST_SET_MEM_TABLE: 2360 r = vhost_set_memory(d, argp); 2361 break; 2362 case VHOST_SET_LOG_BASE: 2363 if (copy_from_user(&p, argp, sizeof p)) { 2364 r = -EFAULT; 2365 break; 2366 } 2367 if ((u64)(unsigned long)p != p) { 2368 r = -EFAULT; 2369 break; 2370 } 2371 for (i = 0; i < d->nvqs; ++i) { 2372 struct vhost_virtqueue *vq; 2373 void __user *base = (void __user *)(unsigned long)p; 2374 vq = d->vqs[i]; 2375 mutex_lock(&vq->mutex); 2376 /* If ring is inactive, will check when it's enabled. */ 2377 if (vq->private_data && !vq_log_access_ok(vq, base)) 2378 r = -EFAULT; 2379 else 2380 vq->log_base = base; 2381 mutex_unlock(&vq->mutex); 2382 } 2383 break; 2384 case VHOST_SET_LOG_FD: 2385 r = get_user(fd, (int __user *)argp); 2386 if (r < 0) 2387 break; 2388 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd); 2389 if (IS_ERR(ctx)) { 2390 r = PTR_ERR(ctx); 2391 break; 2392 } 2393 swap(ctx, d->log_ctx); 2394 for (i = 0; i < d->nvqs; ++i) { 2395 mutex_lock(&d->vqs[i]->mutex); 2396 d->vqs[i]->log_ctx = d->log_ctx; 2397 mutex_unlock(&d->vqs[i]->mutex); 2398 } 2399 if (ctx) 2400 eventfd_ctx_put(ctx); 2401 break; 2402 default: 2403 r = -ENOIOCTLCMD; 2404 break; 2405 } 2406 done: 2407 return r; 2408 } 2409 EXPORT_SYMBOL_GPL(vhost_dev_ioctl); 2410 2411 /* TODO: This is really inefficient. We need something like get_user() 2412 * (instruction directly accesses the data, with an exception table entry 2413 * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst. 2414 */ 2415 static int set_bit_to_user(int nr, void __user *addr) 2416 { 2417 unsigned long log = (unsigned long)addr; 2418 struct page *page; 2419 void *base; 2420 int bit = nr + (log % PAGE_SIZE) * 8; 2421 int r; 2422 2423 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page); 2424 if (r < 0) 2425 return r; 2426 BUG_ON(r != 1); 2427 base = kmap_atomic(page); 2428 set_bit(bit, base); 2429 kunmap_atomic(base); 2430 unpin_user_pages_dirty_lock(&page, 1, true); 2431 return 0; 2432 } 2433 2434 static int log_write(void __user *log_base, 2435 u64 write_address, u64 write_length) 2436 { 2437 u64 write_page = write_address / VHOST_PAGE_SIZE; 2438 int r; 2439 2440 if (!write_length) 2441 return 0; 2442 write_length += write_address % VHOST_PAGE_SIZE; 2443 for (;;) { 2444 u64 base = (u64)(unsigned long)log_base; 2445 u64 log = base + write_page / 8; 2446 int bit = write_page % 8; 2447 if ((u64)(unsigned long)log != log) 2448 return -EFAULT; 2449 r = set_bit_to_user(bit, (void __user *)(unsigned long)log); 2450 if (r < 0) 2451 return r; 2452 if (write_length <= VHOST_PAGE_SIZE) 2453 break; 2454 write_length -= VHOST_PAGE_SIZE; 2455 write_page += 1; 2456 } 2457 return r; 2458 } 2459 2460 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len) 2461 { 2462 struct vhost_iotlb *umem = vq->umem; 2463 struct vhost_iotlb_map *u; 2464 u64 start, end, l, min; 2465 int r; 2466 bool hit = false; 2467 2468 while (len) { 2469 min = len; 2470 /* More than one GPAs can be mapped into a single HVA. So 2471 * iterate all possible umems here to be safe. 2472 */ 2473 list_for_each_entry(u, &umem->list, link) { 2474 if (u->addr > hva - 1 + len || 2475 u->addr - 1 + u->size < hva) 2476 continue; 2477 start = max(u->addr, hva); 2478 end = min(u->addr - 1 + u->size, hva - 1 + len); 2479 l = end - start + 1; 2480 r = log_write(vq->log_base, 2481 u->start + start - u->addr, 2482 l); 2483 if (r < 0) 2484 return r; 2485 hit = true; 2486 min = min(l, min); 2487 } 2488 2489 if (!hit) 2490 return -EFAULT; 2491 2492 len -= min; 2493 hva += min; 2494 } 2495 2496 return 0; 2497 } 2498 2499 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len) 2500 { 2501 struct iovec *iov = vq->log_iov; 2502 int i, ret; 2503 2504 if (!vq->iotlb) 2505 return log_write(vq->log_base, vq->log_addr + used_offset, len); 2506 2507 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset, 2508 len, iov, 64, VHOST_ACCESS_WO); 2509 if (ret < 0) 2510 return ret; 2511 2512 for (i = 0; i < ret; i++) { 2513 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base, 2514 iov[i].iov_len); 2515 if (ret) 2516 return ret; 2517 } 2518 2519 return 0; 2520 } 2521 2522 /* 2523 * vhost_log_write() - Log in dirty page bitmap 2524 * @vq: vhost virtqueue. 2525 * @log: Array of dirty memory in GPA. 2526 * @log_num: Size of vhost_log arrary. 2527 * @len: The total length of memory buffer to log in the dirty bitmap. 2528 * Some drivers may only partially use pages shared via the last 2529 * vring descriptor (i.e. vhost-net RX buffer). 2530 * Use (len == U64_MAX) to indicate the driver would log all 2531 * pages of vring descriptors. 2532 * @iov: Array of dirty memory in HVA. 2533 * @count: Size of iovec array. 2534 */ 2535 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log, 2536 unsigned int log_num, u64 len, struct iovec *iov, int count) 2537 { 2538 int i, r; 2539 2540 /* Make sure data written is seen before log. */ 2541 smp_wmb(); 2542 2543 if (vq->iotlb) { 2544 for (i = 0; i < count; i++) { 2545 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base, 2546 iov[i].iov_len); 2547 if (r < 0) 2548 return r; 2549 } 2550 return 0; 2551 } 2552 2553 for (i = 0; i < log_num; ++i) { 2554 u64 l = min(log[i].len, len); 2555 r = log_write(vq->log_base, log[i].addr, l); 2556 if (r < 0) 2557 return r; 2558 2559 if (len != U64_MAX) 2560 len -= l; 2561 } 2562 2563 if (vq->log_ctx) 2564 eventfd_signal(vq->log_ctx); 2565 2566 return 0; 2567 } 2568 EXPORT_SYMBOL_GPL(vhost_log_write); 2569 2570 static int vhost_update_used_flags(struct vhost_virtqueue *vq) 2571 { 2572 void __user *used; 2573 if (vhost_put_used_flags(vq)) 2574 return -EFAULT; 2575 if (unlikely(vq->log_used)) { 2576 /* Make sure the flag is seen before log. */ 2577 smp_wmb(); 2578 /* Log used flag write. */ 2579 used = &vq->used->flags; 2580 log_used(vq, (used - (void __user *)vq->used), 2581 sizeof vq->used->flags); 2582 if (vq->log_ctx) 2583 eventfd_signal(vq->log_ctx); 2584 } 2585 return 0; 2586 } 2587 2588 static int vhost_update_avail_event(struct vhost_virtqueue *vq) 2589 { 2590 if (vhost_put_avail_event(vq)) 2591 return -EFAULT; 2592 if (unlikely(vq->log_used)) { 2593 void __user *used; 2594 /* Make sure the event is seen before log. */ 2595 smp_wmb(); 2596 /* Log avail event write */ 2597 used = vhost_avail_event(vq); 2598 log_used(vq, (used - (void __user *)vq->used), 2599 sizeof *vhost_avail_event(vq)); 2600 if (vq->log_ctx) 2601 eventfd_signal(vq->log_ctx); 2602 } 2603 return 0; 2604 } 2605 2606 int vhost_vq_init_access(struct vhost_virtqueue *vq) 2607 { 2608 __virtio16 last_used_idx; 2609 int r; 2610 bool is_le = vq->is_le; 2611 2612 if (!vq->private_data) 2613 return 0; 2614 2615 vhost_init_is_le(vq); 2616 2617 r = vhost_update_used_flags(vq); 2618 if (r) 2619 goto err; 2620 vq->signalled_used_valid = false; 2621 if (!vq->iotlb && 2622 !access_ok(&vq->used->idx, sizeof vq->used->idx)) { 2623 r = -EFAULT; 2624 goto err; 2625 } 2626 r = vhost_get_used_idx(vq, &last_used_idx); 2627 if (r) { 2628 vq_err(vq, "Can't access used idx at %p\n", 2629 &vq->used->idx); 2630 goto err; 2631 } 2632 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx); 2633 return 0; 2634 2635 err: 2636 vq->is_le = is_le; 2637 return r; 2638 } 2639 EXPORT_SYMBOL_GPL(vhost_vq_init_access); 2640 2641 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len, 2642 struct iovec iov[], int iov_size, int access) 2643 { 2644 const struct vhost_iotlb_map *map; 2645 struct vhost_dev *dev = vq->dev; 2646 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem; 2647 struct iovec *_iov; 2648 u64 s = 0, last = addr + len - 1; 2649 int ret = 0; 2650 2651 while ((u64)len > s) { 2652 u64 size; 2653 if (unlikely(ret >= iov_size)) { 2654 ret = -ENOBUFS; 2655 break; 2656 } 2657 2658 map = vhost_iotlb_itree_first(umem, addr, last); 2659 if (map == NULL || map->start > addr) { 2660 if (umem != dev->iotlb) { 2661 ret = -EFAULT; 2662 break; 2663 } 2664 ret = -EAGAIN; 2665 break; 2666 } else if (!(map->perm & access)) { 2667 ret = -EPERM; 2668 break; 2669 } 2670 2671 _iov = iov + ret; 2672 size = map->size - addr + map->start; 2673 _iov->iov_len = min((u64)len - s, size); 2674 _iov->iov_base = (void __user *)(unsigned long) 2675 (map->addr + addr - map->start); 2676 s += size; 2677 addr += size; 2678 ++ret; 2679 } 2680 2681 if (ret == -EAGAIN) 2682 vhost_iotlb_miss(vq, addr, access); 2683 return ret; 2684 } 2685 2686 /* Each buffer in the virtqueues is actually a chain of descriptors. This 2687 * function returns the next descriptor in the chain, 2688 * or -1U if we're at the end. */ 2689 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc) 2690 { 2691 unsigned int next; 2692 2693 /* If this descriptor says it doesn't chain, we're done. */ 2694 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT))) 2695 return -1U; 2696 2697 /* Check they're not leading us off end of descriptors. */ 2698 next = vhost16_to_cpu(vq, READ_ONCE(desc->next)); 2699 return next; 2700 } 2701 2702 static int get_indirect(struct vhost_virtqueue *vq, 2703 struct iovec iov[], unsigned int iov_size, 2704 unsigned int *out_num, unsigned int *in_num, 2705 struct vhost_log *log, unsigned int *log_num, 2706 struct vring_desc *indirect) 2707 { 2708 struct vring_desc desc; 2709 unsigned int i = 0, count, found = 0; 2710 u32 len = vhost32_to_cpu(vq, indirect->len); 2711 struct iov_iter from; 2712 int ret, access; 2713 2714 /* Sanity check */ 2715 if (unlikely(len % sizeof desc)) { 2716 vq_err(vq, "Invalid length in indirect descriptor: " 2717 "len 0x%llx not multiple of 0x%zx\n", 2718 (unsigned long long)len, 2719 sizeof desc); 2720 return -EINVAL; 2721 } 2722 2723 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect, 2724 UIO_MAXIOV, VHOST_ACCESS_RO); 2725 if (unlikely(ret < 0)) { 2726 if (ret != -EAGAIN) 2727 vq_err(vq, "Translation failure %d in indirect.\n", ret); 2728 return ret; 2729 } 2730 iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len); 2731 count = len / sizeof desc; 2732 /* Buffers are chained via a 16 bit next field, so 2733 * we can have at most 2^16 of these. */ 2734 if (unlikely(count > USHRT_MAX + 1)) { 2735 vq_err(vq, "Indirect buffer length too big: %d\n", 2736 indirect->len); 2737 return -E2BIG; 2738 } 2739 2740 do { 2741 unsigned iov_count = *in_num + *out_num; 2742 if (unlikely(++found > count)) { 2743 vq_err(vq, "Loop detected: last one at %u " 2744 "indirect size %u\n", 2745 i, count); 2746 return -EINVAL; 2747 } 2748 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) { 2749 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n", 2750 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc); 2751 return -EINVAL; 2752 } 2753 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) { 2754 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n", 2755 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc); 2756 return -EINVAL; 2757 } 2758 2759 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) 2760 access = VHOST_ACCESS_WO; 2761 else 2762 access = VHOST_ACCESS_RO; 2763 2764 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr), 2765 vhost32_to_cpu(vq, desc.len), iov + iov_count, 2766 iov_size - iov_count, access); 2767 if (unlikely(ret < 0)) { 2768 if (ret != -EAGAIN) 2769 vq_err(vq, "Translation failure %d indirect idx %d\n", 2770 ret, i); 2771 return ret; 2772 } 2773 /* If this is an input descriptor, increment that count. */ 2774 if (access == VHOST_ACCESS_WO) { 2775 *in_num += ret; 2776 if (unlikely(log && ret)) { 2777 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr); 2778 log[*log_num].len = vhost32_to_cpu(vq, desc.len); 2779 ++*log_num; 2780 } 2781 } else { 2782 /* If it's an output descriptor, they're all supposed 2783 * to come before any input descriptors. */ 2784 if (unlikely(*in_num)) { 2785 vq_err(vq, "Indirect descriptor " 2786 "has out after in: idx %d\n", i); 2787 return -EINVAL; 2788 } 2789 *out_num += ret; 2790 } 2791 } while ((i = next_desc(vq, &desc)) != -1); 2792 return 0; 2793 } 2794 2795 /** 2796 * vhost_get_vq_desc_n - Fetch the next available descriptor chain and build iovecs 2797 * @vq: target virtqueue 2798 * @iov: array that receives the scatter/gather segments 2799 * @iov_size: capacity of @iov in elements 2800 * @out_num: the number of output segments 2801 * @in_num: the number of input segments 2802 * @log: optional array to record addr/len for each writable segment; NULL if unused 2803 * @log_num: optional output; number of entries written to @log when provided 2804 * @ndesc: optional output; number of descriptors consumed from the available ring 2805 * (useful for rollback via vhost_discard_vq_desc) 2806 * 2807 * Extracts one available descriptor chain from @vq and translates guest addresses 2808 * into host iovecs. 2809 * 2810 * On success, advances @vq->last_avail_idx by 1 and @vq->next_avail_head by the 2811 * number of descriptors consumed (also stored via @ndesc when non-NULL). 2812 * 2813 * Return: 2814 * - head index in [0, @vq->num) on success; 2815 * - @vq->num if no descriptor is currently available; 2816 * - negative errno on failure 2817 */ 2818 int vhost_get_vq_desc_n(struct vhost_virtqueue *vq, 2819 struct iovec iov[], unsigned int iov_size, 2820 unsigned int *out_num, unsigned int *in_num, 2821 struct vhost_log *log, unsigned int *log_num, 2822 unsigned int *ndesc) 2823 { 2824 bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER); 2825 struct vring_desc desc; 2826 unsigned int i, head, found = 0; 2827 u16 last_avail_idx = vq->last_avail_idx; 2828 __virtio16 ring_head; 2829 int ret, access, c = 0; 2830 2831 if (vq->avail_idx == vq->last_avail_idx) { 2832 ret = vhost_get_avail_idx(vq); 2833 if (unlikely(ret < 0)) 2834 return ret; 2835 2836 if (!ret) 2837 return vq->num; 2838 } 2839 2840 if (in_order) 2841 head = vq->next_avail_head & (vq->num - 1); 2842 else { 2843 /* Grab the next descriptor number they're 2844 * advertising, and increment the index we've seen. */ 2845 if (unlikely(vhost_get_avail_head(vq, &ring_head, 2846 last_avail_idx))) { 2847 vq_err(vq, "Failed to read head: idx %d address %p\n", 2848 last_avail_idx, 2849 &vq->avail->ring[last_avail_idx % vq->num]); 2850 return -EFAULT; 2851 } 2852 head = vhost16_to_cpu(vq, ring_head); 2853 } 2854 2855 /* If their number is silly, that's an error. */ 2856 if (unlikely(head >= vq->num)) { 2857 vq_err(vq, "Guest says index %u > %u is available", 2858 head, vq->num); 2859 return -EINVAL; 2860 } 2861 2862 /* When we start there are none of either input nor output. */ 2863 *out_num = *in_num = 0; 2864 if (unlikely(log)) 2865 *log_num = 0; 2866 2867 i = head; 2868 do { 2869 unsigned iov_count = *in_num + *out_num; 2870 if (unlikely(i >= vq->num)) { 2871 vq_err(vq, "Desc index is %u > %u, head = %u", 2872 i, vq->num, head); 2873 return -EINVAL; 2874 } 2875 if (unlikely(++found > vq->num)) { 2876 vq_err(vq, "Loop detected: last one at %u " 2877 "vq size %u head %u\n", 2878 i, vq->num, head); 2879 return -EINVAL; 2880 } 2881 ret = vhost_get_desc(vq, &desc, i); 2882 if (unlikely(ret)) { 2883 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n", 2884 i, vq->desc + i); 2885 return -EFAULT; 2886 } 2887 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) { 2888 ret = get_indirect(vq, iov, iov_size, 2889 out_num, in_num, 2890 log, log_num, &desc); 2891 if (unlikely(ret < 0)) { 2892 if (ret != -EAGAIN) 2893 vq_err(vq, "Failure detected " 2894 "in indirect descriptor at idx %d\n", i); 2895 return ret; 2896 } 2897 ++c; 2898 continue; 2899 } 2900 2901 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) 2902 access = VHOST_ACCESS_WO; 2903 else 2904 access = VHOST_ACCESS_RO; 2905 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr), 2906 vhost32_to_cpu(vq, desc.len), iov + iov_count, 2907 iov_size - iov_count, access); 2908 if (unlikely(ret < 0)) { 2909 if (ret != -EAGAIN) 2910 vq_err(vq, "Translation failure %d descriptor idx %d\n", 2911 ret, i); 2912 return ret; 2913 } 2914 if (access == VHOST_ACCESS_WO) { 2915 /* If this is an input descriptor, 2916 * increment that count. */ 2917 *in_num += ret; 2918 if (unlikely(log && ret)) { 2919 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr); 2920 log[*log_num].len = vhost32_to_cpu(vq, desc.len); 2921 ++*log_num; 2922 } 2923 } else { 2924 /* If it's an output descriptor, they're all supposed 2925 * to come before any input descriptors. */ 2926 if (unlikely(*in_num)) { 2927 vq_err(vq, "Descriptor has out after in: " 2928 "idx %d\n", i); 2929 return -EINVAL; 2930 } 2931 *out_num += ret; 2932 } 2933 ++c; 2934 } while ((i = next_desc(vq, &desc)) != -1); 2935 2936 /* On success, increment avail index. */ 2937 vq->last_avail_idx++; 2938 vq->next_avail_head += c; 2939 2940 if (ndesc) 2941 *ndesc = c; 2942 2943 /* Assume notifications from guest are disabled at this point, 2944 * if they aren't we would need to update avail_event index. */ 2945 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY)); 2946 return head; 2947 } 2948 EXPORT_SYMBOL_GPL(vhost_get_vq_desc_n); 2949 2950 /* This looks in the virtqueue and for the first available buffer, and converts 2951 * it to an iovec for convenient access. Since descriptors consist of some 2952 * number of output then some number of input descriptors, it's actually two 2953 * iovecs, but we pack them into one and note how many of each there were. 2954 * 2955 * This function returns the descriptor number found, or vq->num (which is 2956 * never a valid descriptor number) if none was found. A negative code is 2957 * returned on error. 2958 */ 2959 int vhost_get_vq_desc(struct vhost_virtqueue *vq, 2960 struct iovec iov[], unsigned int iov_size, 2961 unsigned int *out_num, unsigned int *in_num, 2962 struct vhost_log *log, unsigned int *log_num) 2963 { 2964 return vhost_get_vq_desc_n(vq, iov, iov_size, out_num, in_num, 2965 log, log_num, NULL); 2966 } 2967 EXPORT_SYMBOL_GPL(vhost_get_vq_desc); 2968 2969 /** 2970 * vhost_discard_vq_desc - Reverse the effect of vhost_get_vq_desc_n() 2971 * @vq: target virtqueue 2972 * @nbufs: number of buffers to roll back 2973 * @ndesc: number of descriptors to roll back 2974 * 2975 * Rewinds the internal consumer cursors after a failed attempt to use buffers 2976 * returned by vhost_get_vq_desc_n(). 2977 */ 2978 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int nbufs, 2979 unsigned int ndesc) 2980 { 2981 vq->next_avail_head -= ndesc; 2982 vq->last_avail_idx -= nbufs; 2983 } 2984 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc); 2985 2986 /* After we've used one of their buffers, we tell them about it. We'll then 2987 * want to notify the guest, using eventfd. */ 2988 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len) 2989 { 2990 struct vring_used_elem heads = { 2991 cpu_to_vhost32(vq, head), 2992 cpu_to_vhost32(vq, len) 2993 }; 2994 u16 nheads = 1; 2995 2996 return vhost_add_used_n(vq, &heads, &nheads, 1); 2997 } 2998 EXPORT_SYMBOL_GPL(vhost_add_used); 2999 3000 static int __vhost_add_used_n(struct vhost_virtqueue *vq, 3001 struct vring_used_elem *heads, 3002 unsigned count) 3003 { 3004 vring_used_elem_t __user *used; 3005 u16 old, new; 3006 int start; 3007 3008 start = vq->last_used_idx & (vq->num - 1); 3009 used = vq->used->ring + start; 3010 if (vhost_put_used(vq, heads, start, count)) { 3011 vq_err(vq, "Failed to write used"); 3012 return -EFAULT; 3013 } 3014 if (unlikely(vq->log_used)) { 3015 /* Make sure data is seen before log. */ 3016 smp_wmb(); 3017 /* Log used ring entry write. */ 3018 log_used(vq, ((void __user *)used - (void __user *)vq->used), 3019 count * sizeof *used); 3020 } 3021 old = vq->last_used_idx; 3022 new = (vq->last_used_idx += count); 3023 /* If the driver never bothers to signal in a very long while, 3024 * used index might wrap around. If that happens, invalidate 3025 * signalled_used index we stored. TODO: make sure driver 3026 * signals at least once in 2^16 and remove this. */ 3027 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old))) 3028 vq->signalled_used_valid = false; 3029 return 0; 3030 } 3031 3032 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq, 3033 struct vring_used_elem *heads, 3034 unsigned count) 3035 { 3036 int start, n, r; 3037 3038 start = vq->last_used_idx & (vq->num - 1); 3039 n = vq->num - start; 3040 if (n < count) { 3041 r = __vhost_add_used_n(vq, heads, n); 3042 if (r < 0) 3043 return r; 3044 heads += n; 3045 count -= n; 3046 } 3047 return __vhost_add_used_n(vq, heads, count); 3048 } 3049 3050 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, 3051 struct vring_used_elem *heads, 3052 const u16 *nheads, 3053 unsigned count) 3054 { 3055 vring_used_elem_t __user *used; 3056 u16 old, new = vq->last_used_idx; 3057 int start, i; 3058 3059 if (!nheads) 3060 return -EINVAL; 3061 3062 start = vq->last_used_idx & (vq->num - 1); 3063 used = vq->used->ring + start; 3064 3065 for (i = 0; i < count; i++) { 3066 if (vhost_put_used(vq, &heads[i], start, 1)) { 3067 vq_err(vq, "Failed to write used"); 3068 return -EFAULT; 3069 } 3070 start += nheads[i]; 3071 new += nheads[i]; 3072 if (start >= vq->num) 3073 start -= vq->num; 3074 } 3075 3076 if (unlikely(vq->log_used)) { 3077 /* Make sure data is seen before log. */ 3078 smp_wmb(); 3079 /* Log used ring entry write. */ 3080 log_used(vq, ((void __user *)used - (void __user *)vq->used), 3081 (vq->num - start) * sizeof *used); 3082 if (start + count > vq->num) 3083 log_used(vq, 0, 3084 (start + count - vq->num) * sizeof *used); 3085 } 3086 3087 old = vq->last_used_idx; 3088 vq->last_used_idx = new; 3089 /* If the driver never bothers to signal in a very long while, 3090 * used index might wrap around. If that happens, invalidate 3091 * signalled_used index we stored. TODO: make sure driver 3092 * signals at least once in 2^16 and remove this. */ 3093 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old))) 3094 vq->signalled_used_valid = false; 3095 return 0; 3096 } 3097 3098 /* After we've used one of their buffers, we tell them about it. We'll then 3099 * want to notify the guest, using eventfd. */ 3100 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads, 3101 u16 *nheads, unsigned count) 3102 { 3103 bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER); 3104 int r; 3105 3106 if (!in_order || !nheads) 3107 r = vhost_add_used_n_ooo(vq, heads, count); 3108 else 3109 r = vhost_add_used_n_in_order(vq, heads, nheads, count); 3110 3111 if (r < 0) 3112 return r; 3113 3114 /* Make sure buffer is written before we update index. */ 3115 smp_wmb(); 3116 if (vhost_put_used_idx(vq)) { 3117 vq_err(vq, "Failed to increment used idx"); 3118 return -EFAULT; 3119 } 3120 if (unlikely(vq->log_used)) { 3121 /* Make sure used idx is seen before log. */ 3122 smp_wmb(); 3123 /* Log used index update. */ 3124 log_used(vq, offsetof(struct vring_used, idx), 3125 sizeof vq->used->idx); 3126 if (vq->log_ctx) 3127 eventfd_signal(vq->log_ctx); 3128 } 3129 return r; 3130 } 3131 EXPORT_SYMBOL_GPL(vhost_add_used_n); 3132 3133 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3134 { 3135 __u16 old, new; 3136 __virtio16 event; 3137 bool v; 3138 /* Flush out used index updates. This is paired 3139 * with the barrier that the Guest executes when enabling 3140 * interrupts. */ 3141 smp_mb(); 3142 3143 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) && 3144 unlikely(vq->avail_idx == vq->last_avail_idx)) 3145 return true; 3146 3147 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3148 __virtio16 flags; 3149 if (vhost_get_avail_flags(vq, &flags)) { 3150 vq_err(vq, "Failed to get flags"); 3151 return true; 3152 } 3153 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT)); 3154 } 3155 old = vq->signalled_used; 3156 v = vq->signalled_used_valid; 3157 new = vq->signalled_used = vq->last_used_idx; 3158 vq->signalled_used_valid = true; 3159 3160 if (unlikely(!v)) 3161 return true; 3162 3163 if (vhost_get_used_event(vq, &event)) { 3164 vq_err(vq, "Failed to get used event idx"); 3165 return true; 3166 } 3167 return vring_need_event(vhost16_to_cpu(vq, event), new, old); 3168 } 3169 3170 /* This actually signals the guest, using eventfd. */ 3171 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3172 { 3173 /* Signal the Guest tell them we used something up. */ 3174 if (vq->call_ctx.ctx && vhost_notify(dev, vq)) 3175 eventfd_signal(vq->call_ctx.ctx); 3176 } 3177 EXPORT_SYMBOL_GPL(vhost_signal); 3178 3179 /* And here's the combo meal deal. Supersize me! */ 3180 void vhost_add_used_and_signal(struct vhost_dev *dev, 3181 struct vhost_virtqueue *vq, 3182 unsigned int head, int len) 3183 { 3184 vhost_add_used(vq, head, len); 3185 vhost_signal(dev, vq); 3186 } 3187 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal); 3188 3189 /* multi-buffer version of vhost_add_used_and_signal */ 3190 void vhost_add_used_and_signal_n(struct vhost_dev *dev, 3191 struct vhost_virtqueue *vq, 3192 struct vring_used_elem *heads, 3193 u16 *nheads, 3194 unsigned count) 3195 { 3196 vhost_add_used_n(vq, heads, nheads, count); 3197 vhost_signal(dev, vq); 3198 } 3199 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n); 3200 3201 /* return true if we're sure that available ring is empty */ 3202 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3203 { 3204 int r; 3205 3206 if (vq->avail_idx != vq->last_avail_idx) 3207 return false; 3208 3209 r = vhost_get_avail_idx(vq); 3210 3211 /* Note: we treat error as non-empty here */ 3212 return r == 0; 3213 } 3214 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty); 3215 3216 /* OK, now we need to know about added descriptors. */ 3217 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3218 { 3219 int r; 3220 3221 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY)) 3222 return false; 3223 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY; 3224 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3225 r = vhost_update_used_flags(vq); 3226 if (r) { 3227 vq_err(vq, "Failed to enable notification at %p: %d\n", 3228 &vq->used->flags, r); 3229 return false; 3230 } 3231 } else { 3232 r = vhost_update_avail_event(vq); 3233 if (r) { 3234 vq_err(vq, "Failed to update avail event index at %p: %d\n", 3235 vhost_avail_event(vq), r); 3236 return false; 3237 } 3238 } 3239 /* They could have slipped one in as we were doing that: make 3240 * sure it's written, then check again. */ 3241 smp_mb(); 3242 3243 r = vhost_get_avail_idx(vq); 3244 /* Note: we treat error as empty here */ 3245 if (unlikely(r < 0)) 3246 return false; 3247 3248 return r; 3249 } 3250 EXPORT_SYMBOL_GPL(vhost_enable_notify); 3251 3252 /* We don't need to be notified again. */ 3253 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) 3254 { 3255 int r; 3256 3257 if (vq->used_flags & VRING_USED_F_NO_NOTIFY) 3258 return; 3259 vq->used_flags |= VRING_USED_F_NO_NOTIFY; 3260 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { 3261 r = vhost_update_used_flags(vq); 3262 if (r) 3263 vq_err(vq, "Failed to disable notification at %p: %d\n", 3264 &vq->used->flags, r); 3265 } 3266 } 3267 EXPORT_SYMBOL_GPL(vhost_disable_notify); 3268 3269 /* Create a new message. */ 3270 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type) 3271 { 3272 /* Make sure all padding within the structure is initialized. */ 3273 struct vhost_msg_node *node = kzalloc_obj(*node); 3274 if (!node) 3275 return NULL; 3276 3277 node->vq = vq; 3278 node->msg.type = type; 3279 return node; 3280 } 3281 EXPORT_SYMBOL_GPL(vhost_new_msg); 3282 3283 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head, 3284 struct vhost_msg_node *node) 3285 { 3286 spin_lock(&dev->iotlb_lock); 3287 list_add_tail(&node->node, head); 3288 spin_unlock(&dev->iotlb_lock); 3289 3290 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM); 3291 } 3292 EXPORT_SYMBOL_GPL(vhost_enqueue_msg); 3293 3294 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev, 3295 struct list_head *head) 3296 { 3297 struct vhost_msg_node *node = NULL; 3298 3299 spin_lock(&dev->iotlb_lock); 3300 if (!list_empty(head)) { 3301 node = list_first_entry(head, struct vhost_msg_node, 3302 node); 3303 list_del(&node->node); 3304 } 3305 spin_unlock(&dev->iotlb_lock); 3306 3307 return node; 3308 } 3309 EXPORT_SYMBOL_GPL(vhost_dequeue_msg); 3310 3311 void vhost_set_backend_features(struct vhost_dev *dev, u64 features) 3312 { 3313 struct vhost_virtqueue *vq; 3314 int i; 3315 3316 mutex_lock(&dev->mutex); 3317 for (i = 0; i < dev->nvqs; ++i) { 3318 vq = dev->vqs[i]; 3319 mutex_lock(&vq->mutex); 3320 vq->acked_backend_features = features; 3321 mutex_unlock(&vq->mutex); 3322 } 3323 mutex_unlock(&dev->mutex); 3324 } 3325 EXPORT_SYMBOL_GPL(vhost_set_backend_features); 3326 3327 MODULE_VERSION("0.0.1"); 3328 MODULE_LICENSE("GPL v2"); 3329 MODULE_AUTHOR("Michael S. Tsirkin"); 3330 MODULE_DESCRIPTION("Host kernel accelerator for virtio"); 3331