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