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