xref: /qemu/hw/virtio/vhost-user.c (revision ce0f3b03)
1 /*
2  * vhost-user
3  *
4  * Copyright (c) 2013 Virtual Open Systems Sarl.
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or later.
7  * See the COPYING file in the top-level directory.
8  *
9  */
10 
11 #include "qemu/osdep.h"
12 #include "qapi/error.h"
13 #include "hw/virtio/virtio-dmabuf.h"
14 #include "hw/virtio/vhost.h"
15 #include "hw/virtio/virtio-crypto.h"
16 #include "hw/virtio/vhost-user.h"
17 #include "hw/virtio/vhost-backend.h"
18 #include "hw/virtio/virtio.h"
19 #include "hw/virtio/virtio-net.h"
20 #include "chardev/char-fe.h"
21 #include "io/channel-socket.h"
22 #include "sysemu/kvm.h"
23 #include "qemu/error-report.h"
24 #include "qemu/main-loop.h"
25 #include "qemu/uuid.h"
26 #include "qemu/sockets.h"
27 #include "sysemu/runstate.h"
28 #include "sysemu/cryptodev.h"
29 #include "migration/migration.h"
30 #include "migration/postcopy-ram.h"
31 #include "trace.h"
32 #include "exec/ramblock.h"
33 
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 
38 #include "standard-headers/linux/vhost_types.h"
39 
40 #ifdef CONFIG_LINUX
41 #include <linux/userfaultfd.h>
42 #endif
43 
44 #define VHOST_MEMORY_BASELINE_NREGIONS    8
45 #define VHOST_USER_F_PROTOCOL_FEATURES 30
46 #define VHOST_USER_BACKEND_MAX_FDS     8
47 
48 #if defined(TARGET_PPC) || defined(TARGET_PPC64)
49 #include "hw/ppc/spapr.h"
50 #define VHOST_USER_MAX_RAM_SLOTS SPAPR_MAX_RAM_SLOTS
51 
52 #else
53 #define VHOST_USER_MAX_RAM_SLOTS 512
54 #endif
55 
56 /*
57  * Maximum size of virtio device config space
58  */
59 #define VHOST_USER_MAX_CONFIG_SIZE 256
60 
61 #define VHOST_USER_PROTOCOL_FEATURE_MASK ((1 << VHOST_USER_PROTOCOL_F_MAX) - 1)
62 
63 typedef enum VhostUserRequest {
64     VHOST_USER_NONE = 0,
65     VHOST_USER_GET_FEATURES = 1,
66     VHOST_USER_SET_FEATURES = 2,
67     VHOST_USER_SET_OWNER = 3,
68     VHOST_USER_RESET_OWNER = 4,
69     VHOST_USER_SET_MEM_TABLE = 5,
70     VHOST_USER_SET_LOG_BASE = 6,
71     VHOST_USER_SET_LOG_FD = 7,
72     VHOST_USER_SET_VRING_NUM = 8,
73     VHOST_USER_SET_VRING_ADDR = 9,
74     VHOST_USER_SET_VRING_BASE = 10,
75     VHOST_USER_GET_VRING_BASE = 11,
76     VHOST_USER_SET_VRING_KICK = 12,
77     VHOST_USER_SET_VRING_CALL = 13,
78     VHOST_USER_SET_VRING_ERR = 14,
79     VHOST_USER_GET_PROTOCOL_FEATURES = 15,
80     VHOST_USER_SET_PROTOCOL_FEATURES = 16,
81     VHOST_USER_GET_QUEUE_NUM = 17,
82     VHOST_USER_SET_VRING_ENABLE = 18,
83     VHOST_USER_SEND_RARP = 19,
84     VHOST_USER_NET_SET_MTU = 20,
85     VHOST_USER_SET_BACKEND_REQ_FD = 21,
86     VHOST_USER_IOTLB_MSG = 22,
87     VHOST_USER_SET_VRING_ENDIAN = 23,
88     VHOST_USER_GET_CONFIG = 24,
89     VHOST_USER_SET_CONFIG = 25,
90     VHOST_USER_CREATE_CRYPTO_SESSION = 26,
91     VHOST_USER_CLOSE_CRYPTO_SESSION = 27,
92     VHOST_USER_POSTCOPY_ADVISE  = 28,
93     VHOST_USER_POSTCOPY_LISTEN  = 29,
94     VHOST_USER_POSTCOPY_END     = 30,
95     VHOST_USER_GET_INFLIGHT_FD = 31,
96     VHOST_USER_SET_INFLIGHT_FD = 32,
97     VHOST_USER_GPU_SET_SOCKET = 33,
98     VHOST_USER_RESET_DEVICE = 34,
99     /* Message number 35 reserved for VHOST_USER_VRING_KICK. */
100     VHOST_USER_GET_MAX_MEM_SLOTS = 36,
101     VHOST_USER_ADD_MEM_REG = 37,
102     VHOST_USER_REM_MEM_REG = 38,
103     VHOST_USER_SET_STATUS = 39,
104     VHOST_USER_GET_STATUS = 40,
105     VHOST_USER_GET_SHARED_OBJECT = 41,
106     VHOST_USER_MAX
107 } VhostUserRequest;
108 
109 typedef enum VhostUserBackendRequest {
110     VHOST_USER_BACKEND_NONE = 0,
111     VHOST_USER_BACKEND_IOTLB_MSG = 1,
112     VHOST_USER_BACKEND_CONFIG_CHANGE_MSG = 2,
113     VHOST_USER_BACKEND_VRING_HOST_NOTIFIER_MSG = 3,
114     VHOST_USER_BACKEND_SHARED_OBJECT_ADD = 6,
115     VHOST_USER_BACKEND_SHARED_OBJECT_REMOVE = 7,
116     VHOST_USER_BACKEND_SHARED_OBJECT_LOOKUP = 8,
117     VHOST_USER_BACKEND_MAX
118 }  VhostUserBackendRequest;
119 
120 typedef struct VhostUserMemoryRegion {
121     uint64_t guest_phys_addr;
122     uint64_t memory_size;
123     uint64_t userspace_addr;
124     uint64_t mmap_offset;
125 } VhostUserMemoryRegion;
126 
127 typedef struct VhostUserMemory {
128     uint32_t nregions;
129     uint32_t padding;
130     VhostUserMemoryRegion regions[VHOST_MEMORY_BASELINE_NREGIONS];
131 } VhostUserMemory;
132 
133 typedef struct VhostUserMemRegMsg {
134     uint64_t padding;
135     VhostUserMemoryRegion region;
136 } VhostUserMemRegMsg;
137 
138 typedef struct VhostUserLog {
139     uint64_t mmap_size;
140     uint64_t mmap_offset;
141 } VhostUserLog;
142 
143 typedef struct VhostUserConfig {
144     uint32_t offset;
145     uint32_t size;
146     uint32_t flags;
147     uint8_t region[VHOST_USER_MAX_CONFIG_SIZE];
148 } VhostUserConfig;
149 
150 #define VHOST_CRYPTO_SYM_HMAC_MAX_KEY_LEN    512
151 #define VHOST_CRYPTO_SYM_CIPHER_MAX_KEY_LEN  64
152 #define VHOST_CRYPTO_ASYM_MAX_KEY_LEN  1024
153 
154 typedef struct VhostUserCryptoSession {
155     uint64_t op_code;
156     union {
157         struct {
158             CryptoDevBackendSymSessionInfo session_setup_data;
159             uint8_t key[VHOST_CRYPTO_SYM_CIPHER_MAX_KEY_LEN];
160             uint8_t auth_key[VHOST_CRYPTO_SYM_HMAC_MAX_KEY_LEN];
161         } sym;
162         struct {
163             CryptoDevBackendAsymSessionInfo session_setup_data;
164             uint8_t key[VHOST_CRYPTO_ASYM_MAX_KEY_LEN];
165         } asym;
166     } u;
167 
168     /* session id for success, -1 on errors */
169     int64_t session_id;
170 } VhostUserCryptoSession;
171 
172 static VhostUserConfig c __attribute__ ((unused));
173 #define VHOST_USER_CONFIG_HDR_SIZE (sizeof(c.offset) \
174                                    + sizeof(c.size) \
175                                    + sizeof(c.flags))
176 
177 typedef struct VhostUserVringArea {
178     uint64_t u64;
179     uint64_t size;
180     uint64_t offset;
181 } VhostUserVringArea;
182 
183 typedef struct VhostUserInflight {
184     uint64_t mmap_size;
185     uint64_t mmap_offset;
186     uint16_t num_queues;
187     uint16_t queue_size;
188 } VhostUserInflight;
189 
190 typedef struct VhostUserShared {
191     unsigned char uuid[16];
192 } VhostUserShared;
193 
194 typedef struct {
195     VhostUserRequest request;
196 
197 #define VHOST_USER_VERSION_MASK     (0x3)
198 #define VHOST_USER_REPLY_MASK       (0x1 << 2)
199 #define VHOST_USER_NEED_REPLY_MASK  (0x1 << 3)
200     uint32_t flags;
201     uint32_t size; /* the following payload size */
202 } QEMU_PACKED VhostUserHeader;
203 
204 typedef union {
205 #define VHOST_USER_VRING_IDX_MASK   (0xff)
206 #define VHOST_USER_VRING_NOFD_MASK  (0x1 << 8)
207         uint64_t u64;
208         struct vhost_vring_state state;
209         struct vhost_vring_addr addr;
210         VhostUserMemory memory;
211         VhostUserMemRegMsg mem_reg;
212         VhostUserLog log;
213         struct vhost_iotlb_msg iotlb;
214         VhostUserConfig config;
215         VhostUserCryptoSession session;
216         VhostUserVringArea area;
217         VhostUserInflight inflight;
218         VhostUserShared object;
219 } VhostUserPayload;
220 
221 typedef struct VhostUserMsg {
222     VhostUserHeader hdr;
223     VhostUserPayload payload;
224 } QEMU_PACKED VhostUserMsg;
225 
226 static VhostUserMsg m __attribute__ ((unused));
227 #define VHOST_USER_HDR_SIZE (sizeof(VhostUserHeader))
228 
229 #define VHOST_USER_PAYLOAD_SIZE (sizeof(VhostUserPayload))
230 
231 /* The version of the protocol we support */
232 #define VHOST_USER_VERSION    (0x1)
233 
234 struct vhost_user {
235     struct vhost_dev *dev;
236     /* Shared between vhost devs of the same virtio device */
237     VhostUserState *user;
238     QIOChannel *backend_ioc;
239     GSource *backend_src;
240     NotifierWithReturn postcopy_notifier;
241     struct PostCopyFD  postcopy_fd;
242     uint64_t           postcopy_client_bases[VHOST_USER_MAX_RAM_SLOTS];
243     /* Length of the region_rb and region_rb_offset arrays */
244     size_t             region_rb_len;
245     /* RAMBlock associated with a given region */
246     RAMBlock         **region_rb;
247     /*
248      * The offset from the start of the RAMBlock to the start of the
249      * vhost region.
250      */
251     ram_addr_t        *region_rb_offset;
252 
253     /* True once we've entered postcopy_listen */
254     bool               postcopy_listen;
255 
256     /* Our current regions */
257     int num_shadow_regions;
258     struct vhost_memory_region shadow_regions[VHOST_USER_MAX_RAM_SLOTS];
259 };
260 
261 struct scrub_regions {
262     struct vhost_memory_region *region;
263     int reg_idx;
264     int fd_idx;
265 };
266 
267 static bool ioeventfd_enabled(void)
268 {
269     return !kvm_enabled() || kvm_eventfds_enabled();
270 }
271 
272 static int vhost_user_read_header(struct vhost_dev *dev, VhostUserMsg *msg)
273 {
274     struct vhost_user *u = dev->opaque;
275     CharBackend *chr = u->user->chr;
276     uint8_t *p = (uint8_t *) msg;
277     int r, size = VHOST_USER_HDR_SIZE;
278 
279     r = qemu_chr_fe_read_all(chr, p, size);
280     if (r != size) {
281         int saved_errno = errno;
282         error_report("Failed to read msg header. Read %d instead of %d."
283                      " Original request %d.", r, size, msg->hdr.request);
284         return r < 0 ? -saved_errno : -EIO;
285     }
286 
287     /* validate received flags */
288     if (msg->hdr.flags != (VHOST_USER_REPLY_MASK | VHOST_USER_VERSION)) {
289         error_report("Failed to read msg header."
290                 " Flags 0x%x instead of 0x%x.", msg->hdr.flags,
291                 VHOST_USER_REPLY_MASK | VHOST_USER_VERSION);
292         return -EPROTO;
293     }
294 
295     trace_vhost_user_read(msg->hdr.request, msg->hdr.flags);
296 
297     return 0;
298 }
299 
300 static int vhost_user_read(struct vhost_dev *dev, VhostUserMsg *msg)
301 {
302     struct vhost_user *u = dev->opaque;
303     CharBackend *chr = u->user->chr;
304     uint8_t *p = (uint8_t *) msg;
305     int r, size;
306 
307     r = vhost_user_read_header(dev, msg);
308     if (r < 0) {
309         return r;
310     }
311 
312     /* validate message size is sane */
313     if (msg->hdr.size > VHOST_USER_PAYLOAD_SIZE) {
314         error_report("Failed to read msg header."
315                 " Size %d exceeds the maximum %zu.", msg->hdr.size,
316                 VHOST_USER_PAYLOAD_SIZE);
317         return -EPROTO;
318     }
319 
320     if (msg->hdr.size) {
321         p += VHOST_USER_HDR_SIZE;
322         size = msg->hdr.size;
323         r = qemu_chr_fe_read_all(chr, p, size);
324         if (r != size) {
325             int saved_errno = errno;
326             error_report("Failed to read msg payload."
327                          " Read %d instead of %d.", r, msg->hdr.size);
328             return r < 0 ? -saved_errno : -EIO;
329         }
330     }
331 
332     return 0;
333 }
334 
335 static int process_message_reply(struct vhost_dev *dev,
336                                  const VhostUserMsg *msg)
337 {
338     int ret;
339     VhostUserMsg msg_reply;
340 
341     if ((msg->hdr.flags & VHOST_USER_NEED_REPLY_MASK) == 0) {
342         return 0;
343     }
344 
345     ret = vhost_user_read(dev, &msg_reply);
346     if (ret < 0) {
347         return ret;
348     }
349 
350     if (msg_reply.hdr.request != msg->hdr.request) {
351         error_report("Received unexpected msg type. "
352                      "Expected %d received %d",
353                      msg->hdr.request, msg_reply.hdr.request);
354         return -EPROTO;
355     }
356 
357     return msg_reply.payload.u64 ? -EIO : 0;
358 }
359 
360 static bool vhost_user_per_device_request(VhostUserRequest request)
361 {
362     switch (request) {
363     case VHOST_USER_SET_OWNER:
364     case VHOST_USER_RESET_OWNER:
365     case VHOST_USER_SET_MEM_TABLE:
366     case VHOST_USER_GET_QUEUE_NUM:
367     case VHOST_USER_NET_SET_MTU:
368     case VHOST_USER_RESET_DEVICE:
369     case VHOST_USER_ADD_MEM_REG:
370     case VHOST_USER_REM_MEM_REG:
371         return true;
372     default:
373         return false;
374     }
375 }
376 
377 /* most non-init callers ignore the error */
378 static int vhost_user_write(struct vhost_dev *dev, VhostUserMsg *msg,
379                             int *fds, int fd_num)
380 {
381     struct vhost_user *u = dev->opaque;
382     CharBackend *chr = u->user->chr;
383     int ret, size = VHOST_USER_HDR_SIZE + msg->hdr.size;
384 
385     /*
386      * Some devices, like virtio-scsi, are implemented as a single vhost_dev,
387      * while others, like virtio-net, contain multiple vhost_devs. For
388      * operations such as configuring device memory mappings or issuing device
389      * resets, which affect the whole device instead of individual VQs,
390      * vhost-user messages should only be sent once.
391      *
392      * Devices with multiple vhost_devs are given an associated dev->vq_index
393      * so per_device requests are only sent if vq_index is 0.
394      */
395     if (vhost_user_per_device_request(msg->hdr.request)
396         && dev->vq_index != 0) {
397         msg->hdr.flags &= ~VHOST_USER_NEED_REPLY_MASK;
398         return 0;
399     }
400 
401     if (qemu_chr_fe_set_msgfds(chr, fds, fd_num) < 0) {
402         error_report("Failed to set msg fds.");
403         return -EINVAL;
404     }
405 
406     ret = qemu_chr_fe_write_all(chr, (const uint8_t *) msg, size);
407     if (ret != size) {
408         int saved_errno = errno;
409         error_report("Failed to write msg."
410                      " Wrote %d instead of %d.", ret, size);
411         return ret < 0 ? -saved_errno : -EIO;
412     }
413 
414     trace_vhost_user_write(msg->hdr.request, msg->hdr.flags);
415 
416     return 0;
417 }
418 
419 int vhost_user_gpu_set_socket(struct vhost_dev *dev, int fd)
420 {
421     VhostUserMsg msg = {
422         .hdr.request = VHOST_USER_GPU_SET_SOCKET,
423         .hdr.flags = VHOST_USER_VERSION,
424     };
425 
426     return vhost_user_write(dev, &msg, &fd, 1);
427 }
428 
429 static int vhost_user_set_log_base(struct vhost_dev *dev, uint64_t base,
430                                    struct vhost_log *log)
431 {
432     int fds[VHOST_USER_MAX_RAM_SLOTS];
433     size_t fd_num = 0;
434     bool shmfd = virtio_has_feature(dev->protocol_features,
435                                     VHOST_USER_PROTOCOL_F_LOG_SHMFD);
436     int ret;
437     VhostUserMsg msg = {
438         .hdr.request = VHOST_USER_SET_LOG_BASE,
439         .hdr.flags = VHOST_USER_VERSION,
440         .payload.log.mmap_size = log->size * sizeof(*(log->log)),
441         .payload.log.mmap_offset = 0,
442         .hdr.size = sizeof(msg.payload.log),
443     };
444 
445     /* Send only once with first queue pair */
446     if (dev->vq_index != 0) {
447         return 0;
448     }
449 
450     if (shmfd && log->fd != -1) {
451         fds[fd_num++] = log->fd;
452     }
453 
454     ret = vhost_user_write(dev, &msg, fds, fd_num);
455     if (ret < 0) {
456         return ret;
457     }
458 
459     if (shmfd) {
460         msg.hdr.size = 0;
461         ret = vhost_user_read(dev, &msg);
462         if (ret < 0) {
463             return ret;
464         }
465 
466         if (msg.hdr.request != VHOST_USER_SET_LOG_BASE) {
467             error_report("Received unexpected msg type. "
468                          "Expected %d received %d",
469                          VHOST_USER_SET_LOG_BASE, msg.hdr.request);
470             return -EPROTO;
471         }
472     }
473 
474     return 0;
475 }
476 
477 static MemoryRegion *vhost_user_get_mr_data(uint64_t addr, ram_addr_t *offset,
478                                             int *fd)
479 {
480     MemoryRegion *mr;
481 
482     assert((uintptr_t)addr == addr);
483     mr = memory_region_from_host((void *)(uintptr_t)addr, offset);
484     *fd = memory_region_get_fd(mr);
485     *offset += mr->ram_block->fd_offset;
486 
487     return mr;
488 }
489 
490 static void vhost_user_fill_msg_region(VhostUserMemoryRegion *dst,
491                                        struct vhost_memory_region *src,
492                                        uint64_t mmap_offset)
493 {
494     assert(src != NULL && dst != NULL);
495     dst->userspace_addr = src->userspace_addr;
496     dst->memory_size = src->memory_size;
497     dst->guest_phys_addr = src->guest_phys_addr;
498     dst->mmap_offset = mmap_offset;
499 }
500 
501 static int vhost_user_fill_set_mem_table_msg(struct vhost_user *u,
502                                              struct vhost_dev *dev,
503                                              VhostUserMsg *msg,
504                                              int *fds, size_t *fd_num,
505                                              bool track_ramblocks)
506 {
507     int i, fd;
508     ram_addr_t offset;
509     MemoryRegion *mr;
510     struct vhost_memory_region *reg;
511     VhostUserMemoryRegion region_buffer;
512 
513     msg->hdr.request = VHOST_USER_SET_MEM_TABLE;
514 
515     for (i = 0; i < dev->mem->nregions; ++i) {
516         reg = dev->mem->regions + i;
517 
518         mr = vhost_user_get_mr_data(reg->userspace_addr, &offset, &fd);
519         if (fd > 0) {
520             if (track_ramblocks) {
521                 assert(*fd_num < VHOST_MEMORY_BASELINE_NREGIONS);
522                 trace_vhost_user_set_mem_table_withfd(*fd_num, mr->name,
523                                                       reg->memory_size,
524                                                       reg->guest_phys_addr,
525                                                       reg->userspace_addr,
526                                                       offset);
527                 u->region_rb_offset[i] = offset;
528                 u->region_rb[i] = mr->ram_block;
529             } else if (*fd_num == VHOST_MEMORY_BASELINE_NREGIONS) {
530                 error_report("Failed preparing vhost-user memory table msg");
531                 return -ENOBUFS;
532             }
533             vhost_user_fill_msg_region(&region_buffer, reg, offset);
534             msg->payload.memory.regions[*fd_num] = region_buffer;
535             fds[(*fd_num)++] = fd;
536         } else if (track_ramblocks) {
537             u->region_rb_offset[i] = 0;
538             u->region_rb[i] = NULL;
539         }
540     }
541 
542     msg->payload.memory.nregions = *fd_num;
543 
544     if (!*fd_num) {
545         error_report("Failed initializing vhost-user memory map, "
546                      "consider using -object memory-backend-file share=on");
547         return -EINVAL;
548     }
549 
550     msg->hdr.size = sizeof(msg->payload.memory.nregions);
551     msg->hdr.size += sizeof(msg->payload.memory.padding);
552     msg->hdr.size += *fd_num * sizeof(VhostUserMemoryRegion);
553 
554     return 0;
555 }
556 
557 static inline bool reg_equal(struct vhost_memory_region *shadow_reg,
558                              struct vhost_memory_region *vdev_reg)
559 {
560     return shadow_reg->guest_phys_addr == vdev_reg->guest_phys_addr &&
561         shadow_reg->userspace_addr == vdev_reg->userspace_addr &&
562         shadow_reg->memory_size == vdev_reg->memory_size;
563 }
564 
565 static void scrub_shadow_regions(struct vhost_dev *dev,
566                                  struct scrub_regions *add_reg,
567                                  int *nr_add_reg,
568                                  struct scrub_regions *rem_reg,
569                                  int *nr_rem_reg, uint64_t *shadow_pcb,
570                                  bool track_ramblocks)
571 {
572     struct vhost_user *u = dev->opaque;
573     bool found[VHOST_USER_MAX_RAM_SLOTS] = {};
574     struct vhost_memory_region *reg, *shadow_reg;
575     int i, j, fd, add_idx = 0, rm_idx = 0, fd_num = 0;
576     ram_addr_t offset;
577     MemoryRegion *mr;
578     bool matching;
579 
580     /*
581      * Find memory regions present in our shadow state which are not in
582      * the device's current memory state.
583      *
584      * Mark regions in both the shadow and device state as "found".
585      */
586     for (i = 0; i < u->num_shadow_regions; i++) {
587         shadow_reg = &u->shadow_regions[i];
588         matching = false;
589 
590         for (j = 0; j < dev->mem->nregions; j++) {
591             reg = &dev->mem->regions[j];
592 
593             mr = vhost_user_get_mr_data(reg->userspace_addr, &offset, &fd);
594 
595             if (reg_equal(shadow_reg, reg)) {
596                 matching = true;
597                 found[j] = true;
598                 if (track_ramblocks) {
599                     /*
600                      * Reset postcopy client bases, region_rb, and
601                      * region_rb_offset in case regions are removed.
602                      */
603                     if (fd > 0) {
604                         u->region_rb_offset[j] = offset;
605                         u->region_rb[j] = mr->ram_block;
606                         shadow_pcb[j] = u->postcopy_client_bases[i];
607                     } else {
608                         u->region_rb_offset[j] = 0;
609                         u->region_rb[j] = NULL;
610                     }
611                 }
612                 break;
613             }
614         }
615 
616         /*
617          * If the region was not found in the current device memory state
618          * create an entry for it in the removed list.
619          */
620         if (!matching) {
621             rem_reg[rm_idx].region = shadow_reg;
622             rem_reg[rm_idx++].reg_idx = i;
623         }
624     }
625 
626     /*
627      * For regions not marked "found", create entries in the added list.
628      *
629      * Note their indexes in the device memory state and the indexes of their
630      * file descriptors.
631      */
632     for (i = 0; i < dev->mem->nregions; i++) {
633         reg = &dev->mem->regions[i];
634         vhost_user_get_mr_data(reg->userspace_addr, &offset, &fd);
635         if (fd > 0) {
636             ++fd_num;
637         }
638 
639         /*
640          * If the region was in both the shadow and device state we don't
641          * need to send a VHOST_USER_ADD_MEM_REG message for it.
642          */
643         if (found[i]) {
644             continue;
645         }
646 
647         add_reg[add_idx].region = reg;
648         add_reg[add_idx].reg_idx = i;
649         add_reg[add_idx++].fd_idx = fd_num;
650     }
651     *nr_rem_reg = rm_idx;
652     *nr_add_reg = add_idx;
653 
654     return;
655 }
656 
657 static int send_remove_regions(struct vhost_dev *dev,
658                                struct scrub_regions *remove_reg,
659                                int nr_rem_reg, VhostUserMsg *msg,
660                                bool reply_supported)
661 {
662     struct vhost_user *u = dev->opaque;
663     struct vhost_memory_region *shadow_reg;
664     int i, fd, shadow_reg_idx, ret;
665     ram_addr_t offset;
666     VhostUserMemoryRegion region_buffer;
667 
668     /*
669      * The regions in remove_reg appear in the same order they do in the
670      * shadow table. Therefore we can minimize memory copies by iterating
671      * through remove_reg backwards.
672      */
673     for (i = nr_rem_reg - 1; i >= 0; i--) {
674         shadow_reg = remove_reg[i].region;
675         shadow_reg_idx = remove_reg[i].reg_idx;
676 
677         vhost_user_get_mr_data(shadow_reg->userspace_addr, &offset, &fd);
678 
679         if (fd > 0) {
680             msg->hdr.request = VHOST_USER_REM_MEM_REG;
681             vhost_user_fill_msg_region(&region_buffer, shadow_reg, 0);
682             msg->payload.mem_reg.region = region_buffer;
683 
684             ret = vhost_user_write(dev, msg, NULL, 0);
685             if (ret < 0) {
686                 return ret;
687             }
688 
689             if (reply_supported) {
690                 ret = process_message_reply(dev, msg);
691                 if (ret) {
692                     return ret;
693                 }
694             }
695         }
696 
697         /*
698          * At this point we know the backend has unmapped the region. It is now
699          * safe to remove it from the shadow table.
700          */
701         memmove(&u->shadow_regions[shadow_reg_idx],
702                 &u->shadow_regions[shadow_reg_idx + 1],
703                 sizeof(struct vhost_memory_region) *
704                 (u->num_shadow_regions - shadow_reg_idx - 1));
705         u->num_shadow_regions--;
706     }
707 
708     return 0;
709 }
710 
711 static int send_add_regions(struct vhost_dev *dev,
712                             struct scrub_regions *add_reg, int nr_add_reg,
713                             VhostUserMsg *msg, uint64_t *shadow_pcb,
714                             bool reply_supported, bool track_ramblocks)
715 {
716     struct vhost_user *u = dev->opaque;
717     int i, fd, ret, reg_idx, reg_fd_idx;
718     struct vhost_memory_region *reg;
719     MemoryRegion *mr;
720     ram_addr_t offset;
721     VhostUserMsg msg_reply;
722     VhostUserMemoryRegion region_buffer;
723 
724     for (i = 0; i < nr_add_reg; i++) {
725         reg = add_reg[i].region;
726         reg_idx = add_reg[i].reg_idx;
727         reg_fd_idx = add_reg[i].fd_idx;
728 
729         mr = vhost_user_get_mr_data(reg->userspace_addr, &offset, &fd);
730 
731         if (fd > 0) {
732             if (track_ramblocks) {
733                 trace_vhost_user_set_mem_table_withfd(reg_fd_idx, mr->name,
734                                                       reg->memory_size,
735                                                       reg->guest_phys_addr,
736                                                       reg->userspace_addr,
737                                                       offset);
738                 u->region_rb_offset[reg_idx] = offset;
739                 u->region_rb[reg_idx] = mr->ram_block;
740             }
741             msg->hdr.request = VHOST_USER_ADD_MEM_REG;
742             vhost_user_fill_msg_region(&region_buffer, reg, offset);
743             msg->payload.mem_reg.region = region_buffer;
744 
745             ret = vhost_user_write(dev, msg, &fd, 1);
746             if (ret < 0) {
747                 return ret;
748             }
749 
750             if (track_ramblocks) {
751                 uint64_t reply_gpa;
752 
753                 ret = vhost_user_read(dev, &msg_reply);
754                 if (ret < 0) {
755                     return ret;
756                 }
757 
758                 reply_gpa = msg_reply.payload.mem_reg.region.guest_phys_addr;
759 
760                 if (msg_reply.hdr.request != VHOST_USER_ADD_MEM_REG) {
761                     error_report("%s: Received unexpected msg type."
762                                  "Expected %d received %d", __func__,
763                                  VHOST_USER_ADD_MEM_REG,
764                                  msg_reply.hdr.request);
765                     return -EPROTO;
766                 }
767 
768                 /*
769                  * We're using the same structure, just reusing one of the
770                  * fields, so it should be the same size.
771                  */
772                 if (msg_reply.hdr.size != msg->hdr.size) {
773                     error_report("%s: Unexpected size for postcopy reply "
774                                  "%d vs %d", __func__, msg_reply.hdr.size,
775                                  msg->hdr.size);
776                     return -EPROTO;
777                 }
778 
779                 /* Get the postcopy client base from the backend's reply. */
780                 if (reply_gpa == dev->mem->regions[reg_idx].guest_phys_addr) {
781                     shadow_pcb[reg_idx] =
782                         msg_reply.payload.mem_reg.region.userspace_addr;
783                     trace_vhost_user_set_mem_table_postcopy(
784                         msg_reply.payload.mem_reg.region.userspace_addr,
785                         msg->payload.mem_reg.region.userspace_addr,
786                         reg_fd_idx, reg_idx);
787                 } else {
788                     error_report("%s: invalid postcopy reply for region. "
789                                  "Got guest physical address %" PRIX64 ", expected "
790                                  "%" PRIX64, __func__, reply_gpa,
791                                  dev->mem->regions[reg_idx].guest_phys_addr);
792                     return -EPROTO;
793                 }
794             } else if (reply_supported) {
795                 ret = process_message_reply(dev, msg);
796                 if (ret) {
797                     return ret;
798                 }
799             }
800         } else if (track_ramblocks) {
801             u->region_rb_offset[reg_idx] = 0;
802             u->region_rb[reg_idx] = NULL;
803         }
804 
805         /*
806          * At this point, we know the backend has mapped in the new
807          * region, if the region has a valid file descriptor.
808          *
809          * The region should now be added to the shadow table.
810          */
811         u->shadow_regions[u->num_shadow_regions].guest_phys_addr =
812             reg->guest_phys_addr;
813         u->shadow_regions[u->num_shadow_regions].userspace_addr =
814             reg->userspace_addr;
815         u->shadow_regions[u->num_shadow_regions].memory_size =
816             reg->memory_size;
817         u->num_shadow_regions++;
818     }
819 
820     return 0;
821 }
822 
823 static int vhost_user_add_remove_regions(struct vhost_dev *dev,
824                                          VhostUserMsg *msg,
825                                          bool reply_supported,
826                                          bool track_ramblocks)
827 {
828     struct vhost_user *u = dev->opaque;
829     struct scrub_regions add_reg[VHOST_USER_MAX_RAM_SLOTS];
830     struct scrub_regions rem_reg[VHOST_USER_MAX_RAM_SLOTS];
831     uint64_t shadow_pcb[VHOST_USER_MAX_RAM_SLOTS] = {};
832     int nr_add_reg, nr_rem_reg;
833     int ret;
834 
835     msg->hdr.size = sizeof(msg->payload.mem_reg);
836 
837     /* Find the regions which need to be removed or added. */
838     scrub_shadow_regions(dev, add_reg, &nr_add_reg, rem_reg, &nr_rem_reg,
839                          shadow_pcb, track_ramblocks);
840 
841     if (nr_rem_reg) {
842         ret = send_remove_regions(dev, rem_reg, nr_rem_reg, msg,
843                                   reply_supported);
844         if (ret < 0) {
845             goto err;
846         }
847     }
848 
849     if (nr_add_reg) {
850         ret = send_add_regions(dev, add_reg, nr_add_reg, msg, shadow_pcb,
851                                reply_supported, track_ramblocks);
852         if (ret < 0) {
853             goto err;
854         }
855     }
856 
857     if (track_ramblocks) {
858         memcpy(u->postcopy_client_bases, shadow_pcb,
859                sizeof(uint64_t) * VHOST_USER_MAX_RAM_SLOTS);
860         /*
861          * Now we've registered this with the postcopy code, we ack to the
862          * client, because now we're in the position to be able to deal with
863          * any faults it generates.
864          */
865         /* TODO: Use this for failure cases as well with a bad value. */
866         msg->hdr.size = sizeof(msg->payload.u64);
867         msg->payload.u64 = 0; /* OK */
868 
869         ret = vhost_user_write(dev, msg, NULL, 0);
870         if (ret < 0) {
871             return ret;
872         }
873     }
874 
875     return 0;
876 
877 err:
878     if (track_ramblocks) {
879         memcpy(u->postcopy_client_bases, shadow_pcb,
880                sizeof(uint64_t) * VHOST_USER_MAX_RAM_SLOTS);
881     }
882 
883     return ret;
884 }
885 
886 static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,
887                                              struct vhost_memory *mem,
888                                              bool reply_supported,
889                                              bool config_mem_slots)
890 {
891     struct vhost_user *u = dev->opaque;
892     int fds[VHOST_MEMORY_BASELINE_NREGIONS];
893     size_t fd_num = 0;
894     VhostUserMsg msg_reply;
895     int region_i, msg_i;
896     int ret;
897 
898     VhostUserMsg msg = {
899         .hdr.flags = VHOST_USER_VERSION,
900     };
901 
902     if (u->region_rb_len < dev->mem->nregions) {
903         u->region_rb = g_renew(RAMBlock*, u->region_rb, dev->mem->nregions);
904         u->region_rb_offset = g_renew(ram_addr_t, u->region_rb_offset,
905                                       dev->mem->nregions);
906         memset(&(u->region_rb[u->region_rb_len]), '\0',
907                sizeof(RAMBlock *) * (dev->mem->nregions - u->region_rb_len));
908         memset(&(u->region_rb_offset[u->region_rb_len]), '\0',
909                sizeof(ram_addr_t) * (dev->mem->nregions - u->region_rb_len));
910         u->region_rb_len = dev->mem->nregions;
911     }
912 
913     if (config_mem_slots) {
914         ret = vhost_user_add_remove_regions(dev, &msg, reply_supported, true);
915         if (ret < 0) {
916             return ret;
917         }
918     } else {
919         ret = vhost_user_fill_set_mem_table_msg(u, dev, &msg, fds, &fd_num,
920                                                 true);
921         if (ret < 0) {
922             return ret;
923         }
924 
925         ret = vhost_user_write(dev, &msg, fds, fd_num);
926         if (ret < 0) {
927             return ret;
928         }
929 
930         ret = vhost_user_read(dev, &msg_reply);
931         if (ret < 0) {
932             return ret;
933         }
934 
935         if (msg_reply.hdr.request != VHOST_USER_SET_MEM_TABLE) {
936             error_report("%s: Received unexpected msg type."
937                          "Expected %d received %d", __func__,
938                          VHOST_USER_SET_MEM_TABLE, msg_reply.hdr.request);
939             return -EPROTO;
940         }
941 
942         /*
943          * We're using the same structure, just reusing one of the
944          * fields, so it should be the same size.
945          */
946         if (msg_reply.hdr.size != msg.hdr.size) {
947             error_report("%s: Unexpected size for postcopy reply "
948                          "%d vs %d", __func__, msg_reply.hdr.size,
949                          msg.hdr.size);
950             return -EPROTO;
951         }
952 
953         memset(u->postcopy_client_bases, 0,
954                sizeof(uint64_t) * VHOST_USER_MAX_RAM_SLOTS);
955 
956         /*
957          * They're in the same order as the regions that were sent
958          * but some of the regions were skipped (above) if they
959          * didn't have fd's
960          */
961         for (msg_i = 0, region_i = 0;
962              region_i < dev->mem->nregions;
963              region_i++) {
964             if (msg_i < fd_num &&
965                 msg_reply.payload.memory.regions[msg_i].guest_phys_addr ==
966                 dev->mem->regions[region_i].guest_phys_addr) {
967                 u->postcopy_client_bases[region_i] =
968                     msg_reply.payload.memory.regions[msg_i].userspace_addr;
969                 trace_vhost_user_set_mem_table_postcopy(
970                     msg_reply.payload.memory.regions[msg_i].userspace_addr,
971                     msg.payload.memory.regions[msg_i].userspace_addr,
972                     msg_i, region_i);
973                 msg_i++;
974             }
975         }
976         if (msg_i != fd_num) {
977             error_report("%s: postcopy reply not fully consumed "
978                          "%d vs %zd",
979                          __func__, msg_i, fd_num);
980             return -EIO;
981         }
982 
983         /*
984          * Now we've registered this with the postcopy code, we ack to the
985          * client, because now we're in the position to be able to deal
986          * with any faults it generates.
987          */
988         /* TODO: Use this for failure cases as well with a bad value. */
989         msg.hdr.size = sizeof(msg.payload.u64);
990         msg.payload.u64 = 0; /* OK */
991         ret = vhost_user_write(dev, &msg, NULL, 0);
992         if (ret < 0) {
993             return ret;
994         }
995     }
996 
997     return 0;
998 }
999 
1000 static int vhost_user_set_mem_table(struct vhost_dev *dev,
1001                                     struct vhost_memory *mem)
1002 {
1003     struct vhost_user *u = dev->opaque;
1004     int fds[VHOST_MEMORY_BASELINE_NREGIONS];
1005     size_t fd_num = 0;
1006     bool do_postcopy = u->postcopy_listen && u->postcopy_fd.handler;
1007     bool reply_supported = virtio_has_feature(dev->protocol_features,
1008                                               VHOST_USER_PROTOCOL_F_REPLY_ACK);
1009     bool config_mem_slots =
1010         virtio_has_feature(dev->protocol_features,
1011                            VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTS);
1012     int ret;
1013 
1014     if (do_postcopy) {
1015         /*
1016          * Postcopy has enough differences that it's best done in it's own
1017          * version
1018          */
1019         return vhost_user_set_mem_table_postcopy(dev, mem, reply_supported,
1020                                                  config_mem_slots);
1021     }
1022 
1023     VhostUserMsg msg = {
1024         .hdr.flags = VHOST_USER_VERSION,
1025     };
1026 
1027     if (reply_supported) {
1028         msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
1029     }
1030 
1031     if (config_mem_slots) {
1032         ret = vhost_user_add_remove_regions(dev, &msg, reply_supported, false);
1033         if (ret < 0) {
1034             return ret;
1035         }
1036     } else {
1037         ret = vhost_user_fill_set_mem_table_msg(u, dev, &msg, fds, &fd_num,
1038                                                 false);
1039         if (ret < 0) {
1040             return ret;
1041         }
1042 
1043         ret = vhost_user_write(dev, &msg, fds, fd_num);
1044         if (ret < 0) {
1045             return ret;
1046         }
1047 
1048         if (reply_supported) {
1049             return process_message_reply(dev, &msg);
1050         }
1051     }
1052 
1053     return 0;
1054 }
1055 
1056 static int vhost_user_set_vring_endian(struct vhost_dev *dev,
1057                                        struct vhost_vring_state *ring)
1058 {
1059     bool cross_endian = virtio_has_feature(dev->protocol_features,
1060                                            VHOST_USER_PROTOCOL_F_CROSS_ENDIAN);
1061     VhostUserMsg msg = {
1062         .hdr.request = VHOST_USER_SET_VRING_ENDIAN,
1063         .hdr.flags = VHOST_USER_VERSION,
1064         .payload.state = *ring,
1065         .hdr.size = sizeof(msg.payload.state),
1066     };
1067 
1068     if (!cross_endian) {
1069         error_report("vhost-user trying to send unhandled ioctl");
1070         return -ENOTSUP;
1071     }
1072 
1073     return vhost_user_write(dev, &msg, NULL, 0);
1074 }
1075 
1076 static int vhost_set_vring(struct vhost_dev *dev,
1077                            unsigned long int request,
1078                            struct vhost_vring_state *ring)
1079 {
1080     VhostUserMsg msg = {
1081         .hdr.request = request,
1082         .hdr.flags = VHOST_USER_VERSION,
1083         .payload.state = *ring,
1084         .hdr.size = sizeof(msg.payload.state),
1085     };
1086 
1087     return vhost_user_write(dev, &msg, NULL, 0);
1088 }
1089 
1090 static int vhost_user_set_vring_num(struct vhost_dev *dev,
1091                                     struct vhost_vring_state *ring)
1092 {
1093     return vhost_set_vring(dev, VHOST_USER_SET_VRING_NUM, ring);
1094 }
1095 
1096 static void vhost_user_host_notifier_free(VhostUserHostNotifier *n)
1097 {
1098     assert(n && n->unmap_addr);
1099     munmap(n->unmap_addr, qemu_real_host_page_size());
1100     n->unmap_addr = NULL;
1101 }
1102 
1103 /*
1104  * clean-up function for notifier, will finally free the structure
1105  * under rcu.
1106  */
1107 static void vhost_user_host_notifier_remove(VhostUserHostNotifier *n,
1108                                             VirtIODevice *vdev)
1109 {
1110     if (n->addr) {
1111         if (vdev) {
1112             virtio_queue_set_host_notifier_mr(vdev, n->idx, &n->mr, false);
1113         }
1114         assert(!n->unmap_addr);
1115         n->unmap_addr = n->addr;
1116         n->addr = NULL;
1117         call_rcu(n, vhost_user_host_notifier_free, rcu);
1118     }
1119 }
1120 
1121 static int vhost_user_set_vring_base(struct vhost_dev *dev,
1122                                      struct vhost_vring_state *ring)
1123 {
1124     return vhost_set_vring(dev, VHOST_USER_SET_VRING_BASE, ring);
1125 }
1126 
1127 static int vhost_user_set_vring_enable(struct vhost_dev *dev, int enable)
1128 {
1129     int i;
1130 
1131     if (!virtio_has_feature(dev->features, VHOST_USER_F_PROTOCOL_FEATURES)) {
1132         return -EINVAL;
1133     }
1134 
1135     for (i = 0; i < dev->nvqs; ++i) {
1136         int ret;
1137         struct vhost_vring_state state = {
1138             .index = dev->vq_index + i,
1139             .num   = enable,
1140         };
1141 
1142         ret = vhost_set_vring(dev, VHOST_USER_SET_VRING_ENABLE, &state);
1143         if (ret < 0) {
1144             /*
1145              * Restoring the previous state is likely infeasible, as well as
1146              * proceeding regardless the error, so just bail out and hope for
1147              * the device-level recovery.
1148              */
1149             return ret;
1150         }
1151     }
1152 
1153     return 0;
1154 }
1155 
1156 static VhostUserHostNotifier *fetch_notifier(VhostUserState *u,
1157                                              int idx)
1158 {
1159     if (idx >= u->notifiers->len) {
1160         return NULL;
1161     }
1162     return g_ptr_array_index(u->notifiers, idx);
1163 }
1164 
1165 static int vhost_user_get_vring_base(struct vhost_dev *dev,
1166                                      struct vhost_vring_state *ring)
1167 {
1168     int ret;
1169     VhostUserMsg msg = {
1170         .hdr.request = VHOST_USER_GET_VRING_BASE,
1171         .hdr.flags = VHOST_USER_VERSION,
1172         .payload.state = *ring,
1173         .hdr.size = sizeof(msg.payload.state),
1174     };
1175     struct vhost_user *u = dev->opaque;
1176 
1177     VhostUserHostNotifier *n = fetch_notifier(u->user, ring->index);
1178     if (n) {
1179         vhost_user_host_notifier_remove(n, dev->vdev);
1180     }
1181 
1182     ret = vhost_user_write(dev, &msg, NULL, 0);
1183     if (ret < 0) {
1184         return ret;
1185     }
1186 
1187     ret = vhost_user_read(dev, &msg);
1188     if (ret < 0) {
1189         return ret;
1190     }
1191 
1192     if (msg.hdr.request != VHOST_USER_GET_VRING_BASE) {
1193         error_report("Received unexpected msg type. Expected %d received %d",
1194                      VHOST_USER_GET_VRING_BASE, msg.hdr.request);
1195         return -EPROTO;
1196     }
1197 
1198     if (msg.hdr.size != sizeof(msg.payload.state)) {
1199         error_report("Received bad msg size.");
1200         return -EPROTO;
1201     }
1202 
1203     *ring = msg.payload.state;
1204 
1205     return 0;
1206 }
1207 
1208 static int vhost_set_vring_file(struct vhost_dev *dev,
1209                                 VhostUserRequest request,
1210                                 struct vhost_vring_file *file)
1211 {
1212     int fds[VHOST_USER_MAX_RAM_SLOTS];
1213     size_t fd_num = 0;
1214     VhostUserMsg msg = {
1215         .hdr.request = request,
1216         .hdr.flags = VHOST_USER_VERSION,
1217         .payload.u64 = file->index & VHOST_USER_VRING_IDX_MASK,
1218         .hdr.size = sizeof(msg.payload.u64),
1219     };
1220 
1221     if (ioeventfd_enabled() && file->fd > 0) {
1222         fds[fd_num++] = file->fd;
1223     } else {
1224         msg.payload.u64 |= VHOST_USER_VRING_NOFD_MASK;
1225     }
1226 
1227     return vhost_user_write(dev, &msg, fds, fd_num);
1228 }
1229 
1230 static int vhost_user_set_vring_kick(struct vhost_dev *dev,
1231                                      struct vhost_vring_file *file)
1232 {
1233     return vhost_set_vring_file(dev, VHOST_USER_SET_VRING_KICK, file);
1234 }
1235 
1236 static int vhost_user_set_vring_call(struct vhost_dev *dev,
1237                                      struct vhost_vring_file *file)
1238 {
1239     return vhost_set_vring_file(dev, VHOST_USER_SET_VRING_CALL, file);
1240 }
1241 
1242 static int vhost_user_set_vring_err(struct vhost_dev *dev,
1243                                     struct vhost_vring_file *file)
1244 {
1245     return vhost_set_vring_file(dev, VHOST_USER_SET_VRING_ERR, file);
1246 }
1247 
1248 static int vhost_user_get_u64(struct vhost_dev *dev, int request, uint64_t *u64)
1249 {
1250     int ret;
1251     VhostUserMsg msg = {
1252         .hdr.request = request,
1253         .hdr.flags = VHOST_USER_VERSION,
1254     };
1255 
1256     if (vhost_user_per_device_request(request) && dev->vq_index != 0) {
1257         return 0;
1258     }
1259 
1260     ret = vhost_user_write(dev, &msg, NULL, 0);
1261     if (ret < 0) {
1262         return ret;
1263     }
1264 
1265     ret = vhost_user_read(dev, &msg);
1266     if (ret < 0) {
1267         return ret;
1268     }
1269 
1270     if (msg.hdr.request != request) {
1271         error_report("Received unexpected msg type. Expected %d received %d",
1272                      request, msg.hdr.request);
1273         return -EPROTO;
1274     }
1275 
1276     if (msg.hdr.size != sizeof(msg.payload.u64)) {
1277         error_report("Received bad msg size.");
1278         return -EPROTO;
1279     }
1280 
1281     *u64 = msg.payload.u64;
1282 
1283     return 0;
1284 }
1285 
1286 static int vhost_user_get_features(struct vhost_dev *dev, uint64_t *features)
1287 {
1288     if (vhost_user_get_u64(dev, VHOST_USER_GET_FEATURES, features) < 0) {
1289         return -EPROTO;
1290     }
1291 
1292     return 0;
1293 }
1294 
1295 static int enforce_reply(struct vhost_dev *dev,
1296                          const VhostUserMsg *msg)
1297 {
1298     uint64_t dummy;
1299 
1300     if (msg->hdr.flags & VHOST_USER_NEED_REPLY_MASK) {
1301         return process_message_reply(dev, msg);
1302     }
1303 
1304    /*
1305     * We need to wait for a reply but the backend does not
1306     * support replies for the command we just sent.
1307     * Send VHOST_USER_GET_FEATURES which makes all backends
1308     * send a reply.
1309     */
1310     return vhost_user_get_features(dev, &dummy);
1311 }
1312 
1313 static int vhost_user_set_vring_addr(struct vhost_dev *dev,
1314                                      struct vhost_vring_addr *addr)
1315 {
1316     int ret;
1317     VhostUserMsg msg = {
1318         .hdr.request = VHOST_USER_SET_VRING_ADDR,
1319         .hdr.flags = VHOST_USER_VERSION,
1320         .payload.addr = *addr,
1321         .hdr.size = sizeof(msg.payload.addr),
1322     };
1323 
1324     bool reply_supported = virtio_has_feature(dev->protocol_features,
1325                                               VHOST_USER_PROTOCOL_F_REPLY_ACK);
1326 
1327     /*
1328      * wait for a reply if logging is enabled to make sure
1329      * backend is actually logging changes
1330      */
1331     bool wait_for_reply = addr->flags & (1 << VHOST_VRING_F_LOG);
1332 
1333     if (reply_supported && wait_for_reply) {
1334         msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
1335     }
1336 
1337     ret = vhost_user_write(dev, &msg, NULL, 0);
1338     if (ret < 0) {
1339         return ret;
1340     }
1341 
1342     if (wait_for_reply) {
1343         return enforce_reply(dev, &msg);
1344     }
1345 
1346     return 0;
1347 }
1348 
1349 static int vhost_user_set_u64(struct vhost_dev *dev, int request, uint64_t u64,
1350                               bool wait_for_reply)
1351 {
1352     VhostUserMsg msg = {
1353         .hdr.request = request,
1354         .hdr.flags = VHOST_USER_VERSION,
1355         .payload.u64 = u64,
1356         .hdr.size = sizeof(msg.payload.u64),
1357     };
1358     int ret;
1359 
1360     if (wait_for_reply) {
1361         bool reply_supported = virtio_has_feature(dev->protocol_features,
1362                                           VHOST_USER_PROTOCOL_F_REPLY_ACK);
1363         if (reply_supported) {
1364             msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
1365         }
1366     }
1367 
1368     ret = vhost_user_write(dev, &msg, NULL, 0);
1369     if (ret < 0) {
1370         return ret;
1371     }
1372 
1373     if (wait_for_reply) {
1374         return enforce_reply(dev, &msg);
1375     }
1376 
1377     return 0;
1378 }
1379 
1380 static int vhost_user_set_status(struct vhost_dev *dev, uint8_t status)
1381 {
1382     return vhost_user_set_u64(dev, VHOST_USER_SET_STATUS, status, false);
1383 }
1384 
1385 static int vhost_user_get_status(struct vhost_dev *dev, uint8_t *status)
1386 {
1387     uint64_t value;
1388     int ret;
1389 
1390     ret = vhost_user_get_u64(dev, VHOST_USER_GET_STATUS, &value);
1391     if (ret < 0) {
1392         return ret;
1393     }
1394     *status = value;
1395 
1396     return 0;
1397 }
1398 
1399 static int vhost_user_add_status(struct vhost_dev *dev, uint8_t status)
1400 {
1401     uint8_t s;
1402     int ret;
1403 
1404     ret = vhost_user_get_status(dev, &s);
1405     if (ret < 0) {
1406         return ret;
1407     }
1408 
1409     if ((s & status) == status) {
1410         return 0;
1411     }
1412     s |= status;
1413 
1414     return vhost_user_set_status(dev, s);
1415 }
1416 
1417 static int vhost_user_set_features(struct vhost_dev *dev,
1418                                    uint64_t features)
1419 {
1420     /*
1421      * wait for a reply if logging is enabled to make sure
1422      * backend is actually logging changes
1423      */
1424     bool log_enabled = features & (0x1ULL << VHOST_F_LOG_ALL);
1425     int ret;
1426 
1427     /*
1428      * We need to include any extra backend only feature bits that
1429      * might be needed by our device. Currently this includes the
1430      * VHOST_USER_F_PROTOCOL_FEATURES bit for enabling protocol
1431      * features.
1432      */
1433     ret = vhost_user_set_u64(dev, VHOST_USER_SET_FEATURES,
1434                               features | dev->backend_features,
1435                               log_enabled);
1436 
1437     if (virtio_has_feature(dev->protocol_features,
1438                            VHOST_USER_PROTOCOL_F_STATUS)) {
1439         if (!ret) {
1440             return vhost_user_add_status(dev, VIRTIO_CONFIG_S_FEATURES_OK);
1441         }
1442     }
1443 
1444     return ret;
1445 }
1446 
1447 static int vhost_user_set_protocol_features(struct vhost_dev *dev,
1448                                             uint64_t features)
1449 {
1450     return vhost_user_set_u64(dev, VHOST_USER_SET_PROTOCOL_FEATURES, features,
1451                               false);
1452 }
1453 
1454 static int vhost_user_set_owner(struct vhost_dev *dev)
1455 {
1456     VhostUserMsg msg = {
1457         .hdr.request = VHOST_USER_SET_OWNER,
1458         .hdr.flags = VHOST_USER_VERSION,
1459     };
1460 
1461     return vhost_user_write(dev, &msg, NULL, 0);
1462 }
1463 
1464 static int vhost_user_get_max_memslots(struct vhost_dev *dev,
1465                                        uint64_t *max_memslots)
1466 {
1467     uint64_t backend_max_memslots;
1468     int err;
1469 
1470     err = vhost_user_get_u64(dev, VHOST_USER_GET_MAX_MEM_SLOTS,
1471                              &backend_max_memslots);
1472     if (err < 0) {
1473         return err;
1474     }
1475 
1476     *max_memslots = backend_max_memslots;
1477 
1478     return 0;
1479 }
1480 
1481 static int vhost_user_reset_device(struct vhost_dev *dev)
1482 {
1483     VhostUserMsg msg = {
1484         .hdr.flags = VHOST_USER_VERSION,
1485     };
1486 
1487     msg.hdr.request = virtio_has_feature(dev->protocol_features,
1488                                          VHOST_USER_PROTOCOL_F_RESET_DEVICE)
1489         ? VHOST_USER_RESET_DEVICE
1490         : VHOST_USER_RESET_OWNER;
1491 
1492     return vhost_user_write(dev, &msg, NULL, 0);
1493 }
1494 
1495 static int vhost_user_backend_handle_config_change(struct vhost_dev *dev)
1496 {
1497     if (!dev->config_ops || !dev->config_ops->vhost_dev_config_notifier) {
1498         return -ENOSYS;
1499     }
1500 
1501     return dev->config_ops->vhost_dev_config_notifier(dev);
1502 }
1503 
1504 /*
1505  * Fetch or create the notifier for a given idx. Newly created
1506  * notifiers are added to the pointer array that tracks them.
1507  */
1508 static VhostUserHostNotifier *fetch_or_create_notifier(VhostUserState *u,
1509                                                        int idx)
1510 {
1511     VhostUserHostNotifier *n = NULL;
1512     if (idx >= u->notifiers->len) {
1513         g_ptr_array_set_size(u->notifiers, idx + 1);
1514     }
1515 
1516     n = g_ptr_array_index(u->notifiers, idx);
1517     if (!n) {
1518         /*
1519          * In case notification arrive out-of-order,
1520          * make room for current index.
1521          */
1522         g_ptr_array_remove_index(u->notifiers, idx);
1523         n = g_new0(VhostUserHostNotifier, 1);
1524         n->idx = idx;
1525         g_ptr_array_insert(u->notifiers, idx, n);
1526         trace_vhost_user_create_notifier(idx, n);
1527     }
1528 
1529     return n;
1530 }
1531 
1532 static int vhost_user_backend_handle_vring_host_notifier(struct vhost_dev *dev,
1533                                                        VhostUserVringArea *area,
1534                                                        int fd)
1535 {
1536     int queue_idx = area->u64 & VHOST_USER_VRING_IDX_MASK;
1537     size_t page_size = qemu_real_host_page_size();
1538     struct vhost_user *u = dev->opaque;
1539     VhostUserState *user = u->user;
1540     VirtIODevice *vdev = dev->vdev;
1541     VhostUserHostNotifier *n;
1542     void *addr;
1543     char *name;
1544 
1545     if (!virtio_has_feature(dev->protocol_features,
1546                             VHOST_USER_PROTOCOL_F_HOST_NOTIFIER) ||
1547         vdev == NULL || queue_idx >= virtio_get_num_queues(vdev)) {
1548         return -EINVAL;
1549     }
1550 
1551     /*
1552      * Fetch notifier and invalidate any old data before setting up
1553      * new mapped address.
1554      */
1555     n = fetch_or_create_notifier(user, queue_idx);
1556     vhost_user_host_notifier_remove(n, vdev);
1557 
1558     if (area->u64 & VHOST_USER_VRING_NOFD_MASK) {
1559         return 0;
1560     }
1561 
1562     /* Sanity check. */
1563     if (area->size != page_size) {
1564         return -EINVAL;
1565     }
1566 
1567     addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED,
1568                 fd, area->offset);
1569     if (addr == MAP_FAILED) {
1570         return -EFAULT;
1571     }
1572 
1573     name = g_strdup_printf("vhost-user/host-notifier@%p mmaps[%d]",
1574                            user, queue_idx);
1575     if (!n->mr.ram) { /* Don't init again after suspend. */
1576         memory_region_init_ram_device_ptr(&n->mr, OBJECT(vdev), name,
1577                                           page_size, addr);
1578     } else {
1579         n->mr.ram_block->host = addr;
1580     }
1581     g_free(name);
1582 
1583     if (virtio_queue_set_host_notifier_mr(vdev, queue_idx, &n->mr, true)) {
1584         object_unparent(OBJECT(&n->mr));
1585         munmap(addr, page_size);
1586         return -ENXIO;
1587     }
1588 
1589     n->addr = addr;
1590 
1591     return 0;
1592 }
1593 
1594 static int
1595 vhost_user_backend_handle_shared_object_add(struct vhost_dev *dev,
1596                                             VhostUserShared *object)
1597 {
1598     QemuUUID uuid;
1599 
1600     memcpy(uuid.data, object->uuid, sizeof(object->uuid));
1601     return virtio_add_vhost_device(&uuid, dev);
1602 }
1603 
1604 static int
1605 vhost_user_backend_handle_shared_object_remove(VhostUserShared *object)
1606 {
1607     QemuUUID uuid;
1608 
1609     memcpy(uuid.data, object->uuid, sizeof(object->uuid));
1610     return virtio_remove_resource(&uuid);
1611 }
1612 
1613 static bool vhost_user_send_resp(QIOChannel *ioc, VhostUserHeader *hdr,
1614                                  VhostUserPayload *payload, Error **errp)
1615 {
1616     struct iovec iov[] = {
1617         { .iov_base = hdr,      .iov_len = VHOST_USER_HDR_SIZE },
1618         { .iov_base = payload,  .iov_len = hdr->size },
1619     };
1620 
1621     hdr->flags &= ~VHOST_USER_NEED_REPLY_MASK;
1622     hdr->flags |= VHOST_USER_REPLY_MASK;
1623 
1624     return !qio_channel_writev_all(ioc, iov, ARRAY_SIZE(iov), errp);
1625 }
1626 
1627 static bool
1628 vhost_user_backend_send_dmabuf_fd(QIOChannel *ioc, VhostUserHeader *hdr,
1629                                   VhostUserPayload *payload, Error **errp)
1630 {
1631     hdr->size = sizeof(payload->u64);
1632     return vhost_user_send_resp(ioc, hdr, payload, errp);
1633 }
1634 
1635 int vhost_user_get_shared_object(struct vhost_dev *dev, unsigned char *uuid,
1636                                  int *dmabuf_fd)
1637 {
1638     struct vhost_user *u = dev->opaque;
1639     CharBackend *chr = u->user->chr;
1640     int ret;
1641     VhostUserMsg msg = {
1642         .hdr.request = VHOST_USER_GET_SHARED_OBJECT,
1643         .hdr.flags = VHOST_USER_VERSION,
1644     };
1645     memcpy(msg.payload.object.uuid, uuid, sizeof(msg.payload.object.uuid));
1646 
1647     ret = vhost_user_write(dev, &msg, NULL, 0);
1648     if (ret < 0) {
1649         return ret;
1650     }
1651 
1652     ret = vhost_user_read(dev, &msg);
1653     if (ret < 0) {
1654         return ret;
1655     }
1656 
1657     if (msg.hdr.request != VHOST_USER_GET_SHARED_OBJECT) {
1658         error_report("Received unexpected msg type. "
1659                      "Expected %d received %d",
1660                      VHOST_USER_GET_SHARED_OBJECT, msg.hdr.request);
1661         return -EPROTO;
1662     }
1663 
1664     *dmabuf_fd = qemu_chr_fe_get_msgfd(chr);
1665     if (*dmabuf_fd < 0) {
1666         error_report("Failed to get dmabuf fd");
1667         return -EIO;
1668     }
1669 
1670     return 0;
1671 }
1672 
1673 static int
1674 vhost_user_backend_handle_shared_object_lookup(struct vhost_user *u,
1675                                                QIOChannel *ioc,
1676                                                VhostUserHeader *hdr,
1677                                                VhostUserPayload *payload)
1678 {
1679     QemuUUID uuid;
1680     CharBackend *chr = u->user->chr;
1681     Error *local_err = NULL;
1682     int dmabuf_fd = -1;
1683     int fd_num = 0;
1684 
1685     memcpy(uuid.data, payload->object.uuid, sizeof(payload->object.uuid));
1686 
1687     payload->u64 = 0;
1688     switch (virtio_object_type(&uuid)) {
1689     case TYPE_DMABUF:
1690         dmabuf_fd = virtio_lookup_dmabuf(&uuid);
1691         break;
1692     case TYPE_VHOST_DEV:
1693     {
1694         struct vhost_dev *dev = virtio_lookup_vhost_device(&uuid);
1695         if (dev == NULL) {
1696             payload->u64 = -EINVAL;
1697             break;
1698         }
1699         int ret = vhost_user_get_shared_object(dev, uuid.data, &dmabuf_fd);
1700         if (ret < 0) {
1701             payload->u64 = ret;
1702         }
1703         break;
1704     }
1705     case TYPE_INVALID:
1706         payload->u64 = -EINVAL;
1707         break;
1708     }
1709 
1710     if (dmabuf_fd != -1) {
1711         fd_num++;
1712     }
1713 
1714     if (qemu_chr_fe_set_msgfds(chr, &dmabuf_fd, fd_num) < 0) {
1715         error_report("Failed to set msg fds.");
1716         payload->u64 = -EINVAL;
1717     }
1718 
1719     if (!vhost_user_backend_send_dmabuf_fd(ioc, hdr, payload, &local_err)) {
1720         error_report_err(local_err);
1721         return -EINVAL;
1722     }
1723 
1724     return 0;
1725 }
1726 
1727 static void close_backend_channel(struct vhost_user *u)
1728 {
1729     g_source_destroy(u->backend_src);
1730     g_source_unref(u->backend_src);
1731     u->backend_src = NULL;
1732     object_unref(OBJECT(u->backend_ioc));
1733     u->backend_ioc = NULL;
1734 }
1735 
1736 static gboolean backend_read(QIOChannel *ioc, GIOCondition condition,
1737                            gpointer opaque)
1738 {
1739     struct vhost_dev *dev = opaque;
1740     struct vhost_user *u = dev->opaque;
1741     VhostUserHeader hdr = { 0, };
1742     VhostUserPayload payload = { 0, };
1743     Error *local_err = NULL;
1744     gboolean rc = G_SOURCE_CONTINUE;
1745     int ret = 0;
1746     struct iovec iov;
1747     g_autofree int *fd = NULL;
1748     size_t fdsize = 0;
1749     int i;
1750 
1751     /* Read header */
1752     iov.iov_base = &hdr;
1753     iov.iov_len = VHOST_USER_HDR_SIZE;
1754 
1755     if (qio_channel_readv_full_all(ioc, &iov, 1, &fd, &fdsize, &local_err)) {
1756         error_report_err(local_err);
1757         goto err;
1758     }
1759 
1760     if (hdr.size > VHOST_USER_PAYLOAD_SIZE) {
1761         error_report("Failed to read msg header."
1762                 " Size %d exceeds the maximum %zu.", hdr.size,
1763                 VHOST_USER_PAYLOAD_SIZE);
1764         goto err;
1765     }
1766 
1767     /* Read payload */
1768     if (qio_channel_read_all(ioc, (char *) &payload, hdr.size, &local_err)) {
1769         error_report_err(local_err);
1770         goto err;
1771     }
1772 
1773     switch (hdr.request) {
1774     case VHOST_USER_BACKEND_IOTLB_MSG:
1775         ret = vhost_backend_handle_iotlb_msg(dev, &payload.iotlb);
1776         break;
1777     case VHOST_USER_BACKEND_CONFIG_CHANGE_MSG:
1778         ret = vhost_user_backend_handle_config_change(dev);
1779         break;
1780     case VHOST_USER_BACKEND_VRING_HOST_NOTIFIER_MSG:
1781         ret = vhost_user_backend_handle_vring_host_notifier(dev, &payload.area,
1782                                                           fd ? fd[0] : -1);
1783         break;
1784     case VHOST_USER_BACKEND_SHARED_OBJECT_ADD:
1785         ret = vhost_user_backend_handle_shared_object_add(dev, &payload.object);
1786         break;
1787     case VHOST_USER_BACKEND_SHARED_OBJECT_REMOVE:
1788         ret = vhost_user_backend_handle_shared_object_remove(&payload.object);
1789         break;
1790     case VHOST_USER_BACKEND_SHARED_OBJECT_LOOKUP:
1791         ret = vhost_user_backend_handle_shared_object_lookup(dev->opaque, ioc,
1792                                                              &hdr, &payload);
1793         break;
1794     default:
1795         error_report("Received unexpected msg type: %d.", hdr.request);
1796         ret = -EINVAL;
1797     }
1798 
1799     /*
1800      * REPLY_ACK feature handling. Other reply types has to be managed
1801      * directly in their request handlers.
1802      */
1803     if (hdr.flags & VHOST_USER_NEED_REPLY_MASK) {
1804         payload.u64 = !!ret;
1805         hdr.size = sizeof(payload.u64);
1806 
1807         if (!vhost_user_send_resp(ioc, &hdr, &payload, &local_err)) {
1808             error_report_err(local_err);
1809             goto err;
1810         }
1811     }
1812 
1813     goto fdcleanup;
1814 
1815 err:
1816     close_backend_channel(u);
1817     rc = G_SOURCE_REMOVE;
1818 
1819 fdcleanup:
1820     if (fd) {
1821         for (i = 0; i < fdsize; i++) {
1822             close(fd[i]);
1823         }
1824     }
1825     return rc;
1826 }
1827 
1828 static int vhost_setup_backend_channel(struct vhost_dev *dev)
1829 {
1830     VhostUserMsg msg = {
1831         .hdr.request = VHOST_USER_SET_BACKEND_REQ_FD,
1832         .hdr.flags = VHOST_USER_VERSION,
1833     };
1834     struct vhost_user *u = dev->opaque;
1835     int sv[2], ret = 0;
1836     bool reply_supported = virtio_has_feature(dev->protocol_features,
1837                                               VHOST_USER_PROTOCOL_F_REPLY_ACK);
1838     Error *local_err = NULL;
1839     QIOChannel *ioc;
1840 
1841     if (!virtio_has_feature(dev->protocol_features,
1842                             VHOST_USER_PROTOCOL_F_BACKEND_REQ)) {
1843         return 0;
1844     }
1845 
1846     if (qemu_socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
1847         int saved_errno = errno;
1848         error_report("socketpair() failed");
1849         return -saved_errno;
1850     }
1851 
1852     ioc = QIO_CHANNEL(qio_channel_socket_new_fd(sv[0], &local_err));
1853     if (!ioc) {
1854         error_report_err(local_err);
1855         return -ECONNREFUSED;
1856     }
1857     u->backend_ioc = ioc;
1858     u->backend_src = qio_channel_add_watch_source(u->backend_ioc,
1859                                                 G_IO_IN | G_IO_HUP,
1860                                                 backend_read, dev, NULL, NULL);
1861 
1862     if (reply_supported) {
1863         msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
1864     }
1865 
1866     ret = vhost_user_write(dev, &msg, &sv[1], 1);
1867     if (ret) {
1868         goto out;
1869     }
1870 
1871     if (reply_supported) {
1872         ret = process_message_reply(dev, &msg);
1873     }
1874 
1875 out:
1876     close(sv[1]);
1877     if (ret) {
1878         close_backend_channel(u);
1879     }
1880 
1881     return ret;
1882 }
1883 
1884 #ifdef CONFIG_LINUX
1885 /*
1886  * Called back from the postcopy fault thread when a fault is received on our
1887  * ufd.
1888  * TODO: This is Linux specific
1889  */
1890 static int vhost_user_postcopy_fault_handler(struct PostCopyFD *pcfd,
1891                                              void *ufd)
1892 {
1893     struct vhost_dev *dev = pcfd->data;
1894     struct vhost_user *u = dev->opaque;
1895     struct uffd_msg *msg = ufd;
1896     uint64_t faultaddr = msg->arg.pagefault.address;
1897     RAMBlock *rb = NULL;
1898     uint64_t rb_offset;
1899     int i;
1900 
1901     trace_vhost_user_postcopy_fault_handler(pcfd->idstr, faultaddr,
1902                                             dev->mem->nregions);
1903     for (i = 0; i < MIN(dev->mem->nregions, u->region_rb_len); i++) {
1904         trace_vhost_user_postcopy_fault_handler_loop(i,
1905                 u->postcopy_client_bases[i], dev->mem->regions[i].memory_size);
1906         if (faultaddr >= u->postcopy_client_bases[i]) {
1907             /* Ofset of the fault address in the vhost region */
1908             uint64_t region_offset = faultaddr - u->postcopy_client_bases[i];
1909             if (region_offset < dev->mem->regions[i].memory_size) {
1910                 rb_offset = region_offset + u->region_rb_offset[i];
1911                 trace_vhost_user_postcopy_fault_handler_found(i,
1912                         region_offset, rb_offset);
1913                 rb = u->region_rb[i];
1914                 return postcopy_request_shared_page(pcfd, rb, faultaddr,
1915                                                     rb_offset);
1916             }
1917         }
1918     }
1919     error_report("%s: Failed to find region for fault %" PRIx64,
1920                  __func__, faultaddr);
1921     return -1;
1922 }
1923 
1924 static int vhost_user_postcopy_waker(struct PostCopyFD *pcfd, RAMBlock *rb,
1925                                      uint64_t offset)
1926 {
1927     struct vhost_dev *dev = pcfd->data;
1928     struct vhost_user *u = dev->opaque;
1929     int i;
1930 
1931     trace_vhost_user_postcopy_waker(qemu_ram_get_idstr(rb), offset);
1932 
1933     if (!u) {
1934         return 0;
1935     }
1936     /* Translate the offset into an address in the clients address space */
1937     for (i = 0; i < MIN(dev->mem->nregions, u->region_rb_len); i++) {
1938         if (u->region_rb[i] == rb &&
1939             offset >= u->region_rb_offset[i] &&
1940             offset < (u->region_rb_offset[i] +
1941                       dev->mem->regions[i].memory_size)) {
1942             uint64_t client_addr = (offset - u->region_rb_offset[i]) +
1943                                    u->postcopy_client_bases[i];
1944             trace_vhost_user_postcopy_waker_found(client_addr);
1945             return postcopy_wake_shared(pcfd, client_addr, rb);
1946         }
1947     }
1948 
1949     trace_vhost_user_postcopy_waker_nomatch(qemu_ram_get_idstr(rb), offset);
1950     return 0;
1951 }
1952 #endif
1953 
1954 /*
1955  * Called at the start of an inbound postcopy on reception of the
1956  * 'advise' command.
1957  */
1958 static int vhost_user_postcopy_advise(struct vhost_dev *dev, Error **errp)
1959 {
1960 #ifdef CONFIG_LINUX
1961     struct vhost_user *u = dev->opaque;
1962     CharBackend *chr = u->user->chr;
1963     int ufd;
1964     int ret;
1965     VhostUserMsg msg = {
1966         .hdr.request = VHOST_USER_POSTCOPY_ADVISE,
1967         .hdr.flags = VHOST_USER_VERSION,
1968     };
1969 
1970     ret = vhost_user_write(dev, &msg, NULL, 0);
1971     if (ret < 0) {
1972         error_setg(errp, "Failed to send postcopy_advise to vhost");
1973         return ret;
1974     }
1975 
1976     ret = vhost_user_read(dev, &msg);
1977     if (ret < 0) {
1978         error_setg(errp, "Failed to get postcopy_advise reply from vhost");
1979         return ret;
1980     }
1981 
1982     if (msg.hdr.request != VHOST_USER_POSTCOPY_ADVISE) {
1983         error_setg(errp, "Unexpected msg type. Expected %d received %d",
1984                      VHOST_USER_POSTCOPY_ADVISE, msg.hdr.request);
1985         return -EPROTO;
1986     }
1987 
1988     if (msg.hdr.size) {
1989         error_setg(errp, "Received bad msg size.");
1990         return -EPROTO;
1991     }
1992     ufd = qemu_chr_fe_get_msgfd(chr);
1993     if (ufd < 0) {
1994         error_setg(errp, "%s: Failed to get ufd", __func__);
1995         return -EIO;
1996     }
1997     qemu_socket_set_nonblock(ufd);
1998 
1999     /* register ufd with userfault thread */
2000     u->postcopy_fd.fd = ufd;
2001     u->postcopy_fd.data = dev;
2002     u->postcopy_fd.handler = vhost_user_postcopy_fault_handler;
2003     u->postcopy_fd.waker = vhost_user_postcopy_waker;
2004     u->postcopy_fd.idstr = "vhost-user"; /* Need to find unique name */
2005     postcopy_register_shared_ufd(&u->postcopy_fd);
2006     return 0;
2007 #else
2008     error_setg(errp, "Postcopy not supported on non-Linux systems");
2009     return -ENOSYS;
2010 #endif
2011 }
2012 
2013 /*
2014  * Called at the switch to postcopy on reception of the 'listen' command.
2015  */
2016 static int vhost_user_postcopy_listen(struct vhost_dev *dev, Error **errp)
2017 {
2018     struct vhost_user *u = dev->opaque;
2019     int ret;
2020     VhostUserMsg msg = {
2021         .hdr.request = VHOST_USER_POSTCOPY_LISTEN,
2022         .hdr.flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY_MASK,
2023     };
2024     u->postcopy_listen = true;
2025 
2026     trace_vhost_user_postcopy_listen();
2027 
2028     ret = vhost_user_write(dev, &msg, NULL, 0);
2029     if (ret < 0) {
2030         error_setg(errp, "Failed to send postcopy_listen to vhost");
2031         return ret;
2032     }
2033 
2034     ret = process_message_reply(dev, &msg);
2035     if (ret) {
2036         error_setg(errp, "Failed to receive reply to postcopy_listen");
2037         return ret;
2038     }
2039 
2040     return 0;
2041 }
2042 
2043 /*
2044  * Called at the end of postcopy
2045  */
2046 static int vhost_user_postcopy_end(struct vhost_dev *dev, Error **errp)
2047 {
2048     VhostUserMsg msg = {
2049         .hdr.request = VHOST_USER_POSTCOPY_END,
2050         .hdr.flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY_MASK,
2051     };
2052     int ret;
2053     struct vhost_user *u = dev->opaque;
2054 
2055     trace_vhost_user_postcopy_end_entry();
2056 
2057     ret = vhost_user_write(dev, &msg, NULL, 0);
2058     if (ret < 0) {
2059         error_setg(errp, "Failed to send postcopy_end to vhost");
2060         return ret;
2061     }
2062 
2063     ret = process_message_reply(dev, &msg);
2064     if (ret) {
2065         error_setg(errp, "Failed to receive reply to postcopy_end");
2066         return ret;
2067     }
2068     postcopy_unregister_shared_ufd(&u->postcopy_fd);
2069     close(u->postcopy_fd.fd);
2070     u->postcopy_fd.handler = NULL;
2071 
2072     trace_vhost_user_postcopy_end_exit();
2073 
2074     return 0;
2075 }
2076 
2077 static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,
2078                                         void *opaque)
2079 {
2080     struct PostcopyNotifyData *pnd = opaque;
2081     struct vhost_user *u = container_of(notifier, struct vhost_user,
2082                                          postcopy_notifier);
2083     struct vhost_dev *dev = u->dev;
2084 
2085     switch (pnd->reason) {
2086     case POSTCOPY_NOTIFY_PROBE:
2087         if (!virtio_has_feature(dev->protocol_features,
2088                                 VHOST_USER_PROTOCOL_F_PAGEFAULT)) {
2089             /* TODO: Get the device name into this error somehow */
2090             error_setg(pnd->errp,
2091                        "vhost-user backend not capable of postcopy");
2092             return -ENOENT;
2093         }
2094         break;
2095 
2096     case POSTCOPY_NOTIFY_INBOUND_ADVISE:
2097         return vhost_user_postcopy_advise(dev, pnd->errp);
2098 
2099     case POSTCOPY_NOTIFY_INBOUND_LISTEN:
2100         return vhost_user_postcopy_listen(dev, pnd->errp);
2101 
2102     case POSTCOPY_NOTIFY_INBOUND_END:
2103         return vhost_user_postcopy_end(dev, pnd->errp);
2104 
2105     default:
2106         /* We ignore notifications we don't know */
2107         break;
2108     }
2109 
2110     return 0;
2111 }
2112 
2113 static int vhost_user_backend_init(struct vhost_dev *dev, void *opaque,
2114                                    Error **errp)
2115 {
2116     uint64_t features, ram_slots;
2117     struct vhost_user *u;
2118     VhostUserState *vus = (VhostUserState *) opaque;
2119     int err;
2120 
2121     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER);
2122 
2123     u = g_new0(struct vhost_user, 1);
2124     u->user = vus;
2125     u->dev = dev;
2126     dev->opaque = u;
2127 
2128     err = vhost_user_get_features(dev, &features);
2129     if (err < 0) {
2130         error_setg_errno(errp, -err, "vhost_backend_init failed");
2131         return err;
2132     }
2133 
2134     if (virtio_has_feature(features, VHOST_USER_F_PROTOCOL_FEATURES)) {
2135         bool supports_f_config = vus->supports_config ||
2136             (dev->config_ops && dev->config_ops->vhost_dev_config_notifier);
2137         uint64_t protocol_features;
2138 
2139         dev->backend_features |= 1ULL << VHOST_USER_F_PROTOCOL_FEATURES;
2140 
2141         err = vhost_user_get_u64(dev, VHOST_USER_GET_PROTOCOL_FEATURES,
2142                                  &protocol_features);
2143         if (err < 0) {
2144             error_setg_errno(errp, EPROTO, "vhost_backend_init failed");
2145             return -EPROTO;
2146         }
2147 
2148         /*
2149          * We will use all the protocol features we support - although
2150          * we suppress F_CONFIG if we know QEMUs internal code can not support
2151          * it.
2152          */
2153         protocol_features &= VHOST_USER_PROTOCOL_FEATURE_MASK;
2154 
2155         if (supports_f_config) {
2156             if (!virtio_has_feature(protocol_features,
2157                                     VHOST_USER_PROTOCOL_F_CONFIG)) {
2158                 error_setg(errp, "vhost-user device expecting "
2159                            "VHOST_USER_PROTOCOL_F_CONFIG but the vhost-user backend does "
2160                            "not support it.");
2161                 return -EPROTO;
2162             }
2163         } else {
2164             if (virtio_has_feature(protocol_features,
2165                                    VHOST_USER_PROTOCOL_F_CONFIG)) {
2166                 warn_report("vhost-user backend supports "
2167                             "VHOST_USER_PROTOCOL_F_CONFIG but QEMU does not.");
2168                 protocol_features &= ~(1ULL << VHOST_USER_PROTOCOL_F_CONFIG);
2169             }
2170         }
2171 
2172         /* final set of protocol features */
2173         dev->protocol_features = protocol_features;
2174         err = vhost_user_set_protocol_features(dev, dev->protocol_features);
2175         if (err < 0) {
2176             error_setg_errno(errp, EPROTO, "vhost_backend_init failed");
2177             return -EPROTO;
2178         }
2179 
2180         /* query the max queues we support if backend supports Multiple Queue */
2181         if (dev->protocol_features & (1ULL << VHOST_USER_PROTOCOL_F_MQ)) {
2182             err = vhost_user_get_u64(dev, VHOST_USER_GET_QUEUE_NUM,
2183                                      &dev->max_queues);
2184             if (err < 0) {
2185                 error_setg_errno(errp, EPROTO, "vhost_backend_init failed");
2186                 return -EPROTO;
2187             }
2188         } else {
2189             dev->max_queues = 1;
2190         }
2191 
2192         if (dev->num_queues && dev->max_queues < dev->num_queues) {
2193             error_setg(errp, "The maximum number of queues supported by the "
2194                        "backend is %" PRIu64, dev->max_queues);
2195             return -EINVAL;
2196         }
2197 
2198         if (virtio_has_feature(features, VIRTIO_F_IOMMU_PLATFORM) &&
2199                 !(virtio_has_feature(dev->protocol_features,
2200                     VHOST_USER_PROTOCOL_F_BACKEND_REQ) &&
2201                  virtio_has_feature(dev->protocol_features,
2202                     VHOST_USER_PROTOCOL_F_REPLY_ACK))) {
2203             error_setg(errp, "IOMMU support requires reply-ack and "
2204                        "backend-req protocol features.");
2205             return -EINVAL;
2206         }
2207 
2208         /* get max memory regions if backend supports configurable RAM slots */
2209         if (!virtio_has_feature(dev->protocol_features,
2210                                 VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTS)) {
2211             u->user->memory_slots = VHOST_MEMORY_BASELINE_NREGIONS;
2212         } else {
2213             err = vhost_user_get_max_memslots(dev, &ram_slots);
2214             if (err < 0) {
2215                 error_setg_errno(errp, EPROTO, "vhost_backend_init failed");
2216                 return -EPROTO;
2217             }
2218 
2219             if (ram_slots < u->user->memory_slots) {
2220                 error_setg(errp, "The backend specified a max ram slots limit "
2221                            "of %" PRIu64", when the prior validated limit was "
2222                            "%d. This limit should never decrease.", ram_slots,
2223                            u->user->memory_slots);
2224                 return -EINVAL;
2225             }
2226 
2227             u->user->memory_slots = MIN(ram_slots, VHOST_USER_MAX_RAM_SLOTS);
2228         }
2229     }
2230 
2231     if (dev->migration_blocker == NULL &&
2232         !virtio_has_feature(dev->protocol_features,
2233                             VHOST_USER_PROTOCOL_F_LOG_SHMFD)) {
2234         error_setg(&dev->migration_blocker,
2235                    "Migration disabled: vhost-user backend lacks "
2236                    "VHOST_USER_PROTOCOL_F_LOG_SHMFD feature.");
2237     }
2238 
2239     if (dev->vq_index == 0) {
2240         err = vhost_setup_backend_channel(dev);
2241         if (err < 0) {
2242             error_setg_errno(errp, EPROTO, "vhost_backend_init failed");
2243             return -EPROTO;
2244         }
2245     }
2246 
2247     u->postcopy_notifier.notify = vhost_user_postcopy_notifier;
2248     postcopy_add_notifier(&u->postcopy_notifier);
2249 
2250     return 0;
2251 }
2252 
2253 static int vhost_user_backend_cleanup(struct vhost_dev *dev)
2254 {
2255     struct vhost_user *u;
2256 
2257     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER);
2258 
2259     u = dev->opaque;
2260     if (u->postcopy_notifier.notify) {
2261         postcopy_remove_notifier(&u->postcopy_notifier);
2262         u->postcopy_notifier.notify = NULL;
2263     }
2264     u->postcopy_listen = false;
2265     if (u->postcopy_fd.handler) {
2266         postcopy_unregister_shared_ufd(&u->postcopy_fd);
2267         close(u->postcopy_fd.fd);
2268         u->postcopy_fd.handler = NULL;
2269     }
2270     if (u->backend_ioc) {
2271         close_backend_channel(u);
2272     }
2273     g_free(u->region_rb);
2274     u->region_rb = NULL;
2275     g_free(u->region_rb_offset);
2276     u->region_rb_offset = NULL;
2277     u->region_rb_len = 0;
2278     g_free(u);
2279     dev->opaque = 0;
2280 
2281     return 0;
2282 }
2283 
2284 static int vhost_user_get_vq_index(struct vhost_dev *dev, int idx)
2285 {
2286     assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs);
2287 
2288     return idx;
2289 }
2290 
2291 static int vhost_user_memslots_limit(struct vhost_dev *dev)
2292 {
2293     struct vhost_user *u = dev->opaque;
2294 
2295     return u->user->memory_slots;
2296 }
2297 
2298 static bool vhost_user_requires_shm_log(struct vhost_dev *dev)
2299 {
2300     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER);
2301 
2302     return virtio_has_feature(dev->protocol_features,
2303                               VHOST_USER_PROTOCOL_F_LOG_SHMFD);
2304 }
2305 
2306 static int vhost_user_migration_done(struct vhost_dev *dev, char* mac_addr)
2307 {
2308     VhostUserMsg msg = { };
2309 
2310     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER);
2311 
2312     /* If guest supports GUEST_ANNOUNCE do nothing */
2313     if (virtio_has_feature(dev->acked_features, VIRTIO_NET_F_GUEST_ANNOUNCE)) {
2314         return 0;
2315     }
2316 
2317     /* if backend supports VHOST_USER_PROTOCOL_F_RARP ask it to send the RARP */
2318     if (virtio_has_feature(dev->protocol_features,
2319                            VHOST_USER_PROTOCOL_F_RARP)) {
2320         msg.hdr.request = VHOST_USER_SEND_RARP;
2321         msg.hdr.flags = VHOST_USER_VERSION;
2322         memcpy((char *)&msg.payload.u64, mac_addr, 6);
2323         msg.hdr.size = sizeof(msg.payload.u64);
2324 
2325         return vhost_user_write(dev, &msg, NULL, 0);
2326     }
2327     return -ENOTSUP;
2328 }
2329 
2330 static bool vhost_user_can_merge(struct vhost_dev *dev,
2331                                  uint64_t start1, uint64_t size1,
2332                                  uint64_t start2, uint64_t size2)
2333 {
2334     ram_addr_t offset;
2335     int mfd, rfd;
2336 
2337     (void)vhost_user_get_mr_data(start1, &offset, &mfd);
2338     (void)vhost_user_get_mr_data(start2, &offset, &rfd);
2339 
2340     return mfd == rfd;
2341 }
2342 
2343 static int vhost_user_net_set_mtu(struct vhost_dev *dev, uint16_t mtu)
2344 {
2345     VhostUserMsg msg;
2346     bool reply_supported = virtio_has_feature(dev->protocol_features,
2347                                               VHOST_USER_PROTOCOL_F_REPLY_ACK);
2348     int ret;
2349 
2350     if (!(dev->protocol_features & (1ULL << VHOST_USER_PROTOCOL_F_NET_MTU))) {
2351         return 0;
2352     }
2353 
2354     msg.hdr.request = VHOST_USER_NET_SET_MTU;
2355     msg.payload.u64 = mtu;
2356     msg.hdr.size = sizeof(msg.payload.u64);
2357     msg.hdr.flags = VHOST_USER_VERSION;
2358     if (reply_supported) {
2359         msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
2360     }
2361 
2362     ret = vhost_user_write(dev, &msg, NULL, 0);
2363     if (ret < 0) {
2364         return ret;
2365     }
2366 
2367     /* If reply_ack supported, backend has to ack specified MTU is valid */
2368     if (reply_supported) {
2369         return process_message_reply(dev, &msg);
2370     }
2371 
2372     return 0;
2373 }
2374 
2375 static int vhost_user_send_device_iotlb_msg(struct vhost_dev *dev,
2376                                             struct vhost_iotlb_msg *imsg)
2377 {
2378     int ret;
2379     VhostUserMsg msg = {
2380         .hdr.request = VHOST_USER_IOTLB_MSG,
2381         .hdr.size = sizeof(msg.payload.iotlb),
2382         .hdr.flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY_MASK,
2383         .payload.iotlb = *imsg,
2384     };
2385 
2386     ret = vhost_user_write(dev, &msg, NULL, 0);
2387     if (ret < 0) {
2388         return ret;
2389     }
2390 
2391     return process_message_reply(dev, &msg);
2392 }
2393 
2394 
2395 static void vhost_user_set_iotlb_callback(struct vhost_dev *dev, int enabled)
2396 {
2397     /* No-op as the receive channel is not dedicated to IOTLB messages. */
2398 }
2399 
2400 static int vhost_user_get_config(struct vhost_dev *dev, uint8_t *config,
2401                                  uint32_t config_len, Error **errp)
2402 {
2403     int ret;
2404     VhostUserMsg msg = {
2405         .hdr.request = VHOST_USER_GET_CONFIG,
2406         .hdr.flags = VHOST_USER_VERSION,
2407         .hdr.size = VHOST_USER_CONFIG_HDR_SIZE + config_len,
2408     };
2409 
2410     if (!virtio_has_feature(dev->protocol_features,
2411                 VHOST_USER_PROTOCOL_F_CONFIG)) {
2412         error_setg(errp, "VHOST_USER_PROTOCOL_F_CONFIG not supported");
2413         return -EINVAL;
2414     }
2415 
2416     assert(config_len <= VHOST_USER_MAX_CONFIG_SIZE);
2417 
2418     msg.payload.config.offset = 0;
2419     msg.payload.config.size = config_len;
2420     ret = vhost_user_write(dev, &msg, NULL, 0);
2421     if (ret < 0) {
2422         error_setg_errno(errp, -ret, "vhost_get_config failed");
2423         return ret;
2424     }
2425 
2426     ret = vhost_user_read(dev, &msg);
2427     if (ret < 0) {
2428         error_setg_errno(errp, -ret, "vhost_get_config failed");
2429         return ret;
2430     }
2431 
2432     if (msg.hdr.request != VHOST_USER_GET_CONFIG) {
2433         error_setg(errp,
2434                    "Received unexpected msg type. Expected %d received %d",
2435                    VHOST_USER_GET_CONFIG, msg.hdr.request);
2436         return -EPROTO;
2437     }
2438 
2439     if (msg.hdr.size != VHOST_USER_CONFIG_HDR_SIZE + config_len) {
2440         error_setg(errp, "Received bad msg size.");
2441         return -EPROTO;
2442     }
2443 
2444     memcpy(config, msg.payload.config.region, config_len);
2445 
2446     return 0;
2447 }
2448 
2449 static int vhost_user_set_config(struct vhost_dev *dev, const uint8_t *data,
2450                                  uint32_t offset, uint32_t size, uint32_t flags)
2451 {
2452     int ret;
2453     uint8_t *p;
2454     bool reply_supported = virtio_has_feature(dev->protocol_features,
2455                                               VHOST_USER_PROTOCOL_F_REPLY_ACK);
2456 
2457     VhostUserMsg msg = {
2458         .hdr.request = VHOST_USER_SET_CONFIG,
2459         .hdr.flags = VHOST_USER_VERSION,
2460         .hdr.size = VHOST_USER_CONFIG_HDR_SIZE + size,
2461     };
2462 
2463     if (!virtio_has_feature(dev->protocol_features,
2464                 VHOST_USER_PROTOCOL_F_CONFIG)) {
2465         return -ENOTSUP;
2466     }
2467 
2468     if (reply_supported) {
2469         msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;
2470     }
2471 
2472     if (size > VHOST_USER_MAX_CONFIG_SIZE) {
2473         return -EINVAL;
2474     }
2475 
2476     msg.payload.config.offset = offset,
2477     msg.payload.config.size = size,
2478     msg.payload.config.flags = flags,
2479     p = msg.payload.config.region;
2480     memcpy(p, data, size);
2481 
2482     ret = vhost_user_write(dev, &msg, NULL, 0);
2483     if (ret < 0) {
2484         return ret;
2485     }
2486 
2487     if (reply_supported) {
2488         return process_message_reply(dev, &msg);
2489     }
2490 
2491     return 0;
2492 }
2493 
2494 static int vhost_user_crypto_create_session(struct vhost_dev *dev,
2495                                             void *session_info,
2496                                             uint64_t *session_id)
2497 {
2498     int ret;
2499     bool crypto_session = virtio_has_feature(dev->protocol_features,
2500                                        VHOST_USER_PROTOCOL_F_CRYPTO_SESSION);
2501     CryptoDevBackendSessionInfo *backend_info = session_info;
2502     VhostUserMsg msg = {
2503         .hdr.request = VHOST_USER_CREATE_CRYPTO_SESSION,
2504         .hdr.flags = VHOST_USER_VERSION,
2505         .hdr.size = sizeof(msg.payload.session),
2506     };
2507 
2508     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER);
2509 
2510     if (!crypto_session) {
2511         error_report("vhost-user trying to send unhandled ioctl");
2512         return -ENOTSUP;
2513     }
2514 
2515     if (backend_info->op_code == VIRTIO_CRYPTO_AKCIPHER_CREATE_SESSION) {
2516         CryptoDevBackendAsymSessionInfo *sess = &backend_info->u.asym_sess_info;
2517         size_t keylen;
2518 
2519         memcpy(&msg.payload.session.u.asym.session_setup_data, sess,
2520                sizeof(CryptoDevBackendAsymSessionInfo));
2521         if (sess->keylen) {
2522             keylen = sizeof(msg.payload.session.u.asym.key);
2523             if (sess->keylen > keylen) {
2524                 error_report("Unsupported asymmetric key size");
2525                 return -ENOTSUP;
2526             }
2527 
2528             memcpy(&msg.payload.session.u.asym.key, sess->key,
2529                    sess->keylen);
2530         }
2531     } else {
2532         CryptoDevBackendSymSessionInfo *sess = &backend_info->u.sym_sess_info;
2533         size_t keylen;
2534 
2535         memcpy(&msg.payload.session.u.sym.session_setup_data, sess,
2536                sizeof(CryptoDevBackendSymSessionInfo));
2537         if (sess->key_len) {
2538             keylen = sizeof(msg.payload.session.u.sym.key);
2539             if (sess->key_len > keylen) {
2540                 error_report("Unsupported cipher key size");
2541                 return -ENOTSUP;
2542             }
2543 
2544             memcpy(&msg.payload.session.u.sym.key, sess->cipher_key,
2545                    sess->key_len);
2546         }
2547 
2548         if (sess->auth_key_len > 0) {
2549             keylen = sizeof(msg.payload.session.u.sym.auth_key);
2550             if (sess->auth_key_len > keylen) {
2551                 error_report("Unsupported auth key size");
2552                 return -ENOTSUP;
2553             }
2554 
2555             memcpy(&msg.payload.session.u.sym.auth_key, sess->auth_key,
2556                    sess->auth_key_len);
2557         }
2558     }
2559 
2560     msg.payload.session.op_code = backend_info->op_code;
2561     msg.payload.session.session_id = backend_info->session_id;
2562     ret = vhost_user_write(dev, &msg, NULL, 0);
2563     if (ret < 0) {
2564         error_report("vhost_user_write() return %d, create session failed",
2565                      ret);
2566         return ret;
2567     }
2568 
2569     ret = vhost_user_read(dev, &msg);
2570     if (ret < 0) {
2571         error_report("vhost_user_read() return %d, create session failed",
2572                      ret);
2573         return ret;
2574     }
2575 
2576     if (msg.hdr.request != VHOST_USER_CREATE_CRYPTO_SESSION) {
2577         error_report("Received unexpected msg type. Expected %d received %d",
2578                      VHOST_USER_CREATE_CRYPTO_SESSION, msg.hdr.request);
2579         return -EPROTO;
2580     }
2581 
2582     if (msg.hdr.size != sizeof(msg.payload.session)) {
2583         error_report("Received bad msg size.");
2584         return -EPROTO;
2585     }
2586 
2587     if (msg.payload.session.session_id < 0) {
2588         error_report("Bad session id: %" PRId64 "",
2589                               msg.payload.session.session_id);
2590         return -EINVAL;
2591     }
2592     *session_id = msg.payload.session.session_id;
2593 
2594     return 0;
2595 }
2596 
2597 static int
2598 vhost_user_crypto_close_session(struct vhost_dev *dev, uint64_t session_id)
2599 {
2600     int ret;
2601     bool crypto_session = virtio_has_feature(dev->protocol_features,
2602                                        VHOST_USER_PROTOCOL_F_CRYPTO_SESSION);
2603     VhostUserMsg msg = {
2604         .hdr.request = VHOST_USER_CLOSE_CRYPTO_SESSION,
2605         .hdr.flags = VHOST_USER_VERSION,
2606         .hdr.size = sizeof(msg.payload.u64),
2607     };
2608     msg.payload.u64 = session_id;
2609 
2610     if (!crypto_session) {
2611         error_report("vhost-user trying to send unhandled ioctl");
2612         return -ENOTSUP;
2613     }
2614 
2615     ret = vhost_user_write(dev, &msg, NULL, 0);
2616     if (ret < 0) {
2617         error_report("vhost_user_write() return %d, close session failed",
2618                      ret);
2619         return ret;
2620     }
2621 
2622     return 0;
2623 }
2624 
2625 static bool vhost_user_mem_section_filter(struct vhost_dev *dev,
2626                                           MemoryRegionSection *section)
2627 {
2628     return memory_region_get_fd(section->mr) >= 0;
2629 }
2630 
2631 static int vhost_user_get_inflight_fd(struct vhost_dev *dev,
2632                                       uint16_t queue_size,
2633                                       struct vhost_inflight *inflight)
2634 {
2635     void *addr;
2636     int fd;
2637     int ret;
2638     struct vhost_user *u = dev->opaque;
2639     CharBackend *chr = u->user->chr;
2640     VhostUserMsg msg = {
2641         .hdr.request = VHOST_USER_GET_INFLIGHT_FD,
2642         .hdr.flags = VHOST_USER_VERSION,
2643         .payload.inflight.num_queues = dev->nvqs,
2644         .payload.inflight.queue_size = queue_size,
2645         .hdr.size = sizeof(msg.payload.inflight),
2646     };
2647 
2648     if (!virtio_has_feature(dev->protocol_features,
2649                             VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) {
2650         return 0;
2651     }
2652 
2653     ret = vhost_user_write(dev, &msg, NULL, 0);
2654     if (ret < 0) {
2655         return ret;
2656     }
2657 
2658     ret = vhost_user_read(dev, &msg);
2659     if (ret < 0) {
2660         return ret;
2661     }
2662 
2663     if (msg.hdr.request != VHOST_USER_GET_INFLIGHT_FD) {
2664         error_report("Received unexpected msg type. "
2665                      "Expected %d received %d",
2666                      VHOST_USER_GET_INFLIGHT_FD, msg.hdr.request);
2667         return -EPROTO;
2668     }
2669 
2670     if (msg.hdr.size != sizeof(msg.payload.inflight)) {
2671         error_report("Received bad msg size.");
2672         return -EPROTO;
2673     }
2674 
2675     if (!msg.payload.inflight.mmap_size) {
2676         return 0;
2677     }
2678 
2679     fd = qemu_chr_fe_get_msgfd(chr);
2680     if (fd < 0) {
2681         error_report("Failed to get mem fd");
2682         return -EIO;
2683     }
2684 
2685     addr = mmap(0, msg.payload.inflight.mmap_size, PROT_READ | PROT_WRITE,
2686                 MAP_SHARED, fd, msg.payload.inflight.mmap_offset);
2687 
2688     if (addr == MAP_FAILED) {
2689         error_report("Failed to mmap mem fd");
2690         close(fd);
2691         return -EFAULT;
2692     }
2693 
2694     inflight->addr = addr;
2695     inflight->fd = fd;
2696     inflight->size = msg.payload.inflight.mmap_size;
2697     inflight->offset = msg.payload.inflight.mmap_offset;
2698     inflight->queue_size = queue_size;
2699 
2700     return 0;
2701 }
2702 
2703 static int vhost_user_set_inflight_fd(struct vhost_dev *dev,
2704                                       struct vhost_inflight *inflight)
2705 {
2706     VhostUserMsg msg = {
2707         .hdr.request = VHOST_USER_SET_INFLIGHT_FD,
2708         .hdr.flags = VHOST_USER_VERSION,
2709         .payload.inflight.mmap_size = inflight->size,
2710         .payload.inflight.mmap_offset = inflight->offset,
2711         .payload.inflight.num_queues = dev->nvqs,
2712         .payload.inflight.queue_size = inflight->queue_size,
2713         .hdr.size = sizeof(msg.payload.inflight),
2714     };
2715 
2716     if (!virtio_has_feature(dev->protocol_features,
2717                             VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) {
2718         return 0;
2719     }
2720 
2721     return vhost_user_write(dev, &msg, &inflight->fd, 1);
2722 }
2723 
2724 static void vhost_user_state_destroy(gpointer data)
2725 {
2726     VhostUserHostNotifier *n = (VhostUserHostNotifier *) data;
2727     if (n) {
2728         vhost_user_host_notifier_remove(n, NULL);
2729         object_unparent(OBJECT(&n->mr));
2730         /*
2731          * We can't free until vhost_user_host_notifier_remove has
2732          * done it's thing so schedule the free with RCU.
2733          */
2734         g_free_rcu(n, rcu);
2735     }
2736 }
2737 
2738 bool vhost_user_init(VhostUserState *user, CharBackend *chr, Error **errp)
2739 {
2740     if (user->chr) {
2741         error_setg(errp, "Cannot initialize vhost-user state");
2742         return false;
2743     }
2744     user->chr = chr;
2745     user->memory_slots = 0;
2746     user->notifiers = g_ptr_array_new_full(VIRTIO_QUEUE_MAX / 4,
2747                                            &vhost_user_state_destroy);
2748     return true;
2749 }
2750 
2751 void vhost_user_cleanup(VhostUserState *user)
2752 {
2753     if (!user->chr) {
2754         return;
2755     }
2756     memory_region_transaction_begin();
2757     user->notifiers = (GPtrArray *) g_ptr_array_free(user->notifiers, true);
2758     memory_region_transaction_commit();
2759     user->chr = NULL;
2760 }
2761 
2762 
2763 typedef struct {
2764     vu_async_close_fn cb;
2765     DeviceState *dev;
2766     CharBackend *cd;
2767     struct vhost_dev *vhost;
2768 } VhostAsyncCallback;
2769 
2770 static void vhost_user_async_close_bh(void *opaque)
2771 {
2772     VhostAsyncCallback *data = opaque;
2773     struct vhost_dev *vhost = data->vhost;
2774 
2775     /*
2776      * If the vhost_dev has been cleared in the meantime there is
2777      * nothing left to do as some other path has completed the
2778      * cleanup.
2779      */
2780     if (vhost->vdev) {
2781         data->cb(data->dev);
2782     }
2783 
2784     g_free(data);
2785 }
2786 
2787 /*
2788  * We only schedule the work if the machine is running. If suspended
2789  * we want to keep all the in-flight data as is for migration
2790  * purposes.
2791  */
2792 void vhost_user_async_close(DeviceState *d,
2793                             CharBackend *chardev, struct vhost_dev *vhost,
2794                             vu_async_close_fn cb)
2795 {
2796     if (!runstate_check(RUN_STATE_SHUTDOWN)) {
2797         /*
2798          * A close event may happen during a read/write, but vhost
2799          * code assumes the vhost_dev remains setup, so delay the
2800          * stop & clear.
2801          */
2802         AioContext *ctx = qemu_get_current_aio_context();
2803         VhostAsyncCallback *data = g_new0(VhostAsyncCallback, 1);
2804 
2805         /* Save data for the callback */
2806         data->cb = cb;
2807         data->dev = d;
2808         data->cd = chardev;
2809         data->vhost = vhost;
2810 
2811         /* Disable any further notifications on the chardev */
2812         qemu_chr_fe_set_handlers(chardev,
2813                                  NULL, NULL, NULL, NULL, NULL, NULL,
2814                                  false);
2815 
2816         aio_bh_schedule_oneshot(ctx, vhost_user_async_close_bh, data);
2817 
2818         /*
2819          * Move vhost device to the stopped state. The vhost-user device
2820          * will be clean up and disconnected in BH. This can be useful in
2821          * the vhost migration code. If disconnect was caught there is an
2822          * option for the general vhost code to get the dev state without
2823          * knowing its type (in this case vhost-user).
2824          *
2825          * Note if the vhost device is fully cleared by the time we
2826          * execute the bottom half we won't continue with the cleanup.
2827          */
2828         vhost->started = false;
2829     }
2830 }
2831 
2832 static int vhost_user_dev_start(struct vhost_dev *dev, bool started)
2833 {
2834     if (!virtio_has_feature(dev->protocol_features,
2835                             VHOST_USER_PROTOCOL_F_STATUS)) {
2836         return 0;
2837     }
2838 
2839     /* Set device status only for last queue pair */
2840     if (dev->vq_index + dev->nvqs != dev->vq_index_end) {
2841         return 0;
2842     }
2843 
2844     if (started) {
2845         return vhost_user_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
2846                                           VIRTIO_CONFIG_S_DRIVER |
2847                                           VIRTIO_CONFIG_S_DRIVER_OK);
2848     } else {
2849         return 0;
2850     }
2851 }
2852 
2853 static void vhost_user_reset_status(struct vhost_dev *dev)
2854 {
2855     /* Set device status only for last queue pair */
2856     if (dev->vq_index + dev->nvqs != dev->vq_index_end) {
2857         return;
2858     }
2859 
2860     if (virtio_has_feature(dev->protocol_features,
2861                            VHOST_USER_PROTOCOL_F_STATUS)) {
2862         vhost_user_set_status(dev, 0);
2863     }
2864 }
2865 
2866 const VhostOps user_ops = {
2867         .backend_type = VHOST_BACKEND_TYPE_USER,
2868         .vhost_backend_init = vhost_user_backend_init,
2869         .vhost_backend_cleanup = vhost_user_backend_cleanup,
2870         .vhost_backend_memslots_limit = vhost_user_memslots_limit,
2871         .vhost_set_log_base = vhost_user_set_log_base,
2872         .vhost_set_mem_table = vhost_user_set_mem_table,
2873         .vhost_set_vring_addr = vhost_user_set_vring_addr,
2874         .vhost_set_vring_endian = vhost_user_set_vring_endian,
2875         .vhost_set_vring_num = vhost_user_set_vring_num,
2876         .vhost_set_vring_base = vhost_user_set_vring_base,
2877         .vhost_get_vring_base = vhost_user_get_vring_base,
2878         .vhost_set_vring_kick = vhost_user_set_vring_kick,
2879         .vhost_set_vring_call = vhost_user_set_vring_call,
2880         .vhost_set_vring_err = vhost_user_set_vring_err,
2881         .vhost_set_features = vhost_user_set_features,
2882         .vhost_get_features = vhost_user_get_features,
2883         .vhost_set_owner = vhost_user_set_owner,
2884         .vhost_reset_device = vhost_user_reset_device,
2885         .vhost_get_vq_index = vhost_user_get_vq_index,
2886         .vhost_set_vring_enable = vhost_user_set_vring_enable,
2887         .vhost_requires_shm_log = vhost_user_requires_shm_log,
2888         .vhost_migration_done = vhost_user_migration_done,
2889         .vhost_backend_can_merge = vhost_user_can_merge,
2890         .vhost_net_set_mtu = vhost_user_net_set_mtu,
2891         .vhost_set_iotlb_callback = vhost_user_set_iotlb_callback,
2892         .vhost_send_device_iotlb_msg = vhost_user_send_device_iotlb_msg,
2893         .vhost_get_config = vhost_user_get_config,
2894         .vhost_set_config = vhost_user_set_config,
2895         .vhost_crypto_create_session = vhost_user_crypto_create_session,
2896         .vhost_crypto_close_session = vhost_user_crypto_close_session,
2897         .vhost_backend_mem_section_filter = vhost_user_mem_section_filter,
2898         .vhost_get_inflight_fd = vhost_user_get_inflight_fd,
2899         .vhost_set_inflight_fd = vhost_user_set_inflight_fd,
2900         .vhost_dev_start = vhost_user_dev_start,
2901         .vhost_reset_status = vhost_user_reset_status,
2902 };
2903