xref: /openbmc/qemu/hw/virtio/vhost.c (revision 87d67ffe)
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/virtio/virtio-access.h"
27 #include "migration/blocker.h"
28 #include "migration/qemu-file-types.h"
29 #include "sysemu/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;
47 static struct vhost_log *vhost_log_shm;
48 
49 static unsigned int used_memslots;
50 static QLIST_HEAD(, vhost_dev) vhost_devices =
51     QLIST_HEAD_INITIALIZER(vhost_devices);
52 
53 bool vhost_has_free_slot(void)
54 {
55     unsigned int slots_limit = ~0U;
56     struct vhost_dev *hdev;
57 
58     QLIST_FOREACH(hdev, &vhost_devices, entry) {
59         unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
60         slots_limit = MIN(slots_limit, r);
61     }
62     return slots_limit > used_memslots;
63 }
64 
65 static void vhost_dev_sync_region(struct vhost_dev *dev,
66                                   MemoryRegionSection *section,
67                                   uint64_t mfirst, uint64_t mlast,
68                                   uint64_t rfirst, uint64_t rlast)
69 {
70     vhost_log_chunk_t *log = dev->log->log;
71 
72     uint64_t start = MAX(mfirst, rfirst);
73     uint64_t end = MIN(mlast, rlast);
74     vhost_log_chunk_t *from = log + start / VHOST_LOG_CHUNK;
75     vhost_log_chunk_t *to = log + end / VHOST_LOG_CHUNK + 1;
76     uint64_t addr = QEMU_ALIGN_DOWN(start, VHOST_LOG_CHUNK);
77 
78     if (end < start) {
79         return;
80     }
81     assert(end / VHOST_LOG_CHUNK < dev->log_size);
82     assert(start / VHOST_LOG_CHUNK < dev->log_size);
83 
84     for (;from < to; ++from) {
85         vhost_log_chunk_t log;
86         /* We first check with non-atomic: much cheaper,
87          * and we expect non-dirty to be the common case. */
88         if (!*from) {
89             addr += VHOST_LOG_CHUNK;
90             continue;
91         }
92         /* Data must be read atomically. We don't really need barrier semantics
93          * but it's easier to use atomic_* than roll our own. */
94         log = qatomic_xchg(from, 0);
95         while (log) {
96             int bit = ctzl(log);
97             hwaddr page_addr;
98             hwaddr section_offset;
99             hwaddr mr_offset;
100             page_addr = addr + bit * VHOST_LOG_PAGE;
101             section_offset = page_addr - section->offset_within_address_space;
102             mr_offset = section_offset + section->offset_within_region;
103             memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
104             log &= ~(0x1ull << bit);
105         }
106         addr += VHOST_LOG_CHUNK;
107     }
108 }
109 
110 static bool vhost_dev_has_iommu(struct vhost_dev *dev)
111 {
112     VirtIODevice *vdev = dev->vdev;
113 
114     /*
115      * For vhost, VIRTIO_F_IOMMU_PLATFORM means the backend support
116      * incremental memory mapping API via IOTLB API. For platform that
117      * does not have IOMMU, there's no need to enable this feature
118      * which may cause unnecessary IOTLB miss/update transactions.
119      */
120     if (vdev) {
121         return virtio_bus_device_iommu_enabled(vdev) &&
122             virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM);
123     } else {
124         return false;
125     }
126 }
127 
128 static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
129                                    MemoryRegionSection *section,
130                                    hwaddr first,
131                                    hwaddr last)
132 {
133     int i;
134     hwaddr start_addr;
135     hwaddr end_addr;
136 
137     if (!dev->log_enabled || !dev->started) {
138         return 0;
139     }
140     start_addr = section->offset_within_address_space;
141     end_addr = range_get_last(start_addr, int128_get64(section->size));
142     start_addr = MAX(first, start_addr);
143     end_addr = MIN(last, end_addr);
144 
145     for (i = 0; i < dev->mem->nregions; ++i) {
146         struct vhost_memory_region *reg = dev->mem->regions + i;
147         vhost_dev_sync_region(dev, section, start_addr, end_addr,
148                               reg->guest_phys_addr,
149                               range_get_last(reg->guest_phys_addr,
150                                              reg->memory_size));
151     }
152     for (i = 0; i < dev->nvqs; ++i) {
153         struct vhost_virtqueue *vq = dev->vqs + i;
154 
155         if (!vq->used_phys && !vq->used_size) {
156             continue;
157         }
158 
159         if (vhost_dev_has_iommu(dev)) {
160             IOMMUTLBEntry iotlb;
161             hwaddr used_phys = vq->used_phys, used_size = vq->used_size;
162             hwaddr phys, s, offset;
163 
164             while (used_size) {
165                 rcu_read_lock();
166                 iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
167                                                       used_phys,
168                                                       true,
169                                                       MEMTXATTRS_UNSPECIFIED);
170                 rcu_read_unlock();
171 
172                 if (!iotlb.target_as) {
173                     qemu_log_mask(LOG_GUEST_ERROR, "translation "
174                                   "failure for used_iova %"PRIx64"\n",
175                                   used_phys);
176                     return -EINVAL;
177                 }
178 
179                 offset = used_phys & iotlb.addr_mask;
180                 phys = iotlb.translated_addr + offset;
181 
182                 /*
183                  * Distance from start of used ring until last byte of
184                  * IOMMU page.
185                  */
186                 s = iotlb.addr_mask - offset;
187                 /*
188                  * Size of used ring, or of the part of it until end
189                  * of IOMMU page. To avoid zero result, do the adding
190                  * outside of MIN().
191                  */
192                 s = MIN(s, used_size - 1) + 1;
193 
194                 vhost_dev_sync_region(dev, section, start_addr, end_addr, phys,
195                                       range_get_last(phys, s));
196                 used_size -= s;
197                 used_phys += s;
198             }
199         } else {
200             vhost_dev_sync_region(dev, section, start_addr,
201                                   end_addr, vq->used_phys,
202                                   range_get_last(vq->used_phys, vq->used_size));
203         }
204     }
205     return 0;
206 }
207 
208 static void vhost_log_sync(MemoryListener *listener,
209                           MemoryRegionSection *section)
210 {
211     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
212                                          memory_listener);
213     vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
214 }
215 
216 static void vhost_log_sync_range(struct vhost_dev *dev,
217                                  hwaddr first, hwaddr last)
218 {
219     int i;
220     /* FIXME: this is N^2 in number of sections */
221     for (i = 0; i < dev->n_mem_sections; ++i) {
222         MemoryRegionSection *section = &dev->mem_sections[i];
223         vhost_sync_dirty_bitmap(dev, section, first, last);
224     }
225 }
226 
227 static uint64_t vhost_get_log_size(struct vhost_dev *dev)
228 {
229     uint64_t log_size = 0;
230     int i;
231     for (i = 0; i < dev->mem->nregions; ++i) {
232         struct vhost_memory_region *reg = dev->mem->regions + i;
233         uint64_t last = range_get_last(reg->guest_phys_addr,
234                                        reg->memory_size);
235         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
236     }
237     return log_size;
238 }
239 
240 static int vhost_set_backend_type(struct vhost_dev *dev,
241                                   VhostBackendType backend_type)
242 {
243     int r = 0;
244 
245     switch (backend_type) {
246 #ifdef CONFIG_VHOST_KERNEL
247     case VHOST_BACKEND_TYPE_KERNEL:
248         dev->vhost_ops = &kernel_ops;
249         break;
250 #endif
251 #ifdef CONFIG_VHOST_USER
252     case VHOST_BACKEND_TYPE_USER:
253         dev->vhost_ops = &user_ops;
254         break;
255 #endif
256 #ifdef CONFIG_VHOST_VDPA
257     case VHOST_BACKEND_TYPE_VDPA:
258         dev->vhost_ops = &vdpa_ops;
259         break;
260 #endif
261     default:
262         error_report("Unknown vhost backend type");
263         r = -1;
264     }
265 
266     return r;
267 }
268 
269 static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
270 {
271     Error *err = NULL;
272     struct vhost_log *log;
273     uint64_t logsize = size * sizeof(*(log->log));
274     int fd = -1;
275 
276     log = g_new0(struct vhost_log, 1);
277     if (share) {
278         log->log = qemu_memfd_alloc("vhost-log", logsize,
279                                     F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
280                                     &fd, &err);
281         if (err) {
282             error_report_err(err);
283             g_free(log);
284             return NULL;
285         }
286         memset(log->log, 0, logsize);
287     } else {
288         log->log = g_malloc0(logsize);
289     }
290 
291     log->size = size;
292     log->refcnt = 1;
293     log->fd = fd;
294 
295     return log;
296 }
297 
298 static struct vhost_log *vhost_log_get(uint64_t size, bool share)
299 {
300     struct vhost_log *log = share ? vhost_log_shm : vhost_log;
301 
302     if (!log || log->size != size) {
303         log = vhost_log_alloc(size, share);
304         if (share) {
305             vhost_log_shm = log;
306         } else {
307             vhost_log = log;
308         }
309     } else {
310         ++log->refcnt;
311     }
312 
313     return log;
314 }
315 
316 static void vhost_log_put(struct vhost_dev *dev, bool sync)
317 {
318     struct vhost_log *log = dev->log;
319 
320     if (!log) {
321         return;
322     }
323 
324     --log->refcnt;
325     if (log->refcnt == 0) {
326         /* Sync only the range covered by the old log */
327         if (dev->log_size && sync) {
328             vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
329         }
330 
331         if (vhost_log == log) {
332             g_free(log->log);
333             vhost_log = NULL;
334         } else if (vhost_log_shm == log) {
335             qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
336                             log->fd);
337             vhost_log_shm = NULL;
338         }
339 
340         g_free(log);
341     }
342 
343     dev->log = NULL;
344     dev->log_size = 0;
345 }
346 
347 static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
348 {
349     return dev->vhost_ops->vhost_requires_shm_log &&
350            dev->vhost_ops->vhost_requires_shm_log(dev);
351 }
352 
353 static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
354 {
355     struct vhost_log *log = vhost_log_get(size, vhost_dev_log_is_shared(dev));
356     uint64_t log_base = (uintptr_t)log->log;
357     int r;
358 
359     /* inform backend of log switching, this must be done before
360        releasing the current log, to ensure no logging is lost */
361     r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
362     if (r < 0) {
363         VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
364     }
365 
366     vhost_log_put(dev, true);
367     dev->log = log;
368     dev->log_size = size;
369 }
370 
371 static void *vhost_memory_map(struct vhost_dev *dev, hwaddr addr,
372                               hwaddr *plen, bool is_write)
373 {
374     if (!vhost_dev_has_iommu(dev)) {
375         return cpu_physical_memory_map(addr, plen, is_write);
376     } else {
377         return (void *)(uintptr_t)addr;
378     }
379 }
380 
381 static void vhost_memory_unmap(struct vhost_dev *dev, void *buffer,
382                                hwaddr len, int is_write,
383                                hwaddr access_len)
384 {
385     if (!vhost_dev_has_iommu(dev)) {
386         cpu_physical_memory_unmap(buffer, len, is_write, access_len);
387     }
388 }
389 
390 static int vhost_verify_ring_part_mapping(void *ring_hva,
391                                           uint64_t ring_gpa,
392                                           uint64_t ring_size,
393                                           void *reg_hva,
394                                           uint64_t reg_gpa,
395                                           uint64_t reg_size)
396 {
397     uint64_t hva_ring_offset;
398     uint64_t ring_last = range_get_last(ring_gpa, ring_size);
399     uint64_t reg_last = range_get_last(reg_gpa, reg_size);
400 
401     if (ring_last < reg_gpa || ring_gpa > reg_last) {
402         return 0;
403     }
404     /* check that whole ring's is mapped */
405     if (ring_last > reg_last) {
406         return -ENOMEM;
407     }
408     /* check that ring's MemoryRegion wasn't replaced */
409     hva_ring_offset = ring_gpa - reg_gpa;
410     if (ring_hva != reg_hva + hva_ring_offset) {
411         return -EBUSY;
412     }
413 
414     return 0;
415 }
416 
417 static int vhost_verify_ring_mappings(struct vhost_dev *dev,
418                                       void *reg_hva,
419                                       uint64_t reg_gpa,
420                                       uint64_t reg_size)
421 {
422     int i, j;
423     int r = 0;
424     const char *part_name[] = {
425         "descriptor table",
426         "available ring",
427         "used ring"
428     };
429 
430     if (vhost_dev_has_iommu(dev)) {
431         return 0;
432     }
433 
434     for (i = 0; i < dev->nvqs; ++i) {
435         struct vhost_virtqueue *vq = dev->vqs + i;
436 
437         if (vq->desc_phys == 0) {
438             continue;
439         }
440 
441         j = 0;
442         r = vhost_verify_ring_part_mapping(
443                 vq->desc, vq->desc_phys, vq->desc_size,
444                 reg_hva, reg_gpa, reg_size);
445         if (r) {
446             break;
447         }
448 
449         j++;
450         r = vhost_verify_ring_part_mapping(
451                 vq->avail, vq->avail_phys, vq->avail_size,
452                 reg_hva, reg_gpa, reg_size);
453         if (r) {
454             break;
455         }
456 
457         j++;
458         r = vhost_verify_ring_part_mapping(
459                 vq->used, vq->used_phys, vq->used_size,
460                 reg_hva, reg_gpa, reg_size);
461         if (r) {
462             break;
463         }
464     }
465 
466     if (r == -ENOMEM) {
467         error_report("Unable to map %s for ring %d", part_name[j], i);
468     } else if (r == -EBUSY) {
469         error_report("%s relocated for ring %d", part_name[j], i);
470     }
471     return r;
472 }
473 
474 /*
475  * vhost_section: identify sections needed for vhost access
476  *
477  * We only care about RAM sections here (where virtqueue and guest
478  * internals accessed by virtio might live). If we find one we still
479  * allow the backend to potentially filter it out of our list.
480  */
481 static bool vhost_section(struct vhost_dev *dev, MemoryRegionSection *section)
482 {
483     MemoryRegion *mr = section->mr;
484 
485     if (memory_region_is_ram(mr) && !memory_region_is_rom(mr)) {
486         uint8_t dirty_mask = memory_region_get_dirty_log_mask(mr);
487         uint8_t handled_dirty;
488 
489         /*
490          * Kernel based vhost doesn't handle any block which is doing
491          * dirty-tracking other than migration for which it has
492          * specific logging support. However for TCG the kernel never
493          * gets involved anyway so we can also ignore it's
494          * self-modiying code detection flags. However a vhost-user
495          * client could still confuse a TCG guest if it re-writes
496          * executable memory that has already been translated.
497          */
498         handled_dirty = (1 << DIRTY_MEMORY_MIGRATION) |
499             (1 << DIRTY_MEMORY_CODE);
500 
501         if (dirty_mask & ~handled_dirty) {
502             trace_vhost_reject_section(mr->name, 1);
503             return false;
504         }
505 
506         if (dev->vhost_ops->vhost_backend_mem_section_filter &&
507             !dev->vhost_ops->vhost_backend_mem_section_filter(dev, section)) {
508             trace_vhost_reject_section(mr->name, 2);
509             return false;
510         }
511 
512         trace_vhost_section(mr->name);
513         return true;
514     } else {
515         trace_vhost_reject_section(mr->name, 3);
516         return false;
517     }
518 }
519 
520 static void vhost_begin(MemoryListener *listener)
521 {
522     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
523                                          memory_listener);
524     dev->tmp_sections = NULL;
525     dev->n_tmp_sections = 0;
526 }
527 
528 static void vhost_commit(MemoryListener *listener)
529 {
530     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
531                                          memory_listener);
532     MemoryRegionSection *old_sections;
533     int n_old_sections;
534     uint64_t log_size;
535     size_t regions_size;
536     int r;
537     int i;
538     bool changed = false;
539 
540     /* Note we can be called before the device is started, but then
541      * starting the device calls set_mem_table, so we need to have
542      * built the data structures.
543      */
544     old_sections = dev->mem_sections;
545     n_old_sections = dev->n_mem_sections;
546     dev->mem_sections = dev->tmp_sections;
547     dev->n_mem_sections = dev->n_tmp_sections;
548 
549     if (dev->n_mem_sections != n_old_sections) {
550         changed = true;
551     } else {
552         /* Same size, lets check the contents */
553         for (int i = 0; i < n_old_sections; i++) {
554             if (!MemoryRegionSection_eq(&old_sections[i],
555                                         &dev->mem_sections[i])) {
556                 changed = true;
557                 break;
558             }
559         }
560     }
561 
562     trace_vhost_commit(dev->started, changed);
563     if (!changed) {
564         goto out;
565     }
566 
567     /* Rebuild the regions list from the new sections list */
568     regions_size = offsetof(struct vhost_memory, regions) +
569                        dev->n_mem_sections * sizeof dev->mem->regions[0];
570     dev->mem = g_realloc(dev->mem, regions_size);
571     dev->mem->nregions = dev->n_mem_sections;
572     used_memslots = dev->mem->nregions;
573     for (i = 0; i < dev->n_mem_sections; i++) {
574         struct vhost_memory_region *cur_vmr = dev->mem->regions + i;
575         struct MemoryRegionSection *mrs = dev->mem_sections + i;
576 
577         cur_vmr->guest_phys_addr = mrs->offset_within_address_space;
578         cur_vmr->memory_size     = int128_get64(mrs->size);
579         cur_vmr->userspace_addr  =
580             (uintptr_t)memory_region_get_ram_ptr(mrs->mr) +
581             mrs->offset_within_region;
582         cur_vmr->flags_padding   = 0;
583     }
584 
585     if (!dev->started) {
586         goto out;
587     }
588 
589     for (i = 0; i < dev->mem->nregions; i++) {
590         if (vhost_verify_ring_mappings(dev,
591                        (void *)(uintptr_t)dev->mem->regions[i].userspace_addr,
592                        dev->mem->regions[i].guest_phys_addr,
593                        dev->mem->regions[i].memory_size)) {
594             error_report("Verify ring failure on region %d", i);
595             abort();
596         }
597     }
598 
599     if (!dev->log_enabled) {
600         r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
601         if (r < 0) {
602             VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
603         }
604         goto out;
605     }
606     log_size = vhost_get_log_size(dev);
607     /* We allocate an extra 4K bytes to log,
608      * to reduce the * number of reallocations. */
609 #define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
610     /* To log more, must increase log size before table update. */
611     if (dev->log_size < log_size) {
612         vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
613     }
614     r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
615     if (r < 0) {
616         VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
617     }
618     /* To log less, can only decrease log size after table update. */
619     if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
620         vhost_dev_log_resize(dev, log_size);
621     }
622 
623 out:
624     /* Deref the old list of sections, this must happen _after_ the
625      * vhost_set_mem_table to ensure the client isn't still using the
626      * section we're about to unref.
627      */
628     while (n_old_sections--) {
629         memory_region_unref(old_sections[n_old_sections].mr);
630     }
631     g_free(old_sections);
632     return;
633 }
634 
635 /* Adds the section data to the tmp_section structure.
636  * It relies on the listener calling us in memory address order
637  * and for each region (via the _add and _nop methods) to
638  * join neighbours.
639  */
640 static void vhost_region_add_section(struct vhost_dev *dev,
641                                      MemoryRegionSection *section)
642 {
643     bool need_add = true;
644     uint64_t mrs_size = int128_get64(section->size);
645     uint64_t mrs_gpa = section->offset_within_address_space;
646     uintptr_t mrs_host = (uintptr_t)memory_region_get_ram_ptr(section->mr) +
647                          section->offset_within_region;
648     RAMBlock *mrs_rb = section->mr->ram_block;
649 
650     trace_vhost_region_add_section(section->mr->name, mrs_gpa, mrs_size,
651                                    mrs_host);
652 
653     if (dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER) {
654         /* Round the section to it's page size */
655         /* First align the start down to a page boundary */
656         size_t mrs_page = qemu_ram_pagesize(mrs_rb);
657         uint64_t alignage = mrs_host & (mrs_page - 1);
658         if (alignage) {
659             mrs_host -= alignage;
660             mrs_size += alignage;
661             mrs_gpa  -= alignage;
662         }
663         /* Now align the size up to a page boundary */
664         alignage = mrs_size & (mrs_page - 1);
665         if (alignage) {
666             mrs_size += mrs_page - alignage;
667         }
668         trace_vhost_region_add_section_aligned(section->mr->name, mrs_gpa,
669                                                mrs_size, mrs_host);
670     }
671 
672     if (dev->n_tmp_sections) {
673         /* Since we already have at least one section, lets see if
674          * this extends it; since we're scanning in order, we only
675          * have to look at the last one, and the FlatView that calls
676          * us shouldn't have overlaps.
677          */
678         MemoryRegionSection *prev_sec = dev->tmp_sections +
679                                                (dev->n_tmp_sections - 1);
680         uint64_t prev_gpa_start = prev_sec->offset_within_address_space;
681         uint64_t prev_size = int128_get64(prev_sec->size);
682         uint64_t prev_gpa_end   = range_get_last(prev_gpa_start, prev_size);
683         uint64_t prev_host_start =
684                         (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr) +
685                         prev_sec->offset_within_region;
686         uint64_t prev_host_end   = range_get_last(prev_host_start, prev_size);
687 
688         if (mrs_gpa <= (prev_gpa_end + 1)) {
689             /* OK, looks like overlapping/intersecting - it's possible that
690              * the rounding to page sizes has made them overlap, but they should
691              * match up in the same RAMBlock if they do.
692              */
693             if (mrs_gpa < prev_gpa_start) {
694                 error_report("%s:Section '%s' rounded to %"PRIx64
695                              " prior to previous '%s' %"PRIx64,
696                              __func__, section->mr->name, mrs_gpa,
697                              prev_sec->mr->name, prev_gpa_start);
698                 /* A way to cleanly fail here would be better */
699                 return;
700             }
701             /* Offset from the start of the previous GPA to this GPA */
702             size_t offset = mrs_gpa - prev_gpa_start;
703 
704             if (prev_host_start + offset == mrs_host &&
705                 section->mr == prev_sec->mr &&
706                 (!dev->vhost_ops->vhost_backend_can_merge ||
707                  dev->vhost_ops->vhost_backend_can_merge(dev,
708                     mrs_host, mrs_size,
709                     prev_host_start, prev_size))) {
710                 uint64_t max_end = MAX(prev_host_end, mrs_host + mrs_size);
711                 need_add = false;
712                 prev_sec->offset_within_address_space =
713                     MIN(prev_gpa_start, mrs_gpa);
714                 prev_sec->offset_within_region =
715                     MIN(prev_host_start, mrs_host) -
716                     (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr);
717                 prev_sec->size = int128_make64(max_end - MIN(prev_host_start,
718                                                mrs_host));
719                 trace_vhost_region_add_section_merge(section->mr->name,
720                                         int128_get64(prev_sec->size),
721                                         prev_sec->offset_within_address_space,
722                                         prev_sec->offset_within_region);
723             } else {
724                 /* adjoining regions are fine, but overlapping ones with
725                  * different blocks/offsets shouldn't happen
726                  */
727                 if (mrs_gpa != prev_gpa_end + 1) {
728                     error_report("%s: Overlapping but not coherent sections "
729                                  "at %"PRIx64,
730                                  __func__, mrs_gpa);
731                     return;
732                 }
733             }
734         }
735     }
736 
737     if (need_add) {
738         ++dev->n_tmp_sections;
739         dev->tmp_sections = g_renew(MemoryRegionSection, dev->tmp_sections,
740                                     dev->n_tmp_sections);
741         dev->tmp_sections[dev->n_tmp_sections - 1] = *section;
742         /* The flatview isn't stable and we don't use it, making it NULL
743          * means we can memcmp the list.
744          */
745         dev->tmp_sections[dev->n_tmp_sections - 1].fv = NULL;
746         memory_region_ref(section->mr);
747     }
748 }
749 
750 /* Used for both add and nop callbacks */
751 static void vhost_region_addnop(MemoryListener *listener,
752                                 MemoryRegionSection *section)
753 {
754     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
755                                          memory_listener);
756 
757     if (!vhost_section(dev, section)) {
758         return;
759     }
760     vhost_region_add_section(dev, section);
761 }
762 
763 static void vhost_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
764 {
765     struct vhost_iommu *iommu = container_of(n, struct vhost_iommu, n);
766     struct vhost_dev *hdev = iommu->hdev;
767     hwaddr iova = iotlb->iova + iommu->iommu_offset;
768 
769     if (vhost_backend_invalidate_device_iotlb(hdev, iova,
770                                               iotlb->addr_mask + 1)) {
771         error_report("Fail to invalidate device iotlb");
772     }
773 }
774 
775 static void vhost_iommu_region_add(MemoryListener *listener,
776                                    MemoryRegionSection *section)
777 {
778     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
779                                          iommu_listener);
780     struct vhost_iommu *iommu;
781     Int128 end;
782     int iommu_idx;
783     IOMMUMemoryRegion *iommu_mr;
784     int ret;
785 
786     if (!memory_region_is_iommu(section->mr)) {
787         return;
788     }
789 
790     iommu_mr = IOMMU_MEMORY_REGION(section->mr);
791 
792     iommu = g_malloc0(sizeof(*iommu));
793     end = int128_add(int128_make64(section->offset_within_region),
794                      section->size);
795     end = int128_sub(end, int128_one());
796     iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
797                                                    MEMTXATTRS_UNSPECIFIED);
798     iommu_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
799                         IOMMU_NOTIFIER_DEVIOTLB_UNMAP,
800                         section->offset_within_region,
801                         int128_get64(end),
802                         iommu_idx);
803     iommu->mr = section->mr;
804     iommu->iommu_offset = section->offset_within_address_space -
805                           section->offset_within_region;
806     iommu->hdev = dev;
807     ret = memory_region_register_iommu_notifier(section->mr, &iommu->n, NULL);
808     if (ret) {
809         /*
810          * Some vIOMMUs do not support dev-iotlb yet.  If so, try to use the
811          * UNMAP legacy message
812          */
813         iommu->n.notifier_flags = IOMMU_NOTIFIER_UNMAP;
814         memory_region_register_iommu_notifier(section->mr, &iommu->n,
815                                               &error_fatal);
816     }
817     QLIST_INSERT_HEAD(&dev->iommu_list, iommu, iommu_next);
818     /* TODO: can replay help performance here? */
819 }
820 
821 static void vhost_iommu_region_del(MemoryListener *listener,
822                                    MemoryRegionSection *section)
823 {
824     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
825                                          iommu_listener);
826     struct vhost_iommu *iommu;
827 
828     if (!memory_region_is_iommu(section->mr)) {
829         return;
830     }
831 
832     QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
833         if (iommu->mr == section->mr &&
834             iommu->n.start == section->offset_within_region) {
835             memory_region_unregister_iommu_notifier(iommu->mr,
836                                                     &iommu->n);
837             QLIST_REMOVE(iommu, iommu_next);
838             g_free(iommu);
839             break;
840         }
841     }
842 }
843 
844 static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
845                                     struct vhost_virtqueue *vq,
846                                     unsigned idx, bool enable_log)
847 {
848     struct vhost_vring_addr addr;
849     int r;
850     memset(&addr, 0, sizeof(struct vhost_vring_addr));
851 
852     if (dev->vhost_ops->vhost_vq_get_addr) {
853         r = dev->vhost_ops->vhost_vq_get_addr(dev, &addr, vq);
854         if (r < 0) {
855             VHOST_OPS_DEBUG(r, "vhost_vq_get_addr failed");
856             return r;
857         }
858     } else {
859         addr.desc_user_addr = (uint64_t)(unsigned long)vq->desc;
860         addr.avail_user_addr = (uint64_t)(unsigned long)vq->avail;
861         addr.used_user_addr = (uint64_t)(unsigned long)vq->used;
862     }
863     addr.index = idx;
864     addr.log_guest_addr = vq->used_phys;
865     addr.flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0;
866     r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
867     if (r < 0) {
868         VHOST_OPS_DEBUG(r, "vhost_set_vring_addr failed");
869     }
870     return r;
871 }
872 
873 static int vhost_dev_set_features(struct vhost_dev *dev,
874                                   bool enable_log)
875 {
876     uint64_t features = dev->acked_features;
877     int r;
878     if (enable_log) {
879         features |= 0x1ULL << VHOST_F_LOG_ALL;
880     }
881     if (!vhost_dev_has_iommu(dev)) {
882         features &= ~(0x1ULL << VIRTIO_F_IOMMU_PLATFORM);
883     }
884     if (dev->vhost_ops->vhost_force_iommu) {
885         if (dev->vhost_ops->vhost_force_iommu(dev) == true) {
886             features |= 0x1ULL << VIRTIO_F_IOMMU_PLATFORM;
887        }
888     }
889     r = dev->vhost_ops->vhost_set_features(dev, features);
890     if (r < 0) {
891         VHOST_OPS_DEBUG(r, "vhost_set_features failed");
892         goto out;
893     }
894     if (dev->vhost_ops->vhost_set_backend_cap) {
895         r = dev->vhost_ops->vhost_set_backend_cap(dev);
896         if (r < 0) {
897             VHOST_OPS_DEBUG(r, "vhost_set_backend_cap failed");
898             goto out;
899         }
900     }
901 
902 out:
903     return r;
904 }
905 
906 static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
907 {
908     int r, i, idx;
909     hwaddr addr;
910 
911     r = vhost_dev_set_features(dev, enable_log);
912     if (r < 0) {
913         goto err_features;
914     }
915     for (i = 0; i < dev->nvqs; ++i) {
916         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
917         addr = virtio_queue_get_desc_addr(dev->vdev, idx);
918         if (!addr) {
919             /*
920              * The queue might not be ready for start. If this
921              * is the case there is no reason to continue the process.
922              * The similar logic is used by the vhost_virtqueue_start()
923              * routine.
924              */
925             continue;
926         }
927         r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
928                                      enable_log);
929         if (r < 0) {
930             goto err_vq;
931         }
932     }
933     return 0;
934 err_vq:
935     for (; i >= 0; --i) {
936         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
937         addr = virtio_queue_get_desc_addr(dev->vdev, idx);
938         if (!addr) {
939             continue;
940         }
941         vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
942                                  dev->log_enabled);
943     }
944     vhost_dev_set_features(dev, dev->log_enabled);
945 err_features:
946     return r;
947 }
948 
949 static int vhost_migration_log(MemoryListener *listener, bool enable)
950 {
951     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
952                                          memory_listener);
953     int r;
954     if (enable == dev->log_enabled) {
955         return 0;
956     }
957     if (!dev->started) {
958         dev->log_enabled = enable;
959         return 0;
960     }
961 
962     r = 0;
963     if (!enable) {
964         r = vhost_dev_set_log(dev, false);
965         if (r < 0) {
966             goto check_dev_state;
967         }
968         vhost_log_put(dev, false);
969     } else {
970         vhost_dev_log_resize(dev, vhost_get_log_size(dev));
971         r = vhost_dev_set_log(dev, true);
972         if (r < 0) {
973             goto check_dev_state;
974         }
975     }
976 
977 check_dev_state:
978     dev->log_enabled = enable;
979     /*
980      * vhost-user-* devices could change their state during log
981      * initialization due to disconnect. So check dev state after
982      * vhost communication.
983      */
984     if (!dev->started) {
985         /*
986          * Since device is in the stopped state, it is okay for
987          * migration. Return success.
988          */
989         r = 0;
990     }
991     if (r) {
992         /* An error occurred. */
993         dev->log_enabled = false;
994     }
995 
996     return r;
997 }
998 
999 static void vhost_log_global_start(MemoryListener *listener)
1000 {
1001     int r;
1002 
1003     r = vhost_migration_log(listener, true);
1004     if (r < 0) {
1005         abort();
1006     }
1007 }
1008 
1009 static void vhost_log_global_stop(MemoryListener *listener)
1010 {
1011     int r;
1012 
1013     r = vhost_migration_log(listener, false);
1014     if (r < 0) {
1015         abort();
1016     }
1017 }
1018 
1019 static void vhost_log_start(MemoryListener *listener,
1020                             MemoryRegionSection *section,
1021                             int old, int new)
1022 {
1023     /* FIXME: implement */
1024 }
1025 
1026 static void vhost_log_stop(MemoryListener *listener,
1027                            MemoryRegionSection *section,
1028                            int old, int new)
1029 {
1030     /* FIXME: implement */
1031 }
1032 
1033 /* The vhost driver natively knows how to handle the vrings of non
1034  * cross-endian legacy devices and modern devices. Only legacy devices
1035  * exposed to a bi-endian guest may require the vhost driver to use a
1036  * specific endianness.
1037  */
1038 static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
1039 {
1040     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1041         return false;
1042     }
1043 #if HOST_BIG_ENDIAN
1044     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
1045 #else
1046     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
1047 #endif
1048 }
1049 
1050 static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
1051                                                    bool is_big_endian,
1052                                                    int vhost_vq_index)
1053 {
1054     int r;
1055     struct vhost_vring_state s = {
1056         .index = vhost_vq_index,
1057         .num = is_big_endian
1058     };
1059 
1060     r = dev->vhost_ops->vhost_set_vring_endian(dev, &s);
1061     if (r < 0) {
1062         VHOST_OPS_DEBUG(r, "vhost_set_vring_endian failed");
1063     }
1064     return r;
1065 }
1066 
1067 static int vhost_memory_region_lookup(struct vhost_dev *hdev,
1068                                       uint64_t gpa, uint64_t *uaddr,
1069                                       uint64_t *len)
1070 {
1071     int i;
1072 
1073     for (i = 0; i < hdev->mem->nregions; i++) {
1074         struct vhost_memory_region *reg = hdev->mem->regions + i;
1075 
1076         if (gpa >= reg->guest_phys_addr &&
1077             reg->guest_phys_addr + reg->memory_size > gpa) {
1078             *uaddr = reg->userspace_addr + gpa - reg->guest_phys_addr;
1079             *len = reg->guest_phys_addr + reg->memory_size - gpa;
1080             return 0;
1081         }
1082     }
1083 
1084     return -EFAULT;
1085 }
1086 
1087 int vhost_device_iotlb_miss(struct vhost_dev *dev, uint64_t iova, int write)
1088 {
1089     IOMMUTLBEntry iotlb;
1090     uint64_t uaddr, len;
1091     int ret = -EFAULT;
1092 
1093     RCU_READ_LOCK_GUARD();
1094 
1095     trace_vhost_iotlb_miss(dev, 1);
1096 
1097     iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
1098                                           iova, write,
1099                                           MEMTXATTRS_UNSPECIFIED);
1100     if (iotlb.target_as != NULL) {
1101         ret = vhost_memory_region_lookup(dev, iotlb.translated_addr,
1102                                          &uaddr, &len);
1103         if (ret) {
1104             trace_vhost_iotlb_miss(dev, 3);
1105             error_report("Fail to lookup the translated address "
1106                          "%"PRIx64, iotlb.translated_addr);
1107             goto out;
1108         }
1109 
1110         len = MIN(iotlb.addr_mask + 1, len);
1111         iova = iova & ~iotlb.addr_mask;
1112 
1113         ret = vhost_backend_update_device_iotlb(dev, iova, uaddr,
1114                                                 len, iotlb.perm);
1115         if (ret) {
1116             trace_vhost_iotlb_miss(dev, 4);
1117             error_report("Fail to update device iotlb");
1118             goto out;
1119         }
1120     }
1121 
1122     trace_vhost_iotlb_miss(dev, 2);
1123 
1124 out:
1125     return ret;
1126 }
1127 
1128 int vhost_virtqueue_start(struct vhost_dev *dev,
1129                           struct VirtIODevice *vdev,
1130                           struct vhost_virtqueue *vq,
1131                           unsigned idx)
1132 {
1133     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1134     VirtioBusState *vbus = VIRTIO_BUS(qbus);
1135     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
1136     hwaddr s, l, a;
1137     int r;
1138     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1139     struct vhost_vring_file file = {
1140         .index = vhost_vq_index
1141     };
1142     struct vhost_vring_state state = {
1143         .index = vhost_vq_index
1144     };
1145     struct VirtQueue *vvq = virtio_get_queue(vdev, idx);
1146 
1147     a = virtio_queue_get_desc_addr(vdev, idx);
1148     if (a == 0) {
1149         /* Queue might not be ready for start */
1150         return 0;
1151     }
1152 
1153     vq->num = state.num = virtio_queue_get_num(vdev, idx);
1154     r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
1155     if (r) {
1156         VHOST_OPS_DEBUG(r, "vhost_set_vring_num failed");
1157         return r;
1158     }
1159 
1160     state.num = virtio_queue_get_last_avail_idx(vdev, idx);
1161     r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
1162     if (r) {
1163         VHOST_OPS_DEBUG(r, "vhost_set_vring_base failed");
1164         return r;
1165     }
1166 
1167     if (vhost_needs_vring_endian(vdev)) {
1168         r = vhost_virtqueue_set_vring_endian_legacy(dev,
1169                                                     virtio_is_big_endian(vdev),
1170                                                     vhost_vq_index);
1171         if (r) {
1172             return r;
1173         }
1174     }
1175 
1176     vq->desc_size = s = l = virtio_queue_get_desc_size(vdev, idx);
1177     vq->desc_phys = a;
1178     vq->desc = vhost_memory_map(dev, a, &l, false);
1179     if (!vq->desc || l != s) {
1180         r = -ENOMEM;
1181         goto fail_alloc_desc;
1182     }
1183     vq->avail_size = s = l = virtio_queue_get_avail_size(vdev, idx);
1184     vq->avail_phys = a = virtio_queue_get_avail_addr(vdev, idx);
1185     vq->avail = vhost_memory_map(dev, a, &l, false);
1186     if (!vq->avail || l != s) {
1187         r = -ENOMEM;
1188         goto fail_alloc_avail;
1189     }
1190     vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
1191     vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
1192     vq->used = vhost_memory_map(dev, a, &l, true);
1193     if (!vq->used || l != s) {
1194         r = -ENOMEM;
1195         goto fail_alloc_used;
1196     }
1197 
1198     r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
1199     if (r < 0) {
1200         goto fail_alloc;
1201     }
1202 
1203     file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
1204     r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
1205     if (r) {
1206         VHOST_OPS_DEBUG(r, "vhost_set_vring_kick failed");
1207         goto fail_kick;
1208     }
1209 
1210     /* Clear and discard previous events if any. */
1211     event_notifier_test_and_clear(&vq->masked_notifier);
1212 
1213     /* Init vring in unmasked state, unless guest_notifier_mask
1214      * will do it later.
1215      */
1216     if (!vdev->use_guest_notifier_mask) {
1217         /* TODO: check and handle errors. */
1218         vhost_virtqueue_mask(dev, vdev, idx, false);
1219     }
1220 
1221     if (k->query_guest_notifiers &&
1222         k->query_guest_notifiers(qbus->parent) &&
1223         virtio_queue_vector(vdev, idx) == VIRTIO_NO_VECTOR) {
1224         file.fd = -1;
1225         r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1226         if (r) {
1227             goto fail_vector;
1228         }
1229     }
1230 
1231     return 0;
1232 
1233 fail_vector:
1234 fail_kick:
1235 fail_alloc:
1236     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1237                        0, 0);
1238 fail_alloc_used:
1239     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1240                        0, 0);
1241 fail_alloc_avail:
1242     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1243                        0, 0);
1244 fail_alloc_desc:
1245     return r;
1246 }
1247 
1248 void vhost_virtqueue_stop(struct vhost_dev *dev,
1249                           struct VirtIODevice *vdev,
1250                           struct vhost_virtqueue *vq,
1251                           unsigned idx)
1252 {
1253     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1254     struct vhost_vring_state state = {
1255         .index = vhost_vq_index,
1256     };
1257     int r;
1258 
1259     if (virtio_queue_get_desc_addr(vdev, idx) == 0) {
1260         /* Don't stop the virtqueue which might have not been started */
1261         return;
1262     }
1263 
1264     r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
1265     if (r < 0) {
1266         VHOST_OPS_DEBUG(r, "vhost VQ %u ring restore failed: %d", idx, r);
1267         /* Connection to the backend is broken, so let's sync internal
1268          * last avail idx to the device used idx.
1269          */
1270         virtio_queue_restore_last_avail_idx(vdev, idx);
1271     } else {
1272         virtio_queue_set_last_avail_idx(vdev, idx, state.num);
1273     }
1274     virtio_queue_invalidate_signalled_used(vdev, idx);
1275     virtio_queue_update_used_idx(vdev, idx);
1276 
1277     /* In the cross-endian case, we need to reset the vring endianness to
1278      * native as legacy devices expect so by default.
1279      */
1280     if (vhost_needs_vring_endian(vdev)) {
1281         vhost_virtqueue_set_vring_endian_legacy(dev,
1282                                                 !virtio_is_big_endian(vdev),
1283                                                 vhost_vq_index);
1284     }
1285 
1286     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1287                        1, virtio_queue_get_used_size(vdev, idx));
1288     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1289                        0, virtio_queue_get_avail_size(vdev, idx));
1290     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1291                        0, virtio_queue_get_desc_size(vdev, idx));
1292 }
1293 
1294 static void vhost_eventfd_add(MemoryListener *listener,
1295                               MemoryRegionSection *section,
1296                               bool match_data, uint64_t data, EventNotifier *e)
1297 {
1298 }
1299 
1300 static void vhost_eventfd_del(MemoryListener *listener,
1301                               MemoryRegionSection *section,
1302                               bool match_data, uint64_t data, EventNotifier *e)
1303 {
1304 }
1305 
1306 static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
1307                                                 int n, uint32_t timeout)
1308 {
1309     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1310     struct vhost_vring_state state = {
1311         .index = vhost_vq_index,
1312         .num = timeout,
1313     };
1314     int r;
1315 
1316     if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
1317         return -EINVAL;
1318     }
1319 
1320     r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
1321     if (r) {
1322         VHOST_OPS_DEBUG(r, "vhost_set_vring_busyloop_timeout failed");
1323         return r;
1324     }
1325 
1326     return 0;
1327 }
1328 
1329 static void vhost_virtqueue_error_notifier(EventNotifier *n)
1330 {
1331     struct vhost_virtqueue *vq = container_of(n, struct vhost_virtqueue,
1332                                               error_notifier);
1333     struct vhost_dev *dev = vq->dev;
1334     int index = vq - dev->vqs;
1335 
1336     if (event_notifier_test_and_clear(n) && dev->vdev) {
1337         VHOST_OPS_DEBUG(-EINVAL,  "vhost vring error in virtqueue %d",
1338                         dev->vq_index + index);
1339     }
1340 }
1341 
1342 static int vhost_virtqueue_init(struct vhost_dev *dev,
1343                                 struct vhost_virtqueue *vq, int n)
1344 {
1345     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1346     struct vhost_vring_file file = {
1347         .index = vhost_vq_index,
1348     };
1349     int r = event_notifier_init(&vq->masked_notifier, 0);
1350     if (r < 0) {
1351         return r;
1352     }
1353 
1354     file.fd = event_notifier_get_wfd(&vq->masked_notifier);
1355     r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1356     if (r) {
1357         VHOST_OPS_DEBUG(r, "vhost_set_vring_call failed");
1358         goto fail_call;
1359     }
1360 
1361     vq->dev = dev;
1362 
1363     if (dev->vhost_ops->vhost_set_vring_err) {
1364         r = event_notifier_init(&vq->error_notifier, 0);
1365         if (r < 0) {
1366             goto fail_call;
1367         }
1368 
1369         file.fd = event_notifier_get_fd(&vq->error_notifier);
1370         r = dev->vhost_ops->vhost_set_vring_err(dev, &file);
1371         if (r) {
1372             VHOST_OPS_DEBUG(r, "vhost_set_vring_err failed");
1373             goto fail_err;
1374         }
1375 
1376         event_notifier_set_handler(&vq->error_notifier,
1377                                    vhost_virtqueue_error_notifier);
1378     }
1379 
1380     return 0;
1381 
1382 fail_err:
1383     event_notifier_cleanup(&vq->error_notifier);
1384 fail_call:
1385     event_notifier_cleanup(&vq->masked_notifier);
1386     return r;
1387 }
1388 
1389 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1390 {
1391     event_notifier_cleanup(&vq->masked_notifier);
1392     if (vq->dev->vhost_ops->vhost_set_vring_err) {
1393         event_notifier_set_handler(&vq->error_notifier, NULL);
1394         event_notifier_cleanup(&vq->error_notifier);
1395     }
1396 }
1397 
1398 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1399                    VhostBackendType backend_type, uint32_t busyloop_timeout,
1400                    Error **errp)
1401 {
1402     uint64_t features;
1403     int i, r, n_initialized_vqs = 0;
1404 
1405     hdev->vdev = NULL;
1406     hdev->migration_blocker = NULL;
1407 
1408     r = vhost_set_backend_type(hdev, backend_type);
1409     assert(r >= 0);
1410 
1411     r = hdev->vhost_ops->vhost_backend_init(hdev, opaque, errp);
1412     if (r < 0) {
1413         goto fail;
1414     }
1415 
1416     r = hdev->vhost_ops->vhost_set_owner(hdev);
1417     if (r < 0) {
1418         error_setg_errno(errp, -r, "vhost_set_owner failed");
1419         goto fail;
1420     }
1421 
1422     r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1423     if (r < 0) {
1424         error_setg_errno(errp, -r, "vhost_get_features failed");
1425         goto fail;
1426     }
1427 
1428     for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1429         r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1430         if (r < 0) {
1431             error_setg_errno(errp, -r, "Failed to initialize virtqueue %d", i);
1432             goto fail;
1433         }
1434     }
1435 
1436     if (busyloop_timeout) {
1437         for (i = 0; i < hdev->nvqs; ++i) {
1438             r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1439                                                      busyloop_timeout);
1440             if (r < 0) {
1441                 error_setg_errno(errp, -r, "Failed to set busyloop timeout");
1442                 goto fail_busyloop;
1443             }
1444         }
1445     }
1446 
1447     hdev->features = features;
1448 
1449     hdev->memory_listener = (MemoryListener) {
1450         .name = "vhost",
1451         .begin = vhost_begin,
1452         .commit = vhost_commit,
1453         .region_add = vhost_region_addnop,
1454         .region_nop = vhost_region_addnop,
1455         .log_start = vhost_log_start,
1456         .log_stop = vhost_log_stop,
1457         .log_sync = vhost_log_sync,
1458         .log_global_start = vhost_log_global_start,
1459         .log_global_stop = vhost_log_global_stop,
1460         .eventfd_add = vhost_eventfd_add,
1461         .eventfd_del = vhost_eventfd_del,
1462         .priority = 10
1463     };
1464 
1465     hdev->iommu_listener = (MemoryListener) {
1466         .name = "vhost-iommu",
1467         .region_add = vhost_iommu_region_add,
1468         .region_del = vhost_iommu_region_del,
1469     };
1470 
1471     if (hdev->migration_blocker == NULL) {
1472         if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1473             error_setg(&hdev->migration_blocker,
1474                        "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1475         } else if (vhost_dev_log_is_shared(hdev) && !qemu_memfd_alloc_check()) {
1476             error_setg(&hdev->migration_blocker,
1477                        "Migration disabled: failed to allocate shared memory");
1478         }
1479     }
1480 
1481     if (hdev->migration_blocker != NULL) {
1482         r = migrate_add_blocker(hdev->migration_blocker, errp);
1483         if (r < 0) {
1484             error_free(hdev->migration_blocker);
1485             goto fail_busyloop;
1486         }
1487     }
1488 
1489     hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1490     hdev->n_mem_sections = 0;
1491     hdev->mem_sections = NULL;
1492     hdev->log = NULL;
1493     hdev->log_size = 0;
1494     hdev->log_enabled = false;
1495     hdev->started = false;
1496     memory_listener_register(&hdev->memory_listener, &address_space_memory);
1497     QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1498 
1499     if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
1500         error_setg(errp, "vhost backend memory slots limit is less"
1501                    " than current number of present memory slots");
1502         r = -EINVAL;
1503         goto fail_busyloop;
1504     }
1505 
1506     return 0;
1507 
1508 fail_busyloop:
1509     if (busyloop_timeout) {
1510         while (--i >= 0) {
1511             vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1512         }
1513     }
1514 fail:
1515     hdev->nvqs = n_initialized_vqs;
1516     vhost_dev_cleanup(hdev);
1517     return r;
1518 }
1519 
1520 void vhost_dev_cleanup(struct vhost_dev *hdev)
1521 {
1522     int i;
1523 
1524     trace_vhost_dev_cleanup(hdev);
1525 
1526     for (i = 0; i < hdev->nvqs; ++i) {
1527         vhost_virtqueue_cleanup(hdev->vqs + i);
1528     }
1529     if (hdev->mem) {
1530         /* those are only safe after successful init */
1531         memory_listener_unregister(&hdev->memory_listener);
1532         QLIST_REMOVE(hdev, entry);
1533     }
1534     if (hdev->migration_blocker) {
1535         migrate_del_blocker(hdev->migration_blocker);
1536         error_free(hdev->migration_blocker);
1537     }
1538     g_free(hdev->mem);
1539     g_free(hdev->mem_sections);
1540     if (hdev->vhost_ops) {
1541         hdev->vhost_ops->vhost_backend_cleanup(hdev);
1542     }
1543     assert(!hdev->log);
1544 
1545     memset(hdev, 0, sizeof(struct vhost_dev));
1546 }
1547 
1548 /* Stop processing guest IO notifications in qemu.
1549  * Start processing them in vhost in kernel.
1550  */
1551 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1552 {
1553     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1554     int i, r, e;
1555 
1556     /* We will pass the notifiers to the kernel, make sure that QEMU
1557      * doesn't interfere.
1558      */
1559     r = virtio_device_grab_ioeventfd(vdev);
1560     if (r < 0) {
1561         error_report("binding does not support host notifiers");
1562         goto fail;
1563     }
1564 
1565     for (i = 0; i < hdev->nvqs; ++i) {
1566         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1567                                          true);
1568         if (r < 0) {
1569             error_report("vhost VQ %d notifier binding failed: %d", i, -r);
1570             goto fail_vq;
1571         }
1572     }
1573 
1574     return 0;
1575 fail_vq:
1576     while (--i >= 0) {
1577         e = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1578                                          false);
1579         if (e < 0) {
1580             error_report("vhost VQ %d notifier cleanup error: %d", i, -r);
1581         }
1582         assert (e >= 0);
1583         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1584     }
1585     virtio_device_release_ioeventfd(vdev);
1586 fail:
1587     return r;
1588 }
1589 
1590 /* Stop processing guest IO notifications in vhost.
1591  * Start processing them in qemu.
1592  * This might actually run the qemu handlers right away,
1593  * so virtio in qemu must be completely setup when this is called.
1594  */
1595 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1596 {
1597     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1598     int i, r;
1599 
1600     for (i = 0; i < hdev->nvqs; ++i) {
1601         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1602                                          false);
1603         if (r < 0) {
1604             error_report("vhost VQ %d notifier cleanup failed: %d", i, -r);
1605         }
1606         assert (r >= 0);
1607         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1608     }
1609     virtio_device_release_ioeventfd(vdev);
1610 }
1611 
1612 /* Test and clear event pending status.
1613  * Should be called after unmask to avoid losing events.
1614  */
1615 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1616 {
1617     struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1618     assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1619     return event_notifier_test_and_clear(&vq->masked_notifier);
1620 }
1621 
1622 /* Mask/unmask events from this vq. */
1623 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1624                          bool mask)
1625 {
1626     struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1627     int r, index = n - hdev->vq_index;
1628     struct vhost_vring_file file;
1629 
1630     /* should only be called after backend is connected */
1631     assert(hdev->vhost_ops);
1632 
1633     if (mask) {
1634         assert(vdev->use_guest_notifier_mask);
1635         file.fd = event_notifier_get_wfd(&hdev->vqs[index].masked_notifier);
1636     } else {
1637         file.fd = event_notifier_get_wfd(virtio_queue_get_guest_notifier(vvq));
1638     }
1639 
1640     file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1641     r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1642     if (r < 0) {
1643         VHOST_OPS_DEBUG(r, "vhost_set_vring_call failed");
1644     }
1645 }
1646 
1647 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1648                             uint64_t features)
1649 {
1650     const int *bit = feature_bits;
1651     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1652         uint64_t bit_mask = (1ULL << *bit);
1653         if (!(hdev->features & bit_mask)) {
1654             features &= ~bit_mask;
1655         }
1656         bit++;
1657     }
1658     return features;
1659 }
1660 
1661 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1662                         uint64_t features)
1663 {
1664     const int *bit = feature_bits;
1665     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1666         uint64_t bit_mask = (1ULL << *bit);
1667         if (features & bit_mask) {
1668             hdev->acked_features |= bit_mask;
1669         }
1670         bit++;
1671     }
1672 }
1673 
1674 int vhost_dev_get_config(struct vhost_dev *hdev, uint8_t *config,
1675                          uint32_t config_len, Error **errp)
1676 {
1677     assert(hdev->vhost_ops);
1678 
1679     if (hdev->vhost_ops->vhost_get_config) {
1680         return hdev->vhost_ops->vhost_get_config(hdev, config, config_len,
1681                                                  errp);
1682     }
1683 
1684     error_setg(errp, "vhost_get_config not implemented");
1685     return -ENOSYS;
1686 }
1687 
1688 int vhost_dev_set_config(struct vhost_dev *hdev, const uint8_t *data,
1689                          uint32_t offset, uint32_t size, uint32_t flags)
1690 {
1691     assert(hdev->vhost_ops);
1692 
1693     if (hdev->vhost_ops->vhost_set_config) {
1694         return hdev->vhost_ops->vhost_set_config(hdev, data, offset,
1695                                                  size, flags);
1696     }
1697 
1698     return -ENOSYS;
1699 }
1700 
1701 void vhost_dev_set_config_notifier(struct vhost_dev *hdev,
1702                                    const VhostDevConfigOps *ops)
1703 {
1704     hdev->config_ops = ops;
1705 }
1706 
1707 void vhost_dev_free_inflight(struct vhost_inflight *inflight)
1708 {
1709     if (inflight && inflight->addr) {
1710         qemu_memfd_free(inflight->addr, inflight->size, inflight->fd);
1711         inflight->addr = NULL;
1712         inflight->fd = -1;
1713     }
1714 }
1715 
1716 static int vhost_dev_resize_inflight(struct vhost_inflight *inflight,
1717                                      uint64_t new_size)
1718 {
1719     Error *err = NULL;
1720     int fd = -1;
1721     void *addr = qemu_memfd_alloc("vhost-inflight", new_size,
1722                                   F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
1723                                   &fd, &err);
1724 
1725     if (err) {
1726         error_report_err(err);
1727         return -ENOMEM;
1728     }
1729 
1730     vhost_dev_free_inflight(inflight);
1731     inflight->offset = 0;
1732     inflight->addr = addr;
1733     inflight->fd = fd;
1734     inflight->size = new_size;
1735 
1736     return 0;
1737 }
1738 
1739 void vhost_dev_save_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1740 {
1741     if (inflight->addr) {
1742         qemu_put_be64(f, inflight->size);
1743         qemu_put_be16(f, inflight->queue_size);
1744         qemu_put_buffer(f, inflight->addr, inflight->size);
1745     } else {
1746         qemu_put_be64(f, 0);
1747     }
1748 }
1749 
1750 int vhost_dev_load_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1751 {
1752     uint64_t size;
1753 
1754     size = qemu_get_be64(f);
1755     if (!size) {
1756         return 0;
1757     }
1758 
1759     if (inflight->size != size) {
1760         int ret = vhost_dev_resize_inflight(inflight, size);
1761         if (ret < 0) {
1762             return ret;
1763         }
1764     }
1765     inflight->queue_size = qemu_get_be16(f);
1766 
1767     qemu_get_buffer(f, inflight->addr, size);
1768 
1769     return 0;
1770 }
1771 
1772 int vhost_dev_prepare_inflight(struct vhost_dev *hdev, VirtIODevice *vdev)
1773 {
1774     int r;
1775 
1776     if (hdev->vhost_ops->vhost_get_inflight_fd == NULL ||
1777         hdev->vhost_ops->vhost_set_inflight_fd == NULL) {
1778         return 0;
1779     }
1780 
1781     hdev->vdev = vdev;
1782 
1783     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1784     if (r < 0) {
1785         VHOST_OPS_DEBUG(r, "vhost_dev_prepare_inflight failed");
1786         return r;
1787     }
1788 
1789     return 0;
1790 }
1791 
1792 int vhost_dev_set_inflight(struct vhost_dev *dev,
1793                            struct vhost_inflight *inflight)
1794 {
1795     int r;
1796 
1797     if (dev->vhost_ops->vhost_set_inflight_fd && inflight->addr) {
1798         r = dev->vhost_ops->vhost_set_inflight_fd(dev, inflight);
1799         if (r) {
1800             VHOST_OPS_DEBUG(r, "vhost_set_inflight_fd failed");
1801             return r;
1802         }
1803     }
1804 
1805     return 0;
1806 }
1807 
1808 int vhost_dev_get_inflight(struct vhost_dev *dev, uint16_t queue_size,
1809                            struct vhost_inflight *inflight)
1810 {
1811     int r;
1812 
1813     if (dev->vhost_ops->vhost_get_inflight_fd) {
1814         r = dev->vhost_ops->vhost_get_inflight_fd(dev, queue_size, inflight);
1815         if (r) {
1816             VHOST_OPS_DEBUG(r, "vhost_get_inflight_fd failed");
1817             return r;
1818         }
1819     }
1820 
1821     return 0;
1822 }
1823 
1824 static int vhost_dev_set_vring_enable(struct vhost_dev *hdev, int enable)
1825 {
1826     if (!hdev->vhost_ops->vhost_set_vring_enable) {
1827         return 0;
1828     }
1829 
1830     /*
1831      * For vhost-user devices, if VHOST_USER_F_PROTOCOL_FEATURES has not
1832      * been negotiated, the rings start directly in the enabled state, and
1833      * .vhost_set_vring_enable callback will fail since
1834      * VHOST_USER_SET_VRING_ENABLE is not supported.
1835      */
1836     if (hdev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER &&
1837         !virtio_has_feature(hdev->backend_features,
1838                             VHOST_USER_F_PROTOCOL_FEATURES)) {
1839         return 0;
1840     }
1841 
1842     return hdev->vhost_ops->vhost_set_vring_enable(hdev, enable);
1843 }
1844 
1845 /* Host notifiers must be enabled at this point. */
1846 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
1847 {
1848     int i, r;
1849 
1850     /* should only be called after backend is connected */
1851     assert(hdev->vhost_ops);
1852 
1853     trace_vhost_dev_start(hdev, vdev->name, vrings);
1854 
1855     vdev->vhost_started = true;
1856     hdev->started = true;
1857     hdev->vdev = vdev;
1858 
1859     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1860     if (r < 0) {
1861         goto fail_features;
1862     }
1863 
1864     if (vhost_dev_has_iommu(hdev)) {
1865         memory_listener_register(&hdev->iommu_listener, vdev->dma_as);
1866     }
1867 
1868     r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
1869     if (r < 0) {
1870         VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
1871         goto fail_mem;
1872     }
1873     for (i = 0; i < hdev->nvqs; ++i) {
1874         r = vhost_virtqueue_start(hdev,
1875                                   vdev,
1876                                   hdev->vqs + i,
1877                                   hdev->vq_index + i);
1878         if (r < 0) {
1879             goto fail_vq;
1880         }
1881     }
1882 
1883     if (hdev->log_enabled) {
1884         uint64_t log_base;
1885 
1886         hdev->log_size = vhost_get_log_size(hdev);
1887         hdev->log = vhost_log_get(hdev->log_size,
1888                                   vhost_dev_log_is_shared(hdev));
1889         log_base = (uintptr_t)hdev->log->log;
1890         r = hdev->vhost_ops->vhost_set_log_base(hdev,
1891                                                 hdev->log_size ? log_base : 0,
1892                                                 hdev->log);
1893         if (r < 0) {
1894             VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
1895             goto fail_log;
1896         }
1897     }
1898     if (vrings) {
1899         r = vhost_dev_set_vring_enable(hdev, true);
1900         if (r) {
1901             goto fail_log;
1902         }
1903     }
1904     if (hdev->vhost_ops->vhost_dev_start) {
1905         r = hdev->vhost_ops->vhost_dev_start(hdev, true);
1906         if (r) {
1907             goto fail_start;
1908         }
1909     }
1910     if (vhost_dev_has_iommu(hdev) &&
1911         hdev->vhost_ops->vhost_set_iotlb_callback) {
1912             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, true);
1913 
1914         /* Update used ring information for IOTLB to work correctly,
1915          * vhost-kernel code requires for this.*/
1916         for (i = 0; i < hdev->nvqs; ++i) {
1917             struct vhost_virtqueue *vq = hdev->vqs + i;
1918             vhost_device_iotlb_miss(hdev, vq->used_phys, true);
1919         }
1920     }
1921     return 0;
1922 fail_start:
1923     if (vrings) {
1924         vhost_dev_set_vring_enable(hdev, false);
1925     }
1926 fail_log:
1927     vhost_log_put(hdev, false);
1928 fail_vq:
1929     while (--i >= 0) {
1930         vhost_virtqueue_stop(hdev,
1931                              vdev,
1932                              hdev->vqs + i,
1933                              hdev->vq_index + i);
1934     }
1935 
1936 fail_mem:
1937 fail_features:
1938     vdev->vhost_started = false;
1939     hdev->started = false;
1940     return r;
1941 }
1942 
1943 /* Host notifiers must be enabled at this point. */
1944 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
1945 {
1946     int i;
1947 
1948     /* should only be called after backend is connected */
1949     assert(hdev->vhost_ops);
1950 
1951     trace_vhost_dev_stop(hdev, vdev->name, vrings);
1952 
1953     if (hdev->vhost_ops->vhost_dev_start) {
1954         hdev->vhost_ops->vhost_dev_start(hdev, false);
1955     }
1956     if (vrings) {
1957         vhost_dev_set_vring_enable(hdev, false);
1958     }
1959     for (i = 0; i < hdev->nvqs; ++i) {
1960         vhost_virtqueue_stop(hdev,
1961                              vdev,
1962                              hdev->vqs + i,
1963                              hdev->vq_index + i);
1964     }
1965 
1966     if (vhost_dev_has_iommu(hdev)) {
1967         if (hdev->vhost_ops->vhost_set_iotlb_callback) {
1968             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
1969         }
1970         memory_listener_unregister(&hdev->iommu_listener);
1971     }
1972     vhost_log_put(hdev, true);
1973     hdev->started = false;
1974     vdev->vhost_started = false;
1975     hdev->vdev = NULL;
1976 }
1977 
1978 int vhost_net_set_backend(struct vhost_dev *hdev,
1979                           struct vhost_vring_file *file)
1980 {
1981     if (hdev->vhost_ops->vhost_net_set_backend) {
1982         return hdev->vhost_ops->vhost_net_set_backend(hdev, file);
1983     }
1984 
1985     return -ENOSYS;
1986 }
1987