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