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