hw/core: Improve the query-hotpluggable-cpus error message
[qemu/armbru.git] / hw / virtio / vhost.c
blobeb8c4c378c69ad81a68fb514b617c16dbaaab200
1 /*
2 * vhost support
4 * Copyright Red Hat, Inc. 2010
6 * Authors:
7 * Michael S. Tsirkin <mst@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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.
16 #include "qemu/osdep.h"
17 #include "qapi/error.h"
18 #include "hw/virtio/vhost.h"
19 #include "qemu/atomic.h"
20 #include "qemu/range.h"
21 #include "qemu/error-report.h"
22 #include "qemu/memfd.h"
23 #include "qemu/log.h"
24 #include "standard-headers/linux/vhost_types.h"
25 #include "hw/virtio/virtio-bus.h"
26 #include "hw/virtio/virtio-access.h"
27 #include "migration/blocker.h"
28 #include "migration/qemu-file-types.h"
29 #include "sysemu/dma.h"
30 #include "trace.h"
32 /* enabled until disconnected backend stabilizes */
33 #define _VHOST_DEBUG 1
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
46 static struct vhost_log *vhost_log;
47 static struct vhost_log *vhost_log_shm;
49 static unsigned int used_memslots;
50 static QLIST_HEAD(, vhost_dev) vhost_devices =
51 QLIST_HEAD_INITIALIZER(vhost_devices);
53 bool vhost_has_free_slot(void)
55 unsigned int slots_limit = ~0U;
56 struct vhost_dev *hdev;
58 QLIST_FOREACH(hdev, &vhost_devices, entry) {
59 unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
60 slots_limit = MIN(slots_limit, r);
62 return slots_limit > used_memslots;
65 static void vhost_dev_sync_region(struct vhost_dev *dev,
66 MemoryRegionSection *section,
67 uint64_t mfirst, uint64_t mlast,
68 uint64_t rfirst, uint64_t rlast)
70 vhost_log_chunk_t *log = dev->log->log;
72 uint64_t start = MAX(mfirst, rfirst);
73 uint64_t end = MIN(mlast, rlast);
74 vhost_log_chunk_t *from = log + start / VHOST_LOG_CHUNK;
75 vhost_log_chunk_t *to = log + end / VHOST_LOG_CHUNK + 1;
76 uint64_t addr = QEMU_ALIGN_DOWN(start, VHOST_LOG_CHUNK);
78 if (end < start) {
79 return;
81 assert(end / VHOST_LOG_CHUNK < dev->log_size);
82 assert(start / VHOST_LOG_CHUNK < dev->log_size);
84 for (;from < to; ++from) {
85 vhost_log_chunk_t log;
86 /* We first check with non-atomic: much cheaper,
87 * and we expect non-dirty to be the common case. */
88 if (!*from) {
89 addr += VHOST_LOG_CHUNK;
90 continue;
92 /* Data must be read atomically. We don't really need barrier semantics
93 * but it's easier to use atomic_* than roll our own. */
94 log = qatomic_xchg(from, 0);
95 while (log) {
96 int bit = ctzl(log);
97 hwaddr page_addr;
98 hwaddr section_offset;
99 hwaddr mr_offset;
100 page_addr = addr + bit * VHOST_LOG_PAGE;
101 section_offset = page_addr - section->offset_within_address_space;
102 mr_offset = section_offset + section->offset_within_region;
103 memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
104 log &= ~(0x1ull << bit);
106 addr += VHOST_LOG_CHUNK;
110 static bool vhost_dev_has_iommu(struct vhost_dev *dev)
112 VirtIODevice *vdev = dev->vdev;
115 * For vhost, VIRTIO_F_IOMMU_PLATFORM means the backend support
116 * incremental memory mapping API via IOTLB API. For platform that
117 * does not have IOMMU, there's no need to enable this feature
118 * which may cause unnecessary IOTLB miss/update transactions.
120 if (vdev) {
121 return virtio_bus_device_iommu_enabled(vdev) &&
122 virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM);
123 } else {
124 return false;
128 static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
129 MemoryRegionSection *section,
130 hwaddr first,
131 hwaddr last)
133 int i;
134 hwaddr start_addr;
135 hwaddr end_addr;
137 if (!dev->log_enabled || !dev->started) {
138 return 0;
140 start_addr = section->offset_within_address_space;
141 end_addr = range_get_last(start_addr, int128_get64(section->size));
142 start_addr = MAX(first, start_addr);
143 end_addr = MIN(last, end_addr);
145 for (i = 0; i < dev->mem->nregions; ++i) {
146 struct vhost_memory_region *reg = dev->mem->regions + i;
147 vhost_dev_sync_region(dev, section, start_addr, end_addr,
148 reg->guest_phys_addr,
149 range_get_last(reg->guest_phys_addr,
150 reg->memory_size));
152 for (i = 0; i < dev->nvqs; ++i) {
153 struct vhost_virtqueue *vq = dev->vqs + i;
155 if (!vq->used_phys && !vq->used_size) {
156 continue;
159 if (vhost_dev_has_iommu(dev)) {
160 IOMMUTLBEntry iotlb;
161 hwaddr used_phys = vq->used_phys, used_size = vq->used_size;
162 hwaddr phys, s, offset;
164 while (used_size) {
165 rcu_read_lock();
166 iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
167 used_phys,
168 true,
169 MEMTXATTRS_UNSPECIFIED);
170 rcu_read_unlock();
172 if (!iotlb.target_as) {
173 qemu_log_mask(LOG_GUEST_ERROR, "translation "
174 "failure for used_iova %"PRIx64"\n",
175 used_phys);
176 return -EINVAL;
179 offset = used_phys & iotlb.addr_mask;
180 phys = iotlb.translated_addr + offset;
183 * Distance from start of used ring until last byte of
184 * IOMMU page.
186 s = iotlb.addr_mask - offset;
188 * Size of used ring, or of the part of it until end
189 * of IOMMU page. To avoid zero result, do the adding
190 * outside of MIN().
192 s = MIN(s, used_size - 1) + 1;
194 vhost_dev_sync_region(dev, section, start_addr, end_addr, phys,
195 range_get_last(phys, s));
196 used_size -= s;
197 used_phys += s;
199 } else {
200 vhost_dev_sync_region(dev, section, start_addr,
201 end_addr, vq->used_phys,
202 range_get_last(vq->used_phys, vq->used_size));
205 return 0;
208 static void vhost_log_sync(MemoryListener *listener,
209 MemoryRegionSection *section)
211 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
212 memory_listener);
213 vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
216 static void vhost_log_sync_range(struct vhost_dev *dev,
217 hwaddr first, hwaddr last)
219 int i;
220 /* FIXME: this is N^2 in number of sections */
221 for (i = 0; i < dev->n_mem_sections; ++i) {
222 MemoryRegionSection *section = &dev->mem_sections[i];
223 vhost_sync_dirty_bitmap(dev, section, first, last);
227 static uint64_t vhost_get_log_size(struct vhost_dev *dev)
229 uint64_t log_size = 0;
230 int i;
231 for (i = 0; i < dev->mem->nregions; ++i) {
232 struct vhost_memory_region *reg = dev->mem->regions + i;
233 uint64_t last = range_get_last(reg->guest_phys_addr,
234 reg->memory_size);
235 log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
237 return log_size;
240 static int vhost_set_backend_type(struct vhost_dev *dev,
241 VhostBackendType backend_type)
243 int r = 0;
245 switch (backend_type) {
246 #ifdef CONFIG_VHOST_KERNEL
247 case VHOST_BACKEND_TYPE_KERNEL:
248 dev->vhost_ops = &kernel_ops;
249 break;
250 #endif
251 #ifdef CONFIG_VHOST_USER
252 case VHOST_BACKEND_TYPE_USER:
253 dev->vhost_ops = &user_ops;
254 break;
255 #endif
256 #ifdef CONFIG_VHOST_VDPA
257 case VHOST_BACKEND_TYPE_VDPA:
258 dev->vhost_ops = &vdpa_ops;
259 break;
260 #endif
261 default:
262 error_report("Unknown vhost backend type");
263 r = -1;
266 return r;
269 static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
271 Error *err = NULL;
272 struct vhost_log *log;
273 uint64_t logsize = size * sizeof(*(log->log));
274 int fd = -1;
276 log = g_new0(struct vhost_log, 1);
277 if (share) {
278 log->log = qemu_memfd_alloc("vhost-log", logsize,
279 F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
280 &fd, &err);
281 if (err) {
282 error_report_err(err);
283 g_free(log);
284 return NULL;
286 memset(log->log, 0, logsize);
287 } else {
288 log->log = g_malloc0(logsize);
291 log->size = size;
292 log->refcnt = 1;
293 log->fd = fd;
295 return log;
298 static struct vhost_log *vhost_log_get(uint64_t size, bool share)
300 struct vhost_log *log = share ? vhost_log_shm : vhost_log;
302 if (!log || log->size != size) {
303 log = vhost_log_alloc(size, share);
304 if (share) {
305 vhost_log_shm = log;
306 } else {
307 vhost_log = log;
309 } else {
310 ++log->refcnt;
313 return log;
316 static void vhost_log_put(struct vhost_dev *dev, bool sync)
318 struct vhost_log *log = dev->log;
320 if (!log) {
321 return;
324 --log->refcnt;
325 if (log->refcnt == 0) {
326 /* Sync only the range covered by the old log */
327 if (dev->log_size && sync) {
328 vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
331 if (vhost_log == log) {
332 g_free(log->log);
333 vhost_log = NULL;
334 } else if (vhost_log_shm == log) {
335 qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
336 log->fd);
337 vhost_log_shm = NULL;
340 g_free(log);
343 dev->log = NULL;
344 dev->log_size = 0;
347 static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
349 return dev->vhost_ops->vhost_requires_shm_log &&
350 dev->vhost_ops->vhost_requires_shm_log(dev);
353 static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
355 struct vhost_log *log = vhost_log_get(size, vhost_dev_log_is_shared(dev));
356 uint64_t log_base = (uintptr_t)log->log;
357 int r;
359 /* inform backend of log switching, this must be done before
360 releasing the current log, to ensure no logging is lost */
361 r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
362 if (r < 0) {
363 VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
366 vhost_log_put(dev, true);
367 dev->log = log;
368 dev->log_size = size;
371 static void *vhost_memory_map(struct vhost_dev *dev, hwaddr addr,
372 hwaddr *plen, bool is_write)
374 if (!vhost_dev_has_iommu(dev)) {
375 return cpu_physical_memory_map(addr, plen, is_write);
376 } else {
377 return (void *)(uintptr_t)addr;
381 static void vhost_memory_unmap(struct vhost_dev *dev, void *buffer,
382 hwaddr len, int is_write,
383 hwaddr access_len)
385 if (!vhost_dev_has_iommu(dev)) {
386 cpu_physical_memory_unmap(buffer, len, is_write, access_len);
390 static int vhost_verify_ring_part_mapping(void *ring_hva,
391 uint64_t ring_gpa,
392 uint64_t ring_size,
393 void *reg_hva,
394 uint64_t reg_gpa,
395 uint64_t reg_size)
397 uint64_t hva_ring_offset;
398 uint64_t ring_last = range_get_last(ring_gpa, ring_size);
399 uint64_t reg_last = range_get_last(reg_gpa, reg_size);
401 if (ring_last < reg_gpa || ring_gpa > reg_last) {
402 return 0;
404 /* check that whole ring's is mapped */
405 if (ring_last > reg_last) {
406 return -ENOMEM;
408 /* check that ring's MemoryRegion wasn't replaced */
409 hva_ring_offset = ring_gpa - reg_gpa;
410 if (ring_hva != reg_hva + hva_ring_offset) {
411 return -EBUSY;
414 return 0;
417 static int vhost_verify_ring_mappings(struct vhost_dev *dev,
418 void *reg_hva,
419 uint64_t reg_gpa,
420 uint64_t reg_size)
422 int i, j;
423 int r = 0;
424 const char *part_name[] = {
425 "descriptor table",
426 "available ring",
427 "used ring"
430 if (vhost_dev_has_iommu(dev)) {
431 return 0;
434 for (i = 0; i < dev->nvqs; ++i) {
435 struct vhost_virtqueue *vq = dev->vqs + i;
437 if (vq->desc_phys == 0) {
438 continue;
441 j = 0;
442 r = vhost_verify_ring_part_mapping(
443 vq->desc, vq->desc_phys, vq->desc_size,
444 reg_hva, reg_gpa, reg_size);
445 if (r) {
446 break;
449 j++;
450 r = vhost_verify_ring_part_mapping(
451 vq->avail, vq->avail_phys, vq->avail_size,
452 reg_hva, reg_gpa, reg_size);
453 if (r) {
454 break;
457 j++;
458 r = vhost_verify_ring_part_mapping(
459 vq->used, vq->used_phys, vq->used_size,
460 reg_hva, reg_gpa, reg_size);
461 if (r) {
462 break;
466 if (r == -ENOMEM) {
467 error_report("Unable to map %s for ring %d", part_name[j], i);
468 } else if (r == -EBUSY) {
469 error_report("%s relocated for ring %d", part_name[j], i);
471 return r;
475 * vhost_section: identify sections needed for vhost access
477 * We only care about RAM sections here (where virtqueue and guest
478 * internals accessed by virtio might live). If we find one we still
479 * allow the backend to potentially filter it out of our list.
481 static bool vhost_section(struct vhost_dev *dev, MemoryRegionSection *section)
483 MemoryRegion *mr = section->mr;
485 if (memory_region_is_ram(mr) && !memory_region_is_rom(mr)) {
486 uint8_t dirty_mask = memory_region_get_dirty_log_mask(mr);
487 uint8_t handled_dirty;
490 * Kernel based vhost doesn't handle any block which is doing
491 * dirty-tracking other than migration for which it has
492 * specific logging support. However for TCG the kernel never
493 * gets involved anyway so we can also ignore it's
494 * self-modiying code detection flags. However a vhost-user
495 * client could still confuse a TCG guest if it re-writes
496 * executable memory that has already been translated.
498 handled_dirty = (1 << DIRTY_MEMORY_MIGRATION) |
499 (1 << DIRTY_MEMORY_CODE);
501 if (dirty_mask & ~handled_dirty) {
502 trace_vhost_reject_section(mr->name, 1);
503 return false;
506 if (dev->vhost_ops->vhost_backend_mem_section_filter &&
507 !dev->vhost_ops->vhost_backend_mem_section_filter(dev, section)) {
508 trace_vhost_reject_section(mr->name, 2);
509 return false;
512 trace_vhost_section(mr->name);
513 return true;
514 } else {
515 trace_vhost_reject_section(mr->name, 3);
516 return false;
520 static void vhost_begin(MemoryListener *listener)
522 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
523 memory_listener);
524 dev->tmp_sections = NULL;
525 dev->n_tmp_sections = 0;
528 static void vhost_commit(MemoryListener *listener)
530 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
531 memory_listener);
532 MemoryRegionSection *old_sections;
533 int n_old_sections;
534 uint64_t log_size;
535 size_t regions_size;
536 int r;
537 int i;
538 bool changed = false;
540 /* Note we can be called before the device is started, but then
541 * starting the device calls set_mem_table, so we need to have
542 * built the data structures.
544 old_sections = dev->mem_sections;
545 n_old_sections = dev->n_mem_sections;
546 dev->mem_sections = dev->tmp_sections;
547 dev->n_mem_sections = dev->n_tmp_sections;
549 if (dev->n_mem_sections != n_old_sections) {
550 changed = true;
551 } else {
552 /* Same size, lets check the contents */
553 for (int i = 0; i < n_old_sections; i++) {
554 if (!MemoryRegionSection_eq(&old_sections[i],
555 &dev->mem_sections[i])) {
556 changed = true;
557 break;
562 trace_vhost_commit(dev->started, changed);
563 if (!changed) {
564 goto out;
567 /* Rebuild the regions list from the new sections list */
568 regions_size = offsetof(struct vhost_memory, regions) +
569 dev->n_mem_sections * sizeof dev->mem->regions[0];
570 dev->mem = g_realloc(dev->mem, regions_size);
571 dev->mem->nregions = dev->n_mem_sections;
572 used_memslots = dev->mem->nregions;
573 for (i = 0; i < dev->n_mem_sections; i++) {
574 struct vhost_memory_region *cur_vmr = dev->mem->regions + i;
575 struct MemoryRegionSection *mrs = dev->mem_sections + i;
577 cur_vmr->guest_phys_addr = mrs->offset_within_address_space;
578 cur_vmr->memory_size = int128_get64(mrs->size);
579 cur_vmr->userspace_addr =
580 (uintptr_t)memory_region_get_ram_ptr(mrs->mr) +
581 mrs->offset_within_region;
582 cur_vmr->flags_padding = 0;
585 if (!dev->started) {
586 goto out;
589 for (i = 0; i < dev->mem->nregions; i++) {
590 if (vhost_verify_ring_mappings(dev,
591 (void *)(uintptr_t)dev->mem->regions[i].userspace_addr,
592 dev->mem->regions[i].guest_phys_addr,
593 dev->mem->regions[i].memory_size)) {
594 error_report("Verify ring failure on region %d", i);
595 abort();
599 if (!dev->log_enabled) {
600 r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
601 if (r < 0) {
602 VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
604 goto out;
606 log_size = vhost_get_log_size(dev);
607 /* We allocate an extra 4K bytes to log,
608 * to reduce the * number of reallocations. */
609 #define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
610 /* To log more, must increase log size before table update. */
611 if (dev->log_size < log_size) {
612 vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
614 r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
615 if (r < 0) {
616 VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
618 /* To log less, can only decrease log size after table update. */
619 if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
620 vhost_dev_log_resize(dev, log_size);
623 out:
624 /* Deref the old list of sections, this must happen _after_ the
625 * vhost_set_mem_table to ensure the client isn't still using the
626 * section we're about to unref.
628 while (n_old_sections--) {
629 memory_region_unref(old_sections[n_old_sections].mr);
631 g_free(old_sections);
632 return;
635 /* Adds the section data to the tmp_section structure.
636 * It relies on the listener calling us in memory address order
637 * and for each region (via the _add and _nop methods) to
638 * join neighbours.
640 static void vhost_region_add_section(struct vhost_dev *dev,
641 MemoryRegionSection *section)
643 bool need_add = true;
644 uint64_t mrs_size = int128_get64(section->size);
645 uint64_t mrs_gpa = section->offset_within_address_space;
646 uintptr_t mrs_host = (uintptr_t)memory_region_get_ram_ptr(section->mr) +
647 section->offset_within_region;
648 RAMBlock *mrs_rb = section->mr->ram_block;
650 trace_vhost_region_add_section(section->mr->name, mrs_gpa, mrs_size,
651 mrs_host);
653 if (dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER) {
654 /* Round the section to it's page size */
655 /* First align the start down to a page boundary */
656 size_t mrs_page = qemu_ram_pagesize(mrs_rb);
657 uint64_t alignage = mrs_host & (mrs_page - 1);
658 if (alignage) {
659 mrs_host -= alignage;
660 mrs_size += alignage;
661 mrs_gpa -= alignage;
663 /* Now align the size up to a page boundary */
664 alignage = mrs_size & (mrs_page - 1);
665 if (alignage) {
666 mrs_size += mrs_page - alignage;
668 trace_vhost_region_add_section_aligned(section->mr->name, mrs_gpa,
669 mrs_size, mrs_host);
672 if (dev->n_tmp_sections) {
673 /* Since we already have at least one section, lets see if
674 * this extends it; since we're scanning in order, we only
675 * have to look at the last one, and the FlatView that calls
676 * us shouldn't have overlaps.
678 MemoryRegionSection *prev_sec = dev->tmp_sections +
679 (dev->n_tmp_sections - 1);
680 uint64_t prev_gpa_start = prev_sec->offset_within_address_space;
681 uint64_t prev_size = int128_get64(prev_sec->size);
682 uint64_t prev_gpa_end = range_get_last(prev_gpa_start, prev_size);
683 uint64_t prev_host_start =
684 (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr) +
685 prev_sec->offset_within_region;
686 uint64_t prev_host_end = range_get_last(prev_host_start, prev_size);
688 if (mrs_gpa <= (prev_gpa_end + 1)) {
689 /* OK, looks like overlapping/intersecting - it's possible that
690 * the rounding to page sizes has made them overlap, but they should
691 * match up in the same RAMBlock if they do.
693 if (mrs_gpa < prev_gpa_start) {
694 error_report("%s:Section '%s' rounded to %"PRIx64
695 " prior to previous '%s' %"PRIx64,
696 __func__, section->mr->name, mrs_gpa,
697 prev_sec->mr->name, prev_gpa_start);
698 /* A way to cleanly fail here would be better */
699 return;
701 /* Offset from the start of the previous GPA to this GPA */
702 size_t offset = mrs_gpa - prev_gpa_start;
704 if (prev_host_start + offset == mrs_host &&
705 section->mr == prev_sec->mr &&
706 (!dev->vhost_ops->vhost_backend_can_merge ||
707 dev->vhost_ops->vhost_backend_can_merge(dev,
708 mrs_host, mrs_size,
709 prev_host_start, prev_size))) {
710 uint64_t max_end = MAX(prev_host_end, mrs_host + mrs_size);
711 need_add = false;
712 prev_sec->offset_within_address_space =
713 MIN(prev_gpa_start, mrs_gpa);
714 prev_sec->offset_within_region =
715 MIN(prev_host_start, mrs_host) -
716 (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr);
717 prev_sec->size = int128_make64(max_end - MIN(prev_host_start,
718 mrs_host));
719 trace_vhost_region_add_section_merge(section->mr->name,
720 int128_get64(prev_sec->size),
721 prev_sec->offset_within_address_space,
722 prev_sec->offset_within_region);
723 } else {
724 /* adjoining regions are fine, but overlapping ones with
725 * different blocks/offsets shouldn't happen
727 if (mrs_gpa != prev_gpa_end + 1) {
728 error_report("%s: Overlapping but not coherent sections "
729 "at %"PRIx64,
730 __func__, mrs_gpa);
731 return;
737 if (need_add) {
738 ++dev->n_tmp_sections;
739 dev->tmp_sections = g_renew(MemoryRegionSection, dev->tmp_sections,
740 dev->n_tmp_sections);
741 dev->tmp_sections[dev->n_tmp_sections - 1] = *section;
742 /* The flatview isn't stable and we don't use it, making it NULL
743 * means we can memcmp the list.
745 dev->tmp_sections[dev->n_tmp_sections - 1].fv = NULL;
746 memory_region_ref(section->mr);
750 /* Used for both add and nop callbacks */
751 static void vhost_region_addnop(MemoryListener *listener,
752 MemoryRegionSection *section)
754 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
755 memory_listener);
757 if (!vhost_section(dev, section)) {
758 return;
760 vhost_region_add_section(dev, section);
763 static void vhost_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
765 struct vhost_iommu *iommu = container_of(n, struct vhost_iommu, n);
766 struct vhost_dev *hdev = iommu->hdev;
767 hwaddr iova = iotlb->iova + iommu->iommu_offset;
769 if (vhost_backend_invalidate_device_iotlb(hdev, iova,
770 iotlb->addr_mask + 1)) {
771 error_report("Fail to invalidate device iotlb");
775 static void vhost_iommu_region_add(MemoryListener *listener,
776 MemoryRegionSection *section)
778 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
779 iommu_listener);
780 struct vhost_iommu *iommu;
781 Int128 end;
782 int iommu_idx;
783 IOMMUMemoryRegion *iommu_mr;
784 int ret;
786 if (!memory_region_is_iommu(section->mr)) {
787 return;
790 iommu_mr = IOMMU_MEMORY_REGION(section->mr);
792 iommu = g_malloc0(sizeof(*iommu));
793 end = int128_add(int128_make64(section->offset_within_region),
794 section->size);
795 end = int128_sub(end, int128_one());
796 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
797 MEMTXATTRS_UNSPECIFIED);
798 iommu_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
799 IOMMU_NOTIFIER_DEVIOTLB_UNMAP,
800 section->offset_within_region,
801 int128_get64(end),
802 iommu_idx);
803 iommu->mr = section->mr;
804 iommu->iommu_offset = section->offset_within_address_space -
805 section->offset_within_region;
806 iommu->hdev = dev;
807 ret = memory_region_register_iommu_notifier(section->mr, &iommu->n, NULL);
808 if (ret) {
810 * Some vIOMMUs do not support dev-iotlb yet. If so, try to use the
811 * UNMAP legacy message
813 iommu->n.notifier_flags = IOMMU_NOTIFIER_UNMAP;
814 memory_region_register_iommu_notifier(section->mr, &iommu->n,
815 &error_fatal);
817 QLIST_INSERT_HEAD(&dev->iommu_list, iommu, iommu_next);
818 /* TODO: can replay help performance here? */
821 static void vhost_iommu_region_del(MemoryListener *listener,
822 MemoryRegionSection *section)
824 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
825 iommu_listener);
826 struct vhost_iommu *iommu;
828 if (!memory_region_is_iommu(section->mr)) {
829 return;
832 QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
833 if (iommu->mr == section->mr &&
834 iommu->n.start == section->offset_within_region) {
835 memory_region_unregister_iommu_notifier(iommu->mr,
836 &iommu->n);
837 QLIST_REMOVE(iommu, iommu_next);
838 g_free(iommu);
839 break;
844 static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
845 struct vhost_virtqueue *vq,
846 unsigned idx, bool enable_log)
848 struct vhost_vring_addr addr;
849 int r;
850 memset(&addr, 0, sizeof(struct vhost_vring_addr));
852 if (dev->vhost_ops->vhost_vq_get_addr) {
853 r = dev->vhost_ops->vhost_vq_get_addr(dev, &addr, vq);
854 if (r < 0) {
855 VHOST_OPS_DEBUG(r, "vhost_vq_get_addr failed");
856 return r;
858 } else {
859 addr.desc_user_addr = (uint64_t)(unsigned long)vq->desc;
860 addr.avail_user_addr = (uint64_t)(unsigned long)vq->avail;
861 addr.used_user_addr = (uint64_t)(unsigned long)vq->used;
863 addr.index = idx;
864 addr.log_guest_addr = vq->used_phys;
865 addr.flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0;
866 r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
867 if (r < 0) {
868 VHOST_OPS_DEBUG(r, "vhost_set_vring_addr failed");
870 return r;
873 static int vhost_dev_set_features(struct vhost_dev *dev,
874 bool enable_log)
876 uint64_t features = dev->acked_features;
877 int r;
878 if (enable_log) {
879 features |= 0x1ULL << VHOST_F_LOG_ALL;
881 if (!vhost_dev_has_iommu(dev)) {
882 features &= ~(0x1ULL << VIRTIO_F_IOMMU_PLATFORM);
884 if (dev->vhost_ops->vhost_force_iommu) {
885 if (dev->vhost_ops->vhost_force_iommu(dev) == true) {
886 features |= 0x1ULL << VIRTIO_F_IOMMU_PLATFORM;
889 r = dev->vhost_ops->vhost_set_features(dev, features);
890 if (r < 0) {
891 VHOST_OPS_DEBUG(r, "vhost_set_features failed");
892 goto out;
894 if (dev->vhost_ops->vhost_set_backend_cap) {
895 r = dev->vhost_ops->vhost_set_backend_cap(dev);
896 if (r < 0) {
897 VHOST_OPS_DEBUG(r, "vhost_set_backend_cap failed");
898 goto out;
902 out:
903 return r;
906 static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
908 int r, i, idx;
909 hwaddr addr;
911 r = vhost_dev_set_features(dev, enable_log);
912 if (r < 0) {
913 goto err_features;
915 for (i = 0; i < dev->nvqs; ++i) {
916 idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
917 addr = virtio_queue_get_desc_addr(dev->vdev, idx);
918 if (!addr) {
920 * The queue might not be ready for start. If this
921 * is the case there is no reason to continue the process.
922 * The similar logic is used by the vhost_virtqueue_start()
923 * routine.
925 continue;
927 r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
928 enable_log);
929 if (r < 0) {
930 goto err_vq;
933 return 0;
934 err_vq:
935 for (; i >= 0; --i) {
936 idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
937 addr = virtio_queue_get_desc_addr(dev->vdev, idx);
938 if (!addr) {
939 continue;
941 vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
942 dev->log_enabled);
944 vhost_dev_set_features(dev, dev->log_enabled);
945 err_features:
946 return r;
949 static int vhost_migration_log(MemoryListener *listener, bool enable)
951 struct vhost_dev *dev = container_of(listener, struct vhost_dev,
952 memory_listener);
953 int r;
954 if (enable == dev->log_enabled) {
955 return 0;
957 if (!dev->started) {
958 dev->log_enabled = enable;
959 return 0;
962 r = 0;
963 if (!enable) {
964 r = vhost_dev_set_log(dev, false);
965 if (r < 0) {
966 goto check_dev_state;
968 vhost_log_put(dev, false);
969 } else {
970 vhost_dev_log_resize(dev, vhost_get_log_size(dev));
971 r = vhost_dev_set_log(dev, true);
972 if (r < 0) {
973 goto check_dev_state;
977 check_dev_state:
978 dev->log_enabled = enable;
980 * vhost-user-* devices could change their state during log
981 * initialization due to disconnect. So check dev state after
982 * vhost communication.
984 if (!dev->started) {
986 * Since device is in the stopped state, it is okay for
987 * migration. Return success.
989 r = 0;
991 if (r) {
992 /* An error occurred. */
993 dev->log_enabled = false;
996 return r;
999 static void vhost_log_global_start(MemoryListener *listener)
1001 int r;
1003 r = vhost_migration_log(listener, true);
1004 if (r < 0) {
1005 abort();
1009 static void vhost_log_global_stop(MemoryListener *listener)
1011 int r;
1013 r = vhost_migration_log(listener, false);
1014 if (r < 0) {
1015 abort();
1019 static void vhost_log_start(MemoryListener *listener,
1020 MemoryRegionSection *section,
1021 int old, int new)
1023 /* FIXME: implement */
1026 static void vhost_log_stop(MemoryListener *listener,
1027 MemoryRegionSection *section,
1028 int old, int new)
1030 /* FIXME: implement */
1033 /* The vhost driver natively knows how to handle the vrings of non
1034 * cross-endian legacy devices and modern devices. Only legacy devices
1035 * exposed to a bi-endian guest may require the vhost driver to use a
1036 * specific endianness.
1038 static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
1040 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1041 return false;
1043 #if HOST_BIG_ENDIAN
1044 return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
1045 #else
1046 return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
1047 #endif
1050 static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
1051 bool is_big_endian,
1052 int vhost_vq_index)
1054 int r;
1055 struct vhost_vring_state s = {
1056 .index = vhost_vq_index,
1057 .num = is_big_endian
1060 r = dev->vhost_ops->vhost_set_vring_endian(dev, &s);
1061 if (r < 0) {
1062 VHOST_OPS_DEBUG(r, "vhost_set_vring_endian failed");
1064 return r;
1067 static int vhost_memory_region_lookup(struct vhost_dev *hdev,
1068 uint64_t gpa, uint64_t *uaddr,
1069 uint64_t *len)
1071 int i;
1073 for (i = 0; i < hdev->mem->nregions; i++) {
1074 struct vhost_memory_region *reg = hdev->mem->regions + i;
1076 if (gpa >= reg->guest_phys_addr &&
1077 reg->guest_phys_addr + reg->memory_size > gpa) {
1078 *uaddr = reg->userspace_addr + gpa - reg->guest_phys_addr;
1079 *len = reg->guest_phys_addr + reg->memory_size - gpa;
1080 return 0;
1084 return -EFAULT;
1087 int vhost_device_iotlb_miss(struct vhost_dev *dev, uint64_t iova, int write)
1089 IOMMUTLBEntry iotlb;
1090 uint64_t uaddr, len;
1091 int ret = -EFAULT;
1093 RCU_READ_LOCK_GUARD();
1095 trace_vhost_iotlb_miss(dev, 1);
1097 iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
1098 iova, write,
1099 MEMTXATTRS_UNSPECIFIED);
1100 if (iotlb.target_as != NULL) {
1101 ret = vhost_memory_region_lookup(dev, iotlb.translated_addr,
1102 &uaddr, &len);
1103 if (ret) {
1104 trace_vhost_iotlb_miss(dev, 3);
1105 error_report("Fail to lookup the translated address "
1106 "%"PRIx64, iotlb.translated_addr);
1107 goto out;
1110 len = MIN(iotlb.addr_mask + 1, len);
1111 iova = iova & ~iotlb.addr_mask;
1113 ret = vhost_backend_update_device_iotlb(dev, iova, uaddr,
1114 len, iotlb.perm);
1115 if (ret) {
1116 trace_vhost_iotlb_miss(dev, 4);
1117 error_report("Fail to update device iotlb");
1118 goto out;
1122 trace_vhost_iotlb_miss(dev, 2);
1124 out:
1125 return ret;
1128 int vhost_virtqueue_start(struct vhost_dev *dev,
1129 struct VirtIODevice *vdev,
1130 struct vhost_virtqueue *vq,
1131 unsigned idx)
1133 BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1134 VirtioBusState *vbus = VIRTIO_BUS(qbus);
1135 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
1136 hwaddr s, l, a;
1137 int r;
1138 int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1139 struct vhost_vring_file file = {
1140 .index = vhost_vq_index
1142 struct vhost_vring_state state = {
1143 .index = vhost_vq_index
1145 struct VirtQueue *vvq = virtio_get_queue(vdev, idx);
1147 a = virtio_queue_get_desc_addr(vdev, idx);
1148 if (a == 0) {
1149 /* Queue might not be ready for start */
1150 return 0;
1153 vq->num = state.num = virtio_queue_get_num(vdev, idx);
1154 r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
1155 if (r) {
1156 VHOST_OPS_DEBUG(r, "vhost_set_vring_num failed");
1157 return r;
1160 state.num = virtio_queue_get_last_avail_idx(vdev, idx);
1161 r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
1162 if (r) {
1163 VHOST_OPS_DEBUG(r, "vhost_set_vring_base failed");
1164 return r;
1167 if (vhost_needs_vring_endian(vdev)) {
1168 r = vhost_virtqueue_set_vring_endian_legacy(dev,
1169 virtio_is_big_endian(vdev),
1170 vhost_vq_index);
1171 if (r) {
1172 return r;
1176 vq->desc_size = s = l = virtio_queue_get_desc_size(vdev, idx);
1177 vq->desc_phys = a;
1178 vq->desc = vhost_memory_map(dev, a, &l, false);
1179 if (!vq->desc || l != s) {
1180 r = -ENOMEM;
1181 goto fail_alloc_desc;
1183 vq->avail_size = s = l = virtio_queue_get_avail_size(vdev, idx);
1184 vq->avail_phys = a = virtio_queue_get_avail_addr(vdev, idx);
1185 vq->avail = vhost_memory_map(dev, a, &l, false);
1186 if (!vq->avail || l != s) {
1187 r = -ENOMEM;
1188 goto fail_alloc_avail;
1190 vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
1191 vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
1192 vq->used = vhost_memory_map(dev, a, &l, true);
1193 if (!vq->used || l != s) {
1194 r = -ENOMEM;
1195 goto fail_alloc_used;
1198 r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
1199 if (r < 0) {
1200 goto fail_alloc;
1203 file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
1204 r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
1205 if (r) {
1206 VHOST_OPS_DEBUG(r, "vhost_set_vring_kick failed");
1207 goto fail_kick;
1210 /* Clear and discard previous events if any. */
1211 event_notifier_test_and_clear(&vq->masked_notifier);
1213 /* Init vring in unmasked state, unless guest_notifier_mask
1214 * will do it later.
1216 if (!vdev->use_guest_notifier_mask) {
1217 /* TODO: check and handle errors. */
1218 vhost_virtqueue_mask(dev, vdev, idx, false);
1221 if (k->query_guest_notifiers &&
1222 k->query_guest_notifiers(qbus->parent) &&
1223 virtio_queue_vector(vdev, idx) == VIRTIO_NO_VECTOR) {
1224 file.fd = -1;
1225 r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1226 if (r) {
1227 goto fail_vector;
1231 return 0;
1233 fail_vector:
1234 fail_kick:
1235 fail_alloc:
1236 vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1237 0, 0);
1238 fail_alloc_used:
1239 vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1240 0, 0);
1241 fail_alloc_avail:
1242 vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1243 0, 0);
1244 fail_alloc_desc:
1245 return r;
1248 void vhost_virtqueue_stop(struct vhost_dev *dev,
1249 struct VirtIODevice *vdev,
1250 struct vhost_virtqueue *vq,
1251 unsigned idx)
1253 int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1254 struct vhost_vring_state state = {
1255 .index = vhost_vq_index,
1257 int r;
1259 if (virtio_queue_get_desc_addr(vdev, idx) == 0) {
1260 /* Don't stop the virtqueue which might have not been started */
1261 return;
1264 r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
1265 if (r < 0) {
1266 VHOST_OPS_DEBUG(r, "vhost VQ %u ring restore failed: %d", idx, r);
1267 /* Connection to the backend is broken, so let's sync internal
1268 * last avail idx to the device used idx.
1270 virtio_queue_restore_last_avail_idx(vdev, idx);
1271 } else {
1272 virtio_queue_set_last_avail_idx(vdev, idx, state.num);
1274 virtio_queue_invalidate_signalled_used(vdev, idx);
1275 virtio_queue_update_used_idx(vdev, idx);
1277 /* In the cross-endian case, we need to reset the vring endianness to
1278 * native as legacy devices expect so by default.
1280 if (vhost_needs_vring_endian(vdev)) {
1281 vhost_virtqueue_set_vring_endian_legacy(dev,
1282 !virtio_is_big_endian(vdev),
1283 vhost_vq_index);
1286 vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1287 1, virtio_queue_get_used_size(vdev, idx));
1288 vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1289 0, virtio_queue_get_avail_size(vdev, idx));
1290 vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1291 0, virtio_queue_get_desc_size(vdev, idx));
1294 static void vhost_eventfd_add(MemoryListener *listener,
1295 MemoryRegionSection *section,
1296 bool match_data, uint64_t data, EventNotifier *e)
1300 static void vhost_eventfd_del(MemoryListener *listener,
1301 MemoryRegionSection *section,
1302 bool match_data, uint64_t data, EventNotifier *e)
1306 static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
1307 int n, uint32_t timeout)
1309 int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1310 struct vhost_vring_state state = {
1311 .index = vhost_vq_index,
1312 .num = timeout,
1314 int r;
1316 if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
1317 return -EINVAL;
1320 r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
1321 if (r) {
1322 VHOST_OPS_DEBUG(r, "vhost_set_vring_busyloop_timeout failed");
1323 return r;
1326 return 0;
1329 static void vhost_virtqueue_error_notifier(EventNotifier *n)
1331 struct vhost_virtqueue *vq = container_of(n, struct vhost_virtqueue,
1332 error_notifier);
1333 struct vhost_dev *dev = vq->dev;
1334 int index = vq - dev->vqs;
1336 if (event_notifier_test_and_clear(n) && dev->vdev) {
1337 VHOST_OPS_DEBUG(-EINVAL, "vhost vring error in virtqueue %d",
1338 dev->vq_index + index);
1342 static int vhost_virtqueue_init(struct vhost_dev *dev,
1343 struct vhost_virtqueue *vq, int n)
1345 int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1346 struct vhost_vring_file file = {
1347 .index = vhost_vq_index,
1349 int r = event_notifier_init(&vq->masked_notifier, 0);
1350 if (r < 0) {
1351 return r;
1354 file.fd = event_notifier_get_wfd(&vq->masked_notifier);
1355 r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1356 if (r) {
1357 VHOST_OPS_DEBUG(r, "vhost_set_vring_call failed");
1358 goto fail_call;
1361 vq->dev = dev;
1363 if (dev->vhost_ops->vhost_set_vring_err) {
1364 r = event_notifier_init(&vq->error_notifier, 0);
1365 if (r < 0) {
1366 goto fail_call;
1369 file.fd = event_notifier_get_fd(&vq->error_notifier);
1370 r = dev->vhost_ops->vhost_set_vring_err(dev, &file);
1371 if (r) {
1372 VHOST_OPS_DEBUG(r, "vhost_set_vring_err failed");
1373 goto fail_err;
1376 event_notifier_set_handler(&vq->error_notifier,
1377 vhost_virtqueue_error_notifier);
1380 return 0;
1382 fail_err:
1383 event_notifier_cleanup(&vq->error_notifier);
1384 fail_call:
1385 event_notifier_cleanup(&vq->masked_notifier);
1386 return r;
1389 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1391 event_notifier_cleanup(&vq->masked_notifier);
1392 if (vq->dev->vhost_ops->vhost_set_vring_err) {
1393 event_notifier_set_handler(&vq->error_notifier, NULL);
1394 event_notifier_cleanup(&vq->error_notifier);
1398 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1399 VhostBackendType backend_type, uint32_t busyloop_timeout,
1400 Error **errp)
1402 uint64_t features;
1403 int i, r, n_initialized_vqs = 0;
1405 hdev->vdev = NULL;
1406 hdev->migration_blocker = NULL;
1408 r = vhost_set_backend_type(hdev, backend_type);
1409 assert(r >= 0);
1411 r = hdev->vhost_ops->vhost_backend_init(hdev, opaque, errp);
1412 if (r < 0) {
1413 goto fail;
1416 r = hdev->vhost_ops->vhost_set_owner(hdev);
1417 if (r < 0) {
1418 error_setg_errno(errp, -r, "vhost_set_owner failed");
1419 goto fail;
1422 r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1423 if (r < 0) {
1424 error_setg_errno(errp, -r, "vhost_get_features failed");
1425 goto fail;
1428 for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1429 r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1430 if (r < 0) {
1431 error_setg_errno(errp, -r, "Failed to initialize virtqueue %d", i);
1432 goto fail;
1436 if (busyloop_timeout) {
1437 for (i = 0; i < hdev->nvqs; ++i) {
1438 r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1439 busyloop_timeout);
1440 if (r < 0) {
1441 error_setg_errno(errp, -r, "Failed to set busyloop timeout");
1442 goto fail_busyloop;
1447 hdev->features = features;
1449 hdev->memory_listener = (MemoryListener) {
1450 .name = "vhost",
1451 .begin = vhost_begin,
1452 .commit = vhost_commit,
1453 .region_add = vhost_region_addnop,
1454 .region_nop = vhost_region_addnop,
1455 .log_start = vhost_log_start,
1456 .log_stop = vhost_log_stop,
1457 .log_sync = vhost_log_sync,
1458 .log_global_start = vhost_log_global_start,
1459 .log_global_stop = vhost_log_global_stop,
1460 .eventfd_add = vhost_eventfd_add,
1461 .eventfd_del = vhost_eventfd_del,
1462 .priority = 10
1465 hdev->iommu_listener = (MemoryListener) {
1466 .name = "vhost-iommu",
1467 .region_add = vhost_iommu_region_add,
1468 .region_del = vhost_iommu_region_del,
1471 if (hdev->migration_blocker == NULL) {
1472 if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1473 error_setg(&hdev->migration_blocker,
1474 "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1475 } else if (vhost_dev_log_is_shared(hdev) && !qemu_memfd_alloc_check()) {
1476 error_setg(&hdev->migration_blocker,
1477 "Migration disabled: failed to allocate shared memory");
1481 if (hdev->migration_blocker != NULL) {
1482 r = migrate_add_blocker(hdev->migration_blocker, errp);
1483 if (r < 0) {
1484 error_free(hdev->migration_blocker);
1485 goto fail_busyloop;
1489 hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1490 hdev->n_mem_sections = 0;
1491 hdev->mem_sections = NULL;
1492 hdev->log = NULL;
1493 hdev->log_size = 0;
1494 hdev->log_enabled = false;
1495 hdev->started = false;
1496 memory_listener_register(&hdev->memory_listener, &address_space_memory);
1497 QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1499 if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
1500 error_setg(errp, "vhost backend memory slots limit is less"
1501 " than current number of present memory slots");
1502 r = -EINVAL;
1503 goto fail_busyloop;
1506 return 0;
1508 fail_busyloop:
1509 if (busyloop_timeout) {
1510 while (--i >= 0) {
1511 vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1514 fail:
1515 hdev->nvqs = n_initialized_vqs;
1516 vhost_dev_cleanup(hdev);
1517 return r;
1520 void vhost_dev_cleanup(struct vhost_dev *hdev)
1522 int i;
1524 trace_vhost_dev_cleanup(hdev);
1526 for (i = 0; i < hdev->nvqs; ++i) {
1527 vhost_virtqueue_cleanup(hdev->vqs + i);
1529 if (hdev->mem) {
1530 /* those are only safe after successful init */
1531 memory_listener_unregister(&hdev->memory_listener);
1532 QLIST_REMOVE(hdev, entry);
1534 if (hdev->migration_blocker) {
1535 migrate_del_blocker(hdev->migration_blocker);
1536 error_free(hdev->migration_blocker);
1538 g_free(hdev->mem);
1539 g_free(hdev->mem_sections);
1540 if (hdev->vhost_ops) {
1541 hdev->vhost_ops->vhost_backend_cleanup(hdev);
1543 assert(!hdev->log);
1545 memset(hdev, 0, sizeof(struct vhost_dev));
1548 /* Stop processing guest IO notifications in qemu.
1549 * Start processing them in vhost in kernel.
1551 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1553 BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1554 int i, r;
1556 /* We will pass the notifiers to the kernel, make sure that QEMU
1557 * doesn't interfere.
1559 r = virtio_device_grab_ioeventfd(vdev);
1560 if (r < 0) {
1561 error_report("binding does not support host notifiers");
1562 return r;
1566 * Batch all the host notifiers in a single transaction to avoid
1567 * quadratic time complexity in address_space_update_ioeventfds().
1569 memory_region_transaction_begin();
1571 for (i = 0; i < hdev->nvqs; ++i) {
1572 r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1573 true);
1574 if (r < 0) {
1575 error_report("vhost VQ %d notifier binding failed: %d", i, -r);
1576 memory_region_transaction_commit();
1577 vhost_dev_disable_notifiers(hdev, vdev);
1578 return r;
1582 memory_region_transaction_commit();
1584 return 0;
1587 /* Stop processing guest IO notifications in vhost.
1588 * Start processing them in qemu.
1589 * This might actually run the qemu handlers right away,
1590 * so virtio in qemu must be completely setup when this is called.
1592 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1594 BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1595 int i, r;
1598 * Batch all the host notifiers in a single transaction to avoid
1599 * quadratic time complexity in address_space_update_ioeventfds().
1601 memory_region_transaction_begin();
1603 for (i = 0; i < hdev->nvqs; ++i) {
1604 r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1605 false);
1606 if (r < 0) {
1607 error_report("vhost VQ %d notifier cleanup failed: %d", i, -r);
1609 assert (r >= 0);
1613 * The transaction expects the ioeventfds to be open when it
1614 * commits. Do it now, before the cleanup loop.
1616 memory_region_transaction_commit();
1618 for (i = 0; i < hdev->nvqs; ++i) {
1619 virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1621 virtio_device_release_ioeventfd(vdev);
1624 /* Test and clear event pending status.
1625 * Should be called after unmask to avoid losing events.
1627 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1629 struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1630 assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1631 return event_notifier_test_and_clear(&vq->masked_notifier);
1634 /* Mask/unmask events from this vq. */
1635 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1636 bool mask)
1638 struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1639 int r, index = n - hdev->vq_index;
1640 struct vhost_vring_file file;
1642 /* should only be called after backend is connected */
1643 assert(hdev->vhost_ops);
1645 if (mask) {
1646 assert(vdev->use_guest_notifier_mask);
1647 file.fd = event_notifier_get_wfd(&hdev->vqs[index].masked_notifier);
1648 } else {
1649 file.fd = event_notifier_get_wfd(virtio_queue_get_guest_notifier(vvq));
1652 file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1653 r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1654 if (r < 0) {
1655 error_report("vhost_set_vring_call failed %d", -r);
1659 bool vhost_config_pending(struct vhost_dev *hdev)
1661 assert(hdev->vhost_ops);
1662 if ((hdev->started == false) ||
1663 (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1664 return false;
1667 EventNotifier *notifier =
1668 &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1669 return event_notifier_test_and_clear(notifier);
1672 void vhost_config_mask(struct vhost_dev *hdev, VirtIODevice *vdev, bool mask)
1674 int fd;
1675 int r;
1676 EventNotifier *notifier =
1677 &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier;
1678 EventNotifier *config_notifier = &vdev->config_notifier;
1679 assert(hdev->vhost_ops);
1681 if ((hdev->started == false) ||
1682 (hdev->vhost_ops->vhost_set_config_call == NULL)) {
1683 return;
1685 if (mask) {
1686 assert(vdev->use_guest_notifier_mask);
1687 fd = event_notifier_get_fd(notifier);
1688 } else {
1689 fd = event_notifier_get_fd(config_notifier);
1691 r = hdev->vhost_ops->vhost_set_config_call(hdev, fd);
1692 if (r < 0) {
1693 error_report("vhost_set_config_call failed %d", -r);
1697 static void vhost_stop_config_intr(struct vhost_dev *dev)
1699 int fd = -1;
1700 assert(dev->vhost_ops);
1701 if (dev->vhost_ops->vhost_set_config_call) {
1702 dev->vhost_ops->vhost_set_config_call(dev, fd);
1706 static void vhost_start_config_intr(struct vhost_dev *dev)
1708 int r;
1710 assert(dev->vhost_ops);
1711 int fd = event_notifier_get_fd(&dev->vdev->config_notifier);
1712 if (dev->vhost_ops->vhost_set_config_call) {
1713 r = dev->vhost_ops->vhost_set_config_call(dev, fd);
1714 if (!r) {
1715 event_notifier_set(&dev->vdev->config_notifier);
1720 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1721 uint64_t features)
1723 const int *bit = feature_bits;
1724 while (*bit != VHOST_INVALID_FEATURE_BIT) {
1725 uint64_t bit_mask = (1ULL << *bit);
1726 if (!(hdev->features & bit_mask)) {
1727 features &= ~bit_mask;
1729 bit++;
1731 return features;
1734 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1735 uint64_t features)
1737 const int *bit = feature_bits;
1738 while (*bit != VHOST_INVALID_FEATURE_BIT) {
1739 uint64_t bit_mask = (1ULL << *bit);
1740 if (features & bit_mask) {
1741 hdev->acked_features |= bit_mask;
1743 bit++;
1747 int vhost_dev_get_config(struct vhost_dev *hdev, uint8_t *config,
1748 uint32_t config_len, Error **errp)
1750 assert(hdev->vhost_ops);
1752 if (hdev->vhost_ops->vhost_get_config) {
1753 return hdev->vhost_ops->vhost_get_config(hdev, config, config_len,
1754 errp);
1757 error_setg(errp, "vhost_get_config not implemented");
1758 return -ENOSYS;
1761 int vhost_dev_set_config(struct vhost_dev *hdev, const uint8_t *data,
1762 uint32_t offset, uint32_t size, uint32_t flags)
1764 assert(hdev->vhost_ops);
1766 if (hdev->vhost_ops->vhost_set_config) {
1767 return hdev->vhost_ops->vhost_set_config(hdev, data, offset,
1768 size, flags);
1771 return -ENOSYS;
1774 void vhost_dev_set_config_notifier(struct vhost_dev *hdev,
1775 const VhostDevConfigOps *ops)
1777 hdev->config_ops = ops;
1780 void vhost_dev_free_inflight(struct vhost_inflight *inflight)
1782 if (inflight && inflight->addr) {
1783 qemu_memfd_free(inflight->addr, inflight->size, inflight->fd);
1784 inflight->addr = NULL;
1785 inflight->fd = -1;
1789 static int vhost_dev_resize_inflight(struct vhost_inflight *inflight,
1790 uint64_t new_size)
1792 Error *err = NULL;
1793 int fd = -1;
1794 void *addr = qemu_memfd_alloc("vhost-inflight", new_size,
1795 F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
1796 &fd, &err);
1798 if (err) {
1799 error_report_err(err);
1800 return -ENOMEM;
1803 vhost_dev_free_inflight(inflight);
1804 inflight->offset = 0;
1805 inflight->addr = addr;
1806 inflight->fd = fd;
1807 inflight->size = new_size;
1809 return 0;
1812 void vhost_dev_save_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1814 if (inflight->addr) {
1815 qemu_put_be64(f, inflight->size);
1816 qemu_put_be16(f, inflight->queue_size);
1817 qemu_put_buffer(f, inflight->addr, inflight->size);
1818 } else {
1819 qemu_put_be64(f, 0);
1823 int vhost_dev_load_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1825 uint64_t size;
1827 size = qemu_get_be64(f);
1828 if (!size) {
1829 return 0;
1832 if (inflight->size != size) {
1833 int ret = vhost_dev_resize_inflight(inflight, size);
1834 if (ret < 0) {
1835 return ret;
1838 inflight->queue_size = qemu_get_be16(f);
1840 qemu_get_buffer(f, inflight->addr, size);
1842 return 0;
1845 int vhost_dev_prepare_inflight(struct vhost_dev *hdev, VirtIODevice *vdev)
1847 int r;
1849 if (hdev->vhost_ops->vhost_get_inflight_fd == NULL ||
1850 hdev->vhost_ops->vhost_set_inflight_fd == NULL) {
1851 return 0;
1854 hdev->vdev = vdev;
1856 r = vhost_dev_set_features(hdev, hdev->log_enabled);
1857 if (r < 0) {
1858 VHOST_OPS_DEBUG(r, "vhost_dev_prepare_inflight failed");
1859 return r;
1862 return 0;
1865 int vhost_dev_set_inflight(struct vhost_dev *dev,
1866 struct vhost_inflight *inflight)
1868 int r;
1870 if (dev->vhost_ops->vhost_set_inflight_fd && inflight->addr) {
1871 r = dev->vhost_ops->vhost_set_inflight_fd(dev, inflight);
1872 if (r) {
1873 VHOST_OPS_DEBUG(r, "vhost_set_inflight_fd failed");
1874 return r;
1878 return 0;
1881 int vhost_dev_get_inflight(struct vhost_dev *dev, uint16_t queue_size,
1882 struct vhost_inflight *inflight)
1884 int r;
1886 if (dev->vhost_ops->vhost_get_inflight_fd) {
1887 r = dev->vhost_ops->vhost_get_inflight_fd(dev, queue_size, inflight);
1888 if (r) {
1889 VHOST_OPS_DEBUG(r, "vhost_get_inflight_fd failed");
1890 return r;
1894 return 0;
1897 static int vhost_dev_set_vring_enable(struct vhost_dev *hdev, int enable)
1899 if (!hdev->vhost_ops->vhost_set_vring_enable) {
1900 return 0;
1904 * For vhost-user devices, if VHOST_USER_F_PROTOCOL_FEATURES has not
1905 * been negotiated, the rings start directly in the enabled state, and
1906 * .vhost_set_vring_enable callback will fail since
1907 * VHOST_USER_SET_VRING_ENABLE is not supported.
1909 if (hdev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER &&
1910 !virtio_has_feature(hdev->backend_features,
1911 VHOST_USER_F_PROTOCOL_FEATURES)) {
1912 return 0;
1915 return hdev->vhost_ops->vhost_set_vring_enable(hdev, enable);
1918 /* Host notifiers must be enabled at this point. */
1919 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
1921 int i, r;
1923 /* should only be called after backend is connected */
1924 assert(hdev->vhost_ops);
1926 trace_vhost_dev_start(hdev, vdev->name, vrings);
1928 vdev->vhost_started = true;
1929 hdev->started = true;
1930 hdev->vdev = vdev;
1932 r = vhost_dev_set_features(hdev, hdev->log_enabled);
1933 if (r < 0) {
1934 goto fail_features;
1937 if (vhost_dev_has_iommu(hdev)) {
1938 memory_listener_register(&hdev->iommu_listener, vdev->dma_as);
1941 r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
1942 if (r < 0) {
1943 VHOST_OPS_DEBUG(r, "vhost_set_mem_table failed");
1944 goto fail_mem;
1946 for (i = 0; i < hdev->nvqs; ++i) {
1947 r = vhost_virtqueue_start(hdev,
1948 vdev,
1949 hdev->vqs + i,
1950 hdev->vq_index + i);
1951 if (r < 0) {
1952 goto fail_vq;
1956 r = event_notifier_init(
1957 &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier, 0);
1958 if (r < 0) {
1959 return r;
1961 event_notifier_test_and_clear(
1962 &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
1963 if (!vdev->use_guest_notifier_mask) {
1964 vhost_config_mask(hdev, vdev, true);
1966 if (hdev->log_enabled) {
1967 uint64_t log_base;
1969 hdev->log_size = vhost_get_log_size(hdev);
1970 hdev->log = vhost_log_get(hdev->log_size,
1971 vhost_dev_log_is_shared(hdev));
1972 log_base = (uintptr_t)hdev->log->log;
1973 r = hdev->vhost_ops->vhost_set_log_base(hdev,
1974 hdev->log_size ? log_base : 0,
1975 hdev->log);
1976 if (r < 0) {
1977 VHOST_OPS_DEBUG(r, "vhost_set_log_base failed");
1978 goto fail_log;
1981 if (vrings) {
1982 r = vhost_dev_set_vring_enable(hdev, true);
1983 if (r) {
1984 goto fail_log;
1987 if (hdev->vhost_ops->vhost_dev_start) {
1988 r = hdev->vhost_ops->vhost_dev_start(hdev, true);
1989 if (r) {
1990 goto fail_start;
1993 if (vhost_dev_has_iommu(hdev) &&
1994 hdev->vhost_ops->vhost_set_iotlb_callback) {
1995 hdev->vhost_ops->vhost_set_iotlb_callback(hdev, true);
1997 /* Update used ring information for IOTLB to work correctly,
1998 * vhost-kernel code requires for this.*/
1999 for (i = 0; i < hdev->nvqs; ++i) {
2000 struct vhost_virtqueue *vq = hdev->vqs + i;
2001 vhost_device_iotlb_miss(hdev, vq->used_phys, true);
2004 vhost_start_config_intr(hdev);
2005 return 0;
2006 fail_start:
2007 if (vrings) {
2008 vhost_dev_set_vring_enable(hdev, false);
2010 fail_log:
2011 vhost_log_put(hdev, false);
2012 fail_vq:
2013 while (--i >= 0) {
2014 vhost_virtqueue_stop(hdev,
2015 vdev,
2016 hdev->vqs + i,
2017 hdev->vq_index + i);
2020 fail_mem:
2021 fail_features:
2022 vdev->vhost_started = false;
2023 hdev->started = false;
2024 return r;
2027 /* Host notifiers must be enabled at this point. */
2028 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev, bool vrings)
2030 int i;
2032 /* should only be called after backend is connected */
2033 assert(hdev->vhost_ops);
2034 event_notifier_test_and_clear(
2035 &hdev->vqs[VHOST_QUEUE_NUM_CONFIG_INR].masked_config_notifier);
2036 event_notifier_test_and_clear(&vdev->config_notifier);
2038 trace_vhost_dev_stop(hdev, vdev->name, vrings);
2040 if (hdev->vhost_ops->vhost_dev_start) {
2041 hdev->vhost_ops->vhost_dev_start(hdev, false);
2043 if (vrings) {
2044 vhost_dev_set_vring_enable(hdev, false);
2046 for (i = 0; i < hdev->nvqs; ++i) {
2047 vhost_virtqueue_stop(hdev,
2048 vdev,
2049 hdev->vqs + i,
2050 hdev->vq_index + i);
2053 if (vhost_dev_has_iommu(hdev)) {
2054 if (hdev->vhost_ops->vhost_set_iotlb_callback) {
2055 hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
2057 memory_listener_unregister(&hdev->iommu_listener);
2059 vhost_stop_config_intr(hdev);
2060 vhost_log_put(hdev, true);
2061 hdev->started = false;
2062 vdev->vhost_started = false;
2063 hdev->vdev = NULL;
2066 int vhost_net_set_backend(struct vhost_dev *hdev,
2067 struct vhost_vring_file *file)
2069 if (hdev->vhost_ops->vhost_net_set_backend) {
2070 return hdev->vhost_ops->vhost_net_set_backend(hdev, file);
2073 return -ENOSYS;