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