1 /* 2 * Vhost User library 3 * 4 * Copyright IBM, Corp. 2007 5 * Copyright (c) 2016 Red Hat, Inc. 6 * 7 * Authors: 8 * Anthony Liguori <aliguori@us.ibm.com> 9 * Marc-André Lureau <mlureau@redhat.com> 10 * Victor Kaplansky <victork@redhat.com> 11 * 12 * This work is licensed under the terms of the GNU GPL, version 2 or 13 * later. See the COPYING file in the top-level directory. 14 */ 15 16 #ifndef _GNU_SOURCE 17 #define _GNU_SOURCE 18 #endif 19 20 /* this code avoids GLib dependency */ 21 #include <stdlib.h> 22 #include <stdio.h> 23 #include <unistd.h> 24 #include <stdarg.h> 25 #include <errno.h> 26 #include <string.h> 27 #include <assert.h> 28 #include <inttypes.h> 29 #include <sys/types.h> 30 #include <sys/socket.h> 31 #include <sys/eventfd.h> 32 #include <sys/mman.h> 33 #include <endian.h> 34 35 /* Necessary to provide VIRTIO_F_VERSION_1 on system 36 * with older linux headers. Must appear before 37 * <linux/vhost.h> below. 38 */ 39 #include "standard-headers/linux/virtio_config.h" 40 41 #if defined(__linux__) 42 #include <sys/syscall.h> 43 #include <fcntl.h> 44 #include <sys/ioctl.h> 45 #include <linux/vhost.h> 46 47 #ifdef __NR_userfaultfd 48 #include <linux/userfaultfd.h> 49 #endif 50 51 #endif 52 53 #include "include/atomic.h" 54 55 #include "libvhost-user.h" 56 57 /* usually provided by GLib */ 58 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4) 59 #if !defined(__clang__) && (__GNUC__ == 4 && __GNUC_MINOR__ == 4) 60 #define G_GNUC_PRINTF(format_idx, arg_idx) \ 61 __attribute__((__format__(gnu_printf, format_idx, arg_idx))) 62 #else 63 #define G_GNUC_PRINTF(format_idx, arg_idx) \ 64 __attribute__((__format__(__printf__, format_idx, arg_idx))) 65 #endif 66 #else /* !__GNUC__ */ 67 #define G_GNUC_PRINTF(format_idx, arg_idx) 68 #endif /* !__GNUC__ */ 69 #ifndef MIN 70 #define MIN(x, y) ({ \ 71 __typeof__(x) _min1 = (x); \ 72 __typeof__(y) _min2 = (y); \ 73 (void) (&_min1 == &_min2); \ 74 _min1 < _min2 ? _min1 : _min2; }) 75 #endif 76 77 /* Round number down to multiple */ 78 #define ALIGN_DOWN(n, m) ((n) / (m) * (m)) 79 80 /* Round number up to multiple */ 81 #define ALIGN_UP(n, m) ALIGN_DOWN((n) + (m) - 1, (m)) 82 83 #ifndef unlikely 84 #define unlikely(x) __builtin_expect(!!(x), 0) 85 #endif 86 87 /* Align each region to cache line size in inflight buffer */ 88 #define INFLIGHT_ALIGNMENT 64 89 90 /* The version of inflight buffer */ 91 #define INFLIGHT_VERSION 1 92 93 /* The version of the protocol we support */ 94 #define VHOST_USER_VERSION 1 95 #define LIBVHOST_USER_DEBUG 0 96 97 #define DPRINT(...) \ 98 do { \ 99 if (LIBVHOST_USER_DEBUG) { \ 100 fprintf(stderr, __VA_ARGS__); \ 101 } \ 102 } while (0) 103 104 static inline 105 bool has_feature(uint64_t features, unsigned int fbit) 106 { 107 assert(fbit < 64); 108 return !!(features & (1ULL << fbit)); 109 } 110 111 static inline 112 bool vu_has_feature(VuDev *dev, 113 unsigned int fbit) 114 { 115 return has_feature(dev->features, fbit); 116 } 117 118 static inline bool vu_has_protocol_feature(VuDev *dev, unsigned int fbit) 119 { 120 return has_feature(dev->protocol_features, fbit); 121 } 122 123 const char * 124 vu_request_to_string(unsigned int req) 125 { 126 #define REQ(req) [req] = #req 127 static const char *vu_request_str[] = { 128 REQ(VHOST_USER_NONE), 129 REQ(VHOST_USER_GET_FEATURES), 130 REQ(VHOST_USER_SET_FEATURES), 131 REQ(VHOST_USER_SET_OWNER), 132 REQ(VHOST_USER_RESET_OWNER), 133 REQ(VHOST_USER_SET_MEM_TABLE), 134 REQ(VHOST_USER_SET_LOG_BASE), 135 REQ(VHOST_USER_SET_LOG_FD), 136 REQ(VHOST_USER_SET_VRING_NUM), 137 REQ(VHOST_USER_SET_VRING_ADDR), 138 REQ(VHOST_USER_SET_VRING_BASE), 139 REQ(VHOST_USER_GET_VRING_BASE), 140 REQ(VHOST_USER_SET_VRING_KICK), 141 REQ(VHOST_USER_SET_VRING_CALL), 142 REQ(VHOST_USER_SET_VRING_ERR), 143 REQ(VHOST_USER_GET_PROTOCOL_FEATURES), 144 REQ(VHOST_USER_SET_PROTOCOL_FEATURES), 145 REQ(VHOST_USER_GET_QUEUE_NUM), 146 REQ(VHOST_USER_SET_VRING_ENABLE), 147 REQ(VHOST_USER_SEND_RARP), 148 REQ(VHOST_USER_NET_SET_MTU), 149 REQ(VHOST_USER_SET_BACKEND_REQ_FD), 150 REQ(VHOST_USER_IOTLB_MSG), 151 REQ(VHOST_USER_SET_VRING_ENDIAN), 152 REQ(VHOST_USER_GET_CONFIG), 153 REQ(VHOST_USER_SET_CONFIG), 154 REQ(VHOST_USER_POSTCOPY_ADVISE), 155 REQ(VHOST_USER_POSTCOPY_LISTEN), 156 REQ(VHOST_USER_POSTCOPY_END), 157 REQ(VHOST_USER_GET_INFLIGHT_FD), 158 REQ(VHOST_USER_SET_INFLIGHT_FD), 159 REQ(VHOST_USER_GPU_SET_SOCKET), 160 REQ(VHOST_USER_VRING_KICK), 161 REQ(VHOST_USER_GET_MAX_MEM_SLOTS), 162 REQ(VHOST_USER_ADD_MEM_REG), 163 REQ(VHOST_USER_REM_MEM_REG), 164 REQ(VHOST_USER_GET_SHARED_OBJECT), 165 REQ(VHOST_USER_MAX), 166 }; 167 #undef REQ 168 169 if (req < VHOST_USER_MAX) { 170 return vu_request_str[req]; 171 } else { 172 return "unknown"; 173 } 174 } 175 176 static void G_GNUC_PRINTF(2, 3) 177 vu_panic(VuDev *dev, const char *msg, ...) 178 { 179 char *buf = NULL; 180 va_list ap; 181 182 va_start(ap, msg); 183 if (vasprintf(&buf, msg, ap) < 0) { 184 buf = NULL; 185 } 186 va_end(ap); 187 188 dev->broken = true; 189 dev->panic(dev, buf); 190 free(buf); 191 192 /* 193 * FIXME: 194 * find a way to call virtio_error, or perhaps close the connection? 195 */ 196 } 197 198 /* Translate guest physical address to our virtual address. */ 199 void * 200 vu_gpa_to_va(VuDev *dev, uint64_t *plen, uint64_t guest_addr) 201 { 202 unsigned int i; 203 204 if (*plen == 0) { 205 return NULL; 206 } 207 208 /* Find matching memory region. */ 209 for (i = 0; i < dev->nregions; i++) { 210 VuDevRegion *r = &dev->regions[i]; 211 212 if ((guest_addr >= r->gpa) && (guest_addr < (r->gpa + r->size))) { 213 if ((guest_addr + *plen) > (r->gpa + r->size)) { 214 *plen = r->gpa + r->size - guest_addr; 215 } 216 return (void *)(uintptr_t) 217 guest_addr - r->gpa + r->mmap_addr + r->mmap_offset; 218 } 219 } 220 221 return NULL; 222 } 223 224 /* Translate qemu virtual address to our virtual address. */ 225 static void * 226 qva_to_va(VuDev *dev, uint64_t qemu_addr) 227 { 228 unsigned int i; 229 230 /* Find matching memory region. */ 231 for (i = 0; i < dev->nregions; i++) { 232 VuDevRegion *r = &dev->regions[i]; 233 234 if ((qemu_addr >= r->qva) && (qemu_addr < (r->qva + r->size))) { 235 return (void *)(uintptr_t) 236 qemu_addr - r->qva + r->mmap_addr + r->mmap_offset; 237 } 238 } 239 240 return NULL; 241 } 242 243 static void 244 vu_remove_all_mem_regs(VuDev *dev) 245 { 246 unsigned int i; 247 248 for (i = 0; i < dev->nregions; i++) { 249 VuDevRegion *r = &dev->regions[i]; 250 void *ma = (void *)(uintptr_t)r->mmap_addr; 251 252 if (ma) { 253 munmap(ma, r->size + r->mmap_offset); 254 } 255 } 256 dev->nregions = 0; 257 } 258 259 static void 260 vmsg_close_fds(VhostUserMsg *vmsg) 261 { 262 int i; 263 264 for (i = 0; i < vmsg->fd_num; i++) { 265 close(vmsg->fds[i]); 266 } 267 } 268 269 /* Set reply payload.u64 and clear request flags and fd_num */ 270 static void vmsg_set_reply_u64(VhostUserMsg *vmsg, uint64_t val) 271 { 272 vmsg->flags = 0; /* defaults will be set by vu_send_reply() */ 273 vmsg->size = sizeof(vmsg->payload.u64); 274 vmsg->payload.u64 = val; 275 vmsg->fd_num = 0; 276 } 277 278 /* A test to see if we have userfault available */ 279 static bool 280 have_userfault(void) 281 { 282 #if defined(__linux__) && defined(__NR_userfaultfd) &&\ 283 defined(UFFD_FEATURE_MISSING_SHMEM) &&\ 284 defined(UFFD_FEATURE_MISSING_HUGETLBFS) 285 /* Now test the kernel we're running on really has the features */ 286 int ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK); 287 struct uffdio_api api_struct; 288 if (ufd < 0) { 289 return false; 290 } 291 292 api_struct.api = UFFD_API; 293 api_struct.features = UFFD_FEATURE_MISSING_SHMEM | 294 UFFD_FEATURE_MISSING_HUGETLBFS; 295 if (ioctl(ufd, UFFDIO_API, &api_struct)) { 296 close(ufd); 297 return false; 298 } 299 close(ufd); 300 return true; 301 302 #else 303 return false; 304 #endif 305 } 306 307 static bool 308 vu_message_read_default(VuDev *dev, int conn_fd, VhostUserMsg *vmsg) 309 { 310 char control[CMSG_SPACE(VHOST_MEMORY_BASELINE_NREGIONS * sizeof(int))] = {}; 311 struct iovec iov = { 312 .iov_base = (char *)vmsg, 313 .iov_len = VHOST_USER_HDR_SIZE, 314 }; 315 struct msghdr msg = { 316 .msg_iov = &iov, 317 .msg_iovlen = 1, 318 .msg_control = control, 319 .msg_controllen = sizeof(control), 320 }; 321 size_t fd_size; 322 struct cmsghdr *cmsg; 323 int rc; 324 325 do { 326 rc = recvmsg(conn_fd, &msg, 0); 327 } while (rc < 0 && (errno == EINTR || errno == EAGAIN)); 328 329 if (rc < 0) { 330 vu_panic(dev, "Error while recvmsg: %s", strerror(errno)); 331 return false; 332 } 333 334 vmsg->fd_num = 0; 335 for (cmsg = CMSG_FIRSTHDR(&msg); 336 cmsg != NULL; 337 cmsg = CMSG_NXTHDR(&msg, cmsg)) 338 { 339 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { 340 fd_size = cmsg->cmsg_len - CMSG_LEN(0); 341 vmsg->fd_num = fd_size / sizeof(int); 342 assert(fd_size < VHOST_MEMORY_BASELINE_NREGIONS); 343 memcpy(vmsg->fds, CMSG_DATA(cmsg), fd_size); 344 break; 345 } 346 } 347 348 if (vmsg->size > sizeof(vmsg->payload)) { 349 vu_panic(dev, 350 "Error: too big message request: %d, size: vmsg->size: %u, " 351 "while sizeof(vmsg->payload) = %zu\n", 352 vmsg->request, vmsg->size, sizeof(vmsg->payload)); 353 goto fail; 354 } 355 356 if (vmsg->size) { 357 do { 358 rc = read(conn_fd, &vmsg->payload, vmsg->size); 359 } while (rc < 0 && (errno == EINTR || errno == EAGAIN)); 360 361 if (rc <= 0) { 362 vu_panic(dev, "Error while reading: %s", strerror(errno)); 363 goto fail; 364 } 365 366 assert((uint32_t)rc == vmsg->size); 367 } 368 369 return true; 370 371 fail: 372 vmsg_close_fds(vmsg); 373 374 return false; 375 } 376 377 static bool 378 vu_message_write(VuDev *dev, int conn_fd, VhostUserMsg *vmsg) 379 { 380 int rc; 381 uint8_t *p = (uint8_t *)vmsg; 382 char control[CMSG_SPACE(VHOST_MEMORY_BASELINE_NREGIONS * sizeof(int))] = {}; 383 struct iovec iov = { 384 .iov_base = (char *)vmsg, 385 .iov_len = VHOST_USER_HDR_SIZE, 386 }; 387 struct msghdr msg = { 388 .msg_iov = &iov, 389 .msg_iovlen = 1, 390 .msg_control = control, 391 }; 392 struct cmsghdr *cmsg; 393 394 memset(control, 0, sizeof(control)); 395 assert(vmsg->fd_num <= VHOST_MEMORY_BASELINE_NREGIONS); 396 if (vmsg->fd_num > 0) { 397 size_t fdsize = vmsg->fd_num * sizeof(int); 398 msg.msg_controllen = CMSG_SPACE(fdsize); 399 cmsg = CMSG_FIRSTHDR(&msg); 400 cmsg->cmsg_len = CMSG_LEN(fdsize); 401 cmsg->cmsg_level = SOL_SOCKET; 402 cmsg->cmsg_type = SCM_RIGHTS; 403 memcpy(CMSG_DATA(cmsg), vmsg->fds, fdsize); 404 } else { 405 msg.msg_controllen = 0; 406 } 407 408 do { 409 rc = sendmsg(conn_fd, &msg, 0); 410 } while (rc < 0 && (errno == EINTR || errno == EAGAIN)); 411 412 if (vmsg->size) { 413 do { 414 if (vmsg->data) { 415 rc = write(conn_fd, vmsg->data, vmsg->size); 416 } else { 417 rc = write(conn_fd, p + VHOST_USER_HDR_SIZE, vmsg->size); 418 } 419 } while (rc < 0 && (errno == EINTR || errno == EAGAIN)); 420 } 421 422 if (rc <= 0) { 423 vu_panic(dev, "Error while writing: %s", strerror(errno)); 424 return false; 425 } 426 427 return true; 428 } 429 430 static bool 431 vu_send_reply(VuDev *dev, int conn_fd, VhostUserMsg *vmsg) 432 { 433 /* Set the version in the flags when sending the reply */ 434 vmsg->flags &= ~VHOST_USER_VERSION_MASK; 435 vmsg->flags |= VHOST_USER_VERSION; 436 vmsg->flags |= VHOST_USER_REPLY_MASK; 437 438 return vu_message_write(dev, conn_fd, vmsg); 439 } 440 441 /* 442 * Processes a reply on the backend channel. 443 * Entered with backend_mutex held and releases it before exit. 444 * Returns true on success. 445 */ 446 static bool 447 vu_process_message_reply(VuDev *dev, const VhostUserMsg *vmsg) 448 { 449 VhostUserMsg msg_reply; 450 bool result = false; 451 452 if ((vmsg->flags & VHOST_USER_NEED_REPLY_MASK) == 0) { 453 result = true; 454 goto out; 455 } 456 457 if (!vu_message_read_default(dev, dev->backend_fd, &msg_reply)) { 458 goto out; 459 } 460 461 if (msg_reply.request != vmsg->request) { 462 DPRINT("Received unexpected msg type. Expected %d received %d", 463 vmsg->request, msg_reply.request); 464 goto out; 465 } 466 467 result = msg_reply.payload.u64 == 0; 468 469 out: 470 pthread_mutex_unlock(&dev->backend_mutex); 471 return result; 472 } 473 474 /* Kick the log_call_fd if required. */ 475 static void 476 vu_log_kick(VuDev *dev) 477 { 478 if (dev->log_call_fd != -1) { 479 DPRINT("Kicking the QEMU's log...\n"); 480 if (eventfd_write(dev->log_call_fd, 1) < 0) { 481 vu_panic(dev, "Error writing eventfd: %s", strerror(errno)); 482 } 483 } 484 } 485 486 static void 487 vu_log_page(uint8_t *log_table, uint64_t page) 488 { 489 DPRINT("Logged dirty guest page: %"PRId64"\n", page); 490 qatomic_or(&log_table[page / 8], 1 << (page % 8)); 491 } 492 493 static void 494 vu_log_write(VuDev *dev, uint64_t address, uint64_t length) 495 { 496 uint64_t page; 497 498 if (!(dev->features & (1ULL << VHOST_F_LOG_ALL)) || 499 !dev->log_table || !length) { 500 return; 501 } 502 503 assert(dev->log_size > ((address + length - 1) / VHOST_LOG_PAGE / 8)); 504 505 page = address / VHOST_LOG_PAGE; 506 while (page * VHOST_LOG_PAGE < address + length) { 507 vu_log_page(dev->log_table, page); 508 page += 1; 509 } 510 511 vu_log_kick(dev); 512 } 513 514 static void 515 vu_kick_cb(VuDev *dev, int condition, void *data) 516 { 517 int index = (intptr_t)data; 518 VuVirtq *vq = &dev->vq[index]; 519 int sock = vq->kick_fd; 520 eventfd_t kick_data; 521 ssize_t rc; 522 523 rc = eventfd_read(sock, &kick_data); 524 if (rc == -1) { 525 vu_panic(dev, "kick eventfd_read(): %s", strerror(errno)); 526 dev->remove_watch(dev, dev->vq[index].kick_fd); 527 } else { 528 DPRINT("Got kick_data: %016"PRIx64" handler:%p idx:%d\n", 529 kick_data, vq->handler, index); 530 if (vq->handler) { 531 vq->handler(dev, index); 532 } 533 } 534 } 535 536 static bool 537 vu_get_features_exec(VuDev *dev, VhostUserMsg *vmsg) 538 { 539 vmsg->payload.u64 = 540 /* 541 * The following VIRTIO feature bits are supported by our virtqueue 542 * implementation: 543 */ 544 1ULL << VIRTIO_F_NOTIFY_ON_EMPTY | 545 1ULL << VIRTIO_RING_F_INDIRECT_DESC | 546 1ULL << VIRTIO_RING_F_EVENT_IDX | 547 1ULL << VIRTIO_F_VERSION_1 | 548 549 /* vhost-user feature bits */ 550 1ULL << VHOST_F_LOG_ALL | 551 1ULL << VHOST_USER_F_PROTOCOL_FEATURES; 552 553 if (dev->iface->get_features) { 554 vmsg->payload.u64 |= dev->iface->get_features(dev); 555 } 556 557 vmsg->size = sizeof(vmsg->payload.u64); 558 vmsg->fd_num = 0; 559 560 DPRINT("Sending back to guest u64: 0x%016"PRIx64"\n", vmsg->payload.u64); 561 562 return true; 563 } 564 565 static void 566 vu_set_enable_all_rings(VuDev *dev, bool enabled) 567 { 568 uint16_t i; 569 570 for (i = 0; i < dev->max_queues; i++) { 571 dev->vq[i].enable = enabled; 572 } 573 } 574 575 static bool 576 vu_set_features_exec(VuDev *dev, VhostUserMsg *vmsg) 577 { 578 DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64); 579 580 dev->features = vmsg->payload.u64; 581 if (!vu_has_feature(dev, VIRTIO_F_VERSION_1)) { 582 /* 583 * We only support devices conforming to VIRTIO 1.0 or 584 * later 585 */ 586 vu_panic(dev, "virtio legacy devices aren't supported by libvhost-user"); 587 return false; 588 } 589 590 if (!(dev->features & VHOST_USER_F_PROTOCOL_FEATURES)) { 591 vu_set_enable_all_rings(dev, true); 592 } 593 594 if (dev->iface->set_features) { 595 dev->iface->set_features(dev, dev->features); 596 } 597 598 return false; 599 } 600 601 static bool 602 vu_set_owner_exec(VuDev *dev, VhostUserMsg *vmsg) 603 { 604 return false; 605 } 606 607 static void 608 vu_close_log(VuDev *dev) 609 { 610 if (dev->log_table) { 611 if (munmap(dev->log_table, dev->log_size) != 0) { 612 perror("close log munmap() error"); 613 } 614 615 dev->log_table = NULL; 616 } 617 if (dev->log_call_fd != -1) { 618 close(dev->log_call_fd); 619 dev->log_call_fd = -1; 620 } 621 } 622 623 static bool 624 vu_reset_device_exec(VuDev *dev, VhostUserMsg *vmsg) 625 { 626 vu_set_enable_all_rings(dev, false); 627 628 return false; 629 } 630 631 static bool 632 map_ring(VuDev *dev, VuVirtq *vq) 633 { 634 vq->vring.desc = qva_to_va(dev, vq->vra.desc_user_addr); 635 vq->vring.used = qva_to_va(dev, vq->vra.used_user_addr); 636 vq->vring.avail = qva_to_va(dev, vq->vra.avail_user_addr); 637 638 DPRINT("Setting virtq addresses:\n"); 639 DPRINT(" vring_desc at %p\n", vq->vring.desc); 640 DPRINT(" vring_used at %p\n", vq->vring.used); 641 DPRINT(" vring_avail at %p\n", vq->vring.avail); 642 643 return !(vq->vring.desc && vq->vring.used && vq->vring.avail); 644 } 645 646 static bool 647 generate_faults(VuDev *dev) { 648 unsigned int i; 649 for (i = 0; i < dev->nregions; i++) { 650 #ifdef UFFDIO_REGISTER 651 VuDevRegion *dev_region = &dev->regions[i]; 652 int ret; 653 struct uffdio_register reg_struct; 654 655 /* 656 * We should already have an open ufd. Mark each memory 657 * range as ufd. 658 * Discard any mapping we have here; note I can't use MADV_REMOVE 659 * or fallocate to make the hole since I don't want to lose 660 * data that's already arrived in the shared process. 661 * TODO: How to do hugepage 662 */ 663 ret = madvise((void *)(uintptr_t)dev_region->mmap_addr, 664 dev_region->size + dev_region->mmap_offset, 665 MADV_DONTNEED); 666 if (ret) { 667 fprintf(stderr, 668 "%s: Failed to madvise(DONTNEED) region %d: %s\n", 669 __func__, i, strerror(errno)); 670 } 671 /* 672 * Turn off transparent hugepages so we dont get lose wakeups 673 * in neighbouring pages. 674 * TODO: Turn this backon later. 675 */ 676 ret = madvise((void *)(uintptr_t)dev_region->mmap_addr, 677 dev_region->size + dev_region->mmap_offset, 678 MADV_NOHUGEPAGE); 679 if (ret) { 680 /* 681 * Note: This can happen legally on kernels that are configured 682 * without madvise'able hugepages 683 */ 684 fprintf(stderr, 685 "%s: Failed to madvise(NOHUGEPAGE) region %d: %s\n", 686 __func__, i, strerror(errno)); 687 } 688 689 reg_struct.range.start = (uintptr_t)dev_region->mmap_addr; 690 reg_struct.range.len = dev_region->size + dev_region->mmap_offset; 691 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING; 692 693 if (ioctl(dev->postcopy_ufd, UFFDIO_REGISTER, ®_struct)) { 694 vu_panic(dev, "%s: Failed to userfault region %d " 695 "@%" PRIx64 " + size:%" PRIx64 " offset: %" PRIx64 696 ": (ufd=%d)%s\n", 697 __func__, i, 698 dev_region->mmap_addr, 699 dev_region->size, dev_region->mmap_offset, 700 dev->postcopy_ufd, strerror(errno)); 701 return false; 702 } 703 if (!(reg_struct.ioctls & (1ULL << _UFFDIO_COPY))) { 704 vu_panic(dev, "%s Region (%d) doesn't support COPY", 705 __func__, i); 706 return false; 707 } 708 DPRINT("%s: region %d: Registered userfault for %" 709 PRIx64 " + %" PRIx64 "\n", __func__, i, 710 (uint64_t)reg_struct.range.start, 711 (uint64_t)reg_struct.range.len); 712 /* Now it's registered we can let the client at it */ 713 if (mprotect((void *)(uintptr_t)dev_region->mmap_addr, 714 dev_region->size + dev_region->mmap_offset, 715 PROT_READ | PROT_WRITE)) { 716 vu_panic(dev, "failed to mprotect region %d for postcopy (%s)", 717 i, strerror(errno)); 718 return false; 719 } 720 /* TODO: Stash 'zero' support flags somewhere */ 721 #endif 722 } 723 724 return true; 725 } 726 727 static bool 728 vu_add_mem_reg(VuDev *dev, VhostUserMsg *vmsg) { 729 int i; 730 bool track_ramblocks = dev->postcopy_listening; 731 VhostUserMemoryRegion m = vmsg->payload.memreg.region, *msg_region = &m; 732 VuDevRegion *dev_region = &dev->regions[dev->nregions]; 733 void *mmap_addr; 734 735 if (vmsg->fd_num != 1) { 736 vmsg_close_fds(vmsg); 737 vu_panic(dev, "VHOST_USER_ADD_MEM_REG received %d fds - only 1 fd " 738 "should be sent for this message type", vmsg->fd_num); 739 return false; 740 } 741 742 if (vmsg->size < VHOST_USER_MEM_REG_SIZE) { 743 close(vmsg->fds[0]); 744 vu_panic(dev, "VHOST_USER_ADD_MEM_REG requires a message size of at " 745 "least %zu bytes and only %d bytes were received", 746 VHOST_USER_MEM_REG_SIZE, vmsg->size); 747 return false; 748 } 749 750 if (dev->nregions == VHOST_USER_MAX_RAM_SLOTS) { 751 close(vmsg->fds[0]); 752 vu_panic(dev, "failing attempt to hot add memory via " 753 "VHOST_USER_ADD_MEM_REG message because the backend has " 754 "no free ram slots available"); 755 return false; 756 } 757 758 /* 759 * If we are in postcopy mode and we receive a u64 payload with a 0 value 760 * we know all the postcopy client bases have been received, and we 761 * should start generating faults. 762 */ 763 if (track_ramblocks && 764 vmsg->size == sizeof(vmsg->payload.u64) && 765 vmsg->payload.u64 == 0) { 766 (void)generate_faults(dev); 767 return false; 768 } 769 770 DPRINT("Adding region: %u\n", dev->nregions); 771 DPRINT(" guest_phys_addr: 0x%016"PRIx64"\n", 772 msg_region->guest_phys_addr); 773 DPRINT(" memory_size: 0x%016"PRIx64"\n", 774 msg_region->memory_size); 775 DPRINT(" userspace_addr 0x%016"PRIx64"\n", 776 msg_region->userspace_addr); 777 DPRINT(" mmap_offset 0x%016"PRIx64"\n", 778 msg_region->mmap_offset); 779 780 dev_region->gpa = msg_region->guest_phys_addr; 781 dev_region->size = msg_region->memory_size; 782 dev_region->qva = msg_region->userspace_addr; 783 dev_region->mmap_offset = msg_region->mmap_offset; 784 785 /* 786 * We don't use offset argument of mmap() since the 787 * mapped address has to be page aligned, and we use huge 788 * pages. 789 */ 790 if (track_ramblocks) { 791 /* 792 * In postcopy we're using PROT_NONE here to catch anyone 793 * accessing it before we userfault. 794 */ 795 mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset, 796 PROT_NONE, MAP_SHARED | MAP_NORESERVE, 797 vmsg->fds[0], 0); 798 } else { 799 mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset, 800 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, 801 vmsg->fds[0], 0); 802 } 803 804 if (mmap_addr == MAP_FAILED) { 805 vu_panic(dev, "region mmap error: %s", strerror(errno)); 806 } else { 807 dev_region->mmap_addr = (uint64_t)(uintptr_t)mmap_addr; 808 DPRINT(" mmap_addr: 0x%016"PRIx64"\n", 809 dev_region->mmap_addr); 810 } 811 812 close(vmsg->fds[0]); 813 814 if (track_ramblocks) { 815 /* 816 * Return the address to QEMU so that it can translate the ufd 817 * fault addresses back. 818 */ 819 msg_region->userspace_addr = (uintptr_t)(mmap_addr + 820 dev_region->mmap_offset); 821 822 /* Send the message back to qemu with the addresses filled in. */ 823 vmsg->fd_num = 0; 824 DPRINT("Successfully added new region in postcopy\n"); 825 dev->nregions++; 826 return true; 827 } else { 828 for (i = 0; i < dev->max_queues; i++) { 829 if (dev->vq[i].vring.desc) { 830 if (map_ring(dev, &dev->vq[i])) { 831 vu_panic(dev, "remapping queue %d for new memory region", 832 i); 833 } 834 } 835 } 836 837 DPRINT("Successfully added new region\n"); 838 dev->nregions++; 839 return false; 840 } 841 } 842 843 static inline bool reg_equal(VuDevRegion *vudev_reg, 844 VhostUserMemoryRegion *msg_reg) 845 { 846 if (vudev_reg->gpa == msg_reg->guest_phys_addr && 847 vudev_reg->qva == msg_reg->userspace_addr && 848 vudev_reg->size == msg_reg->memory_size) { 849 return true; 850 } 851 852 return false; 853 } 854 855 static bool 856 vu_rem_mem_reg(VuDev *dev, VhostUserMsg *vmsg) { 857 VhostUserMemoryRegion m = vmsg->payload.memreg.region, *msg_region = &m; 858 unsigned int i; 859 bool found = false; 860 861 if (vmsg->fd_num > 1) { 862 vmsg_close_fds(vmsg); 863 vu_panic(dev, "VHOST_USER_REM_MEM_REG received %d fds - at most 1 fd " 864 "should be sent for this message type", vmsg->fd_num); 865 return false; 866 } 867 868 if (vmsg->size < VHOST_USER_MEM_REG_SIZE) { 869 vmsg_close_fds(vmsg); 870 vu_panic(dev, "VHOST_USER_REM_MEM_REG requires a message size of at " 871 "least %zu bytes and only %d bytes were received", 872 VHOST_USER_MEM_REG_SIZE, vmsg->size); 873 return false; 874 } 875 876 DPRINT("Removing region:\n"); 877 DPRINT(" guest_phys_addr: 0x%016"PRIx64"\n", 878 msg_region->guest_phys_addr); 879 DPRINT(" memory_size: 0x%016"PRIx64"\n", 880 msg_region->memory_size); 881 DPRINT(" userspace_addr 0x%016"PRIx64"\n", 882 msg_region->userspace_addr); 883 DPRINT(" mmap_offset 0x%016"PRIx64"\n", 884 msg_region->mmap_offset); 885 886 for (i = 0; i < dev->nregions; i++) { 887 if (reg_equal(&dev->regions[i], msg_region)) { 888 VuDevRegion *r = &dev->regions[i]; 889 void *ma = (void *) (uintptr_t) r->mmap_addr; 890 891 if (ma) { 892 munmap(ma, r->size + r->mmap_offset); 893 } 894 895 /* 896 * Shift all affected entries by 1 to close the hole at index i and 897 * zero out the last entry. 898 */ 899 memmove(dev->regions + i, dev->regions + i + 1, 900 sizeof(VuDevRegion) * (dev->nregions - i - 1)); 901 memset(dev->regions + dev->nregions - 1, 0, sizeof(VuDevRegion)); 902 DPRINT("Successfully removed a region\n"); 903 dev->nregions--; 904 i--; 905 906 found = true; 907 908 /* Continue the search for eventual duplicates. */ 909 } 910 } 911 912 if (!found) { 913 vu_panic(dev, "Specified region not found\n"); 914 } 915 916 vmsg_close_fds(vmsg); 917 918 return false; 919 } 920 921 static bool 922 vu_get_shared_object(VuDev *dev, VhostUserMsg *vmsg) 923 { 924 int fd_num = 0; 925 int dmabuf_fd = -1; 926 if (dev->iface->get_shared_object) { 927 dmabuf_fd = dev->iface->get_shared_object( 928 dev, &vmsg->payload.object.uuid[0]); 929 } 930 if (dmabuf_fd != -1) { 931 DPRINT("dmabuf_fd found for requested UUID\n"); 932 vmsg->fds[fd_num++] = dmabuf_fd; 933 } 934 vmsg->fd_num = fd_num; 935 936 return true; 937 } 938 939 static bool 940 vu_set_mem_table_exec_postcopy(VuDev *dev, VhostUserMsg *vmsg) 941 { 942 unsigned int i; 943 VhostUserMemory m = vmsg->payload.memory, *memory = &m; 944 dev->nregions = memory->nregions; 945 946 DPRINT("Nregions: %u\n", memory->nregions); 947 for (i = 0; i < dev->nregions; i++) { 948 void *mmap_addr; 949 VhostUserMemoryRegion *msg_region = &memory->regions[i]; 950 VuDevRegion *dev_region = &dev->regions[i]; 951 952 DPRINT("Region %d\n", i); 953 DPRINT(" guest_phys_addr: 0x%016"PRIx64"\n", 954 msg_region->guest_phys_addr); 955 DPRINT(" memory_size: 0x%016"PRIx64"\n", 956 msg_region->memory_size); 957 DPRINT(" userspace_addr 0x%016"PRIx64"\n", 958 msg_region->userspace_addr); 959 DPRINT(" mmap_offset 0x%016"PRIx64"\n", 960 msg_region->mmap_offset); 961 962 dev_region->gpa = msg_region->guest_phys_addr; 963 dev_region->size = msg_region->memory_size; 964 dev_region->qva = msg_region->userspace_addr; 965 dev_region->mmap_offset = msg_region->mmap_offset; 966 967 /* We don't use offset argument of mmap() since the 968 * mapped address has to be page aligned, and we use huge 969 * pages. 970 * In postcopy we're using PROT_NONE here to catch anyone 971 * accessing it before we userfault 972 */ 973 mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset, 974 PROT_NONE, MAP_SHARED | MAP_NORESERVE, 975 vmsg->fds[i], 0); 976 977 if (mmap_addr == MAP_FAILED) { 978 vu_panic(dev, "region mmap error: %s", strerror(errno)); 979 } else { 980 dev_region->mmap_addr = (uint64_t)(uintptr_t)mmap_addr; 981 DPRINT(" mmap_addr: 0x%016"PRIx64"\n", 982 dev_region->mmap_addr); 983 } 984 985 /* Return the address to QEMU so that it can translate the ufd 986 * fault addresses back. 987 */ 988 msg_region->userspace_addr = (uintptr_t)(mmap_addr + 989 dev_region->mmap_offset); 990 close(vmsg->fds[i]); 991 } 992 993 /* Send the message back to qemu with the addresses filled in */ 994 vmsg->fd_num = 0; 995 if (!vu_send_reply(dev, dev->sock, vmsg)) { 996 vu_panic(dev, "failed to respond to set-mem-table for postcopy"); 997 return false; 998 } 999 1000 /* Wait for QEMU to confirm that it's registered the handler for the 1001 * faults. 1002 */ 1003 if (!dev->read_msg(dev, dev->sock, vmsg) || 1004 vmsg->size != sizeof(vmsg->payload.u64) || 1005 vmsg->payload.u64 != 0) { 1006 vu_panic(dev, "failed to receive valid ack for postcopy set-mem-table"); 1007 return false; 1008 } 1009 1010 /* OK, now we can go and register the memory and generate faults */ 1011 (void)generate_faults(dev); 1012 1013 return false; 1014 } 1015 1016 static bool 1017 vu_set_mem_table_exec(VuDev *dev, VhostUserMsg *vmsg) 1018 { 1019 unsigned int i; 1020 VhostUserMemory m = vmsg->payload.memory, *memory = &m; 1021 1022 vu_remove_all_mem_regs(dev); 1023 dev->nregions = memory->nregions; 1024 1025 if (dev->postcopy_listening) { 1026 return vu_set_mem_table_exec_postcopy(dev, vmsg); 1027 } 1028 1029 DPRINT("Nregions: %u\n", memory->nregions); 1030 for (i = 0; i < dev->nregions; i++) { 1031 void *mmap_addr; 1032 VhostUserMemoryRegion *msg_region = &memory->regions[i]; 1033 VuDevRegion *dev_region = &dev->regions[i]; 1034 1035 DPRINT("Region %d\n", i); 1036 DPRINT(" guest_phys_addr: 0x%016"PRIx64"\n", 1037 msg_region->guest_phys_addr); 1038 DPRINT(" memory_size: 0x%016"PRIx64"\n", 1039 msg_region->memory_size); 1040 DPRINT(" userspace_addr 0x%016"PRIx64"\n", 1041 msg_region->userspace_addr); 1042 DPRINT(" mmap_offset 0x%016"PRIx64"\n", 1043 msg_region->mmap_offset); 1044 1045 dev_region->gpa = msg_region->guest_phys_addr; 1046 dev_region->size = msg_region->memory_size; 1047 dev_region->qva = msg_region->userspace_addr; 1048 dev_region->mmap_offset = msg_region->mmap_offset; 1049 1050 /* We don't use offset argument of mmap() since the 1051 * mapped address has to be page aligned, and we use huge 1052 * pages. */ 1053 mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset, 1054 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, 1055 vmsg->fds[i], 0); 1056 1057 if (mmap_addr == MAP_FAILED) { 1058 vu_panic(dev, "region mmap error: %s", strerror(errno)); 1059 } else { 1060 dev_region->mmap_addr = (uint64_t)(uintptr_t)mmap_addr; 1061 DPRINT(" mmap_addr: 0x%016"PRIx64"\n", 1062 dev_region->mmap_addr); 1063 } 1064 1065 close(vmsg->fds[i]); 1066 } 1067 1068 for (i = 0; i < dev->max_queues; i++) { 1069 if (dev->vq[i].vring.desc) { 1070 if (map_ring(dev, &dev->vq[i])) { 1071 vu_panic(dev, "remapping queue %d during setmemtable", i); 1072 } 1073 } 1074 } 1075 1076 return false; 1077 } 1078 1079 static bool 1080 vu_set_log_base_exec(VuDev *dev, VhostUserMsg *vmsg) 1081 { 1082 int fd; 1083 uint64_t log_mmap_size, log_mmap_offset; 1084 void *rc; 1085 1086 if (vmsg->fd_num != 1 || 1087 vmsg->size != sizeof(vmsg->payload.log)) { 1088 vu_panic(dev, "Invalid log_base message"); 1089 return true; 1090 } 1091 1092 fd = vmsg->fds[0]; 1093 log_mmap_offset = vmsg->payload.log.mmap_offset; 1094 log_mmap_size = vmsg->payload.log.mmap_size; 1095 DPRINT("Log mmap_offset: %"PRId64"\n", log_mmap_offset); 1096 DPRINT("Log mmap_size: %"PRId64"\n", log_mmap_size); 1097 1098 rc = mmap(0, log_mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 1099 log_mmap_offset); 1100 close(fd); 1101 if (rc == MAP_FAILED) { 1102 perror("log mmap error"); 1103 } 1104 1105 if (dev->log_table) { 1106 munmap(dev->log_table, dev->log_size); 1107 } 1108 dev->log_table = rc; 1109 dev->log_size = log_mmap_size; 1110 1111 vmsg->size = sizeof(vmsg->payload.u64); 1112 vmsg->fd_num = 0; 1113 1114 return true; 1115 } 1116 1117 static bool 1118 vu_set_log_fd_exec(VuDev *dev, VhostUserMsg *vmsg) 1119 { 1120 if (vmsg->fd_num != 1) { 1121 vu_panic(dev, "Invalid log_fd message"); 1122 return false; 1123 } 1124 1125 if (dev->log_call_fd != -1) { 1126 close(dev->log_call_fd); 1127 } 1128 dev->log_call_fd = vmsg->fds[0]; 1129 DPRINT("Got log_call_fd: %d\n", vmsg->fds[0]); 1130 1131 return false; 1132 } 1133 1134 static bool 1135 vu_set_vring_num_exec(VuDev *dev, VhostUserMsg *vmsg) 1136 { 1137 unsigned int index = vmsg->payload.state.index; 1138 unsigned int num = vmsg->payload.state.num; 1139 1140 DPRINT("State.index: %u\n", index); 1141 DPRINT("State.num: %u\n", num); 1142 dev->vq[index].vring.num = num; 1143 1144 return false; 1145 } 1146 1147 static bool 1148 vu_set_vring_addr_exec(VuDev *dev, VhostUserMsg *vmsg) 1149 { 1150 struct vhost_vring_addr addr = vmsg->payload.addr, *vra = &addr; 1151 unsigned int index = vra->index; 1152 VuVirtq *vq = &dev->vq[index]; 1153 1154 DPRINT("vhost_vring_addr:\n"); 1155 DPRINT(" index: %d\n", vra->index); 1156 DPRINT(" flags: %d\n", vra->flags); 1157 DPRINT(" desc_user_addr: 0x%016" PRIx64 "\n", (uint64_t)vra->desc_user_addr); 1158 DPRINT(" used_user_addr: 0x%016" PRIx64 "\n", (uint64_t)vra->used_user_addr); 1159 DPRINT(" avail_user_addr: 0x%016" PRIx64 "\n", (uint64_t)vra->avail_user_addr); 1160 DPRINT(" log_guest_addr: 0x%016" PRIx64 "\n", (uint64_t)vra->log_guest_addr); 1161 1162 vq->vra = *vra; 1163 vq->vring.flags = vra->flags; 1164 vq->vring.log_guest_addr = vra->log_guest_addr; 1165 1166 1167 if (map_ring(dev, vq)) { 1168 vu_panic(dev, "Invalid vring_addr message"); 1169 return false; 1170 } 1171 1172 vq->used_idx = le16toh(vq->vring.used->idx); 1173 1174 if (vq->last_avail_idx != vq->used_idx) { 1175 bool resume = dev->iface->queue_is_processed_in_order && 1176 dev->iface->queue_is_processed_in_order(dev, index); 1177 1178 DPRINT("Last avail index != used index: %u != %u%s\n", 1179 vq->last_avail_idx, vq->used_idx, 1180 resume ? ", resuming" : ""); 1181 1182 if (resume) { 1183 vq->shadow_avail_idx = vq->last_avail_idx = vq->used_idx; 1184 } 1185 } 1186 1187 return false; 1188 } 1189 1190 static bool 1191 vu_set_vring_base_exec(VuDev *dev, VhostUserMsg *vmsg) 1192 { 1193 unsigned int index = vmsg->payload.state.index; 1194 unsigned int num = vmsg->payload.state.num; 1195 1196 DPRINT("State.index: %u\n", index); 1197 DPRINT("State.num: %u\n", num); 1198 dev->vq[index].shadow_avail_idx = dev->vq[index].last_avail_idx = num; 1199 1200 return false; 1201 } 1202 1203 static bool 1204 vu_get_vring_base_exec(VuDev *dev, VhostUserMsg *vmsg) 1205 { 1206 unsigned int index = vmsg->payload.state.index; 1207 1208 DPRINT("State.index: %u\n", index); 1209 vmsg->payload.state.num = dev->vq[index].last_avail_idx; 1210 vmsg->size = sizeof(vmsg->payload.state); 1211 1212 dev->vq[index].started = false; 1213 if (dev->iface->queue_set_started) { 1214 dev->iface->queue_set_started(dev, index, false); 1215 } 1216 1217 if (dev->vq[index].call_fd != -1) { 1218 close(dev->vq[index].call_fd); 1219 dev->vq[index].call_fd = -1; 1220 } 1221 if (dev->vq[index].kick_fd != -1) { 1222 dev->remove_watch(dev, dev->vq[index].kick_fd); 1223 close(dev->vq[index].kick_fd); 1224 dev->vq[index].kick_fd = -1; 1225 } 1226 1227 return true; 1228 } 1229 1230 static bool 1231 vu_check_queue_msg_file(VuDev *dev, VhostUserMsg *vmsg) 1232 { 1233 int index = vmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK; 1234 bool nofd = vmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK; 1235 1236 if (index >= dev->max_queues) { 1237 vmsg_close_fds(vmsg); 1238 vu_panic(dev, "Invalid queue index: %u", index); 1239 return false; 1240 } 1241 1242 if (nofd) { 1243 vmsg_close_fds(vmsg); 1244 return true; 1245 } 1246 1247 if (vmsg->fd_num != 1) { 1248 vmsg_close_fds(vmsg); 1249 vu_panic(dev, "Invalid fds in request: %d", vmsg->request); 1250 return false; 1251 } 1252 1253 return true; 1254 } 1255 1256 static int 1257 inflight_desc_compare(const void *a, const void *b) 1258 { 1259 VuVirtqInflightDesc *desc0 = (VuVirtqInflightDesc *)a, 1260 *desc1 = (VuVirtqInflightDesc *)b; 1261 1262 if (desc1->counter > desc0->counter && 1263 (desc1->counter - desc0->counter) < VIRTQUEUE_MAX_SIZE * 2) { 1264 return 1; 1265 } 1266 1267 return -1; 1268 } 1269 1270 static int 1271 vu_check_queue_inflights(VuDev *dev, VuVirtq *vq) 1272 { 1273 int i = 0; 1274 1275 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) { 1276 return 0; 1277 } 1278 1279 if (unlikely(!vq->inflight)) { 1280 return -1; 1281 } 1282 1283 if (unlikely(!vq->inflight->version)) { 1284 /* initialize the buffer */ 1285 vq->inflight->version = INFLIGHT_VERSION; 1286 return 0; 1287 } 1288 1289 vq->used_idx = le16toh(vq->vring.used->idx); 1290 vq->resubmit_num = 0; 1291 vq->resubmit_list = NULL; 1292 vq->counter = 0; 1293 1294 if (unlikely(vq->inflight->used_idx != vq->used_idx)) { 1295 vq->inflight->desc[vq->inflight->last_batch_head].inflight = 0; 1296 1297 barrier(); 1298 1299 vq->inflight->used_idx = vq->used_idx; 1300 } 1301 1302 for (i = 0; i < vq->inflight->desc_num; i++) { 1303 if (vq->inflight->desc[i].inflight == 1) { 1304 vq->inuse++; 1305 } 1306 } 1307 1308 vq->shadow_avail_idx = vq->last_avail_idx = vq->inuse + vq->used_idx; 1309 1310 if (vq->inuse) { 1311 vq->resubmit_list = calloc(vq->inuse, sizeof(VuVirtqInflightDesc)); 1312 if (!vq->resubmit_list) { 1313 return -1; 1314 } 1315 1316 for (i = 0; i < vq->inflight->desc_num; i++) { 1317 if (vq->inflight->desc[i].inflight) { 1318 vq->resubmit_list[vq->resubmit_num].index = i; 1319 vq->resubmit_list[vq->resubmit_num].counter = 1320 vq->inflight->desc[i].counter; 1321 vq->resubmit_num++; 1322 } 1323 } 1324 1325 if (vq->resubmit_num > 1) { 1326 qsort(vq->resubmit_list, vq->resubmit_num, 1327 sizeof(VuVirtqInflightDesc), inflight_desc_compare); 1328 } 1329 vq->counter = vq->resubmit_list[0].counter + 1; 1330 } 1331 1332 /* in case of I/O hang after reconnecting */ 1333 if (eventfd_write(vq->kick_fd, 1)) { 1334 return -1; 1335 } 1336 1337 return 0; 1338 } 1339 1340 static bool 1341 vu_set_vring_kick_exec(VuDev *dev, VhostUserMsg *vmsg) 1342 { 1343 int index = vmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK; 1344 bool nofd = vmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK; 1345 1346 DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64); 1347 1348 if (!vu_check_queue_msg_file(dev, vmsg)) { 1349 return false; 1350 } 1351 1352 if (dev->vq[index].kick_fd != -1) { 1353 dev->remove_watch(dev, dev->vq[index].kick_fd); 1354 close(dev->vq[index].kick_fd); 1355 dev->vq[index].kick_fd = -1; 1356 } 1357 1358 dev->vq[index].kick_fd = nofd ? -1 : vmsg->fds[0]; 1359 DPRINT("Got kick_fd: %d for vq: %d\n", dev->vq[index].kick_fd, index); 1360 1361 dev->vq[index].started = true; 1362 if (dev->iface->queue_set_started) { 1363 dev->iface->queue_set_started(dev, index, true); 1364 } 1365 1366 if (dev->vq[index].kick_fd != -1 && dev->vq[index].handler) { 1367 dev->set_watch(dev, dev->vq[index].kick_fd, VU_WATCH_IN, 1368 vu_kick_cb, (void *)(long)index); 1369 1370 DPRINT("Waiting for kicks on fd: %d for vq: %d\n", 1371 dev->vq[index].kick_fd, index); 1372 } 1373 1374 if (vu_check_queue_inflights(dev, &dev->vq[index])) { 1375 vu_panic(dev, "Failed to check inflights for vq: %d\n", index); 1376 } 1377 1378 return false; 1379 } 1380 1381 void vu_set_queue_handler(VuDev *dev, VuVirtq *vq, 1382 vu_queue_handler_cb handler) 1383 { 1384 int qidx = vq - dev->vq; 1385 1386 vq->handler = handler; 1387 if (vq->kick_fd >= 0) { 1388 if (handler) { 1389 dev->set_watch(dev, vq->kick_fd, VU_WATCH_IN, 1390 vu_kick_cb, (void *)(long)qidx); 1391 } else { 1392 dev->remove_watch(dev, vq->kick_fd); 1393 } 1394 } 1395 } 1396 1397 bool vu_set_queue_host_notifier(VuDev *dev, VuVirtq *vq, int fd, 1398 int size, int offset) 1399 { 1400 int qidx = vq - dev->vq; 1401 int fd_num = 0; 1402 VhostUserMsg vmsg = { 1403 .request = VHOST_USER_BACKEND_VRING_HOST_NOTIFIER_MSG, 1404 .flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY_MASK, 1405 .size = sizeof(vmsg.payload.area), 1406 .payload.area = { 1407 .u64 = qidx & VHOST_USER_VRING_IDX_MASK, 1408 .size = size, 1409 .offset = offset, 1410 }, 1411 }; 1412 1413 if (fd == -1) { 1414 vmsg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK; 1415 } else { 1416 vmsg.fds[fd_num++] = fd; 1417 } 1418 1419 vmsg.fd_num = fd_num; 1420 1421 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_BACKEND_SEND_FD)) { 1422 return false; 1423 } 1424 1425 pthread_mutex_lock(&dev->backend_mutex); 1426 if (!vu_message_write(dev, dev->backend_fd, &vmsg)) { 1427 pthread_mutex_unlock(&dev->backend_mutex); 1428 return false; 1429 } 1430 1431 /* Also unlocks the backend_mutex */ 1432 return vu_process_message_reply(dev, &vmsg); 1433 } 1434 1435 bool 1436 vu_lookup_shared_object(VuDev *dev, unsigned char uuid[UUID_LEN], 1437 int *dmabuf_fd) 1438 { 1439 bool result = false; 1440 VhostUserMsg msg_reply; 1441 VhostUserMsg msg = { 1442 .request = VHOST_USER_BACKEND_SHARED_OBJECT_LOOKUP, 1443 .size = sizeof(msg.payload.object), 1444 .flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY_MASK, 1445 }; 1446 1447 memcpy(msg.payload.object.uuid, uuid, sizeof(uuid[0]) * UUID_LEN); 1448 1449 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_SHARED_OBJECT)) { 1450 return false; 1451 } 1452 1453 pthread_mutex_lock(&dev->backend_mutex); 1454 if (!vu_message_write(dev, dev->backend_fd, &msg)) { 1455 goto out; 1456 } 1457 1458 if (!vu_message_read_default(dev, dev->backend_fd, &msg_reply)) { 1459 goto out; 1460 } 1461 1462 if (msg_reply.request != msg.request) { 1463 DPRINT("Received unexpected msg type. Expected %d, received %d", 1464 msg.request, msg_reply.request); 1465 goto out; 1466 } 1467 1468 if (msg_reply.fd_num != 1) { 1469 DPRINT("Received unexpected number of fds. Expected 1, received %d", 1470 msg_reply.fd_num); 1471 goto out; 1472 } 1473 1474 *dmabuf_fd = msg_reply.fds[0]; 1475 result = *dmabuf_fd > 0 && msg_reply.payload.u64 == 0; 1476 out: 1477 pthread_mutex_unlock(&dev->backend_mutex); 1478 1479 return result; 1480 } 1481 1482 static bool 1483 vu_send_message(VuDev *dev, VhostUserMsg *vmsg) 1484 { 1485 bool result = false; 1486 pthread_mutex_lock(&dev->backend_mutex); 1487 if (!vu_message_write(dev, dev->backend_fd, vmsg)) { 1488 goto out; 1489 } 1490 1491 result = true; 1492 out: 1493 pthread_mutex_unlock(&dev->backend_mutex); 1494 1495 return result; 1496 } 1497 1498 bool 1499 vu_add_shared_object(VuDev *dev, unsigned char uuid[UUID_LEN]) 1500 { 1501 VhostUserMsg msg = { 1502 .request = VHOST_USER_BACKEND_SHARED_OBJECT_ADD, 1503 .size = sizeof(msg.payload.object), 1504 .flags = VHOST_USER_VERSION, 1505 }; 1506 1507 memcpy(msg.payload.object.uuid, uuid, sizeof(uuid[0]) * UUID_LEN); 1508 1509 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_SHARED_OBJECT)) { 1510 return false; 1511 } 1512 1513 return vu_send_message(dev, &msg); 1514 } 1515 1516 bool 1517 vu_rm_shared_object(VuDev *dev, unsigned char uuid[UUID_LEN]) 1518 { 1519 VhostUserMsg msg = { 1520 .request = VHOST_USER_BACKEND_SHARED_OBJECT_REMOVE, 1521 .size = sizeof(msg.payload.object), 1522 .flags = VHOST_USER_VERSION, 1523 }; 1524 1525 memcpy(msg.payload.object.uuid, uuid, sizeof(uuid[0]) * UUID_LEN); 1526 1527 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_SHARED_OBJECT)) { 1528 return false; 1529 } 1530 1531 return vu_send_message(dev, &msg); 1532 } 1533 1534 static bool 1535 vu_set_vring_call_exec(VuDev *dev, VhostUserMsg *vmsg) 1536 { 1537 int index = vmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK; 1538 bool nofd = vmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK; 1539 1540 DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64); 1541 1542 if (!vu_check_queue_msg_file(dev, vmsg)) { 1543 return false; 1544 } 1545 1546 if (dev->vq[index].call_fd != -1) { 1547 close(dev->vq[index].call_fd); 1548 dev->vq[index].call_fd = -1; 1549 } 1550 1551 dev->vq[index].call_fd = nofd ? -1 : vmsg->fds[0]; 1552 1553 /* in case of I/O hang after reconnecting */ 1554 if (dev->vq[index].call_fd != -1 && eventfd_write(vmsg->fds[0], 1)) { 1555 return -1; 1556 } 1557 1558 DPRINT("Got call_fd: %d for vq: %d\n", dev->vq[index].call_fd, index); 1559 1560 return false; 1561 } 1562 1563 static bool 1564 vu_set_vring_err_exec(VuDev *dev, VhostUserMsg *vmsg) 1565 { 1566 int index = vmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK; 1567 bool nofd = vmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK; 1568 1569 DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64); 1570 1571 if (!vu_check_queue_msg_file(dev, vmsg)) { 1572 return false; 1573 } 1574 1575 if (dev->vq[index].err_fd != -1) { 1576 close(dev->vq[index].err_fd); 1577 dev->vq[index].err_fd = -1; 1578 } 1579 1580 dev->vq[index].err_fd = nofd ? -1 : vmsg->fds[0]; 1581 1582 return false; 1583 } 1584 1585 static bool 1586 vu_get_protocol_features_exec(VuDev *dev, VhostUserMsg *vmsg) 1587 { 1588 /* 1589 * Note that we support, but intentionally do not set, 1590 * VHOST_USER_PROTOCOL_F_INBAND_NOTIFICATIONS. This means that 1591 * a device implementation can return it in its callback 1592 * (get_protocol_features) if it wants to use this for 1593 * simulation, but it is otherwise not desirable (if even 1594 * implemented by the frontend.) 1595 */ 1596 uint64_t features = 1ULL << VHOST_USER_PROTOCOL_F_MQ | 1597 1ULL << VHOST_USER_PROTOCOL_F_LOG_SHMFD | 1598 1ULL << VHOST_USER_PROTOCOL_F_BACKEND_REQ | 1599 1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER | 1600 1ULL << VHOST_USER_PROTOCOL_F_BACKEND_SEND_FD | 1601 1ULL << VHOST_USER_PROTOCOL_F_REPLY_ACK | 1602 1ULL << VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTS; 1603 1604 if (have_userfault()) { 1605 features |= 1ULL << VHOST_USER_PROTOCOL_F_PAGEFAULT; 1606 } 1607 1608 if (dev->iface->get_config && dev->iface->set_config) { 1609 features |= 1ULL << VHOST_USER_PROTOCOL_F_CONFIG; 1610 } 1611 1612 if (dev->iface->get_protocol_features) { 1613 features |= dev->iface->get_protocol_features(dev); 1614 } 1615 1616 vmsg_set_reply_u64(vmsg, features); 1617 return true; 1618 } 1619 1620 static bool 1621 vu_set_protocol_features_exec(VuDev *dev, VhostUserMsg *vmsg) 1622 { 1623 uint64_t features = vmsg->payload.u64; 1624 1625 DPRINT("u64: 0x%016"PRIx64"\n", features); 1626 1627 dev->protocol_features = vmsg->payload.u64; 1628 1629 if (vu_has_protocol_feature(dev, 1630 VHOST_USER_PROTOCOL_F_INBAND_NOTIFICATIONS) && 1631 (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_BACKEND_REQ) || 1632 !vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_REPLY_ACK))) { 1633 /* 1634 * The use case for using messages for kick/call is simulation, to make 1635 * the kick and call synchronous. To actually get that behaviour, both 1636 * of the other features are required. 1637 * Theoretically, one could use only kick messages, or do them without 1638 * having F_REPLY_ACK, but too many (possibly pending) messages on the 1639 * socket will eventually cause the frontend to hang, to avoid this in 1640 * scenarios where not desired enforce that the settings are in a way 1641 * that actually enables the simulation case. 1642 */ 1643 vu_panic(dev, 1644 "F_IN_BAND_NOTIFICATIONS requires F_BACKEND_REQ && F_REPLY_ACK"); 1645 return false; 1646 } 1647 1648 if (dev->iface->set_protocol_features) { 1649 dev->iface->set_protocol_features(dev, features); 1650 } 1651 1652 return false; 1653 } 1654 1655 static bool 1656 vu_get_queue_num_exec(VuDev *dev, VhostUserMsg *vmsg) 1657 { 1658 vmsg_set_reply_u64(vmsg, dev->max_queues); 1659 return true; 1660 } 1661 1662 static bool 1663 vu_set_vring_enable_exec(VuDev *dev, VhostUserMsg *vmsg) 1664 { 1665 unsigned int index = vmsg->payload.state.index; 1666 unsigned int enable = vmsg->payload.state.num; 1667 1668 DPRINT("State.index: %u\n", index); 1669 DPRINT("State.enable: %u\n", enable); 1670 1671 if (index >= dev->max_queues) { 1672 vu_panic(dev, "Invalid vring_enable index: %u", index); 1673 return false; 1674 } 1675 1676 dev->vq[index].enable = enable; 1677 return false; 1678 } 1679 1680 static bool 1681 vu_set_backend_req_fd(VuDev *dev, VhostUserMsg *vmsg) 1682 { 1683 if (vmsg->fd_num != 1) { 1684 vu_panic(dev, "Invalid backend_req_fd message (%d fd's)", vmsg->fd_num); 1685 return false; 1686 } 1687 1688 if (dev->backend_fd != -1) { 1689 close(dev->backend_fd); 1690 } 1691 dev->backend_fd = vmsg->fds[0]; 1692 DPRINT("Got backend_fd: %d\n", vmsg->fds[0]); 1693 1694 return false; 1695 } 1696 1697 static bool 1698 vu_get_config(VuDev *dev, VhostUserMsg *vmsg) 1699 { 1700 int ret = -1; 1701 1702 if (dev->iface->get_config) { 1703 ret = dev->iface->get_config(dev, vmsg->payload.config.region, 1704 vmsg->payload.config.size); 1705 } 1706 1707 if (ret) { 1708 /* resize to zero to indicate an error to frontend */ 1709 vmsg->size = 0; 1710 } 1711 1712 return true; 1713 } 1714 1715 static bool 1716 vu_set_config(VuDev *dev, VhostUserMsg *vmsg) 1717 { 1718 int ret = -1; 1719 1720 if (dev->iface->set_config) { 1721 ret = dev->iface->set_config(dev, vmsg->payload.config.region, 1722 vmsg->payload.config.offset, 1723 vmsg->payload.config.size, 1724 vmsg->payload.config.flags); 1725 if (ret) { 1726 vu_panic(dev, "Set virtio configuration space failed"); 1727 } 1728 } 1729 1730 return false; 1731 } 1732 1733 static bool 1734 vu_set_postcopy_advise(VuDev *dev, VhostUserMsg *vmsg) 1735 { 1736 #ifdef UFFDIO_API 1737 struct uffdio_api api_struct; 1738 1739 dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK); 1740 vmsg->size = 0; 1741 #else 1742 dev->postcopy_ufd = -1; 1743 #endif 1744 1745 if (dev->postcopy_ufd == -1) { 1746 vu_panic(dev, "Userfaultfd not available: %s", strerror(errno)); 1747 goto out; 1748 } 1749 1750 #ifdef UFFDIO_API 1751 api_struct.api = UFFD_API; 1752 api_struct.features = 0; 1753 if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) { 1754 vu_panic(dev, "Failed UFFDIO_API: %s", strerror(errno)); 1755 close(dev->postcopy_ufd); 1756 dev->postcopy_ufd = -1; 1757 goto out; 1758 } 1759 /* TODO: Stash feature flags somewhere */ 1760 #endif 1761 1762 out: 1763 /* Return a ufd to the QEMU */ 1764 vmsg->fd_num = 1; 1765 vmsg->fds[0] = dev->postcopy_ufd; 1766 return true; /* = send a reply */ 1767 } 1768 1769 static bool 1770 vu_set_postcopy_listen(VuDev *dev, VhostUserMsg *vmsg) 1771 { 1772 if (dev->nregions) { 1773 vu_panic(dev, "Regions already registered at postcopy-listen"); 1774 vmsg_set_reply_u64(vmsg, -1); 1775 return true; 1776 } 1777 dev->postcopy_listening = true; 1778 1779 vmsg_set_reply_u64(vmsg, 0); 1780 return true; 1781 } 1782 1783 static bool 1784 vu_set_postcopy_end(VuDev *dev, VhostUserMsg *vmsg) 1785 { 1786 DPRINT("%s: Entry\n", __func__); 1787 dev->postcopy_listening = false; 1788 if (dev->postcopy_ufd > 0) { 1789 close(dev->postcopy_ufd); 1790 dev->postcopy_ufd = -1; 1791 DPRINT("%s: Done close\n", __func__); 1792 } 1793 1794 vmsg_set_reply_u64(vmsg, 0); 1795 DPRINT("%s: exit\n", __func__); 1796 return true; 1797 } 1798 1799 static inline uint64_t 1800 vu_inflight_queue_size(uint16_t queue_size) 1801 { 1802 return ALIGN_UP(sizeof(VuDescStateSplit) * queue_size + 1803 sizeof(uint16_t), INFLIGHT_ALIGNMENT); 1804 } 1805 1806 #ifdef MFD_ALLOW_SEALING 1807 static void * 1808 memfd_alloc(const char *name, size_t size, unsigned int flags, int *fd) 1809 { 1810 void *ptr; 1811 int ret; 1812 1813 *fd = memfd_create(name, MFD_ALLOW_SEALING); 1814 if (*fd < 0) { 1815 return NULL; 1816 } 1817 1818 ret = ftruncate(*fd, size); 1819 if (ret < 0) { 1820 close(*fd); 1821 return NULL; 1822 } 1823 1824 ret = fcntl(*fd, F_ADD_SEALS, flags); 1825 if (ret < 0) { 1826 close(*fd); 1827 return NULL; 1828 } 1829 1830 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0); 1831 if (ptr == MAP_FAILED) { 1832 close(*fd); 1833 return NULL; 1834 } 1835 1836 return ptr; 1837 } 1838 #endif 1839 1840 static bool 1841 vu_get_inflight_fd(VuDev *dev, VhostUserMsg *vmsg) 1842 { 1843 int fd = -1; 1844 void *addr = NULL; 1845 uint64_t mmap_size; 1846 uint16_t num_queues, queue_size; 1847 1848 if (vmsg->size != sizeof(vmsg->payload.inflight)) { 1849 vu_panic(dev, "Invalid get_inflight_fd message:%d", vmsg->size); 1850 vmsg->payload.inflight.mmap_size = 0; 1851 return true; 1852 } 1853 1854 num_queues = vmsg->payload.inflight.num_queues; 1855 queue_size = vmsg->payload.inflight.queue_size; 1856 1857 DPRINT("set_inflight_fd num_queues: %"PRId16"\n", num_queues); 1858 DPRINT("set_inflight_fd queue_size: %"PRId16"\n", queue_size); 1859 1860 mmap_size = vu_inflight_queue_size(queue_size) * num_queues; 1861 1862 #ifdef MFD_ALLOW_SEALING 1863 addr = memfd_alloc("vhost-inflight", mmap_size, 1864 F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL, 1865 &fd); 1866 #else 1867 vu_panic(dev, "Not implemented: memfd support is missing"); 1868 #endif 1869 1870 if (!addr) { 1871 vu_panic(dev, "Failed to alloc vhost inflight area"); 1872 vmsg->payload.inflight.mmap_size = 0; 1873 return true; 1874 } 1875 1876 memset(addr, 0, mmap_size); 1877 1878 dev->inflight_info.addr = addr; 1879 dev->inflight_info.size = vmsg->payload.inflight.mmap_size = mmap_size; 1880 dev->inflight_info.fd = vmsg->fds[0] = fd; 1881 vmsg->fd_num = 1; 1882 vmsg->payload.inflight.mmap_offset = 0; 1883 1884 DPRINT("send inflight mmap_size: %"PRId64"\n", 1885 vmsg->payload.inflight.mmap_size); 1886 DPRINT("send inflight mmap offset: %"PRId64"\n", 1887 vmsg->payload.inflight.mmap_offset); 1888 1889 return true; 1890 } 1891 1892 static bool 1893 vu_set_inflight_fd(VuDev *dev, VhostUserMsg *vmsg) 1894 { 1895 int fd, i; 1896 uint64_t mmap_size, mmap_offset; 1897 uint16_t num_queues, queue_size; 1898 void *rc; 1899 1900 if (vmsg->fd_num != 1 || 1901 vmsg->size != sizeof(vmsg->payload.inflight)) { 1902 vu_panic(dev, "Invalid set_inflight_fd message size:%d fds:%d", 1903 vmsg->size, vmsg->fd_num); 1904 return false; 1905 } 1906 1907 fd = vmsg->fds[0]; 1908 mmap_size = vmsg->payload.inflight.mmap_size; 1909 mmap_offset = vmsg->payload.inflight.mmap_offset; 1910 num_queues = vmsg->payload.inflight.num_queues; 1911 queue_size = vmsg->payload.inflight.queue_size; 1912 1913 DPRINT("set_inflight_fd mmap_size: %"PRId64"\n", mmap_size); 1914 DPRINT("set_inflight_fd mmap_offset: %"PRId64"\n", mmap_offset); 1915 DPRINT("set_inflight_fd num_queues: %"PRId16"\n", num_queues); 1916 DPRINT("set_inflight_fd queue_size: %"PRId16"\n", queue_size); 1917 1918 rc = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, 1919 fd, mmap_offset); 1920 1921 if (rc == MAP_FAILED) { 1922 vu_panic(dev, "set_inflight_fd mmap error: %s", strerror(errno)); 1923 return false; 1924 } 1925 1926 if (dev->inflight_info.fd) { 1927 close(dev->inflight_info.fd); 1928 } 1929 1930 if (dev->inflight_info.addr) { 1931 munmap(dev->inflight_info.addr, dev->inflight_info.size); 1932 } 1933 1934 dev->inflight_info.fd = fd; 1935 dev->inflight_info.addr = rc; 1936 dev->inflight_info.size = mmap_size; 1937 1938 for (i = 0; i < num_queues; i++) { 1939 dev->vq[i].inflight = (VuVirtqInflight *)rc; 1940 dev->vq[i].inflight->desc_num = queue_size; 1941 rc = (void *)((char *)rc + vu_inflight_queue_size(queue_size)); 1942 } 1943 1944 return false; 1945 } 1946 1947 static bool 1948 vu_handle_vring_kick(VuDev *dev, VhostUserMsg *vmsg) 1949 { 1950 unsigned int index = vmsg->payload.state.index; 1951 1952 if (index >= dev->max_queues) { 1953 vu_panic(dev, "Invalid queue index: %u", index); 1954 return false; 1955 } 1956 1957 DPRINT("Got kick message: handler:%p idx:%u\n", 1958 dev->vq[index].handler, index); 1959 1960 if (!dev->vq[index].started) { 1961 dev->vq[index].started = true; 1962 1963 if (dev->iface->queue_set_started) { 1964 dev->iface->queue_set_started(dev, index, true); 1965 } 1966 } 1967 1968 if (dev->vq[index].handler) { 1969 dev->vq[index].handler(dev, index); 1970 } 1971 1972 return false; 1973 } 1974 1975 static bool vu_handle_get_max_memslots(VuDev *dev, VhostUserMsg *vmsg) 1976 { 1977 vmsg_set_reply_u64(vmsg, VHOST_USER_MAX_RAM_SLOTS); 1978 1979 DPRINT("u64: 0x%016"PRIx64"\n", (uint64_t) VHOST_USER_MAX_RAM_SLOTS); 1980 1981 return true; 1982 } 1983 1984 static bool 1985 vu_process_message(VuDev *dev, VhostUserMsg *vmsg) 1986 { 1987 int do_reply = 0; 1988 1989 /* Print out generic part of the request. */ 1990 DPRINT("================ Vhost user message ================\n"); 1991 DPRINT("Request: %s (%d)\n", vu_request_to_string(vmsg->request), 1992 vmsg->request); 1993 DPRINT("Flags: 0x%x\n", vmsg->flags); 1994 DPRINT("Size: %u\n", vmsg->size); 1995 1996 if (vmsg->fd_num) { 1997 int i; 1998 DPRINT("Fds:"); 1999 for (i = 0; i < vmsg->fd_num; i++) { 2000 DPRINT(" %d", vmsg->fds[i]); 2001 } 2002 DPRINT("\n"); 2003 } 2004 2005 if (dev->iface->process_msg && 2006 dev->iface->process_msg(dev, vmsg, &do_reply)) { 2007 return do_reply; 2008 } 2009 2010 switch (vmsg->request) { 2011 case VHOST_USER_GET_FEATURES: 2012 return vu_get_features_exec(dev, vmsg); 2013 case VHOST_USER_SET_FEATURES: 2014 return vu_set_features_exec(dev, vmsg); 2015 case VHOST_USER_GET_PROTOCOL_FEATURES: 2016 return vu_get_protocol_features_exec(dev, vmsg); 2017 case VHOST_USER_SET_PROTOCOL_FEATURES: 2018 return vu_set_protocol_features_exec(dev, vmsg); 2019 case VHOST_USER_SET_OWNER: 2020 return vu_set_owner_exec(dev, vmsg); 2021 case VHOST_USER_RESET_OWNER: 2022 return vu_reset_device_exec(dev, vmsg); 2023 case VHOST_USER_SET_MEM_TABLE: 2024 return vu_set_mem_table_exec(dev, vmsg); 2025 case VHOST_USER_SET_LOG_BASE: 2026 return vu_set_log_base_exec(dev, vmsg); 2027 case VHOST_USER_SET_LOG_FD: 2028 return vu_set_log_fd_exec(dev, vmsg); 2029 case VHOST_USER_SET_VRING_NUM: 2030 return vu_set_vring_num_exec(dev, vmsg); 2031 case VHOST_USER_SET_VRING_ADDR: 2032 return vu_set_vring_addr_exec(dev, vmsg); 2033 case VHOST_USER_SET_VRING_BASE: 2034 return vu_set_vring_base_exec(dev, vmsg); 2035 case VHOST_USER_GET_VRING_BASE: 2036 return vu_get_vring_base_exec(dev, vmsg); 2037 case VHOST_USER_SET_VRING_KICK: 2038 return vu_set_vring_kick_exec(dev, vmsg); 2039 case VHOST_USER_SET_VRING_CALL: 2040 return vu_set_vring_call_exec(dev, vmsg); 2041 case VHOST_USER_SET_VRING_ERR: 2042 return vu_set_vring_err_exec(dev, vmsg); 2043 case VHOST_USER_GET_QUEUE_NUM: 2044 return vu_get_queue_num_exec(dev, vmsg); 2045 case VHOST_USER_SET_VRING_ENABLE: 2046 return vu_set_vring_enable_exec(dev, vmsg); 2047 case VHOST_USER_SET_BACKEND_REQ_FD: 2048 return vu_set_backend_req_fd(dev, vmsg); 2049 case VHOST_USER_GET_CONFIG: 2050 return vu_get_config(dev, vmsg); 2051 case VHOST_USER_SET_CONFIG: 2052 return vu_set_config(dev, vmsg); 2053 case VHOST_USER_NONE: 2054 /* if you need processing before exit, override iface->process_msg */ 2055 exit(0); 2056 case VHOST_USER_POSTCOPY_ADVISE: 2057 return vu_set_postcopy_advise(dev, vmsg); 2058 case VHOST_USER_POSTCOPY_LISTEN: 2059 return vu_set_postcopy_listen(dev, vmsg); 2060 case VHOST_USER_POSTCOPY_END: 2061 return vu_set_postcopy_end(dev, vmsg); 2062 case VHOST_USER_GET_INFLIGHT_FD: 2063 return vu_get_inflight_fd(dev, vmsg); 2064 case VHOST_USER_SET_INFLIGHT_FD: 2065 return vu_set_inflight_fd(dev, vmsg); 2066 case VHOST_USER_VRING_KICK: 2067 return vu_handle_vring_kick(dev, vmsg); 2068 case VHOST_USER_GET_MAX_MEM_SLOTS: 2069 return vu_handle_get_max_memslots(dev, vmsg); 2070 case VHOST_USER_ADD_MEM_REG: 2071 return vu_add_mem_reg(dev, vmsg); 2072 case VHOST_USER_REM_MEM_REG: 2073 return vu_rem_mem_reg(dev, vmsg); 2074 case VHOST_USER_GET_SHARED_OBJECT: 2075 return vu_get_shared_object(dev, vmsg); 2076 default: 2077 vmsg_close_fds(vmsg); 2078 vu_panic(dev, "Unhandled request: %d", vmsg->request); 2079 } 2080 2081 return false; 2082 } 2083 2084 bool 2085 vu_dispatch(VuDev *dev) 2086 { 2087 VhostUserMsg vmsg = { 0, }; 2088 int reply_requested; 2089 bool need_reply, success = false; 2090 2091 if (!dev->read_msg(dev, dev->sock, &vmsg)) { 2092 goto end; 2093 } 2094 2095 need_reply = vmsg.flags & VHOST_USER_NEED_REPLY_MASK; 2096 2097 reply_requested = vu_process_message(dev, &vmsg); 2098 if (!reply_requested && need_reply) { 2099 vmsg_set_reply_u64(&vmsg, 0); 2100 reply_requested = 1; 2101 } 2102 2103 if (!reply_requested) { 2104 success = true; 2105 goto end; 2106 } 2107 2108 if (!vu_send_reply(dev, dev->sock, &vmsg)) { 2109 goto end; 2110 } 2111 2112 success = true; 2113 2114 end: 2115 free(vmsg.data); 2116 return success; 2117 } 2118 2119 void 2120 vu_deinit(VuDev *dev) 2121 { 2122 unsigned int i; 2123 2124 vu_remove_all_mem_regs(dev); 2125 2126 for (i = 0; i < dev->max_queues; i++) { 2127 VuVirtq *vq = &dev->vq[i]; 2128 2129 if (vq->call_fd != -1) { 2130 close(vq->call_fd); 2131 vq->call_fd = -1; 2132 } 2133 2134 if (vq->kick_fd != -1) { 2135 dev->remove_watch(dev, vq->kick_fd); 2136 close(vq->kick_fd); 2137 vq->kick_fd = -1; 2138 } 2139 2140 if (vq->err_fd != -1) { 2141 close(vq->err_fd); 2142 vq->err_fd = -1; 2143 } 2144 2145 if (vq->resubmit_list) { 2146 free(vq->resubmit_list); 2147 vq->resubmit_list = NULL; 2148 } 2149 2150 vq->inflight = NULL; 2151 } 2152 2153 if (dev->inflight_info.addr) { 2154 munmap(dev->inflight_info.addr, dev->inflight_info.size); 2155 dev->inflight_info.addr = NULL; 2156 } 2157 2158 if (dev->inflight_info.fd > 0) { 2159 close(dev->inflight_info.fd); 2160 dev->inflight_info.fd = -1; 2161 } 2162 2163 vu_close_log(dev); 2164 if (dev->backend_fd != -1) { 2165 close(dev->backend_fd); 2166 dev->backend_fd = -1; 2167 } 2168 pthread_mutex_destroy(&dev->backend_mutex); 2169 2170 if (dev->sock != -1) { 2171 close(dev->sock); 2172 } 2173 2174 free(dev->vq); 2175 dev->vq = NULL; 2176 free(dev->regions); 2177 dev->regions = NULL; 2178 } 2179 2180 bool 2181 vu_init(VuDev *dev, 2182 uint16_t max_queues, 2183 int socket, 2184 vu_panic_cb panic, 2185 vu_read_msg_cb read_msg, 2186 vu_set_watch_cb set_watch, 2187 vu_remove_watch_cb remove_watch, 2188 const VuDevIface *iface) 2189 { 2190 uint16_t i; 2191 2192 assert(max_queues > 0); 2193 assert(socket >= 0); 2194 assert(set_watch); 2195 assert(remove_watch); 2196 assert(iface); 2197 assert(panic); 2198 2199 memset(dev, 0, sizeof(*dev)); 2200 2201 dev->sock = socket; 2202 dev->panic = panic; 2203 dev->read_msg = read_msg ? read_msg : vu_message_read_default; 2204 dev->set_watch = set_watch; 2205 dev->remove_watch = remove_watch; 2206 dev->iface = iface; 2207 dev->log_call_fd = -1; 2208 pthread_mutex_init(&dev->backend_mutex, NULL); 2209 dev->backend_fd = -1; 2210 dev->max_queues = max_queues; 2211 2212 dev->regions = malloc(VHOST_USER_MAX_RAM_SLOTS * sizeof(dev->regions[0])); 2213 if (!dev->regions) { 2214 DPRINT("%s: failed to malloc mem regions\n", __func__); 2215 return false; 2216 } 2217 memset(dev->regions, 0, VHOST_USER_MAX_RAM_SLOTS * sizeof(dev->regions[0])); 2218 2219 dev->vq = malloc(max_queues * sizeof(dev->vq[0])); 2220 if (!dev->vq) { 2221 DPRINT("%s: failed to malloc virtqueues\n", __func__); 2222 free(dev->regions); 2223 dev->regions = NULL; 2224 return false; 2225 } 2226 2227 for (i = 0; i < max_queues; i++) { 2228 dev->vq[i] = (VuVirtq) { 2229 .call_fd = -1, .kick_fd = -1, .err_fd = -1, 2230 .notification = true, 2231 }; 2232 } 2233 2234 return true; 2235 } 2236 2237 VuVirtq * 2238 vu_get_queue(VuDev *dev, int qidx) 2239 { 2240 assert(qidx < dev->max_queues); 2241 return &dev->vq[qidx]; 2242 } 2243 2244 bool 2245 vu_queue_enabled(VuDev *dev, VuVirtq *vq) 2246 { 2247 return vq->enable; 2248 } 2249 2250 bool 2251 vu_queue_started(const VuDev *dev, const VuVirtq *vq) 2252 { 2253 return vq->started; 2254 } 2255 2256 static inline uint16_t 2257 vring_avail_flags(VuVirtq *vq) 2258 { 2259 return le16toh(vq->vring.avail->flags); 2260 } 2261 2262 static inline uint16_t 2263 vring_avail_idx(VuVirtq *vq) 2264 { 2265 vq->shadow_avail_idx = le16toh(vq->vring.avail->idx); 2266 2267 return vq->shadow_avail_idx; 2268 } 2269 2270 static inline uint16_t 2271 vring_avail_ring(VuVirtq *vq, int i) 2272 { 2273 return le16toh(vq->vring.avail->ring[i]); 2274 } 2275 2276 static inline uint16_t 2277 vring_get_used_event(VuVirtq *vq) 2278 { 2279 return vring_avail_ring(vq, vq->vring.num); 2280 } 2281 2282 static int 2283 virtqueue_num_heads(VuDev *dev, VuVirtq *vq, unsigned int idx) 2284 { 2285 uint16_t num_heads = vring_avail_idx(vq) - idx; 2286 2287 /* Check it isn't doing very strange things with descriptor numbers. */ 2288 if (num_heads > vq->vring.num) { 2289 vu_panic(dev, "Guest moved used index from %u to %u", 2290 idx, vq->shadow_avail_idx); 2291 return -1; 2292 } 2293 if (num_heads) { 2294 /* On success, callers read a descriptor at vq->last_avail_idx. 2295 * Make sure descriptor read does not bypass avail index read. */ 2296 smp_rmb(); 2297 } 2298 2299 return num_heads; 2300 } 2301 2302 static bool 2303 virtqueue_get_head(VuDev *dev, VuVirtq *vq, 2304 unsigned int idx, unsigned int *head) 2305 { 2306 /* Grab the next descriptor number they're advertising, and increment 2307 * the index we've seen. */ 2308 *head = vring_avail_ring(vq, idx % vq->vring.num); 2309 2310 /* If their number is silly, that's a fatal mistake. */ 2311 if (*head >= vq->vring.num) { 2312 vu_panic(dev, "Guest says index %u is available", *head); 2313 return false; 2314 } 2315 2316 return true; 2317 } 2318 2319 static int 2320 virtqueue_read_indirect_desc(VuDev *dev, struct vring_desc *desc, 2321 uint64_t addr, size_t len) 2322 { 2323 struct vring_desc *ori_desc; 2324 uint64_t read_len; 2325 2326 if (len > (VIRTQUEUE_MAX_SIZE * sizeof(struct vring_desc))) { 2327 return -1; 2328 } 2329 2330 if (len == 0) { 2331 return -1; 2332 } 2333 2334 while (len) { 2335 read_len = len; 2336 ori_desc = vu_gpa_to_va(dev, &read_len, addr); 2337 if (!ori_desc) { 2338 return -1; 2339 } 2340 2341 memcpy(desc, ori_desc, read_len); 2342 len -= read_len; 2343 addr += read_len; 2344 desc += read_len; 2345 } 2346 2347 return 0; 2348 } 2349 2350 enum { 2351 VIRTQUEUE_READ_DESC_ERROR = -1, 2352 VIRTQUEUE_READ_DESC_DONE = 0, /* end of chain */ 2353 VIRTQUEUE_READ_DESC_MORE = 1, /* more buffers in chain */ 2354 }; 2355 2356 static int 2357 virtqueue_read_next_desc(VuDev *dev, struct vring_desc *desc, 2358 int i, unsigned int max, unsigned int *next) 2359 { 2360 /* If this descriptor says it doesn't chain, we're done. */ 2361 if (!(le16toh(desc[i].flags) & VRING_DESC_F_NEXT)) { 2362 return VIRTQUEUE_READ_DESC_DONE; 2363 } 2364 2365 /* Check they're not leading us off end of descriptors. */ 2366 *next = le16toh(desc[i].next); 2367 /* Make sure compiler knows to grab that: we don't want it changing! */ 2368 smp_wmb(); 2369 2370 if (*next >= max) { 2371 vu_panic(dev, "Desc next is %u", *next); 2372 return VIRTQUEUE_READ_DESC_ERROR; 2373 } 2374 2375 return VIRTQUEUE_READ_DESC_MORE; 2376 } 2377 2378 void 2379 vu_queue_get_avail_bytes(VuDev *dev, VuVirtq *vq, unsigned int *in_bytes, 2380 unsigned int *out_bytes, 2381 unsigned max_in_bytes, unsigned max_out_bytes) 2382 { 2383 unsigned int idx; 2384 unsigned int total_bufs, in_total, out_total; 2385 int rc; 2386 2387 idx = vq->last_avail_idx; 2388 2389 total_bufs = in_total = out_total = 0; 2390 if (unlikely(dev->broken) || 2391 unlikely(!vq->vring.avail)) { 2392 goto done; 2393 } 2394 2395 while ((rc = virtqueue_num_heads(dev, vq, idx)) > 0) { 2396 unsigned int max, desc_len, num_bufs, indirect = 0; 2397 uint64_t desc_addr, read_len; 2398 struct vring_desc *desc; 2399 struct vring_desc desc_buf[VIRTQUEUE_MAX_SIZE]; 2400 unsigned int i; 2401 2402 max = vq->vring.num; 2403 num_bufs = total_bufs; 2404 if (!virtqueue_get_head(dev, vq, idx++, &i)) { 2405 goto err; 2406 } 2407 desc = vq->vring.desc; 2408 2409 if (le16toh(desc[i].flags) & VRING_DESC_F_INDIRECT) { 2410 if (le32toh(desc[i].len) % sizeof(struct vring_desc)) { 2411 vu_panic(dev, "Invalid size for indirect buffer table"); 2412 goto err; 2413 } 2414 2415 /* If we've got too many, that implies a descriptor loop. */ 2416 if (num_bufs >= max) { 2417 vu_panic(dev, "Looped descriptor"); 2418 goto err; 2419 } 2420 2421 /* loop over the indirect descriptor table */ 2422 indirect = 1; 2423 desc_addr = le64toh(desc[i].addr); 2424 desc_len = le32toh(desc[i].len); 2425 max = desc_len / sizeof(struct vring_desc); 2426 read_len = desc_len; 2427 desc = vu_gpa_to_va(dev, &read_len, desc_addr); 2428 if (unlikely(desc && read_len != desc_len)) { 2429 /* Failed to use zero copy */ 2430 desc = NULL; 2431 if (!virtqueue_read_indirect_desc(dev, desc_buf, 2432 desc_addr, 2433 desc_len)) { 2434 desc = desc_buf; 2435 } 2436 } 2437 if (!desc) { 2438 vu_panic(dev, "Invalid indirect buffer table"); 2439 goto err; 2440 } 2441 num_bufs = i = 0; 2442 } 2443 2444 do { 2445 /* If we've got too many, that implies a descriptor loop. */ 2446 if (++num_bufs > max) { 2447 vu_panic(dev, "Looped descriptor"); 2448 goto err; 2449 } 2450 2451 if (le16toh(desc[i].flags) & VRING_DESC_F_WRITE) { 2452 in_total += le32toh(desc[i].len); 2453 } else { 2454 out_total += le32toh(desc[i].len); 2455 } 2456 if (in_total >= max_in_bytes && out_total >= max_out_bytes) { 2457 goto done; 2458 } 2459 rc = virtqueue_read_next_desc(dev, desc, i, max, &i); 2460 } while (rc == VIRTQUEUE_READ_DESC_MORE); 2461 2462 if (rc == VIRTQUEUE_READ_DESC_ERROR) { 2463 goto err; 2464 } 2465 2466 if (!indirect) { 2467 total_bufs = num_bufs; 2468 } else { 2469 total_bufs++; 2470 } 2471 } 2472 if (rc < 0) { 2473 goto err; 2474 } 2475 done: 2476 if (in_bytes) { 2477 *in_bytes = in_total; 2478 } 2479 if (out_bytes) { 2480 *out_bytes = out_total; 2481 } 2482 return; 2483 2484 err: 2485 in_total = out_total = 0; 2486 goto done; 2487 } 2488 2489 bool 2490 vu_queue_avail_bytes(VuDev *dev, VuVirtq *vq, unsigned int in_bytes, 2491 unsigned int out_bytes) 2492 { 2493 unsigned int in_total, out_total; 2494 2495 vu_queue_get_avail_bytes(dev, vq, &in_total, &out_total, 2496 in_bytes, out_bytes); 2497 2498 return in_bytes <= in_total && out_bytes <= out_total; 2499 } 2500 2501 /* Fetch avail_idx from VQ memory only when we really need to know if 2502 * guest has added some buffers. */ 2503 bool 2504 vu_queue_empty(VuDev *dev, VuVirtq *vq) 2505 { 2506 if (unlikely(dev->broken) || 2507 unlikely(!vq->vring.avail)) { 2508 return true; 2509 } 2510 2511 if (vq->shadow_avail_idx != vq->last_avail_idx) { 2512 return false; 2513 } 2514 2515 return vring_avail_idx(vq) == vq->last_avail_idx; 2516 } 2517 2518 static bool 2519 vring_notify(VuDev *dev, VuVirtq *vq) 2520 { 2521 uint16_t old, new; 2522 bool v; 2523 2524 /* We need to expose used array entries before checking used event. */ 2525 smp_mb(); 2526 2527 /* Always notify when queue is empty (when feature acknowledge) */ 2528 if (vu_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY) && 2529 !vq->inuse && vu_queue_empty(dev, vq)) { 2530 return true; 2531 } 2532 2533 if (!vu_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) { 2534 return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT); 2535 } 2536 2537 v = vq->signalled_used_valid; 2538 vq->signalled_used_valid = true; 2539 old = vq->signalled_used; 2540 new = vq->signalled_used = vq->used_idx; 2541 return !v || vring_need_event(vring_get_used_event(vq), new, old); 2542 } 2543 2544 static void _vu_queue_notify(VuDev *dev, VuVirtq *vq, bool sync) 2545 { 2546 if (unlikely(dev->broken) || 2547 unlikely(!vq->vring.avail)) { 2548 return; 2549 } 2550 2551 if (!vring_notify(dev, vq)) { 2552 DPRINT("skipped notify...\n"); 2553 return; 2554 } 2555 2556 if (vq->call_fd < 0 && 2557 vu_has_protocol_feature(dev, 2558 VHOST_USER_PROTOCOL_F_INBAND_NOTIFICATIONS) && 2559 vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_BACKEND_REQ)) { 2560 VhostUserMsg vmsg = { 2561 .request = VHOST_USER_BACKEND_VRING_CALL, 2562 .flags = VHOST_USER_VERSION, 2563 .size = sizeof(vmsg.payload.state), 2564 .payload.state = { 2565 .index = vq - dev->vq, 2566 }, 2567 }; 2568 bool ack = sync && 2569 vu_has_protocol_feature(dev, 2570 VHOST_USER_PROTOCOL_F_REPLY_ACK); 2571 2572 if (ack) { 2573 vmsg.flags |= VHOST_USER_NEED_REPLY_MASK; 2574 } 2575 2576 vu_message_write(dev, dev->backend_fd, &vmsg); 2577 if (ack) { 2578 vu_message_read_default(dev, dev->backend_fd, &vmsg); 2579 } 2580 return; 2581 } 2582 2583 if (eventfd_write(vq->call_fd, 1) < 0) { 2584 vu_panic(dev, "Error writing eventfd: %s", strerror(errno)); 2585 } 2586 } 2587 2588 void vu_queue_notify(VuDev *dev, VuVirtq *vq) 2589 { 2590 _vu_queue_notify(dev, vq, false); 2591 } 2592 2593 void vu_queue_notify_sync(VuDev *dev, VuVirtq *vq) 2594 { 2595 _vu_queue_notify(dev, vq, true); 2596 } 2597 2598 void vu_config_change_msg(VuDev *dev) 2599 { 2600 VhostUserMsg vmsg = { 2601 .request = VHOST_USER_BACKEND_CONFIG_CHANGE_MSG, 2602 .flags = VHOST_USER_VERSION, 2603 }; 2604 2605 vu_message_write(dev, dev->backend_fd, &vmsg); 2606 } 2607 2608 static inline void 2609 vring_used_flags_set_bit(VuVirtq *vq, int mask) 2610 { 2611 uint16_t *flags; 2612 2613 flags = (uint16_t *)((char*)vq->vring.used + 2614 offsetof(struct vring_used, flags)); 2615 *flags = htole16(le16toh(*flags) | mask); 2616 } 2617 2618 static inline void 2619 vring_used_flags_unset_bit(VuVirtq *vq, int mask) 2620 { 2621 uint16_t *flags; 2622 2623 flags = (uint16_t *)((char*)vq->vring.used + 2624 offsetof(struct vring_used, flags)); 2625 *flags = htole16(le16toh(*flags) & ~mask); 2626 } 2627 2628 static inline void 2629 vring_set_avail_event(VuVirtq *vq, uint16_t val) 2630 { 2631 uint16_t val_le = htole16(val); 2632 2633 if (!vq->notification) { 2634 return; 2635 } 2636 2637 memcpy(&vq->vring.used->ring[vq->vring.num], &val_le, sizeof(uint16_t)); 2638 } 2639 2640 void 2641 vu_queue_set_notification(VuDev *dev, VuVirtq *vq, int enable) 2642 { 2643 vq->notification = enable; 2644 if (vu_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) { 2645 vring_set_avail_event(vq, vring_avail_idx(vq)); 2646 } else if (enable) { 2647 vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY); 2648 } else { 2649 vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY); 2650 } 2651 if (enable) { 2652 /* Expose avail event/used flags before caller checks the avail idx. */ 2653 smp_mb(); 2654 } 2655 } 2656 2657 static bool 2658 virtqueue_map_desc(VuDev *dev, 2659 unsigned int *p_num_sg, struct iovec *iov, 2660 unsigned int max_num_sg, bool is_write, 2661 uint64_t pa, size_t sz) 2662 { 2663 unsigned num_sg = *p_num_sg; 2664 2665 assert(num_sg <= max_num_sg); 2666 2667 if (!sz) { 2668 vu_panic(dev, "virtio: zero sized buffers are not allowed"); 2669 return false; 2670 } 2671 2672 while (sz) { 2673 uint64_t len = sz; 2674 2675 if (num_sg == max_num_sg) { 2676 vu_panic(dev, "virtio: too many descriptors in indirect table"); 2677 return false; 2678 } 2679 2680 iov[num_sg].iov_base = vu_gpa_to_va(dev, &len, pa); 2681 if (iov[num_sg].iov_base == NULL) { 2682 vu_panic(dev, "virtio: invalid address for buffers"); 2683 return false; 2684 } 2685 iov[num_sg].iov_len = len; 2686 num_sg++; 2687 sz -= len; 2688 pa += len; 2689 } 2690 2691 *p_num_sg = num_sg; 2692 return true; 2693 } 2694 2695 static void * 2696 virtqueue_alloc_element(size_t sz, 2697 unsigned out_num, unsigned in_num) 2698 { 2699 VuVirtqElement *elem; 2700 size_t in_sg_ofs = ALIGN_UP(sz, __alignof__(elem->in_sg[0])); 2701 size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]); 2702 size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]); 2703 2704 assert(sz >= sizeof(VuVirtqElement)); 2705 elem = malloc(out_sg_end); 2706 if (!elem) { 2707 DPRINT("%s: failed to malloc virtqueue element\n", __func__); 2708 return NULL; 2709 } 2710 elem->out_num = out_num; 2711 elem->in_num = in_num; 2712 elem->in_sg = (void *)elem + in_sg_ofs; 2713 elem->out_sg = (void *)elem + out_sg_ofs; 2714 return elem; 2715 } 2716 2717 static void * 2718 vu_queue_map_desc(VuDev *dev, VuVirtq *vq, unsigned int idx, size_t sz) 2719 { 2720 struct vring_desc *desc = vq->vring.desc; 2721 uint64_t desc_addr, read_len; 2722 unsigned int desc_len; 2723 unsigned int max = vq->vring.num; 2724 unsigned int i = idx; 2725 VuVirtqElement *elem; 2726 unsigned int out_num = 0, in_num = 0; 2727 struct iovec iov[VIRTQUEUE_MAX_SIZE]; 2728 struct vring_desc desc_buf[VIRTQUEUE_MAX_SIZE]; 2729 int rc; 2730 2731 if (le16toh(desc[i].flags) & VRING_DESC_F_INDIRECT) { 2732 if (le32toh(desc[i].len) % sizeof(struct vring_desc)) { 2733 vu_panic(dev, "Invalid size for indirect buffer table"); 2734 return NULL; 2735 } 2736 2737 /* loop over the indirect descriptor table */ 2738 desc_addr = le64toh(desc[i].addr); 2739 desc_len = le32toh(desc[i].len); 2740 max = desc_len / sizeof(struct vring_desc); 2741 read_len = desc_len; 2742 desc = vu_gpa_to_va(dev, &read_len, desc_addr); 2743 if (unlikely(desc && read_len != desc_len)) { 2744 /* Failed to use zero copy */ 2745 desc = NULL; 2746 if (!virtqueue_read_indirect_desc(dev, desc_buf, 2747 desc_addr, 2748 desc_len)) { 2749 desc = desc_buf; 2750 } 2751 } 2752 if (!desc) { 2753 vu_panic(dev, "Invalid indirect buffer table"); 2754 return NULL; 2755 } 2756 i = 0; 2757 } 2758 2759 /* Collect all the descriptors */ 2760 do { 2761 if (le16toh(desc[i].flags) & VRING_DESC_F_WRITE) { 2762 if (!virtqueue_map_desc(dev, &in_num, iov + out_num, 2763 VIRTQUEUE_MAX_SIZE - out_num, true, 2764 le64toh(desc[i].addr), 2765 le32toh(desc[i].len))) { 2766 return NULL; 2767 } 2768 } else { 2769 if (in_num) { 2770 vu_panic(dev, "Incorrect order for descriptors"); 2771 return NULL; 2772 } 2773 if (!virtqueue_map_desc(dev, &out_num, iov, 2774 VIRTQUEUE_MAX_SIZE, false, 2775 le64toh(desc[i].addr), 2776 le32toh(desc[i].len))) { 2777 return NULL; 2778 } 2779 } 2780 2781 /* If we've got too many, that implies a descriptor loop. */ 2782 if ((in_num + out_num) > max) { 2783 vu_panic(dev, "Looped descriptor"); 2784 return NULL; 2785 } 2786 rc = virtqueue_read_next_desc(dev, desc, i, max, &i); 2787 } while (rc == VIRTQUEUE_READ_DESC_MORE); 2788 2789 if (rc == VIRTQUEUE_READ_DESC_ERROR) { 2790 vu_panic(dev, "read descriptor error"); 2791 return NULL; 2792 } 2793 2794 /* Now copy what we have collected and mapped */ 2795 elem = virtqueue_alloc_element(sz, out_num, in_num); 2796 if (!elem) { 2797 return NULL; 2798 } 2799 elem->index = idx; 2800 for (i = 0; i < out_num; i++) { 2801 elem->out_sg[i] = iov[i]; 2802 } 2803 for (i = 0; i < in_num; i++) { 2804 elem->in_sg[i] = iov[out_num + i]; 2805 } 2806 2807 return elem; 2808 } 2809 2810 static int 2811 vu_queue_inflight_get(VuDev *dev, VuVirtq *vq, int desc_idx) 2812 { 2813 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) { 2814 return 0; 2815 } 2816 2817 if (unlikely(!vq->inflight)) { 2818 return -1; 2819 } 2820 2821 vq->inflight->desc[desc_idx].counter = vq->counter++; 2822 vq->inflight->desc[desc_idx].inflight = 1; 2823 2824 return 0; 2825 } 2826 2827 static int 2828 vu_queue_inflight_pre_put(VuDev *dev, VuVirtq *vq, int desc_idx) 2829 { 2830 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) { 2831 return 0; 2832 } 2833 2834 if (unlikely(!vq->inflight)) { 2835 return -1; 2836 } 2837 2838 vq->inflight->last_batch_head = desc_idx; 2839 2840 return 0; 2841 } 2842 2843 static int 2844 vu_queue_inflight_post_put(VuDev *dev, VuVirtq *vq, int desc_idx) 2845 { 2846 if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) { 2847 return 0; 2848 } 2849 2850 if (unlikely(!vq->inflight)) { 2851 return -1; 2852 } 2853 2854 barrier(); 2855 2856 vq->inflight->desc[desc_idx].inflight = 0; 2857 2858 barrier(); 2859 2860 vq->inflight->used_idx = vq->used_idx; 2861 2862 return 0; 2863 } 2864 2865 void * 2866 vu_queue_pop(VuDev *dev, VuVirtq *vq, size_t sz) 2867 { 2868 int i; 2869 unsigned int head; 2870 VuVirtqElement *elem; 2871 2872 if (unlikely(dev->broken) || 2873 unlikely(!vq->vring.avail)) { 2874 return NULL; 2875 } 2876 2877 if (unlikely(vq->resubmit_list && vq->resubmit_num > 0)) { 2878 i = (--vq->resubmit_num); 2879 elem = vu_queue_map_desc(dev, vq, vq->resubmit_list[i].index, sz); 2880 2881 if (!vq->resubmit_num) { 2882 free(vq->resubmit_list); 2883 vq->resubmit_list = NULL; 2884 } 2885 2886 return elem; 2887 } 2888 2889 if (vu_queue_empty(dev, vq)) { 2890 return NULL; 2891 } 2892 /* 2893 * Needed after virtio_queue_empty(), see comment in 2894 * virtqueue_num_heads(). 2895 */ 2896 smp_rmb(); 2897 2898 if (vq->inuse >= vq->vring.num) { 2899 vu_panic(dev, "Virtqueue size exceeded"); 2900 return NULL; 2901 } 2902 2903 if (!virtqueue_get_head(dev, vq, vq->last_avail_idx++, &head)) { 2904 return NULL; 2905 } 2906 2907 if (vu_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) { 2908 vring_set_avail_event(vq, vq->last_avail_idx); 2909 } 2910 2911 elem = vu_queue_map_desc(dev, vq, head, sz); 2912 2913 if (!elem) { 2914 return NULL; 2915 } 2916 2917 vq->inuse++; 2918 2919 vu_queue_inflight_get(dev, vq, head); 2920 2921 return elem; 2922 } 2923 2924 static void 2925 vu_queue_detach_element(VuDev *dev, VuVirtq *vq, VuVirtqElement *elem, 2926 size_t len) 2927 { 2928 vq->inuse--; 2929 /* unmap, when DMA support is added */ 2930 } 2931 2932 void 2933 vu_queue_unpop(VuDev *dev, VuVirtq *vq, VuVirtqElement *elem, 2934 size_t len) 2935 { 2936 vq->last_avail_idx--; 2937 vu_queue_detach_element(dev, vq, elem, len); 2938 } 2939 2940 bool 2941 vu_queue_rewind(VuDev *dev, VuVirtq *vq, unsigned int num) 2942 { 2943 if (num > vq->inuse) { 2944 return false; 2945 } 2946 vq->last_avail_idx -= num; 2947 vq->inuse -= num; 2948 return true; 2949 } 2950 2951 static inline 2952 void vring_used_write(VuDev *dev, VuVirtq *vq, 2953 struct vring_used_elem *uelem, int i) 2954 { 2955 struct vring_used *used = vq->vring.used; 2956 2957 used->ring[i] = *uelem; 2958 vu_log_write(dev, vq->vring.log_guest_addr + 2959 offsetof(struct vring_used, ring[i]), 2960 sizeof(used->ring[i])); 2961 } 2962 2963 2964 static void 2965 vu_log_queue_fill(VuDev *dev, VuVirtq *vq, 2966 const VuVirtqElement *elem, 2967 unsigned int len) 2968 { 2969 struct vring_desc *desc = vq->vring.desc; 2970 unsigned int i, max, min, desc_len; 2971 uint64_t desc_addr, read_len; 2972 struct vring_desc desc_buf[VIRTQUEUE_MAX_SIZE]; 2973 unsigned num_bufs = 0; 2974 2975 max = vq->vring.num; 2976 i = elem->index; 2977 2978 if (le16toh(desc[i].flags) & VRING_DESC_F_INDIRECT) { 2979 if (le32toh(desc[i].len) % sizeof(struct vring_desc)) { 2980 vu_panic(dev, "Invalid size for indirect buffer table"); 2981 return; 2982 } 2983 2984 /* loop over the indirect descriptor table */ 2985 desc_addr = le64toh(desc[i].addr); 2986 desc_len = le32toh(desc[i].len); 2987 max = desc_len / sizeof(struct vring_desc); 2988 read_len = desc_len; 2989 desc = vu_gpa_to_va(dev, &read_len, desc_addr); 2990 if (unlikely(desc && read_len != desc_len)) { 2991 /* Failed to use zero copy */ 2992 desc = NULL; 2993 if (!virtqueue_read_indirect_desc(dev, desc_buf, 2994 desc_addr, 2995 desc_len)) { 2996 desc = desc_buf; 2997 } 2998 } 2999 if (!desc) { 3000 vu_panic(dev, "Invalid indirect buffer table"); 3001 return; 3002 } 3003 i = 0; 3004 } 3005 3006 do { 3007 if (++num_bufs > max) { 3008 vu_panic(dev, "Looped descriptor"); 3009 return; 3010 } 3011 3012 if (le16toh(desc[i].flags) & VRING_DESC_F_WRITE) { 3013 min = MIN(le32toh(desc[i].len), len); 3014 vu_log_write(dev, le64toh(desc[i].addr), min); 3015 len -= min; 3016 } 3017 3018 } while (len > 0 && 3019 (virtqueue_read_next_desc(dev, desc, i, max, &i) 3020 == VIRTQUEUE_READ_DESC_MORE)); 3021 } 3022 3023 void 3024 vu_queue_fill(VuDev *dev, VuVirtq *vq, 3025 const VuVirtqElement *elem, 3026 unsigned int len, unsigned int idx) 3027 { 3028 struct vring_used_elem uelem; 3029 3030 if (unlikely(dev->broken) || 3031 unlikely(!vq->vring.avail)) { 3032 return; 3033 } 3034 3035 vu_log_queue_fill(dev, vq, elem, len); 3036 3037 idx = (idx + vq->used_idx) % vq->vring.num; 3038 3039 uelem.id = htole32(elem->index); 3040 uelem.len = htole32(len); 3041 vring_used_write(dev, vq, &uelem, idx); 3042 } 3043 3044 static inline 3045 void vring_used_idx_set(VuDev *dev, VuVirtq *vq, uint16_t val) 3046 { 3047 vq->vring.used->idx = htole16(val); 3048 vu_log_write(dev, 3049 vq->vring.log_guest_addr + offsetof(struct vring_used, idx), 3050 sizeof(vq->vring.used->idx)); 3051 3052 vq->used_idx = val; 3053 } 3054 3055 void 3056 vu_queue_flush(VuDev *dev, VuVirtq *vq, unsigned int count) 3057 { 3058 uint16_t old, new; 3059 3060 if (unlikely(dev->broken) || 3061 unlikely(!vq->vring.avail)) { 3062 return; 3063 } 3064 3065 /* Make sure buffer is written before we update index. */ 3066 smp_wmb(); 3067 3068 old = vq->used_idx; 3069 new = old + count; 3070 vring_used_idx_set(dev, vq, new); 3071 vq->inuse -= count; 3072 if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old))) { 3073 vq->signalled_used_valid = false; 3074 } 3075 } 3076 3077 void 3078 vu_queue_push(VuDev *dev, VuVirtq *vq, 3079 const VuVirtqElement *elem, unsigned int len) 3080 { 3081 vu_queue_fill(dev, vq, elem, len, 0); 3082 vu_queue_inflight_pre_put(dev, vq, elem->index); 3083 vu_queue_flush(dev, vq, 1); 3084 vu_queue_inflight_post_put(dev, vq, elem->index); 3085 } 3086