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