xref: /qemu/hw/virtio/vhost.c (revision ffd5a60e9b67e14f7bac7ea29300ea46a944e508)
1 /*
2  * vhost support
3  *
4  * Copyright Red Hat, Inc. 2010
5  *
6  * Authors:
7  *  Michael S. Tsirkin <mst@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qapi/error.h"
18 #include "hw/virtio/vhost.h"
19 #include "qemu/atomic.h"
20 #include "qemu/range.h"
21 #include "qemu/error-report.h"
22 #include "qemu/memfd.h"
23 #include "qemu/log.h"
24 #include "standard-headers/linux/vhost_types.h"
25 #include "hw/virtio/virtio-bus.h"
26 #include "hw/mem/memory-device.h"
27 #include "migration/blocker.h"
28 #include "migration/qemu-file-types.h"
29 #include "system/dma.h"
30 #include "trace.h"
31 
32 /* enabled until disconnected backend stabilizes */
33 #define _VHOST_DEBUG 1
34 
35 #ifdef _VHOST_DEBUG
36 #define VHOST_OPS_DEBUG(retval, fmt, ...) \
37     do { \
38         error_report(fmt ": %s (%d)", ## __VA_ARGS__, \
39                      strerror(-retval), -retval); \
40     } while (0)
41 #else
42 #define VHOST_OPS_DEBUG(retval, fmt, ...) \
43     do { } while (0)
44 #endif
45 
46 static struct vhost_log *vhost_log[VHOST_BACKEND_TYPE_MAX];
47 static struct vhost_log *vhost_log_shm[VHOST_BACKEND_TYPE_MAX];
48 static QLIST_HEAD(, vhost_dev) vhost_log_devs[VHOST_BACKEND_TYPE_MAX];
49 
50 /* Memslots used by backends that support private memslots (without an fd). */
51 static unsigned int used_memslots;
52 
53 /* Memslots used by backends that only support shared memslots (with an fd). */
54 static unsigned int used_shared_memslots;
55 
56 static QLIST_HEAD(, vhost_dev) vhost_devices =
57     QLIST_HEAD_INITIALIZER(vhost_devices);
58 
59 unsigned int vhost_get_max_memslots(void)
60 {
61     unsigned int max = UINT_MAX;
62     struct vhost_dev *hdev;
63 
64     QLIST_FOREACH(hdev, &vhost_devices, entry) {
65         max = MIN(max, hdev->vhost_ops->vhost_backend_memslots_limit(hdev));
66     }
67     return max;
68 }
69 
70 unsigned int vhost_get_free_memslots(void)
71 {
72     unsigned int free = UINT_MAX;
73     struct vhost_dev *hdev;
74 
75     QLIST_FOREACH(hdev, &vhost_devices, entry) {
76         unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
77         unsigned int cur_free;
78 
79         if (hdev->vhost_ops->vhost_backend_no_private_memslots &&
80             hdev->vhost_ops->vhost_backend_no_private_memslots(hdev)) {
81             cur_free = r - used_shared_memslots;
82         } else {
83             cur_free = r - used_memslots;
84         }
85         free = MIN(free, cur_free);
86     }
87     return free;
88 }
89 
90 static void vhost_dev_sync_region(struct vhost_dev *dev,
91                                   MemoryRegionSection *section,
92                                   uint64_t mfirst, uint64_t mlast,
93                                   uint64_t rfirst, uint64_t rlast)
94 {
95     vhost_log_chunk_t *dev_log = dev->log->log;
96 
97     uint64_t start = MAX(mfirst, rfirst);
98     uint64_t end = MIN(mlast, rlast);
99     vhost_log_chunk_t *from = dev_log + start / VHOST_LOG_CHUNK;
100     vhost_log_chunk_t *to = dev_log + end / VHOST_LOG_CHUNK + 1;
101     uint64_t addr = QEMU_ALIGN_DOWN(start, VHOST_LOG_CHUNK);
102 
103     if (end < start) {
104         return;
105     }
106     assert(end / VHOST_LOG_CHUNK < dev->log_size);
107     assert(start / VHOST_LOG_CHUNK < dev->log_size);
108 
109     for (;from < to; ++from) {
110         vhost_log_chunk_t log;
111         /* We first check with non-atomic: much cheaper,
112          * and we expect non-dirty to be the common case. */
113         if (!*from) {
114             addr += VHOST_LOG_CHUNK;
115             continue;
116         }
117         /* Data must be read atomically. We don't really need barrier semantics
118          * but it's easier to use atomic_* than roll our own. */
119         log = qatomic_xchg(from, 0);
120         while (log) {
121             int bit = ctzl(log);
122             hwaddr page_addr;
123             hwaddr section_offset;
124             hwaddr mr_offset;
125             page_addr = addr + bit * VHOST_LOG_PAGE;
126             section_offset = page_addr - section->offset_within_address_space;
127             mr_offset = section_offset + section->offset_within_region;
128             memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
129             log &= ~(0x1ull << bit);
130         }
131         addr += VHOST_LOG_CHUNK;
132     }
133 }
134 
135 bool vhost_dev_has_iommu(struct vhost_dev *dev)
136 {
137     VirtIODevice *vdev = dev->vdev;
138 
139     /*
140      * For vhost, VIRTIO_F_IOMMU_PLATFORM means the backend support
141      * incremental memory mapping API via IOTLB API. For platform that
142      * does not have IOMMU, there's no need to enable this feature
143      * which may cause unnecessary IOTLB miss/update transactions.
144      */
145     if (vdev) {
146         return virtio_bus_device_iommu_enabled(vdev) &&
147             virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM);
148     } else {
149         return false;
150     }
151 }
152 
153 static inline bool vhost_dev_should_log(struct vhost_dev *dev)
154 {
155     assert(dev->vhost_ops);
156     assert(dev->vhost_ops->backend_type > VHOST_BACKEND_TYPE_NONE);
157     assert(dev->vhost_ops->backend_type < VHOST_BACKEND_TYPE_MAX);
158 
159     return dev == QLIST_FIRST(&vhost_log_devs[dev->vhost_ops->backend_type]);
160 }
161 
162 static inline void vhost_dev_elect_mem_logger(struct vhost_dev *hdev, bool add)
163 {
164     VhostBackendType backend_type;
165 
166     assert(hdev->vhost_ops);
167 
168     backend_type = hdev->vhost_ops->backend_type;
169     assert(backend_type > VHOST_BACKEND_TYPE_NONE);
170     assert(backend_type < VHOST_BACKEND_TYPE_MAX);
171 
172     if (add && !QLIST_IS_INSERTED(hdev, logdev_entry)) {
173         if (QLIST_EMPTY(&vhost_log_devs[backend_type])) {
174             QLIST_INSERT_HEAD(&vhost_log_devs[backend_type],
175                               hdev, logdev_entry);
176         } else {
177             /*
178              * The first vhost_device in the list is selected as the shared
179              * logger to scan memory sections. Put new entry next to the head
180              * to avoid inadvertent change to the underlying logger device.
181              * This is done in order to get better cache locality and to avoid
182              * performance churn on the hot path for log scanning. Even when
183              * new devices come and go quickly, it wouldn't end up changing
184              * the active leading logger device at all.
185              */
186             QLIST_INSERT_AFTER(QLIST_FIRST(&vhost_log_devs[backend_type]),
187                                hdev, logdev_entry);
188         }
189     } else if (!add && QLIST_IS_INSERTED(hdev, logdev_entry)) {
190         QLIST_REMOVE(hdev, logdev_entry);
191     }
192 }
193 
194 static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
195                                    MemoryRegionSection *section,
196                                    hwaddr first,
197                                    hwaddr last)
198 {
199     int i;
200     hwaddr start_addr;
201     hwaddr end_addr;
202 
203     if (!dev->log_enabled || !dev->started) {
204         return 0;
205     }
206     start_addr = section->offset_within_address_space;
207     end_addr = range_get_last(start_addr, int128_get64(section->size));
208     start_addr = MAX(first, start_addr);
209     end_addr = MIN(last, end_addr);
210 
211     if (vhost_dev_should_log(dev)) {
212         for (i = 0; i < dev->mem->nregions; ++i) {
213             struct vhost_memory_region *reg = dev->mem->regions + i;
214             vhost_dev_sync_region(dev, section, start_addr, end_addr,
215                                   reg->guest_phys_addr,
216                                   range_get_last(reg->guest_phys_addr,
217                                                  reg->memory_size));
218         }
219     }
220     for (i = 0; i < dev->nvqs; ++i) {
221         struct vhost_virtqueue *vq = dev->vqs + i;
222 
223         if (!vq->used_phys && !vq->used_size) {
224             continue;
225         }
226 
227         if (vhost_dev_has_iommu(dev)) {
228             IOMMUTLBEntry iotlb;
229             hwaddr used_phys = vq->used_phys, used_size = vq->used_size;
230             hwaddr phys, s, offset;
231 
232             while (used_size) {
233                 rcu_read_lock();
234                 iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
235                                                       used_phys,
236                                                       true,
237                                                       MEMTXATTRS_UNSPECIFIED);
238                 rcu_read_unlock();
239 
240                 if (!iotlb.target_as) {
241                     qemu_log_mask(LOG_GUEST_ERROR, "translation "
242                                   "failure for used_iova %"PRIx64"\n",
243                                   used_phys);
244                     return -EINVAL;
245                 }
246 
247                 offset = used_phys & iotlb.addr_mask;
248                 phys = iotlb.translated_addr + offset;
249 
250                 /*
251                  * Distance from start of used ring until last byte of
252                  * IOMMU page.
253                  */
254                 s = iotlb.addr_mask - offset;
255                 /*
256                  * Size of used ring, or of the part of it until end
257                  * of IOMMU page. To avoid zero result, do the adding
258                  * outside of MIN().
259                  */
260                 s = MIN(s, used_size - 1) + 1;
261 
262                 vhost_dev_sync_region(dev, section, start_addr, end_addr, phys,
263                                       range_get_last(phys, s));
264                 used_size -= s;
265                 used_phys += s;
266             }
267         } else {
268             vhost_dev_sync_region(dev, section, start_addr,
269                                   end_addr, vq->used_phys,
270                                   range_get_last(vq->used_phys, vq->used_size));
271         }
272     }
273     return 0;
274 }
275 
276 static void vhost_log_sync(MemoryListener *listener,
277                           MemoryRegionSection *section)
278 {
279     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
280                                          memory_listener);
281     vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
282 }
283 
284 static void vhost_log_sync_range(struct vhost_dev *dev,
285                                  hwaddr first, hwaddr last)
286 {
287     int i;
288     /* FIXME: this is N^2 in number of sections */
289     for (i = 0; i < dev->n_mem_sections; ++i) {
290         MemoryRegionSection *section = &dev->mem_sections[i];
291         vhost_sync_dirty_bitmap(dev, section, first, last);
292     }
293 }
294 
295 static uint64_t vhost_get_log_size(struct vhost_dev *dev)
296 {
297     uint64_t log_size = 0;
298     int i;
299     for (i = 0; i < dev->mem->nregions; ++i) {
300         struct vhost_memory_region *reg = dev->mem->regions + i;
301         uint64_t last = range_get_last(reg->guest_phys_addr,
302                                        reg->memory_size);
303         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
304     }
305     return log_size;
306 }
307 
308 static int vhost_set_backend_type(struct vhost_dev *dev,
309                                   VhostBackendType backend_type)
310 {
311     int r = 0;
312 
313     switch (backend_type) {
314 #ifdef CONFIG_VHOST_KERNEL
315     case VHOST_BACKEND_TYPE_KERNEL:
316         dev->vhost_ops = &kernel_ops;
317         break;
318 #endif
319 #ifdef CONFIG_VHOST_USER
320     case VHOST_BACKEND_TYPE_USER:
321         dev->vhost_ops = &user_ops;
322         break;
323 #endif
324 #ifdef CONFIG_VHOST_VDPA
325     case VHOST_BACKEND_TYPE_VDPA:
326         dev->vhost_ops = &vdpa_ops;
327         break;
328 #endif
329     default:
330         error_report("Unknown vhost backend type");
331         r = -1;
332     }
333 
334     if (r == 0) {
335         assert(dev->vhost_ops->backend_type == backend_type);
336     }
337 
338     return r;
339 }
340 
341 static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
342 {
343     Error *err = NULL;
344     struct vhost_log *log;
345     uint64_t logsize = size * sizeof(*(log->log));
346     int fd = -1;
347 
348     log = g_new0(struct vhost_log, 1);
349     if (share) {
350         log->log = qemu_memfd_alloc("vhost-log", logsize,
351                                     F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
352                                     &fd, &err);
353         if (err) {
354             error_report_err(err);
355             g_free(log);
356             return NULL;
357         }
358         memset(log->log, 0, logsize);
359     } else {
360         log->log = g_malloc0(logsize);
361     }
362 
363     log->size = size;
364     log->refcnt = 1;
365     log->fd = fd;
366 
367     return log;
368 }
369 
370 static struct vhost_log *vhost_log_get(VhostBackendType backend_type,
371                                        uint64_t size, bool share)
372 {
373     struct vhost_log *log;
374 
375     assert(backend_type > VHOST_BACKEND_TYPE_NONE);
376     assert(backend_type < VHOST_BACKEND_TYPE_MAX);
377 
378     log = share ? vhost_log_shm[backend_type] : vhost_log[backend_type];
379 
380     if (!log || log->size != size) {
381         log = vhost_log_alloc(size, share);
382         if (share) {
383             vhost_log_shm[backend_type] = log;
384         } else {
385             vhost_log[backend_type] = log;
386         }
387     } else {
388         ++log->refcnt;
389     }
390 
391     return log;
392 }
393 
394 static void vhost_log_put(struct vhost_dev *dev, bool sync)
395 {
396     struct vhost_log *log = dev->log;
397     VhostBackendType backend_type;
398 
399     if (!log) {
400         return;
401     }
402 
403     assert(dev->vhost_ops);
404     backend_type = dev->vhost_ops->backend_type;
405 
406     if (backend_type == VHOST_BACKEND_TYPE_NONE ||
407         backend_type >= VHOST_BACKEND_TYPE_MAX) {
408         return;
409     }
410 
411     --log->refcnt;
412     if (log->refcnt == 0) {
413         /* Sync only the range covered by the old log */
414         if (dev->log_size && sync) {
415             vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
416         }
417 
418         if (vhost_log[backend_type] == log) {
419             g_free(log->log);
420             vhost_log[backend_type] = NULL;
421         } else if (vhost_log_shm[backend_type] == log) {
422             qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
423                             log->fd);
424             vhost_log_shm[backend_type] = NULL;
425         }
426 
427         g_free(log);
428     }
429 
430     vhost_dev_elect_mem_logger(dev, false);
431     dev->log = NULL;
432     dev->log_size = 0;
433 }
434 
435 static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
436 {
437     return dev->vhost_ops->vhost_requires_shm_log &&
438            dev->vhost_ops->vhost_requires_shm_log(dev);
439 }
440 
441 static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
442 {
443     struct vhost_log *log = vhost_log_get(dev->vhost_ops->backend_type,
444                                           size, vhost_dev_log_is_shared(dev));
445     uint64_t log_base = (uintptr_t)log->log;
446     int r;
447 
448     /* inform backend of log switching, this must be done before
449        releasing the current log, to ensure no logging is lost */
450     r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
451     if (r < 0) {
452         VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
453     }
454 
455     vhost_log_put(dev, true);
456     dev->log = log;
457     dev->log_size = size;
458 }
459 
460 static void *vhost_memory_map(struct vhost_dev *dev, hwaddr addr,
461                               hwaddr *plen, bool is_write)
462 {
463     if (!vhost_dev_has_iommu(dev)) {
464         return cpu_physical_memory_map(addr, plen, is_write);
465     } else {
466         return (void *)(uintptr_t)addr;
467     }
468 }
469 
470 static void vhost_memory_unmap(struct vhost_dev *dev, void *buffer,
471                                hwaddr len, int is_write,
472                                hwaddr access_len)
473 {
474     if (!vhost_dev_has_iommu(dev)) {
475         cpu_physical_memory_unmap(buffer, len, is_write, access_len);
476     }
477 }
478 
479 static int vhost_verify_ring_part_mapping(void *ring_hva,
480                                           uint64_t ring_gpa,
481                                           uint64_t ring_size,
482                                           void *reg_hva,
483                                           uint64_t reg_gpa,
484                                           uint64_t reg_size)
485 {
486     uint64_t hva_ring_offset;
487     uint64_t ring_last = range_get_last(ring_gpa, ring_size);
488     uint64_t reg_last = range_get_last(reg_gpa, reg_size);
489 
490     if (ring_last < reg_gpa || ring_gpa > reg_last) {
491         return 0;
492     }
493     /* check that whole ring's is mapped */
494     if (ring_last > reg_last) {
495         return -ENOMEM;
496     }
497     /* check that ring's MemoryRegion wasn't replaced */
498     hva_ring_offset = ring_gpa - reg_gpa;
499     if (ring_hva != reg_hva + hva_ring_offset) {
500         return -EBUSY;
501     }
502 
503     return 0;
504 }
505 
506 static int vhost_verify_ring_mappings(struct vhost_dev *dev,
507                                       void *reg_hva,
508                                       uint64_t reg_gpa,
509                                       uint64_t reg_size)
510 {
511     int i, j;
512     int r = 0;
513     const char *part_name[] = {
514         "descriptor table",
515         "available ring",
516         "used ring"
517     };
518 
519     if (vhost_dev_has_iommu(dev)) {
520         return 0;
521     }
522 
523     for (i = 0; i < dev->nvqs; ++i) {
524         struct vhost_virtqueue *vq = dev->vqs + i;
525 
526         if (vq->desc_phys == 0) {
527             continue;
528         }
529 
530         j = 0;
531         r = vhost_verify_ring_part_mapping(
532                 vq->desc, vq->desc_phys, vq->desc_size,
533                 reg_hva, reg_gpa, reg_size);
534         if (r) {
535             break;
536         }
537 
538         j++;
539         r = vhost_verify_ring_part_mapping(
540                 vq->avail, vq->avail_phys, vq->avail_size,
541                 reg_hva, reg_gpa, reg_size);
542         if (r) {
543             break;
544         }
545 
546         j++;
547         r = vhost_verify_ring_part_mapping(
548                 vq->used, vq->used_phys, vq->used_size,
549                 reg_hva, reg_gpa, reg_size);
550         if (r) {
551             break;
552         }
553     }
554 
555     if (r == -ENOMEM) {
556         error_report("Unable to map %s for ring %d", part_name[j], i);
557     } else if (r == -EBUSY) {
558         error_report("%s relocated for ring %d", part_name[j], i);
559     }
560     return r;
561 }
562 
563 /*
564  * vhost_section: identify sections needed for vhost access
565  *
566  * We only care about RAM sections here (where virtqueue and guest
567  * internals accessed by virtio might live).
568  */
569 static bool vhost_section(struct vhost_dev *dev, MemoryRegionSection *section)
570 {
571     MemoryRegion *mr = section->mr;
572 
573     if (memory_region_is_ram(mr) && !memory_region_is_rom(mr)) {
574         uint8_t dirty_mask = memory_region_get_dirty_log_mask(mr);
575         uint8_t handled_dirty;
576 
577         /*
578          * Kernel based vhost doesn't handle any block which is doing
579          * dirty-tracking other than migration for which it has
580          * specific logging support. However for TCG the kernel never
581          * gets involved anyway so we can also ignore it's
582          * self-modiying code detection flags. However a vhost-user
583          * client could still confuse a TCG guest if it re-writes
584          * executable memory that has already been translated.
585          */
586         handled_dirty = (1 << DIRTY_MEMORY_MIGRATION) |
587             (1 << DIRTY_MEMORY_CODE);
588 
589         if (dirty_mask & ~handled_dirty) {
590             trace_vhost_reject_section(mr->name, 1);
591             return false;
592         }
593 
594         /*
595          * Some backends (like vhost-user) can only handle memory regions
596          * that have an fd (can be mapped into a different process). Filter
597          * the ones without an fd out, if requested.
598          *
599          * TODO: we might have to limit to MAP_SHARED as well.
600          */
601         if (memory_region_get_fd(section->mr) < 0 &&
602             dev->vhost_ops->vhost_backend_no_private_memslots &&
603             dev->vhost_ops->vhost_backend_no_private_memslots(dev)) {
604             trace_vhost_reject_section(mr->name, 2);
605             return false;
606         }
607 
608         trace_vhost_section(mr->name);
609         return true;
610     } else {
611         trace_vhost_reject_section(mr->name, 3);
612         return false;
613     }
614 }
615 
616 static void vhost_begin(MemoryListener *listener)
617 {
618     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
619                                          memory_listener);
620     dev->tmp_sections = NULL;
621     dev->n_tmp_sections = 0;
622 }
623 
624 static void vhost_commit(MemoryListener *listener)
625 {
626     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
627                                          memory_listener);
628     MemoryRegionSection *old_sections;
629     int n_old_sections;
630     uint64_t log_size;
631     size_t regions_size;
632     int r;
633     int i;
634     bool changed = false;
635 
636     /* Note we can be called before the device is started, but then
637      * starting the device calls set_mem_table, so we need to have
638      * built the data structures.
639      */
640     old_sections = dev->mem_sections;
641     n_old_sections = dev->n_mem_sections;
642     dev->mem_sections = dev->tmp_sections;
643     dev->n_mem_sections = dev->n_tmp_sections;
644 
645     if (dev->n_mem_sections != n_old_sections) {
646         changed = true;
647     } else {
648         /* Same size, lets check the contents */
649         for (i = 0; i < n_old_sections; i++) {
650             if (!MemoryRegionSection_eq(&old_sections[i],
651                                         &dev->mem_sections[i])) {
652                 changed = true;
653                 break;
654             }
655         }
656     }
657 
658     trace_vhost_commit(dev->started, changed);
659     if (!changed) {
660         goto out;
661     }
662 
663     /* Rebuild the regions list from the new sections list */
664     regions_size = offsetof(struct vhost_memory, regions) +
665                        dev->n_mem_sections * sizeof dev->mem->regions[0];
666     dev->mem = g_realloc(dev->mem, regions_size);
667     dev->mem->nregions = dev->n_mem_sections;
668 
669     if (dev->vhost_ops->vhost_backend_no_private_memslots &&
670         dev->vhost_ops->vhost_backend_no_private_memslots(dev)) {
671         used_shared_memslots = dev->mem->nregions;
672     } else {
673         used_memslots = dev->mem->nregions;
674     }
675 
676     for (i = 0; i < dev->n_mem_sections; i++) {
677         struct vhost_memory_region *cur_vmr = dev->mem->regions + i;
678         struct MemoryRegionSection *mrs = dev->mem_sections + i;
679 
680         cur_vmr->guest_phys_addr = mrs->offset_within_address_space;
681         cur_vmr->memory_size     = int128_get64(mrs->size);
682         cur_vmr->userspace_addr  =
683             (uintptr_t)memory_region_get_ram_ptr(mrs->mr) +
684             mrs->offset_within_region;
685         cur_vmr->flags_padding   = 0;
686     }
687 
688     if (!dev->started) {
689         goto out;
690     }
691 
692     for (i = 0; i < dev->mem->nregions; i++) {
693         if (vhost_verify_ring_mappings(dev,
694                        (void *)(uintptr_t)dev->mem->regions[i].userspace_addr,
695                        dev->mem->regions[i].guest_phys_addr,
696                        dev->mem->regions[i].memory_size)) {
697             error_report("Verify ring failure on region %d", i);
698             abort();
699         }
700     }
701 
702     if (!dev->log_enabled) {
703         r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
704         if (r < 0) {
705             VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
706         }
707         goto out;
708     }
709     log_size = vhost_get_log_size(dev);
710     /* We allocate an extra 4K bytes to log,
711      * to reduce the * number of reallocations. */
712 #define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
713     /* To log more, must increase log size before table update. */
714     if (dev->log_size < log_size) {
715         vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
716     }
717     r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
718     if (r < 0) {
719         VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
720     }
721     /* To log less, can only decrease log size after table update. */
722     if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
723         vhost_dev_log_resize(dev, log_size);
724     }
725 
726 out:
727     /* Deref the old list of sections, this must happen _after_ the
728      * vhost_set_mem_table to ensure the client isn't still using the
729      * section we're about to unref.
730      */
731     while (n_old_sections--) {
732         memory_region_unref(old_sections[n_old_sections].mr);
733     }
734     g_free(old_sections);
735 }
736 
737 /* Adds the section data to the tmp_section structure.
738  * It relies on the listener calling us in memory address order
739  * and for each region (via the _add and _nop methods) to
740  * join neighbours.
741  */
742 static void vhost_region_add_section(struct vhost_dev *dev,
743                                      MemoryRegionSection *section)
744 {
745     bool need_add = true;
746     uint64_t mrs_size = int128_get64(section->size);
747     uint64_t mrs_gpa = section->offset_within_address_space;
748     uintptr_t mrs_host = (uintptr_t)memory_region_get_ram_ptr(section->mr) +
749                          section->offset_within_region;
750     RAMBlock *mrs_rb = section->mr->ram_block;
751 
752     trace_vhost_region_add_section(section->mr->name, mrs_gpa, mrs_size,
753                                    mrs_host);
754 
755     if (dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER) {
756         /* Round the section to it's page size */
757         /* First align the start down to a page boundary */
758         size_t mrs_page = qemu_ram_pagesize(mrs_rb);
759         uint64_t alignage = mrs_host & (mrs_page - 1);
760         if (alignage) {
761             mrs_host -= alignage;
762             mrs_size += alignage;
763             mrs_gpa  -= alignage;
764         }
765         /* Now align the size up to a page boundary */
766         alignage = mrs_size & (mrs_page - 1);
767         if (alignage) {
768             mrs_size += mrs_page - alignage;
769         }
770         trace_vhost_region_add_section_aligned(section->mr->name, mrs_gpa,
771                                                mrs_size, mrs_host);
772     }
773 
774     if (dev->n_tmp_sections && !section->unmergeable) {
775         /* Since we already have at least one section, lets see if
776          * this extends it; since we're scanning in order, we only
777          * have to look at the last one, and the FlatView that calls
778          * us shouldn't have overlaps.
779          */
780         MemoryRegionSection *prev_sec = dev->tmp_sections +
781                                                (dev->n_tmp_sections - 1);
782         uint64_t prev_gpa_start = prev_sec->offset_within_address_space;
783         uint64_t prev_size = int128_get64(prev_sec->size);
784         uint64_t prev_gpa_end   = range_get_last(prev_gpa_start, prev_size);
785         uint64_t prev_host_start =
786                         (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr) +
787                         prev_sec->offset_within_region;
788         uint64_t prev_host_end   = range_get_last(prev_host_start, prev_size);
789 
790         if (mrs_gpa <= (prev_gpa_end + 1)) {
791             /* OK, looks like overlapping/intersecting - it's possible that
792              * the rounding to page sizes has made them overlap, but they should
793              * match up in the same RAMBlock if they do.
794              */
795             if (mrs_gpa < prev_gpa_start) {
796                 error_report("%s:Section '%s' rounded to %"PRIx64
797                              " prior to previous '%s' %"PRIx64,
798                              __func__, section->mr->name, mrs_gpa,
799                              prev_sec->mr->name, prev_gpa_start);
800                 /* A way to cleanly fail here would be better */
801                 return;
802             }
803             /* Offset from the start of the previous GPA to this GPA */
804             size_t offset = mrs_gpa - prev_gpa_start;
805 
806             if (prev_host_start + offset == mrs_host &&
807                 section->mr == prev_sec->mr && !prev_sec->unmergeable) {
808                 uint64_t max_end = MAX(prev_host_end, mrs_host + mrs_size);
809                 need_add = false;
810                 prev_sec->offset_within_address_space =
811                     MIN(prev_gpa_start, mrs_gpa);
812                 prev_sec->offset_within_region =
813                     MIN(prev_host_start, mrs_host) -
814                     (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr);
815                 prev_sec->size = int128_make64(max_end - MIN(prev_host_start,
816                                                mrs_host));
817                 trace_vhost_region_add_section_merge(section->mr->name,
818                                         int128_get64(prev_sec->size),
819                                         prev_sec->offset_within_address_space,
820                                         prev_sec->offset_within_region);
821             } else {
822                 /* adjoining regions are fine, but overlapping ones with
823                  * different blocks/offsets shouldn't happen
824                  */
825                 if (mrs_gpa != prev_gpa_end + 1) {
826                     error_report("%s: Overlapping but not coherent sections "
827                                  "at %"PRIx64,
828                                  __func__, mrs_gpa);
829                     return;
830                 }
831             }
832         }
833     }
834 
835     if (need_add) {
836         ++dev->n_tmp_sections;
837         dev->tmp_sections = g_renew(MemoryRegionSection, dev->tmp_sections,
838                                     dev->n_tmp_sections);
839         dev->tmp_sections[dev->n_tmp_sections - 1] = *section;
840         /* The flatview isn't stable and we don't use it, making it NULL
841          * means we can memcmp the list.
842          */
843         dev->tmp_sections[dev->n_tmp_sections - 1].fv = NULL;
844         memory_region_ref(section->mr);
845     }
846 }
847 
848 /* Used for both add and nop callbacks */
849 static void vhost_region_addnop(MemoryListener *listener,
850                                 MemoryRegionSection *section)
851 {
852     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
853                                          memory_listener);
854 
855     if (!vhost_section(dev, section)) {
856         return;
857     }
858     vhost_region_add_section(dev, section);
859 }
860 
861 static void vhost_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
862 {
863     struct vhost_iommu *iommu = container_of(n, struct vhost_iommu, n);
864     struct vhost_dev *hdev = iommu->hdev;
865     hwaddr iova = iotlb->iova + iommu->iommu_offset;
866 
867     if (vhost_backend_invalidate_device_iotlb(hdev, iova,
868                                               iotlb->addr_mask + 1)) {
869         error_report("Fail to invalidate device iotlb");
870     }
871 }
872 
873 static void vhost_iommu_region_add(MemoryListener *listener,
874                                    MemoryRegionSection *section)
875 {
876     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
877                                          iommu_listener);
878     struct vhost_iommu *iommu;
879     Int128 end;
880     int iommu_idx;
881     IOMMUMemoryRegion *iommu_mr;
882 
883     if (!memory_region_is_iommu(section->mr)) {
884         return;
885     }
886 
887     iommu_mr = IOMMU_MEMORY_REGION(section->mr);
888 
889     iommu = g_malloc0(sizeof(*iommu));
890     end = int128_add(int128_make64(section->offset_within_region),
891                      section->size);
892     end = int128_sub(end, int128_one());
893     iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
894                                                    MEMTXATTRS_UNSPECIFIED);
895     iommu_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
896                         dev->vdev->device_iotlb_enabled ?
897                             IOMMU_NOTIFIER_DEVIOTLB_UNMAP :
898                             IOMMU_NOTIFIER_UNMAP,
899                         section->offset_within_region,
900                         int128_get64(end),
901                         iommu_idx);
902     iommu->mr = section->mr;
903     iommu->iommu_offset = section->offset_within_address_space -
904                           section->offset_within_region;
905     iommu->hdev = dev;
906     memory_region_register_iommu_notifier(section->mr, &iommu->n,
907                                           &error_fatal);
908     QLIST_INSERT_HEAD(&dev->iommu_list, iommu, iommu_next);
909     /* TODO: can replay help performance here? */
910 }
911 
912 static void vhost_iommu_region_del(MemoryListener *listener,
913                                    MemoryRegionSection *section)
914 {
915     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
916                                          iommu_listener);
917     struct vhost_iommu *iommu;
918 
919     if (!memory_region_is_iommu(section->mr)) {
920         return;
921     }
922 
923     QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
924         if (iommu->mr == section->mr &&
925             iommu->n.start == section->offset_within_region) {
926             memory_region_unregister_iommu_notifier(iommu->mr,
927                                                     &iommu->n);
928             QLIST_REMOVE(iommu, iommu_next);
929             g_free(iommu);
930             break;
931         }
932     }
933 }
934 
935 void vhost_toggle_device_iotlb(VirtIODevice *vdev)
936 {
937     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
938     struct vhost_dev *dev;
939     struct vhost_iommu *iommu;
940 
941     if (vdev->vhost_started) {
942         dev = vdc->get_vhost(vdev);
943     } else {
944         return;
945     }
946 
947     QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
948         memory_region_unregister_iommu_notifier(iommu->mr, &iommu->n);
949         iommu->n.notifier_flags = vdev->device_iotlb_enabled ?
950                 IOMMU_NOTIFIER_DEVIOTLB_UNMAP : IOMMU_NOTIFIER_UNMAP;
951         memory_region_register_iommu_notifier(iommu->mr, &iommu->n,
952                                               &error_fatal);
953     }
954 }
955 
956 static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
957                                     struct vhost_virtqueue *vq,
958                                     unsigned idx, bool enable_log)
959 {
960     struct vhost_vring_addr addr;
961     int r;
962     memset(&addr, 0, sizeof(struct vhost_vring_addr));
963 
964     if (dev->vhost_ops->vhost_vq_get_addr) {
965         r = dev->vhost_ops->vhost_vq_get_addr(dev, &addr, vq);
966         if (r < 0) {
967             VHOST_OPS_DEBUG(r, "vhost_vq_get_addr failed");
968             return r;
969         }
970     } else {
971         addr.desc_user_addr = (uint64_t)(unsigned long)vq->desc;
972         addr.avail_user_addr = (uint64_t)(unsigned long)vq->avail;
973         addr.used_user_addr = (uint64_t)(unsigned long)vq->used;
974     }
975     addr.index = idx;
976     addr.log_guest_addr = vq->used_phys;
977     addr.flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0;
978     r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
979     if (r < 0) {
980         VHOST_OPS_DEBUG(r, "vhost_set_vring_addr failed");
981     }
982     return r;
983 }
984 
985 static int vhost_dev_set_features(struct vhost_dev *dev,
986                                   bool enable_log)
987 {
988     uint64_t features = dev->acked_features;
989     int r;
990     if (enable_log) {
991         features |= 0x1ULL << VHOST_F_LOG_ALL;
992     }
993     if (!vhost_dev_has_iommu(dev)) {
994         features &= ~(0x1ULL << VIRTIO_F_IOMMU_PLATFORM);
995     }
996     if (dev->vhost_ops->vhost_force_iommu) {
997         if (dev->vhost_ops->vhost_force_iommu(dev) == true) {
998             features |= 0x1ULL << VIRTIO_F_IOMMU_PLATFORM;
999        }
1000     }
1001     r = dev->vhost_ops->vhost_set_features(dev, features);
1002     if (r < 0) {
1003         VHOST_OPS_DEBUG(r, "vhost_set_features failed");
1004         goto out;
1005     }
1006     if (dev->vhost_ops->vhost_set_backend_cap) {
1007         r = dev->vhost_ops->vhost_set_backend_cap(dev);
1008         if (r < 0) {
1009             VHOST_OPS_DEBUG(r, "vhost_set_backend_cap failed");
1010             goto out;
1011         }
1012     }
1013 
1014 out:
1015     return r;
1016 }
1017 
1018 static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
1019 {
1020     int r, i, idx;
1021     hwaddr addr;
1022 
1023     r = vhost_dev_set_features(dev, enable_log);
1024     if (r < 0) {
1025         goto err_features;
1026     }
1027     for (i = 0; i < dev->nvqs; ++i) {
1028         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
1029         addr = virtio_queue_get_desc_addr(dev->vdev, idx);
1030         if (!addr) {
1031             /*
1032              * The queue might not be ready for start. If this
1033              * is the case there is no reason to continue the process.
1034              * The similar logic is used by the vhost_virtqueue_start()
1035              * routine.
1036              */
1037             continue;
1038         }
1039         r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
1040                                      enable_log);
1041         if (r < 0) {
1042             goto err_vq;
1043         }
1044     }
1045 
1046     /*
1047      * At log start we select our vhost_device logger that will scan the
1048      * memory sections and skip for the others. This is possible because
1049      * the log is shared amongst all vhost devices for a given type of
1050      * backend.
1051      */
1052     vhost_dev_elect_mem_logger(dev, enable_log);
1053 
1054     return 0;
1055 err_vq:
1056     for (; i >= 0; --i) {
1057         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
1058         addr = virtio_queue_get_desc_addr(dev->vdev, idx);
1059         if (!addr) {
1060             continue;
1061         }
1062         vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
1063                                  dev->log_enabled);
1064     }
1065     vhost_dev_set_features(dev, dev->log_enabled);
1066 err_features:
1067     return r;
1068 }
1069 
1070 static int vhost_migration_log(MemoryListener *listener, bool enable)
1071 {
1072     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
1073                                          memory_listener);
1074     int r;
1075     if (enable == dev->log_enabled) {
1076         return 0;
1077     }
1078     if (!dev->started) {
1079         dev->log_enabled = enable;
1080         return 0;
1081     }
1082 
1083     r = 0;
1084     if (!enable) {
1085         r = vhost_dev_set_log(dev, false);
1086         if (r < 0) {
1087             goto check_dev_state;
1088         }
1089         vhost_log_put(dev, false);
1090     } else {
1091         vhost_dev_log_resize(dev, vhost_get_log_size(dev));
1092         r = vhost_dev_set_log(dev, true);
1093         if (r < 0) {
1094             goto check_dev_state;
1095         }
1096     }
1097 
1098 check_dev_state:
1099     dev->log_enabled = enable;
1100     /*
1101      * vhost-user-* devices could change their state during log
1102      * initialization due to disconnect. So check dev state after
1103      * vhost communication.
1104      */
1105     if (!dev->started) {
1106         /*
1107          * Since device is in the stopped state, it is okay for
1108          * migration. Return success.
1109          */
1110         r = 0;
1111     }
1112     if (r) {
1113         /* An error occurred. */
1114         dev->log_enabled = false;
1115     }
1116 
1117     return r;
1118 }
1119 
1120 static bool vhost_log_global_start(MemoryListener *listener, Error **errp)
1121 {
1122     int r;
1123 
1124     r = vhost_migration_log(listener, true);
1125     if (r < 0) {
1126         abort();
1127     }
1128     return true;
1129 }
1130 
1131 static void vhost_log_global_stop(MemoryListener *listener)
1132 {
1133     int r;
1134 
1135     r = vhost_migration_log(listener, false);
1136     if (r < 0) {
1137         abort();
1138     }
1139 }
1140 
1141 static void vhost_log_start(MemoryListener *listener,
1142                             MemoryRegionSection *section,
1143                             int old, int new)
1144 {
1145     /* FIXME: implement */
1146 }
1147 
1148 static void vhost_log_stop(MemoryListener *listener,
1149                            MemoryRegionSection *section,
1150                            int old, int new)
1151 {
1152     /* FIXME: implement */
1153 }
1154 
1155 /* The vhost driver natively knows how to handle the vrings of non
1156  * cross-endian legacy devices and modern devices. Only legacy devices
1157  * exposed to a bi-endian guest may require the vhost driver to use a
1158  * specific endianness.
1159  */
1160 static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
1161 {
1162     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1163         return false;
1164     }
1165 #if HOST_BIG_ENDIAN
1166     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
1167 #else
1168     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
1169 #endif
1170 }
1171 
1172 static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
1173                                                    bool is_big_endian,
1174                                                    int vhost_vq_index)
1175 {
1176     int r;
1177     struct vhost_vring_state s = {
1178         .index = vhost_vq_index,
1179         .num = is_big_endian
1180     };
1181 
1182     r = dev->vhost_ops->vhost_set_vring_endian(dev, &s);
1183     if (r < 0) {
1184         VHOST_OPS_DEBUG(r, "vhost_set_vring_endian failed");
1185     }
1186     return r;
1187 }
1188 
1189 static int vhost_memory_region_lookup(struct vhost_dev *hdev,
1190                                       uint64_t gpa, uint64_t *uaddr,
1191                                       uint64_t *len)
1192 {
1193     int i;
1194 
1195     for (i = 0; i < hdev->mem->nregions; i++) {
1196         struct vhost_memory_region *reg = hdev->mem->regions + i;
1197 
1198         if (gpa >= reg->guest_phys_addr &&
1199             reg->guest_phys_addr + reg->memory_size > gpa) {
1200             *uaddr = reg->userspace_addr + gpa - reg->guest_phys_addr;
1201             *len = reg->guest_phys_addr + reg->memory_size - gpa;
1202             return 0;
1203         }
1204     }
1205 
1206     return -EFAULT;
1207 }
1208 
1209 int vhost_device_iotlb_miss(struct vhost_dev *dev, uint64_t iova, int write)
1210 {
1211     IOMMUTLBEntry iotlb;
1212     uint64_t uaddr, len;
1213     int ret = -EFAULT;
1214 
1215     RCU_READ_LOCK_GUARD();
1216 
1217     trace_vhost_iotlb_miss(dev, 1);
1218 
1219     iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
1220                                           iova, write,
1221                                           MEMTXATTRS_UNSPECIFIED);
1222     if (iotlb.target_as != NULL) {
1223         ret = vhost_memory_region_lookup(dev, iotlb.translated_addr,
1224                                          &uaddr, &len);
1225         if (ret) {
1226             trace_vhost_iotlb_miss(dev, 3);
1227             error_report("Fail to lookup the translated address "
1228                          "%"PRIx64, iotlb.translated_addr);
1229             goto out;
1230         }
1231 
1232         len = MIN(iotlb.addr_mask + 1, len);
1233         iova = iova & ~iotlb.addr_mask;
1234 
1235         ret = vhost_backend_update_device_iotlb(dev, iova, uaddr,
1236                                                 len, iotlb.perm);
1237         if (ret) {
1238             trace_vhost_iotlb_miss(dev, 4);
1239             error_report("Fail to update device iotlb");
1240             goto out;
1241         }
1242     }
1243 
1244     trace_vhost_iotlb_miss(dev, 2);
1245 
1246 out:
1247     return ret;
1248 }
1249 
1250 int vhost_virtqueue_start(struct vhost_dev *dev,
1251                           struct VirtIODevice *vdev,
1252                           struct vhost_virtqueue *vq,
1253                           unsigned idx)
1254 {
1255     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1256     VirtioBusState *vbus = VIRTIO_BUS(qbus);
1257     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
1258     hwaddr s, l, a;
1259     int r;
1260     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1261     struct vhost_vring_file file = {
1262         .index = vhost_vq_index
1263     };
1264     struct vhost_vring_state state = {
1265         .index = vhost_vq_index
1266     };
1267     struct VirtQueue *vvq = virtio_get_queue(vdev, idx);
1268 
1269     a = virtio_queue_get_desc_addr(vdev, idx);
1270     if (a == 0) {
1271         /* Queue might not be ready for start */
1272         return 0;
1273     }
1274 
1275     vq->num = state.num = virtio_queue_get_num(vdev, idx);
1276     r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
1277     if (r) {
1278         VHOST_OPS_DEBUG(r, "vhost_set_vring_num failed");
1279         return r;
1280     }
1281 
1282     state.num = virtio_queue_get_last_avail_idx(vdev, idx);
1283     r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
1284     if (r) {
1285         VHOST_OPS_DEBUG(r, "vhost_set_vring_base failed");
1286         return r;
1287     }
1288 
1289     if (vhost_needs_vring_endian(vdev)) {
1290         r = vhost_virtqueue_set_vring_endian_legacy(dev,
1291                                                     virtio_is_big_endian(vdev),
1292                                                     vhost_vq_index);
1293         if (r) {
1294             return r;
1295         }
1296     }
1297 
1298     vq->desc_size = s = l = virtio_queue_get_desc_size(vdev, idx);
1299     vq->desc_phys = a;
1300     vq->desc = vhost_memory_map(dev, a, &l, false);
1301     if (!vq->desc || l != s) {
1302         r = -ENOMEM;
1303         goto fail_alloc_desc;
1304     }
1305     vq->avail_size = s = l = virtio_queue_get_avail_size(vdev, idx);
1306     vq->avail_phys = a = virtio_queue_get_avail_addr(vdev, idx);
1307     vq->avail = vhost_memory_map(dev, a, &l, false);
1308     if (!vq->avail || l != s) {
1309         r = -ENOMEM;
1310         goto fail_alloc_avail;
1311     }
1312     vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
1313     vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
1314     vq->used = vhost_memory_map(dev, a, &l, true);
1315     if (!vq->used || l != s) {
1316         r = -ENOMEM;
1317         goto fail_alloc_used;
1318     }
1319 
1320     r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
1321     if (r < 0) {
1322         goto fail_alloc;
1323     }
1324 
1325     file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
1326     r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
1327     if (r) {
1328         VHOST_OPS_DEBUG(r, "vhost_set_vring_kick failed");
1329         goto fail_kick;
1330     }
1331 
1332     /* Clear and discard previous events if any. */
1333     event_notifier_test_and_clear(&vq->masked_notifier);
1334 
1335     /* Init vring in unmasked state, unless guest_notifier_mask
1336      * will do it later.
1337      */
1338     if (!vdev->use_guest_notifier_mask) {
1339         /* TODO: check and handle errors. */
1340         vhost_virtqueue_mask(dev, vdev, idx, false);
1341     }
1342 
1343     if (k->query_guest_notifiers &&
1344         k->query_guest_notifiers(qbus->parent) &&
1345         virtio_queue_vector(vdev, idx) == VIRTIO_NO_VECTOR) {
1346         file.fd = -1;
1347         r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1348         if (r) {
1349             goto fail_vector;
1350         }
1351     }
1352 
1353     return 0;
1354 
1355 fail_vector:
1356 fail_kick:
1357 fail_alloc:
1358     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1359                        0, 0);
1360 fail_alloc_used:
1361     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1362                        0, 0);
1363 fail_alloc_avail:
1364     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1365                        0, 0);
1366 fail_alloc_desc:
1367     return r;
1368 }
1369 
1370 void vhost_virtqueue_stop(struct vhost_dev *dev,
1371                           struct VirtIODevice *vdev,
1372                           struct vhost_virtqueue *vq,
1373                           unsigned idx)
1374 {
1375     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1376     struct vhost_vring_state state = {
1377         .index = vhost_vq_index,
1378     };
1379     int r;
1380 
1381     if (virtio_queue_get_desc_addr(vdev, idx) == 0) {
1382         /* Don't stop the virtqueue which might have not been started */
1383         return;
1384     }
1385 
1386     r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
1387     if (r < 0) {
1388         VHOST_OPS_DEBUG(r, "vhost VQ %u ring restore failed: %d", idx, r);
1389         /* Connection to the backend is broken, so let's sync internal
1390          * last avail idx to the device used idx.
1391          */
1392         virtio_queue_restore_last_avail_idx(vdev, idx);
1393     } else {
1394         virtio_queue_set_last_avail_idx(vdev, idx, state.num);
1395     }
1396     virtio_queue_invalidate_signalled_used(vdev, idx);
1397     virtio_queue_update_used_idx(vdev, idx);
1398 
1399     /* In the cross-endian case, we need to reset the vring endianness to
1400      * native as legacy devices expect so by default.
1401      */
1402     if (vhost_needs_vring_endian(vdev)) {
1403         vhost_virtqueue_set_vring_endian_legacy(dev,
1404                                                 !virtio_is_big_endian(vdev),
1405                                                 vhost_vq_index);
1406     }
1407 
1408     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1409                        1, virtio_queue_get_used_size(vdev, idx));
1410     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1411                        0, virtio_queue_get_avail_size(vdev, idx));
1412     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1413                        0, virtio_queue_get_desc_size(vdev, idx));
1414 }
1415 
1416 static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
1417                                                 int n, uint32_t timeout)
1418 {
1419     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1420     struct vhost_vring_state state = {
1421         .index = vhost_vq_index,
1422         .num = timeout,
1423     };
1424     int r;
1425 
1426     if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
1427         return -EINVAL;
1428     }
1429 
1430     r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
1431     if (r) {
1432         VHOST_OPS_DEBUG(r, "vhost_set_vring_busyloop_timeout failed");
1433         return r;
1434     }
1435 
1436     return 0;
1437 }
1438 
1439 static void vhost_virtqueue_error_notifier(EventNotifier *n)
1440 {
1441     struct vhost_virtqueue *vq = container_of(n, struct vhost_virtqueue,
1442                                               error_notifier);
1443     struct vhost_dev *dev = vq->dev;
1444     int index = vq - dev->vqs;
1445 
1446     if (event_notifier_test_and_clear(n) && dev->vdev) {
1447         VHOST_OPS_DEBUG(-EINVAL,  "vhost vring error in virtqueue %d",
1448                         dev->vq_index + index);
1449     }
1450 }
1451 
1452 static int vhost_virtqueue_init(struct vhost_dev *dev,
1453                                 struct vhost_virtqueue *vq, int n)
1454 {
1455     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1456     struct vhost_vring_file file = {
1457         .index = vhost_vq_index,
1458     };
1459     int r = event_notifier_init(&vq->masked_notifier, 0);
1460     if (r < 0) {
1461         return r;
1462     }
1463 
1464     file.fd = event_notifier_get_wfd(&vq->masked_notifier);
1465     r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1466     if (r) {
1467         VHOST_OPS_DEBUG(r, "vhost_set_vring_call failed");
1468         goto fail_call;
1469     }
1470 
1471     vq->dev = dev;
1472 
1473     if (dev->vhost_ops->vhost_set_vring_err) {
1474         r = event_notifier_init(&vq->error_notifier, 0);
1475         if (r < 0) {
1476             goto fail_call;
1477         }
1478 
1479         file.fd = event_notifier_get_fd(&vq->error_notifier);
1480         r = dev->vhost_ops->vhost_set_vring_err(dev, &file);
1481         if (r) {
1482             VHOST_OPS_DEBUG(r, "vhost_set_vring_err failed");
1483             goto fail_err;
1484         }
1485 
1486         event_notifier_set_handler(&vq->error_notifier,
1487                                    vhost_virtqueue_error_notifier);
1488     }
1489 
1490     return 0;
1491 
1492 fail_err:
1493     event_notifier_cleanup(&vq->error_notifier);
1494 fail_call:
1495     event_notifier_cleanup(&vq->masked_notifier);
1496     return r;
1497 }
1498 
1499 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1500 {
1501     event_notifier_cleanup(&vq->masked_notifier);
1502     if (vq->dev->vhost_ops->vhost_set_vring_err) {
1503         event_notifier_set_handler(&vq->error_notifier, NULL);
1504         event_notifier_cleanup(&vq->error_notifier);
1505     }
1506 }
1507 
1508 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1509                    VhostBackendType backend_type, uint32_t busyloop_timeout,
1510                    Error **errp)
1511 {
1512     unsigned int used, reserved, limit;
1513     uint64_t features;
1514     int i, r, n_initialized_vqs = 0;
1515 
1516     hdev->vdev = NULL;
1517     hdev->migration_blocker = NULL;
1518 
1519     r = vhost_set_backend_type(hdev, backend_type);
1520     assert(r >= 0);
1521 
1522     r = hdev->vhost_ops->vhost_backend_init(hdev, opaque, errp);
1523     if (r < 0) {
1524         goto fail;
1525     }
1526 
1527     r = hdev->vhost_ops->vhost_set_owner(hdev);
1528     if (r < 0) {
1529         error_setg_errno(errp, -r, "vhost_set_owner failed");
1530         goto fail;
1531     }
1532 
1533     r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1534     if (r < 0) {
1535         error_setg_errno(errp, -r, "vhost_get_features failed");
1536         goto fail;
1537     }
1538 
1539     limit = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
1540     if (limit < MEMORY_DEVICES_SAFE_MAX_MEMSLOTS &&
1541         memory_devices_memslot_auto_decision_active()) {
1542         error_setg(errp, "some memory device (like virtio-mem)"
1543             " decided how many memory slots to use based on the overall"
1544             " number of memory slots; this vhost backend would further"
1545             " restricts the overall number of memory slots");
1546         error_append_hint(errp, "Try plugging this vhost backend before"
1547             " plugging such memory devices.\n");
1548         r = -EINVAL;
1549         goto fail;
1550     }
1551 
1552     for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1553         r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1554         if (r < 0) {
1555             error_setg_errno(errp, -r, "Failed to initialize virtqueue %d", i);
1556             goto fail;
1557         }
1558     }
1559 
1560     if (busyloop_timeout) {
1561         for (i = 0; i < hdev->nvqs; ++i) {
1562             r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1563                                                      busyloop_timeout);
1564             if (r < 0) {
1565                 error_setg_errno(errp, -r, "Failed to set busyloop timeout");
1566                 goto fail_busyloop;
1567             }
1568         }
1569     }
1570 
1571     hdev->features = features;
1572 
1573     hdev->memory_listener = (MemoryListener) {
1574         .name = "vhost",
1575         .begin = vhost_begin,
1576         .commit = vhost_commit,
1577         .region_add = vhost_region_addnop,
1578         .region_nop = vhost_region_addnop,
1579         .log_start = vhost_log_start,
1580         .log_stop = vhost_log_stop,
1581         .log_sync = vhost_log_sync,
1582         .log_global_start = vhost_log_global_start,
1583         .log_global_stop = vhost_log_global_stop,
1584         .priority = MEMORY_LISTENER_PRIORITY_DEV_BACKEND
1585     };
1586 
1587     hdev->iommu_listener = (MemoryListener) {
1588         .name = "vhost-iommu",
1589         .region_add = vhost_iommu_region_add,
1590         .region_del = vhost_iommu_region_del,
1591     };
1592 
1593     if (hdev->migration_blocker == NULL) {
1594         if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1595             error_setg(&hdev->migration_blocker,
1596                        "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1597         } else if (vhost_dev_log_is_shared(hdev) && !qemu_memfd_alloc_check()) {
1598             error_setg(&hdev->migration_blocker,
1599                        "Migration disabled: failed to allocate shared memory");
1600         }
1601     }
1602 
1603     if (hdev->migration_blocker != NULL) {
1604         r = migrate_add_blocker_normal(&hdev->migration_blocker, errp);
1605         if (r < 0) {
1606             goto fail_busyloop;
1607         }
1608     }
1609 
1610     hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1611     hdev->n_mem_sections = 0;
1612     hdev->mem_sections = NULL;
1613     hdev->log = NULL;
1614     hdev->log_size = 0;
1615     hdev->log_enabled = false;
1616     hdev->started = false;
1617     memory_listener_register(&hdev->memory_listener, &address_space_memory);
1618     QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1619 
1620     /*
1621      * The listener we registered properly updated the corresponding counter.
1622      * So we can trust that these values are accurate.
1623      */
1624     if (hdev->vhost_ops->vhost_backend_no_private_memslots &&
1625         hdev->vhost_ops->vhost_backend_no_private_memslots(hdev)) {
1626         used = used_shared_memslots;
1627     } else {
1628         used = used_memslots;
1629     }
1630     /*
1631      * We assume that all reserved memslots actually require a real memslot
1632      * in our vhost backend. This might not be true, for example, if the
1633      * memslot would be ROM. If ever relevant, we can optimize for that --
1634      * but we'll need additional information about the reservations.
1635      */
1636     reserved = memory_devices_get_reserved_memslots();
1637     if (used + reserved > limit) {
1638         error_setg(errp, "vhost backend memory slots limit (%d) is less"
1639                    " than current number of used (%d) and reserved (%d)"
1640                    " memory slots for memory devices.", limit, used, reserved);
1641         r = -EINVAL;
1642         goto fail_busyloop;
1643     }
1644 
1645     return 0;
1646 
1647 fail_busyloop:
1648     if (busyloop_timeout) {
1649         while (--i >= 0) {
1650             vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1651         }
1652     }
1653 fail:
1654     hdev->nvqs = n_initialized_vqs;
1655     vhost_dev_cleanup(hdev);
1656     return r;
1657 }
1658 
1659 void vhost_dev_cleanup(struct vhost_dev *hdev)
1660 {
1661     int i;
1662 
1663     trace_vhost_dev_cleanup(hdev);
1664 
1665     for (i = 0; i < hdev->nvqs; ++i) {
1666         vhost_virtqueue_cleanup(hdev->vqs + i);
1667     }
1668     if (hdev->mem) {
1669         /* those are only safe after successful init */
1670         memory_listener_unregister(&hdev->memory_listener);
1671         QLIST_REMOVE(hdev, entry);
1672     }
1673     migrate_del_blocker(&hdev->migration_blocker);
1674     g_free(hdev->mem);
1675     g_free(hdev->mem_sections);
1676     if (hdev->vhost_ops) {
1677         hdev->vhost_ops->vhost_backend_cleanup(hdev);
1678     }
1679     assert(!hdev->log);
1680 
1681     memset(hdev, 0, sizeof(struct vhost_dev));
1682 }
1683 
1684 void vhost_dev_disable_notifiers_nvqs(struct vhost_dev *hdev,
1685                                       VirtIODevice *vdev,
1686                                       unsigned int nvqs)
1687 {
1688     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1689     int i, r;
1690 
1691     /*
1692      * Batch all the host notifiers in a single transaction to avoid
1693      * quadratic time complexity in address_space_update_ioeventfds().
1694      */
1695     memory_region_transaction_begin();
1696 
1697     for (i = 0; i < nvqs; ++i) {
1698         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1699                                          false);
1700         if (r < 0) {
1701             error_report("vhost VQ %d notifier cleanup failed: %d", i, -r);
1702         }
1703         assert(r >= 0);
1704     }
1705 
1706     /*
1707      * The transaction expects the ioeventfds to be open when it
1708      * commits. Do it now, before the cleanup loop.
1709      */
1710     memory_region_transaction_commit();
1711 
1712     for (i = 0; i < nvqs; ++i) {
1713         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1714     }
1715     virtio_device_release_ioeventfd(vdev);
1716 }
1717 
1718 /* Stop processing guest IO notifications in qemu.
1719  * Start processing them in vhost in kernel.
1720  */
1721 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1722 {
1723     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1724     int i, r;
1725 
1726     /* We will pass the notifiers to the kernel, make sure that QEMU
1727      * doesn't interfere.
1728      */
1729     r = virtio_device_grab_ioeventfd(vdev);
1730     if (r < 0) {
1731         error_report("binding does not support host notifiers");
1732         return r;
1733     }
1734 
1735     /*
1736      * Batch all the host notifiers in a single transaction to avoid
1737      * quadratic time complexity in address_space_update_ioeventfds().
1738      */
1739     memory_region_transaction_begin();
1740 
1741     for (i = 0; i < hdev->nvqs; ++i) {
1742         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1743                                          true);
1744         if (r < 0) {
1745             error_report("vhost VQ %d notifier binding failed: %d", i, -r);
1746             memory_region_transaction_commit();
1747             vhost_dev_disable_notifiers_nvqs(hdev, vdev, i);
1748             return r;
1749         }
1750     }
1751 
1752     memory_region_transaction_commit();
1753 
1754     return 0;
1755 }
1756 
1757 /* Stop processing guest IO notifications in vhost.
1758  * Start processing them in qemu.
1759  * This might actually run the qemu handlers right away,
1760  * so virtio in qemu must be completely setup when this is called.
1761  */
1762 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1763 {
1764     vhost_dev_disable_notifiers_nvqs(hdev, vdev, hdev->nvqs);
1765 }
1766 
1767 /* Test and clear event pending status.
1768  * Should be called after unmask to avoid losing events.
1769  */
1770 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1771 {
1772     struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1773     assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1774     return event_notifier_test_and_clear(&vq->masked_notifier);
1775 }
1776 
1777 /* Mask/unmask events from this vq. */
1778 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1779                          bool mask)
1780 {
1781     struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1782     int r, index = n - hdev->vq_index;
1783     struct vhost_vring_file file;
1784 
1785     /* should only be called after backend is connected */
1786     assert(hdev->vhost_ops);
1787 
1788     if (mask) {
1789         assert(vdev->use_guest_notifier_mask);
1790         file.fd = event_notifier_get_wfd(&hdev->vqs[index].masked_notifier);
1791     } else {
1792         file.fd = event_notifier_get_wfd(virtio_queue_get_guest_notifier(vvq));
1793     }
1794 
1795     file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1796     r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1797     if (r < 0) {
1798         error_report("vhost_set_vring_call failed %d", -r);
1799     }
1800 }
1801 
1802 bool vhost_config_pending(struct vhost_dev *hdev)
1803 {
1804     assert(hdev->vhost_ops);
1805     if ((hdev->started == false) ||
1806         (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1807         return false;
1808     }
1809 
1810     EventNotifier *notifier =
1811         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1812     return event_notifier_test_and_clear(notifier);
1813 }
1814 
1815 void vhost_config_mask(struct vhost_dev *hdev, VirtIODevice *vdev, bool mask)
1816 {
1817     int fd;
1818     int r;
1819     EventNotifier *notifier =
1820         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1821     EventNotifier *config_notifier = &vdev->config_notifier;
1822     assert(hdev->vhost_ops);
1823 
1824     if ((hdev->started == false) ||
1825         (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1826         return;
1827     }
1828     if (mask) {
1829         assert(vdev->use_guest_notifier_mask);
1830         fd = event_notifier_get_fd(notifier);
1831     } else {
1832         fd = event_notifier_get_fd(config_notifier);
1833     }
1834     r = hdev->vhost_ops->vhost_set_config_call(hdev, fd);
1835     if (r < 0) {
1836         error_report("vhost_set_config_call failed %d", -r);
1837     }
1838 }
1839 
1840 static void vhost_stop_config_intr(struct vhost_dev *dev)
1841 {
1842     int fd = -1;
1843     assert(dev->vhost_ops);
1844     if (dev->vhost_ops->vhost_set_config_call) {
1845         dev->vhost_ops->vhost_set_config_call(dev, fd);
1846     }
1847 }
1848 
1849 static void vhost_start_config_intr(struct vhost_dev *dev)
1850 {
1851     int r;
1852 
1853     assert(dev->vhost_ops);
1854     int fd = event_notifier_get_fd(&dev->vdev->config_notifier);
1855     if (dev->vhost_ops->vhost_set_config_call) {
1856         r = dev->vhost_ops->vhost_set_config_call(dev, fd);
1857         if (!r) {
1858             event_notifier_set(&dev->vdev->config_notifier);
1859         }
1860     }
1861 }
1862 
1863 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1864                             uint64_t features)
1865 {
1866     const int *bit = feature_bits;
1867     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1868         uint64_t bit_mask = (1ULL << *bit);
1869         if (!(hdev->features & bit_mask)) {
1870             features &= ~bit_mask;
1871         }
1872         bit++;
1873     }
1874     return features;
1875 }
1876 
1877 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1878                         uint64_t features)
1879 {
1880     const int *bit = feature_bits;
1881     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1882         uint64_t bit_mask = (1ULL << *bit);
1883         if (features & bit_mask) {
1884             hdev->acked_features |= bit_mask;
1885         }
1886         bit++;
1887     }
1888 }
1889 
1890 int vhost_dev_get_config(struct vhost_dev *hdev, uint8_t *config,
1891                          uint32_t config_len, Error **errp)
1892 {
1893     assert(hdev->vhost_ops);
1894 
1895     if (hdev->vhost_ops->vhost_get_config) {
1896         return hdev->vhost_ops->vhost_get_config(hdev, config, config_len,
1897                                                  errp);
1898     }
1899 
1900     error_setg(errp, "vhost_get_config not implemented");
1901     return -ENOSYS;
1902 }
1903 
1904 int vhost_dev_set_config(struct vhost_dev *hdev, const uint8_t *data,
1905                          uint32_t offset, uint32_t size, uint32_t flags)
1906 {
1907     assert(hdev->vhost_ops);
1908 
1909     if (hdev->vhost_ops->vhost_set_config) {
1910         return hdev->vhost_ops->vhost_set_config(hdev, data, offset,
1911                                                  size, flags);
1912     }
1913 
1914     return -ENOSYS;
1915 }
1916 
1917 void vhost_dev_set_config_notifier(struct vhost_dev *hdev,
1918                                    const VhostDevConfigOps *ops)
1919 {
1920     hdev->config_ops = ops;
1921 }
1922 
1923 void vhost_dev_free_inflight(struct vhost_inflight *inflight)
1924 {
1925     if (inflight && inflight->addr) {
1926         qemu_memfd_free(inflight->addr, inflight->size, inflight->fd);
1927         inflight->addr = NULL;
1928         inflight->fd = -1;
1929     }
1930 }
1931 
1932 int vhost_dev_prepare_inflight(struct vhost_dev *hdev, VirtIODevice *vdev)
1933 {
1934     int r;
1935 
1936     if (hdev->vhost_ops->vhost_get_inflight_fd == NULL ||
1937         hdev->vhost_ops->vhost_set_inflight_fd == NULL) {
1938         return 0;
1939     }
1940 
1941     hdev->vdev = vdev;
1942 
1943     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1944     if (r < 0) {
1945         VHOST_OPS_DEBUG(r, "vhost_dev_prepare_inflight failed");
1946         return r;
1947     }
1948 
1949     return 0;
1950 }
1951 
1952 int vhost_dev_set_inflight(struct vhost_dev *dev,
1953                            struct vhost_inflight *inflight)
1954 {
1955     int r;
1956 
1957     if (dev->vhost_ops->vhost_set_inflight_fd && inflight->addr) {
1958         r = dev->vhost_ops->vhost_set_inflight_fd(dev, inflight);
1959         if (r) {
1960             VHOST_OPS_DEBUG(r, "vhost_set_inflight_fd failed");
1961             return r;
1962         }
1963     }
1964 
1965     return 0;
1966 }
1967 
1968 int vhost_dev_get_inflight(struct vhost_dev *dev, uint16_t queue_size,
1969                            struct vhost_inflight *inflight)
1970 {
1971     int r;
1972 
1973     if (dev->vhost_ops->vhost_get_inflight_fd) {
1974         r = dev->vhost_ops->vhost_get_inflight_fd(dev, queue_size, inflight);
1975         if (r) {
1976             VHOST_OPS_DEBUG(r, "vhost_get_inflight_fd failed");
1977             return r;
1978         }
1979     }
1980 
1981     return 0;
1982 }
1983 
1984 static int vhost_dev_set_vring_enable(struct vhost_dev *hdev, int enable)
1985 {
1986     if (!hdev->vhost_ops->vhost_set_vring_enable) {
1987         return 0;
1988     }
1989 
1990     /*
1991      * For vhost-user devices, if VHOST_USER_F_PROTOCOL_FEATURES has not
1992      * been negotiated, the rings start directly in the enabled state, and
1993      * .vhost_set_vring_enable callback will fail since
1994      * VHOST_USER_SET_VRING_ENABLE is not supported.
1995      */
1996     if (hdev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER &&
1997         !virtio_has_feature(hdev->backend_features,
1998                             VHOST_USER_F_PROTOCOL_FEATURES)) {
1999         return 0;
2000     }
2001 
2002     return hdev->vhost_ops->vhost_set_vring_enable(hdev, enable);
2003 }
2004 
2005 /*
2006  * Host notifiers must be enabled at this point.
2007  *
2008  * If @vrings is true, this function will enable all vrings before starting the
2009  * device. If it is false, the vring initialization is left to be done by the
2010  * caller.
2011  */
2012 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
2013 {
2014     int i, r;
2015 
2016     /* should only be called after backend is connected */
2017     assert(hdev->vhost_ops);
2018 
2019     trace_vhost_dev_start(hdev, vdev->name, vrings);
2020 
2021     vdev->vhost_started = true;
2022     hdev->started = true;
2023     hdev->vdev = vdev;
2024 
2025     r = vhost_dev_set_features(hdev, hdev->log_enabled);
2026     if (r < 0) {
2027         goto fail_features;
2028     }
2029 
2030     if (vhost_dev_has_iommu(hdev)) {
2031         memory_listener_register(&hdev->iommu_listener, vdev->dma_as);
2032     }
2033 
2034     r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
2035     if (r < 0) {
2036         VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
2037         goto fail_mem;
2038     }
2039     for (i = 0; i < hdev->nvqs; ++i) {
2040         r = vhost_virtqueue_start(hdev,
2041                                   vdev,
2042                                   hdev->vqs + i,
2043                                   hdev->vq_index + i);
2044         if (r < 0) {
2045             goto fail_vq;
2046         }
2047     }
2048 
2049     r = event_notifier_init(
2050         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier, 0);
2051     if (r < 0) {
2052         VHOST_OPS_DEBUG(r, "event_notifier_init failed");
2053         goto fail_vq;
2054     }
2055     event_notifier_test_and_clear(
2056         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
2057     if (!vdev->use_guest_notifier_mask) {
2058         vhost_config_mask(hdev, vdev, true);
2059     }
2060     if (hdev->log_enabled) {
2061         uint64_t log_base;
2062 
2063         hdev->log_size = vhost_get_log_size(hdev);
2064         hdev->log = vhost_log_get(hdev->vhost_ops->backend_type,
2065                                   hdev->log_size,
2066                                   vhost_dev_log_is_shared(hdev));
2067         log_base = (uintptr_t)hdev->log->log;
2068         r = hdev->vhost_ops->vhost_set_log_base(hdev,
2069                                                 hdev->log_size ? log_base : 0,
2070                                                 hdev->log);
2071         if (r < 0) {
2072             VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
2073             goto fail_log;
2074         }
2075         vhost_dev_elect_mem_logger(hdev, true);
2076     }
2077     if (vrings) {
2078         r = vhost_dev_set_vring_enable(hdev, true);
2079         if (r) {
2080             goto fail_log;
2081         }
2082     }
2083     if (hdev->vhost_ops->vhost_dev_start) {
2084         r = hdev->vhost_ops->vhost_dev_start(hdev, true);
2085         if (r) {
2086             goto fail_start;
2087         }
2088     }
2089     if (vhost_dev_has_iommu(hdev) &&
2090         hdev->vhost_ops->vhost_set_iotlb_callback) {
2091             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, true);
2092 
2093         /* Update used ring information for IOTLB to work correctly,
2094          * vhost-kernel code requires for this.*/
2095         for (i = 0; i < hdev->nvqs; ++i) {
2096             struct vhost_virtqueue *vq = hdev->vqs + i;
2097             r = vhost_device_iotlb_miss(hdev, vq->used_phys, true);
2098             if (r) {
2099                 goto fail_iotlb;
2100             }
2101         }
2102     }
2103     vhost_start_config_intr(hdev);
2104     return 0;
2105 fail_iotlb:
2106     if (vhost_dev_has_iommu(hdev) &&
2107         hdev->vhost_ops->vhost_set_iotlb_callback) {
2108         hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
2109     }
2110     if (hdev->vhost_ops->vhost_dev_start) {
2111         hdev->vhost_ops->vhost_dev_start(hdev, false);
2112     }
2113 fail_start:
2114     if (vrings) {
2115         vhost_dev_set_vring_enable(hdev, false);
2116     }
2117 fail_log:
2118     vhost_log_put(hdev, false);
2119 fail_vq:
2120     while (--i >= 0) {
2121         vhost_virtqueue_stop(hdev,
2122                              vdev,
2123                              hdev->vqs + i,
2124                              hdev->vq_index + i);
2125     }
2126 
2127 fail_mem:
2128     if (vhost_dev_has_iommu(hdev)) {
2129         memory_listener_unregister(&hdev->iommu_listener);
2130     }
2131 fail_features:
2132     vdev->vhost_started = false;
2133     hdev->started = false;
2134     return r;
2135 }
2136 
2137 /* Host notifiers must be enabled at this point. */
2138 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
2139 {
2140     int i;
2141 
2142     /* should only be called after backend is connected */
2143     assert(hdev->vhost_ops);
2144     event_notifier_test_and_clear(
2145         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
2146     event_notifier_test_and_clear(&vdev->config_notifier);
2147     event_notifier_cleanup(
2148         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
2149 
2150     trace_vhost_dev_stop(hdev, vdev->name, vrings);
2151 
2152     if (hdev->vhost_ops->vhost_dev_start) {
2153         hdev->vhost_ops->vhost_dev_start(hdev, false);
2154     }
2155     if (vrings) {
2156         vhost_dev_set_vring_enable(hdev, false);
2157     }
2158     for (i = 0; i < hdev->nvqs; ++i) {
2159         vhost_virtqueue_stop(hdev,
2160                              vdev,
2161                              hdev->vqs + i,
2162                              hdev->vq_index + i);
2163     }
2164     if (hdev->vhost_ops->vhost_reset_status) {
2165         hdev->vhost_ops->vhost_reset_status(hdev);
2166     }
2167 
2168     if (vhost_dev_has_iommu(hdev)) {
2169         if (hdev->vhost_ops->vhost_set_iotlb_callback) {
2170             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
2171         }
2172         memory_listener_unregister(&hdev->iommu_listener);
2173     }
2174     vhost_stop_config_intr(hdev);
2175     vhost_log_put(hdev, true);
2176     hdev->started = false;
2177     vdev->vhost_started = false;
2178     hdev->vdev = NULL;
2179 }
2180 
2181 int vhost_net_set_backend(struct vhost_dev *hdev,
2182                           struct vhost_vring_file *file)
2183 {
2184     if (hdev->vhost_ops->vhost_net_set_backend) {
2185         return hdev->vhost_ops->vhost_net_set_backend(hdev, file);
2186     }
2187 
2188     return -ENOSYS;
2189 }
2190 
2191 int vhost_reset_device(struct vhost_dev *hdev)
2192 {
2193     if (hdev->vhost_ops->vhost_reset_device) {
2194         return hdev->vhost_ops->vhost_reset_device(hdev);
2195     }
2196 
2197     return -ENOSYS;
2198 }
2199 
2200 bool vhost_supports_device_state(struct vhost_dev *dev)
2201 {
2202     if (dev->vhost_ops->vhost_supports_device_state) {
2203         return dev->vhost_ops->vhost_supports_device_state(dev);
2204     }
2205 
2206     return false;
2207 }
2208 
2209 int vhost_set_device_state_fd(struct vhost_dev *dev,
2210                               VhostDeviceStateDirection direction,
2211                               VhostDeviceStatePhase phase,
2212                               int fd,
2213                               int *reply_fd,
2214                               Error **errp)
2215 {
2216     if (dev->vhost_ops->vhost_set_device_state_fd) {
2217         return dev->vhost_ops->vhost_set_device_state_fd(dev, direction, phase,
2218                                                          fd, reply_fd, errp);
2219     }
2220 
2221     error_setg(errp,
2222                "vhost transport does not support migration state transfer");
2223     return -ENOSYS;
2224 }
2225 
2226 int vhost_check_device_state(struct vhost_dev *dev, Error **errp)
2227 {
2228     if (dev->vhost_ops->vhost_check_device_state) {
2229         return dev->vhost_ops->vhost_check_device_state(dev, errp);
2230     }
2231 
2232     error_setg(errp,
2233                "vhost transport does not support migration state transfer");
2234     return -ENOSYS;
2235 }
2236 
2237 int vhost_save_backend_state(struct vhost_dev *dev, QEMUFile *f, Error **errp)
2238 {
2239     ERRP_GUARD();
2240     /* Maximum chunk size in which to transfer the state */
2241     const size_t chunk_size = 1 * 1024 * 1024;
2242     g_autofree void *transfer_buf = NULL;
2243     g_autoptr(GError) g_err = NULL;
2244     int pipe_fds[2], read_fd = -1, write_fd = -1, reply_fd = -1;
2245     int ret;
2246 
2247     /* [0] for reading (our end), [1] for writing (back-end's end) */
2248     if (!g_unix_open_pipe(pipe_fds, FD_CLOEXEC, &g_err)) {
2249         error_setg(errp, "Failed to set up state transfer pipe: %s",
2250                    g_err->message);
2251         ret = -EINVAL;
2252         goto fail;
2253     }
2254 
2255     read_fd = pipe_fds[0];
2256     write_fd = pipe_fds[1];
2257 
2258     /*
2259      * VHOST_TRANSFER_STATE_PHASE_STOPPED means the device must be stopped.
2260      * Ideally, it is suspended, but SUSPEND/RESUME currently do not exist for
2261      * vhost-user, so just check that it is stopped at all.
2262      */
2263     assert(!dev->started);
2264 
2265     /* Transfer ownership of write_fd to the back-end */
2266     ret = vhost_set_device_state_fd(dev,
2267                                     VHOST_TRANSFER_STATE_DIRECTION_SAVE,
2268                                     VHOST_TRANSFER_STATE_PHASE_STOPPED,
2269                                     write_fd,
2270                                     &reply_fd,
2271                                     errp);
2272     if (ret < 0) {
2273         error_prepend(errp, "Failed to initiate state transfer: ");
2274         goto fail;
2275     }
2276 
2277     /* If the back-end wishes to use a different pipe, switch over */
2278     if (reply_fd >= 0) {
2279         close(read_fd);
2280         read_fd = reply_fd;
2281     }
2282 
2283     transfer_buf = g_malloc(chunk_size);
2284 
2285     while (true) {
2286         ssize_t read_ret;
2287 
2288         read_ret = RETRY_ON_EINTR(read(read_fd, transfer_buf, chunk_size));
2289         if (read_ret < 0) {
2290             ret = -errno;
2291             error_setg_errno(errp, -ret, "Failed to receive state");
2292             goto fail;
2293         }
2294 
2295         assert(read_ret <= chunk_size);
2296         qemu_put_be32(f, read_ret);
2297 
2298         if (read_ret == 0) {
2299             /* EOF */
2300             break;
2301         }
2302 
2303         qemu_put_buffer(f, transfer_buf, read_ret);
2304     }
2305 
2306     /*
2307      * Back-end will not really care, but be clean and close our end of the pipe
2308      * before inquiring the back-end about whether transfer was successful
2309      */
2310     close(read_fd);
2311     read_fd = -1;
2312 
2313     /* Also, verify that the device is still stopped */
2314     assert(!dev->started);
2315 
2316     ret = vhost_check_device_state(dev, errp);
2317     if (ret < 0) {
2318         goto fail;
2319     }
2320 
2321     ret = 0;
2322 fail:
2323     if (read_fd >= 0) {
2324         close(read_fd);
2325     }
2326 
2327     return ret;
2328 }
2329 
2330 int vhost_load_backend_state(struct vhost_dev *dev, QEMUFile *f, Error **errp)
2331 {
2332     ERRP_GUARD();
2333     size_t transfer_buf_size = 0;
2334     g_autofree void *transfer_buf = NULL;
2335     g_autoptr(GError) g_err = NULL;
2336     int pipe_fds[2], read_fd = -1, write_fd = -1, reply_fd = -1;
2337     int ret;
2338 
2339     /* [0] for reading (back-end's end), [1] for writing (our end) */
2340     if (!g_unix_open_pipe(pipe_fds, FD_CLOEXEC, &g_err)) {
2341         error_setg(errp, "Failed to set up state transfer pipe: %s",
2342                    g_err->message);
2343         ret = -EINVAL;
2344         goto fail;
2345     }
2346 
2347     read_fd = pipe_fds[0];
2348     write_fd = pipe_fds[1];
2349 
2350     /*
2351      * VHOST_TRANSFER_STATE_PHASE_STOPPED means the device must be stopped.
2352      * Ideally, it is suspended, but SUSPEND/RESUME currently do not exist for
2353      * vhost-user, so just check that it is stopped at all.
2354      */
2355     assert(!dev->started);
2356 
2357     /* Transfer ownership of read_fd to the back-end */
2358     ret = vhost_set_device_state_fd(dev,
2359                                     VHOST_TRANSFER_STATE_DIRECTION_LOAD,
2360                                     VHOST_TRANSFER_STATE_PHASE_STOPPED,
2361                                     read_fd,
2362                                     &reply_fd,
2363                                     errp);
2364     if (ret < 0) {
2365         error_prepend(errp, "Failed to initiate state transfer: ");
2366         goto fail;
2367     }
2368 
2369     /* If the back-end wishes to use a different pipe, switch over */
2370     if (reply_fd >= 0) {
2371         close(write_fd);
2372         write_fd = reply_fd;
2373     }
2374 
2375     while (true) {
2376         size_t this_chunk_size = qemu_get_be32(f);
2377         ssize_t write_ret;
2378         const uint8_t *transfer_pointer;
2379 
2380         if (this_chunk_size == 0) {
2381             /* End of state */
2382             break;
2383         }
2384 
2385         if (transfer_buf_size < this_chunk_size) {
2386             transfer_buf = g_realloc(transfer_buf, this_chunk_size);
2387             transfer_buf_size = this_chunk_size;
2388         }
2389 
2390         if (qemu_get_buffer(f, transfer_buf, this_chunk_size) <
2391                 this_chunk_size)
2392         {
2393             error_setg(errp, "Failed to read state");
2394             ret = -EINVAL;
2395             goto fail;
2396         }
2397 
2398         transfer_pointer = transfer_buf;
2399         while (this_chunk_size > 0) {
2400             write_ret = RETRY_ON_EINTR(
2401                 write(write_fd, transfer_pointer, this_chunk_size)
2402             );
2403             if (write_ret < 0) {
2404                 ret = -errno;
2405                 error_setg_errno(errp, -ret, "Failed to send state");
2406                 goto fail;
2407             } else if (write_ret == 0) {
2408                 error_setg(errp, "Failed to send state: Connection is closed");
2409                 ret = -ECONNRESET;
2410                 goto fail;
2411             }
2412 
2413             assert(write_ret <= this_chunk_size);
2414             this_chunk_size -= write_ret;
2415             transfer_pointer += write_ret;
2416         }
2417     }
2418 
2419     /*
2420      * Close our end, thus ending transfer, before inquiring the back-end about
2421      * whether transfer was successful
2422      */
2423     close(write_fd);
2424     write_fd = -1;
2425 
2426     /* Also, verify that the device is still stopped */
2427     assert(!dev->started);
2428 
2429     ret = vhost_check_device_state(dev, errp);
2430     if (ret < 0) {
2431         goto fail;
2432     }
2433 
2434     ret = 0;
2435 fail:
2436     if (write_fd >= 0) {
2437         close(write_fd);
2438     }
2439 
2440     return ret;
2441 }
2442