xref: /openbmc/qemu/hw/virtio/vhost.c (revision 8e6c718a)
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 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 int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
1295                                                 int n, uint32_t timeout)
1296 {
1297     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1298     struct vhost_vring_state state = {
1299         .index = vhost_vq_index,
1300         .num = timeout,
1301     };
1302     int r;
1303 
1304     if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
1305         return -EINVAL;
1306     }
1307 
1308     r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
1309     if (r) {
1310         VHOST_OPS_DEBUG(r, "vhost_set_vring_busyloop_timeout failed");
1311         return r;
1312     }
1313 
1314     return 0;
1315 }
1316 
1317 static void vhost_virtqueue_error_notifier(EventNotifier *n)
1318 {
1319     struct vhost_virtqueue *vq = container_of(n, struct vhost_virtqueue,
1320                                               error_notifier);
1321     struct vhost_dev *dev = vq->dev;
1322     int index = vq - dev->vqs;
1323 
1324     if (event_notifier_test_and_clear(n) && dev->vdev) {
1325         VHOST_OPS_DEBUG(-EINVAL,  "vhost vring error in virtqueue %d",
1326                         dev->vq_index + index);
1327     }
1328 }
1329 
1330 static int vhost_virtqueue_init(struct vhost_dev *dev,
1331                                 struct vhost_virtqueue *vq, int n)
1332 {
1333     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1334     struct vhost_vring_file file = {
1335         .index = vhost_vq_index,
1336     };
1337     int r = event_notifier_init(&vq->masked_notifier, 0);
1338     if (r < 0) {
1339         return r;
1340     }
1341 
1342     file.fd = event_notifier_get_wfd(&vq->masked_notifier);
1343     r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1344     if (r) {
1345         VHOST_OPS_DEBUG(r, "vhost_set_vring_call failed");
1346         goto fail_call;
1347     }
1348 
1349     vq->dev = dev;
1350 
1351     if (dev->vhost_ops->vhost_set_vring_err) {
1352         r = event_notifier_init(&vq->error_notifier, 0);
1353         if (r < 0) {
1354             goto fail_call;
1355         }
1356 
1357         file.fd = event_notifier_get_fd(&vq->error_notifier);
1358         r = dev->vhost_ops->vhost_set_vring_err(dev, &file);
1359         if (r) {
1360             VHOST_OPS_DEBUG(r, "vhost_set_vring_err failed");
1361             goto fail_err;
1362         }
1363 
1364         event_notifier_set_handler(&vq->error_notifier,
1365                                    vhost_virtqueue_error_notifier);
1366     }
1367 
1368     return 0;
1369 
1370 fail_err:
1371     event_notifier_cleanup(&vq->error_notifier);
1372 fail_call:
1373     event_notifier_cleanup(&vq->masked_notifier);
1374     return r;
1375 }
1376 
1377 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1378 {
1379     event_notifier_cleanup(&vq->masked_notifier);
1380     if (vq->dev->vhost_ops->vhost_set_vring_err) {
1381         event_notifier_set_handler(&vq->error_notifier, NULL);
1382         event_notifier_cleanup(&vq->error_notifier);
1383     }
1384 }
1385 
1386 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1387                    VhostBackendType backend_type, uint32_t busyloop_timeout,
1388                    Error **errp)
1389 {
1390     uint64_t features;
1391     int i, r, n_initialized_vqs = 0;
1392 
1393     hdev->vdev = NULL;
1394     hdev->migration_blocker = NULL;
1395 
1396     r = vhost_set_backend_type(hdev, backend_type);
1397     assert(r >= 0);
1398 
1399     r = hdev->vhost_ops->vhost_backend_init(hdev, opaque, errp);
1400     if (r < 0) {
1401         goto fail;
1402     }
1403 
1404     r = hdev->vhost_ops->vhost_set_owner(hdev);
1405     if (r < 0) {
1406         error_setg_errno(errp, -r, "vhost_set_owner failed");
1407         goto fail;
1408     }
1409 
1410     r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1411     if (r < 0) {
1412         error_setg_errno(errp, -r, "vhost_get_features failed");
1413         goto fail;
1414     }
1415 
1416     for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1417         r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1418         if (r < 0) {
1419             error_setg_errno(errp, -r, "Failed to initialize virtqueue %d", i);
1420             goto fail;
1421         }
1422     }
1423 
1424     if (busyloop_timeout) {
1425         for (i = 0; i < hdev->nvqs; ++i) {
1426             r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1427                                                      busyloop_timeout);
1428             if (r < 0) {
1429                 error_setg_errno(errp, -r, "Failed to set busyloop timeout");
1430                 goto fail_busyloop;
1431             }
1432         }
1433     }
1434 
1435     hdev->features = features;
1436 
1437     hdev->memory_listener = (MemoryListener) {
1438         .name = "vhost",
1439         .begin = vhost_begin,
1440         .commit = vhost_commit,
1441         .region_add = vhost_region_addnop,
1442         .region_nop = vhost_region_addnop,
1443         .log_start = vhost_log_start,
1444         .log_stop = vhost_log_stop,
1445         .log_sync = vhost_log_sync,
1446         .log_global_start = vhost_log_global_start,
1447         .log_global_stop = vhost_log_global_stop,
1448         .priority = 10
1449     };
1450 
1451     hdev->iommu_listener = (MemoryListener) {
1452         .name = "vhost-iommu",
1453         .region_add = vhost_iommu_region_add,
1454         .region_del = vhost_iommu_region_del,
1455     };
1456 
1457     if (hdev->migration_blocker == NULL) {
1458         if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1459             error_setg(&hdev->migration_blocker,
1460                        "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1461         } else if (vhost_dev_log_is_shared(hdev) && !qemu_memfd_alloc_check()) {
1462             error_setg(&hdev->migration_blocker,
1463                        "Migration disabled: failed to allocate shared memory");
1464         }
1465     }
1466 
1467     if (hdev->migration_blocker != NULL) {
1468         r = migrate_add_blocker(hdev->migration_blocker, errp);
1469         if (r < 0) {
1470             error_free(hdev->migration_blocker);
1471             goto fail_busyloop;
1472         }
1473     }
1474 
1475     hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1476     hdev->n_mem_sections = 0;
1477     hdev->mem_sections = NULL;
1478     hdev->log = NULL;
1479     hdev->log_size = 0;
1480     hdev->log_enabled = false;
1481     hdev->started = false;
1482     memory_listener_register(&hdev->memory_listener, &address_space_memory);
1483     QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1484 
1485     if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
1486         error_setg(errp, "vhost backend memory slots limit is less"
1487                    " than current number of present memory slots");
1488         r = -EINVAL;
1489         goto fail_busyloop;
1490     }
1491 
1492     return 0;
1493 
1494 fail_busyloop:
1495     if (busyloop_timeout) {
1496         while (--i >= 0) {
1497             vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1498         }
1499     }
1500 fail:
1501     hdev->nvqs = n_initialized_vqs;
1502     vhost_dev_cleanup(hdev);
1503     return r;
1504 }
1505 
1506 void vhost_dev_cleanup(struct vhost_dev *hdev)
1507 {
1508     int i;
1509 
1510     trace_vhost_dev_cleanup(hdev);
1511 
1512     for (i = 0; i < hdev->nvqs; ++i) {
1513         vhost_virtqueue_cleanup(hdev->vqs + i);
1514     }
1515     if (hdev->mem) {
1516         /* those are only safe after successful init */
1517         memory_listener_unregister(&hdev->memory_listener);
1518         QLIST_REMOVE(hdev, entry);
1519     }
1520     if (hdev->migration_blocker) {
1521         migrate_del_blocker(hdev->migration_blocker);
1522         error_free(hdev->migration_blocker);
1523     }
1524     g_free(hdev->mem);
1525     g_free(hdev->mem_sections);
1526     if (hdev->vhost_ops) {
1527         hdev->vhost_ops->vhost_backend_cleanup(hdev);
1528     }
1529     assert(!hdev->log);
1530 
1531     memset(hdev, 0, sizeof(struct vhost_dev));
1532 }
1533 
1534 /* Stop processing guest IO notifications in qemu.
1535  * Start processing them in vhost in kernel.
1536  */
1537 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1538 {
1539     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1540     int i, r;
1541 
1542     /* We will pass the notifiers to the kernel, make sure that QEMU
1543      * doesn't interfere.
1544      */
1545     r = virtio_device_grab_ioeventfd(vdev);
1546     if (r < 0) {
1547         error_report("binding does not support host notifiers");
1548         return r;
1549     }
1550 
1551     /*
1552      * Batch all the host notifiers in a single transaction to avoid
1553      * quadratic time complexity in address_space_update_ioeventfds().
1554      */
1555     memory_region_transaction_begin();
1556 
1557     for (i = 0; i < hdev->nvqs; ++i) {
1558         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1559                                          true);
1560         if (r < 0) {
1561             error_report("vhost VQ %d notifier binding failed: %d", i, -r);
1562             memory_region_transaction_commit();
1563             vhost_dev_disable_notifiers(hdev, vdev);
1564             return r;
1565         }
1566     }
1567 
1568     memory_region_transaction_commit();
1569 
1570     return 0;
1571 }
1572 
1573 /* Stop processing guest IO notifications in vhost.
1574  * Start processing them in qemu.
1575  * This might actually run the qemu handlers right away,
1576  * so virtio in qemu must be completely setup when this is called.
1577  */
1578 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1579 {
1580     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1581     int i, r;
1582 
1583     /*
1584      * Batch all the host notifiers in a single transaction to avoid
1585      * quadratic time complexity in address_space_update_ioeventfds().
1586      */
1587     memory_region_transaction_begin();
1588 
1589     for (i = 0; i < hdev->nvqs; ++i) {
1590         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1591                                          false);
1592         if (r < 0) {
1593             error_report("vhost VQ %d notifier cleanup failed: %d", i, -r);
1594         }
1595         assert (r >= 0);
1596     }
1597 
1598     /*
1599      * The transaction expects the ioeventfds to be open when it
1600      * commits. Do it now, before the cleanup loop.
1601      */
1602     memory_region_transaction_commit();
1603 
1604     for (i = 0; i < hdev->nvqs; ++i) {
1605         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1606     }
1607     virtio_device_release_ioeventfd(vdev);
1608 }
1609 
1610 /* Test and clear event pending status.
1611  * Should be called after unmask to avoid losing events.
1612  */
1613 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1614 {
1615     struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1616     assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1617     return event_notifier_test_and_clear(&vq->masked_notifier);
1618 }
1619 
1620 /* Mask/unmask events from this vq. */
1621 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1622                          bool mask)
1623 {
1624     struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1625     int r, index = n - hdev->vq_index;
1626     struct vhost_vring_file file;
1627 
1628     /* should only be called after backend is connected */
1629     assert(hdev->vhost_ops);
1630 
1631     if (mask) {
1632         assert(vdev->use_guest_notifier_mask);
1633         file.fd = event_notifier_get_wfd(&hdev->vqs[index].masked_notifier);
1634     } else {
1635         file.fd = event_notifier_get_wfd(virtio_queue_get_guest_notifier(vvq));
1636     }
1637 
1638     file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1639     r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1640     if (r < 0) {
1641         error_report("vhost_set_vring_call failed %d", -r);
1642     }
1643 }
1644 
1645 bool vhost_config_pending(struct vhost_dev *hdev)
1646 {
1647     assert(hdev->vhost_ops);
1648     if ((hdev->started == false) ||
1649         (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1650         return false;
1651     }
1652 
1653     EventNotifier *notifier =
1654         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1655     return event_notifier_test_and_clear(notifier);
1656 }
1657 
1658 void vhost_config_mask(struct vhost_dev *hdev, VirtIODevice *vdev, bool mask)
1659 {
1660     int fd;
1661     int r;
1662     EventNotifier *notifier =
1663         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1664     EventNotifier *config_notifier = &vdev->config_notifier;
1665     assert(hdev->vhost_ops);
1666 
1667     if ((hdev->started == false) ||
1668         (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1669         return;
1670     }
1671     if (mask) {
1672         assert(vdev->use_guest_notifier_mask);
1673         fd = event_notifier_get_fd(notifier);
1674     } else {
1675         fd = event_notifier_get_fd(config_notifier);
1676     }
1677     r = hdev->vhost_ops->vhost_set_config_call(hdev, fd);
1678     if (r < 0) {
1679         error_report("vhost_set_config_call failed %d", -r);
1680     }
1681 }
1682 
1683 static void vhost_stop_config_intr(struct vhost_dev *dev)
1684 {
1685     int fd = -1;
1686     assert(dev->vhost_ops);
1687     if (dev->vhost_ops->vhost_set_config_call) {
1688         dev->vhost_ops->vhost_set_config_call(dev, fd);
1689     }
1690 }
1691 
1692 static void vhost_start_config_intr(struct vhost_dev *dev)
1693 {
1694     int r;
1695 
1696     assert(dev->vhost_ops);
1697     int fd = event_notifier_get_fd(&dev->vdev->config_notifier);
1698     if (dev->vhost_ops->vhost_set_config_call) {
1699         r = dev->vhost_ops->vhost_set_config_call(dev, fd);
1700         if (!r) {
1701             event_notifier_set(&dev->vdev->config_notifier);
1702         }
1703     }
1704 }
1705 
1706 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1707                             uint64_t features)
1708 {
1709     const int *bit = feature_bits;
1710     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1711         uint64_t bit_mask = (1ULL << *bit);
1712         if (!(hdev->features & bit_mask)) {
1713             features &= ~bit_mask;
1714         }
1715         bit++;
1716     }
1717     return features;
1718 }
1719 
1720 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1721                         uint64_t features)
1722 {
1723     const int *bit = feature_bits;
1724     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1725         uint64_t bit_mask = (1ULL << *bit);
1726         if (features & bit_mask) {
1727             hdev->acked_features |= bit_mask;
1728         }
1729         bit++;
1730     }
1731 }
1732 
1733 int vhost_dev_get_config(struct vhost_dev *hdev, uint8_t *config,
1734                          uint32_t config_len, Error **errp)
1735 {
1736     assert(hdev->vhost_ops);
1737 
1738     if (hdev->vhost_ops->vhost_get_config) {
1739         return hdev->vhost_ops->vhost_get_config(hdev, config, config_len,
1740                                                  errp);
1741     }
1742 
1743     error_setg(errp, "vhost_get_config not implemented");
1744     return -ENOSYS;
1745 }
1746 
1747 int vhost_dev_set_config(struct vhost_dev *hdev, const uint8_t *data,
1748                          uint32_t offset, uint32_t size, uint32_t flags)
1749 {
1750     assert(hdev->vhost_ops);
1751 
1752     if (hdev->vhost_ops->vhost_set_config) {
1753         return hdev->vhost_ops->vhost_set_config(hdev, data, offset,
1754                                                  size, flags);
1755     }
1756 
1757     return -ENOSYS;
1758 }
1759 
1760 void vhost_dev_set_config_notifier(struct vhost_dev *hdev,
1761                                    const VhostDevConfigOps *ops)
1762 {
1763     hdev->config_ops = ops;
1764 }
1765 
1766 void vhost_dev_free_inflight(struct vhost_inflight *inflight)
1767 {
1768     if (inflight && inflight->addr) {
1769         qemu_memfd_free(inflight->addr, inflight->size, inflight->fd);
1770         inflight->addr = NULL;
1771         inflight->fd = -1;
1772     }
1773 }
1774 
1775 static int vhost_dev_resize_inflight(struct vhost_inflight *inflight,
1776                                      uint64_t new_size)
1777 {
1778     Error *err = NULL;
1779     int fd = -1;
1780     void *addr = qemu_memfd_alloc("vhost-inflight", new_size,
1781                                   F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
1782                                   &fd, &err);
1783 
1784     if (err) {
1785         error_report_err(err);
1786         return -ENOMEM;
1787     }
1788 
1789     vhost_dev_free_inflight(inflight);
1790     inflight->offset = 0;
1791     inflight->addr = addr;
1792     inflight->fd = fd;
1793     inflight->size = new_size;
1794 
1795     return 0;
1796 }
1797 
1798 void vhost_dev_save_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1799 {
1800     if (inflight->addr) {
1801         qemu_put_be64(f, inflight->size);
1802         qemu_put_be16(f, inflight->queue_size);
1803         qemu_put_buffer(f, inflight->addr, inflight->size);
1804     } else {
1805         qemu_put_be64(f, 0);
1806     }
1807 }
1808 
1809 int vhost_dev_load_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1810 {
1811     uint64_t size;
1812 
1813     size = qemu_get_be64(f);
1814     if (!size) {
1815         return 0;
1816     }
1817 
1818     if (inflight->size != size) {
1819         int ret = vhost_dev_resize_inflight(inflight, size);
1820         if (ret < 0) {
1821             return ret;
1822         }
1823     }
1824     inflight->queue_size = qemu_get_be16(f);
1825 
1826     qemu_get_buffer(f, inflight->addr, size);
1827 
1828     return 0;
1829 }
1830 
1831 int vhost_dev_prepare_inflight(struct vhost_dev *hdev, VirtIODevice *vdev)
1832 {
1833     int r;
1834 
1835     if (hdev->vhost_ops->vhost_get_inflight_fd == NULL ||
1836         hdev->vhost_ops->vhost_set_inflight_fd == NULL) {
1837         return 0;
1838     }
1839 
1840     hdev->vdev = vdev;
1841 
1842     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1843     if (r < 0) {
1844         VHOST_OPS_DEBUG(r, "vhost_dev_prepare_inflight failed");
1845         return r;
1846     }
1847 
1848     return 0;
1849 }
1850 
1851 int vhost_dev_set_inflight(struct vhost_dev *dev,
1852                            struct vhost_inflight *inflight)
1853 {
1854     int r;
1855 
1856     if (dev->vhost_ops->vhost_set_inflight_fd && inflight->addr) {
1857         r = dev->vhost_ops->vhost_set_inflight_fd(dev, inflight);
1858         if (r) {
1859             VHOST_OPS_DEBUG(r, "vhost_set_inflight_fd failed");
1860             return r;
1861         }
1862     }
1863 
1864     return 0;
1865 }
1866 
1867 int vhost_dev_get_inflight(struct vhost_dev *dev, uint16_t queue_size,
1868                            struct vhost_inflight *inflight)
1869 {
1870     int r;
1871 
1872     if (dev->vhost_ops->vhost_get_inflight_fd) {
1873         r = dev->vhost_ops->vhost_get_inflight_fd(dev, queue_size, inflight);
1874         if (r) {
1875             VHOST_OPS_DEBUG(r, "vhost_get_inflight_fd failed");
1876             return r;
1877         }
1878     }
1879 
1880     return 0;
1881 }
1882 
1883 static int vhost_dev_set_vring_enable(struct vhost_dev *hdev, int enable)
1884 {
1885     if (!hdev->vhost_ops->vhost_set_vring_enable) {
1886         return 0;
1887     }
1888 
1889     /*
1890      * For vhost-user devices, if VHOST_USER_F_PROTOCOL_FEATURES has not
1891      * been negotiated, the rings start directly in the enabled state, and
1892      * .vhost_set_vring_enable callback will fail since
1893      * VHOST_USER_SET_VRING_ENABLE is not supported.
1894      */
1895     if (hdev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER &&
1896         !virtio_has_feature(hdev->backend_features,
1897                             VHOST_USER_F_PROTOCOL_FEATURES)) {
1898         return 0;
1899     }
1900 
1901     return hdev->vhost_ops->vhost_set_vring_enable(hdev, enable);
1902 }
1903 
1904 /* Host notifiers must be enabled at this point. */
1905 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
1906 {
1907     int i, r;
1908 
1909     /* should only be called after backend is connected */
1910     assert(hdev->vhost_ops);
1911 
1912     trace_vhost_dev_start(hdev, vdev->name, vrings);
1913 
1914     vdev->vhost_started = true;
1915     hdev->started = true;
1916     hdev->vdev = vdev;
1917 
1918     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1919     if (r < 0) {
1920         goto fail_features;
1921     }
1922 
1923     if (vhost_dev_has_iommu(hdev)) {
1924         memory_listener_register(&hdev->iommu_listener, vdev->dma_as);
1925     }
1926 
1927     r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
1928     if (r < 0) {
1929         VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
1930         goto fail_mem;
1931     }
1932     for (i = 0; i < hdev->nvqs; ++i) {
1933         r = vhost_virtqueue_start(hdev,
1934                                   vdev,
1935                                   hdev->vqs + i,
1936                                   hdev->vq_index + i);
1937         if (r < 0) {
1938             goto fail_vq;
1939         }
1940     }
1941 
1942     r = event_notifier_init(
1943         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier, 0);
1944     if (r < 0) {
1945         return r;
1946     }
1947     event_notifier_test_and_clear(
1948         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
1949     if (!vdev->use_guest_notifier_mask) {
1950         vhost_config_mask(hdev, vdev, true);
1951     }
1952     if (hdev->log_enabled) {
1953         uint64_t log_base;
1954 
1955         hdev->log_size = vhost_get_log_size(hdev);
1956         hdev->log = vhost_log_get(hdev->log_size,
1957                                   vhost_dev_log_is_shared(hdev));
1958         log_base = (uintptr_t)hdev->log->log;
1959         r = hdev->vhost_ops->vhost_set_log_base(hdev,
1960                                                 hdev->log_size ? log_base : 0,
1961                                                 hdev->log);
1962         if (r < 0) {
1963             VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
1964             goto fail_log;
1965         }
1966     }
1967     if (vrings) {
1968         r = vhost_dev_set_vring_enable(hdev, true);
1969         if (r) {
1970             goto fail_log;
1971         }
1972     }
1973     if (hdev->vhost_ops->vhost_dev_start) {
1974         r = hdev->vhost_ops->vhost_dev_start(hdev, true);
1975         if (r) {
1976             goto fail_start;
1977         }
1978     }
1979     if (vhost_dev_has_iommu(hdev) &&
1980         hdev->vhost_ops->vhost_set_iotlb_callback) {
1981             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, true);
1982 
1983         /* Update used ring information for IOTLB to work correctly,
1984          * vhost-kernel code requires for this.*/
1985         for (i = 0; i < hdev->nvqs; ++i) {
1986             struct vhost_virtqueue *vq = hdev->vqs + i;
1987             vhost_device_iotlb_miss(hdev, vq->used_phys, true);
1988         }
1989     }
1990     vhost_start_config_intr(hdev);
1991     return 0;
1992 fail_start:
1993     if (vrings) {
1994         vhost_dev_set_vring_enable(hdev, false);
1995     }
1996 fail_log:
1997     vhost_log_put(hdev, false);
1998 fail_vq:
1999     while (--i >= 0) {
2000         vhost_virtqueue_stop(hdev,
2001                              vdev,
2002                              hdev->vqs + i,
2003                              hdev->vq_index + i);
2004     }
2005 
2006 fail_mem:
2007 fail_features:
2008     vdev->vhost_started = false;
2009     hdev->started = false;
2010     return r;
2011 }
2012 
2013 /* Host notifiers must be enabled at this point. */
2014 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
2015 {
2016     int i;
2017 
2018     /* should only be called after backend is connected */
2019     assert(hdev->vhost_ops);
2020     event_notifier_test_and_clear(
2021         &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
2022     event_notifier_test_and_clear(&vdev->config_notifier);
2023 
2024     trace_vhost_dev_stop(hdev, vdev->name, vrings);
2025 
2026     if (hdev->vhost_ops->vhost_dev_start) {
2027         hdev->vhost_ops->vhost_dev_start(hdev, false);
2028     }
2029     if (vrings) {
2030         vhost_dev_set_vring_enable(hdev, false);
2031     }
2032     for (i = 0; i < hdev->nvqs; ++i) {
2033         vhost_virtqueue_stop(hdev,
2034                              vdev,
2035                              hdev->vqs + i,
2036                              hdev->vq_index + i);
2037     }
2038     if (hdev->vhost_ops->vhost_reset_status) {
2039         hdev->vhost_ops->vhost_reset_status(hdev);
2040     }
2041 
2042     if (vhost_dev_has_iommu(hdev)) {
2043         if (hdev->vhost_ops->vhost_set_iotlb_callback) {
2044             hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
2045         }
2046         memory_listener_unregister(&hdev->iommu_listener);
2047     }
2048     vhost_stop_config_intr(hdev);
2049     vhost_log_put(hdev, true);
2050     hdev->started = false;
2051     vdev->vhost_started = false;
2052     hdev->vdev = NULL;
2053 }
2054 
2055 int vhost_net_set_backend(struct vhost_dev *hdev,
2056                           struct vhost_vring_file *file)
2057 {
2058     if (hdev->vhost_ops->vhost_net_set_backend) {
2059         return hdev->vhost_ops->vhost_net_set_backend(hdev, file);
2060     }
2061 
2062     return -ENOSYS;
2063 }
2064