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