Merge remote-tracking branch 'qemu/master'
[qemu/ar7.git] / hw / virtio / virtio.c
blobac9b99b9284f7a08c368c29f1df38db71927b438
1 /*
2 * Virtio Support
4 * Copyright IBM, Corp. 2007
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.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.
14 #include "qemu/osdep.h"
15 #include "qapi/error.h"
16 #include "qemu-common.h"
17 #include "cpu.h"
18 #include "trace.h"
19 #include "exec/address-spaces.h"
20 #include "qemu/error-report.h"
21 #include "hw/virtio/virtio.h"
22 #include "qemu/atomic.h"
23 #include "hw/virtio/virtio-bus.h"
24 #include "migration/migration.h"
25 #include "hw/virtio/virtio-access.h"
26 #include "sysemu/dma.h"
29 * The alignment to use between consumer and producer parts of vring.
30 * x86 pagesize again. This is the default, used by transports like PCI
31 * which don't provide a means for the guest to tell the host the alignment.
33 #define VIRTIO_PCI_VRING_ALIGN 4096
35 typedef struct VRingDesc
37 uint64_t addr;
38 uint32_t len;
39 uint16_t flags;
40 uint16_t next;
41 } VRingDesc;
43 typedef struct VRingAvail
45 uint16_t flags;
46 uint16_t idx;
47 uint16_t ring[0];
48 } VRingAvail;
50 typedef struct VRingUsedElem
52 uint32_t id;
53 uint32_t len;
54 } VRingUsedElem;
56 typedef struct VRingUsed
58 uint16_t flags;
59 uint16_t idx;
60 VRingUsedElem ring[0];
61 } VRingUsed;
63 typedef struct VRing
65 unsigned int num;
66 unsigned int num_default;
67 unsigned int align;
68 hwaddr desc;
69 hwaddr avail;
70 hwaddr used;
71 } VRing;
73 struct VirtQueue
75 VRing vring;
77 /* Next head to pop */
78 uint16_t last_avail_idx;
80 /* Last avail_idx read from VQ. */
81 uint16_t shadow_avail_idx;
83 uint16_t used_idx;
85 /* Last used index value we have signalled on */
86 uint16_t signalled_used;
88 /* Last used index value we have signalled on */
89 bool signalled_used_valid;
91 /* Notification enabled? */
92 bool notification;
94 uint16_t queue_index;
96 unsigned int inuse;
98 uint16_t vector;
99 VirtIOHandleOutput handle_output;
100 VirtIOHandleOutput handle_aio_output;
101 VirtIODevice *vdev;
102 EventNotifier guest_notifier;
103 EventNotifier host_notifier;
104 QLIST_ENTRY(VirtQueue) node;
107 /* virt queue functions */
108 void virtio_queue_update_rings(VirtIODevice *vdev, int n)
110 VRing *vring = &vdev->vq[n].vring;
112 if (!vring->desc) {
113 /* not yet setup -> nothing to do */
114 return;
116 vring->avail = vring->desc + vring->num * sizeof(VRingDesc);
117 vring->used = vring_align(vring->avail +
118 offsetof(VRingAvail, ring[vring->num]),
119 vring->align);
122 static void vring_desc_read(VirtIODevice *vdev, VRingDesc *desc,
123 hwaddr desc_pa, int i)
125 address_space_read(vdev->dma_as, desc_pa + i * sizeof(VRingDesc),
126 MEMTXATTRS_UNSPECIFIED, (void *)desc, sizeof(VRingDesc));
127 virtio_tswap64s(vdev, &desc->addr);
128 virtio_tswap32s(vdev, &desc->len);
129 virtio_tswap16s(vdev, &desc->flags);
130 virtio_tswap16s(vdev, &desc->next);
133 static inline uint16_t vring_avail_flags(VirtQueue *vq)
135 hwaddr pa;
136 pa = vq->vring.avail + offsetof(VRingAvail, flags);
137 return virtio_lduw_phys(vq->vdev, pa);
140 static inline uint16_t vring_avail_idx(VirtQueue *vq)
142 hwaddr pa;
143 pa = vq->vring.avail + offsetof(VRingAvail, idx);
144 vq->shadow_avail_idx = virtio_lduw_phys(vq->vdev, pa);
145 return vq->shadow_avail_idx;
148 static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
150 hwaddr pa;
151 pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
152 return virtio_lduw_phys(vq->vdev, pa);
155 static inline uint16_t vring_get_used_event(VirtQueue *vq)
157 return vring_avail_ring(vq, vq->vring.num);
160 static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,
161 int i)
163 hwaddr pa;
164 virtio_tswap32s(vq->vdev, &uelem->id);
165 virtio_tswap32s(vq->vdev, &uelem->len);
166 pa = vq->vring.used + offsetof(VRingUsed, ring[i]);
167 address_space_write(vq->vdev->dma_as, pa, MEMTXATTRS_UNSPECIFIED,
168 (void *)uelem, sizeof(VRingUsedElem));
171 static uint16_t vring_used_idx(VirtQueue *vq)
173 hwaddr pa;
174 pa = vq->vring.used + offsetof(VRingUsed, idx);
175 return virtio_lduw_phys(vq->vdev, pa);
178 static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
180 hwaddr pa;
181 pa = vq->vring.used + offsetof(VRingUsed, idx);
182 virtio_stw_phys(vq->vdev, pa, val);
183 vq->used_idx = val;
186 static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
188 VirtIODevice *vdev = vq->vdev;
189 hwaddr pa;
190 pa = vq->vring.used + offsetof(VRingUsed, flags);
191 virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) | mask);
194 static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
196 VirtIODevice *vdev = vq->vdev;
197 hwaddr pa;
198 pa = vq->vring.used + offsetof(VRingUsed, flags);
199 virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) & ~mask);
202 static inline void vring_set_avail_event(VirtQueue *vq, uint16_t val)
204 hwaddr pa;
205 if (!vq->notification) {
206 return;
208 pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
209 virtio_stw_phys(vq->vdev, pa, val);
212 void virtio_queue_set_notification(VirtQueue *vq, int enable)
214 vq->notification = enable;
215 if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
216 vring_set_avail_event(vq, vring_avail_idx(vq));
217 } else if (enable) {
218 vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
219 } else {
220 vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
222 if (enable) {
223 /* Expose avail event/used flags before caller checks the avail idx. */
224 smp_mb();
228 int virtio_queue_ready(VirtQueue *vq)
230 return vq->vring.avail != 0;
233 /* Fetch avail_idx from VQ memory only when we really need to know if
234 * guest has added some buffers. */
235 int virtio_queue_empty(VirtQueue *vq)
237 if (vq->shadow_avail_idx != vq->last_avail_idx) {
238 return 0;
241 return vring_avail_idx(vq) == vq->last_avail_idx;
244 static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,
245 unsigned int len)
247 AddressSpace *dma_as = vq->vdev->dma_as;
248 unsigned int offset;
249 int i;
251 offset = 0;
252 for (i = 0; i < elem->in_num; i++) {
253 size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
255 dma_memory_unmap(dma_as, elem->in_sg[i].iov_base,
256 elem->in_sg[i].iov_len,
257 DMA_DIRECTION_FROM_DEVICE, size);
259 offset += size;
262 for (i = 0; i < elem->out_num; i++)
263 dma_memory_unmap(dma_as, elem->out_sg[i].iov_base,
264 elem->out_sg[i].iov_len,
265 DMA_DIRECTION_TO_DEVICE,
266 elem->out_sg[i].iov_len);
269 /* virtqueue_detach_element:
270 * @vq: The #VirtQueue
271 * @elem: The #VirtQueueElement
272 * @len: number of bytes written
274 * Detach the element from the virtqueue. This function is suitable for device
275 * reset or other situations where a #VirtQueueElement is simply freed and will
276 * not be pushed or discarded.
278 void virtqueue_detach_element(VirtQueue *vq, const VirtQueueElement *elem,
279 unsigned int len)
281 vq->inuse--;
282 virtqueue_unmap_sg(vq, elem, len);
285 /* virtqueue_unpop:
286 * @vq: The #VirtQueue
287 * @elem: The #VirtQueueElement
288 * @len: number of bytes written
290 * Pretend the most recent element wasn't popped from the virtqueue. The next
291 * call to virtqueue_pop() will refetch the element.
293 void virtqueue_unpop(VirtQueue *vq, const VirtQueueElement *elem,
294 unsigned int len)
296 vq->last_avail_idx--;
297 virtqueue_detach_element(vq, elem, len);
300 /* virtqueue_rewind:
301 * @vq: The #VirtQueue
302 * @num: Number of elements to push back
304 * Pretend that elements weren't popped from the virtqueue. The next
305 * virtqueue_pop() will refetch the oldest element.
307 * Use virtqueue_unpop() instead if you have a VirtQueueElement.
309 * Returns: true on success, false if @num is greater than the number of in use
310 * elements.
312 bool virtqueue_rewind(VirtQueue *vq, unsigned int num)
314 if (num > vq->inuse) {
315 return false;
317 vq->last_avail_idx -= num;
318 vq->inuse -= num;
319 return true;
322 void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
323 unsigned int len, unsigned int idx)
325 VRingUsedElem uelem;
327 trace_virtqueue_fill(vq, elem, len, idx);
329 virtqueue_unmap_sg(vq, elem, len);
331 if (unlikely(vq->vdev->broken)) {
332 return;
335 idx = (idx + vq->used_idx) % vq->vring.num;
337 uelem.id = elem->index;
338 uelem.len = len;
339 vring_used_write(vq, &uelem, idx);
342 void virtqueue_flush(VirtQueue *vq, unsigned int count)
344 uint16_t old, new;
346 if (unlikely(vq->vdev->broken)) {
347 vq->inuse -= count;
348 return;
351 /* Make sure buffer is written before we update index. */
352 smp_wmb();
353 trace_virtqueue_flush(vq, count);
354 old = vq->used_idx;
355 new = old + count;
356 vring_used_idx_set(vq, new);
357 vq->inuse -= count;
358 if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
359 vq->signalled_used_valid = false;
362 void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
363 unsigned int len)
365 virtqueue_fill(vq, elem, len, 0);
366 virtqueue_flush(vq, 1);
369 static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
371 uint16_t num_heads = vring_avail_idx(vq) - idx;
373 /* Check it isn't doing very strange things with descriptor numbers. */
374 if (num_heads > vq->vring.num) {
375 virtio_error(vq->vdev, "Guest moved used index from %u to %u",
376 idx, vq->shadow_avail_idx);
377 return -EINVAL;
379 /* On success, callers read a descriptor at vq->last_avail_idx.
380 * Make sure descriptor read does not bypass avail index read. */
381 if (num_heads) {
382 smp_rmb();
385 return num_heads;
388 static bool virtqueue_get_head(VirtQueue *vq, unsigned int idx,
389 unsigned int *head)
391 /* Grab the next descriptor number they're advertising, and increment
392 * the index we've seen. */
393 *head = vring_avail_ring(vq, idx % vq->vring.num);
395 /* If their number is silly, that's a fatal mistake. */
396 if (*head >= vq->vring.num) {
397 virtio_error(vq->vdev, "Guest says index %u is available", *head);
398 return false;
401 return true;
404 enum {
405 VIRTQUEUE_READ_DESC_ERROR = -1,
406 VIRTQUEUE_READ_DESC_DONE = 0, /* end of chain */
407 VIRTQUEUE_READ_DESC_MORE = 1, /* more buffers in chain */
410 static int virtqueue_read_next_desc(VirtIODevice *vdev, VRingDesc *desc,
411 hwaddr desc_pa, unsigned int max,
412 unsigned int *next)
414 /* If this descriptor says it doesn't chain, we're done. */
415 if (!(desc->flags & VRING_DESC_F_NEXT)) {
416 return VIRTQUEUE_READ_DESC_DONE;
419 /* Check they're not leading us off end of descriptors. */
420 *next = desc->next;
421 /* Make sure compiler knows to grab that: we don't want it changing! */
422 smp_wmb();
424 if (*next >= max) {
425 virtio_error(vdev, "Desc next is %u", *next);
426 return VIRTQUEUE_READ_DESC_ERROR;
429 vring_desc_read(vdev, desc, desc_pa, *next);
430 return VIRTQUEUE_READ_DESC_MORE;
433 void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
434 unsigned int *out_bytes,
435 unsigned max_in_bytes, unsigned max_out_bytes)
437 unsigned int idx;
438 unsigned int total_bufs, in_total, out_total;
439 int rc;
441 idx = vq->last_avail_idx;
443 total_bufs = in_total = out_total = 0;
444 while ((rc = virtqueue_num_heads(vq, idx)) > 0) {
445 VirtIODevice *vdev = vq->vdev;
446 unsigned int max, num_bufs, indirect = 0;
447 VRingDesc desc;
448 hwaddr desc_pa;
449 unsigned int i;
451 max = vq->vring.num;
452 num_bufs = total_bufs;
454 if (!virtqueue_get_head(vq, idx++, &i)) {
455 goto err;
458 desc_pa = vq->vring.desc;
459 vring_desc_read(vdev, &desc, desc_pa, i);
461 if (desc.flags & VRING_DESC_F_INDIRECT) {
462 if (desc.len % sizeof(VRingDesc)) {
463 virtio_error(vdev, "Invalid size for indirect buffer table");
464 goto err;
467 /* If we've got too many, that implies a descriptor loop. */
468 if (num_bufs >= max) {
469 virtio_error(vdev, "Looped descriptor");
470 goto err;
473 /* loop over the indirect descriptor table */
474 indirect = 1;
475 max = desc.len / sizeof(VRingDesc);
476 desc_pa = desc.addr;
477 num_bufs = i = 0;
478 vring_desc_read(vdev, &desc, desc_pa, i);
481 do {
482 /* If we've got too many, that implies a descriptor loop. */
483 if (++num_bufs > max) {
484 virtio_error(vdev, "Looped descriptor");
485 goto err;
488 if (desc.flags & VRING_DESC_F_WRITE) {
489 in_total += desc.len;
490 } else {
491 out_total += desc.len;
493 if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
494 goto done;
497 rc = virtqueue_read_next_desc(vdev, &desc, desc_pa, max, &i);
498 } while (rc == VIRTQUEUE_READ_DESC_MORE);
500 if (rc == VIRTQUEUE_READ_DESC_ERROR) {
501 goto err;
504 if (!indirect)
505 total_bufs = num_bufs;
506 else
507 total_bufs++;
510 if (rc < 0) {
511 goto err;
514 done:
515 if (in_bytes) {
516 *in_bytes = in_total;
518 if (out_bytes) {
519 *out_bytes = out_total;
521 return;
523 err:
524 in_total = out_total = 0;
525 goto done;
528 int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
529 unsigned int out_bytes)
531 unsigned int in_total, out_total;
533 virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
534 return in_bytes <= in_total && out_bytes <= out_total;
537 static bool virtqueue_map_desc(VirtIODevice *vdev, unsigned int *p_num_sg,
538 hwaddr *addr, struct iovec *iov,
539 unsigned int max_num_sg, bool is_write,
540 hwaddr pa, size_t sz)
542 bool ok = false;
543 unsigned num_sg = *p_num_sg;
544 assert(num_sg <= max_num_sg);
546 if (!sz) {
547 virtio_error(vdev, "virtio: zero sized buffers are not allowed");
548 goto out;
551 while (sz) {
552 hwaddr len = sz;
554 if (num_sg == max_num_sg) {
555 virtio_error(vdev, "virtio: too many write descriptors in "
556 "indirect table");
557 goto out;
560 iov[num_sg].iov_base = dma_memory_map(vdev->dma_as, pa, &len,
561 is_write ?
562 DMA_DIRECTION_FROM_DEVICE :
563 DMA_DIRECTION_TO_DEVICE);
564 if (!iov[num_sg].iov_base) {
565 virtio_error(vdev, "virtio: bogus descriptor or out of resources");
566 goto out;
569 iov[num_sg].iov_len = len;
570 addr[num_sg] = pa;
572 sz -= len;
573 pa += len;
574 num_sg++;
576 ok = true;
578 out:
579 *p_num_sg = num_sg;
580 return ok;
583 /* Only used by error code paths before we have a VirtQueueElement (therefore
584 * virtqueue_unmap_sg() can't be used). Assumes buffers weren't written to
585 * yet.
587 static void virtqueue_undo_map_desc(unsigned int out_num, unsigned int in_num,
588 struct iovec *iov)
590 unsigned int i;
592 for (i = 0; i < out_num + in_num; i++) {
593 int is_write = i >= out_num;
595 cpu_physical_memory_unmap(iov->iov_base, iov->iov_len, is_write, 0);
596 iov++;
600 static void virtqueue_map_iovec(VirtIODevice *vdev, struct iovec *sg,
601 hwaddr *addr, unsigned int *num_sg,
602 int is_write)
604 unsigned int i;
605 hwaddr len;
607 for (i = 0; i < *num_sg; i++) {
608 len = sg[i].iov_len;
609 sg[i].iov_base = dma_memory_map(vdev->dma_as,
610 addr[i], &len, is_write ?
611 DMA_DIRECTION_FROM_DEVICE :
612 DMA_DIRECTION_TO_DEVICE);
613 if (!sg[i].iov_base) {
614 error_report("virtio: error trying to map MMIO memory");
615 exit(1);
617 if (len != sg[i].iov_len) {
618 error_report("virtio: unexpected memory split");
619 exit(1);
624 void virtqueue_map(VirtIODevice *vdev, VirtQueueElement *elem)
626 virtqueue_map_iovec(vdev, elem->in_sg, elem->in_addr, &elem->in_num, 1);
627 virtqueue_map_iovec(vdev, elem->out_sg, elem->out_addr, &elem->out_num, 0);
630 static void *virtqueue_alloc_element(size_t sz, unsigned out_num, unsigned in_num)
632 VirtQueueElement *elem;
633 size_t in_addr_ofs = QEMU_ALIGN_UP(sz, __alignof__(elem->in_addr[0]));
634 size_t out_addr_ofs = in_addr_ofs + in_num * sizeof(elem->in_addr[0]);
635 size_t out_addr_end = out_addr_ofs + out_num * sizeof(elem->out_addr[0]);
636 size_t in_sg_ofs = QEMU_ALIGN_UP(out_addr_end, __alignof__(elem->in_sg[0]));
637 size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]);
638 size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]);
640 assert(sz >= sizeof(VirtQueueElement));
641 elem = g_malloc(out_sg_end);
642 elem->out_num = out_num;
643 elem->in_num = in_num;
644 elem->in_addr = (void *)elem + in_addr_ofs;
645 elem->out_addr = (void *)elem + out_addr_ofs;
646 elem->in_sg = (void *)elem + in_sg_ofs;
647 elem->out_sg = (void *)elem + out_sg_ofs;
648 return elem;
651 void *virtqueue_pop(VirtQueue *vq, size_t sz)
653 unsigned int i, head, max;
654 hwaddr desc_pa = vq->vring.desc;
655 VirtIODevice *vdev = vq->vdev;
656 VirtQueueElement *elem;
657 unsigned out_num, in_num;
658 hwaddr addr[VIRTQUEUE_MAX_SIZE];
659 struct iovec iov[VIRTQUEUE_MAX_SIZE];
660 VRingDesc desc;
661 int rc;
663 if (unlikely(vdev->broken)) {
664 return NULL;
666 if (virtio_queue_empty(vq)) {
667 return NULL;
669 /* Needed after virtio_queue_empty(), see comment in
670 * virtqueue_num_heads(). */
671 smp_rmb();
673 /* When we start there are none of either input nor output. */
674 out_num = in_num = 0;
676 max = vq->vring.num;
678 if (vq->inuse >= vq->vring.num) {
679 virtio_error(vdev, "Virtqueue size exceeded");
680 return NULL;
683 if (!virtqueue_get_head(vq, vq->last_avail_idx++, &head)) {
684 return NULL;
687 if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
688 vring_set_avail_event(vq, vq->last_avail_idx);
691 i = head;
692 vring_desc_read(vdev, &desc, desc_pa, i);
693 if (desc.flags & VRING_DESC_F_INDIRECT) {
694 if (desc.len % sizeof(VRingDesc)) {
695 virtio_error(vdev, "Invalid size for indirect buffer table");
696 return NULL;
699 /* loop over the indirect descriptor table */
700 max = desc.len / sizeof(VRingDesc);
701 desc_pa = desc.addr;
702 i = 0;
703 vring_desc_read(vdev, &desc, desc_pa, i);
706 /* Collect all the descriptors */
707 do {
708 bool map_ok;
710 if (desc.flags & VRING_DESC_F_WRITE) {
711 map_ok = virtqueue_map_desc(vdev, &in_num, addr + out_num,
712 iov + out_num,
713 VIRTQUEUE_MAX_SIZE - out_num, true,
714 desc.addr, desc.len);
715 } else {
716 if (in_num) {
717 virtio_error(vdev, "Incorrect order for descriptors");
718 goto err_undo_map;
720 map_ok = virtqueue_map_desc(vdev, &out_num, addr, iov,
721 VIRTQUEUE_MAX_SIZE, false,
722 desc.addr, desc.len);
724 if (!map_ok) {
725 goto err_undo_map;
728 /* If we've got too many, that implies a descriptor loop. */
729 if ((in_num + out_num) > max) {
730 virtio_error(vdev, "Looped descriptor");
731 goto err_undo_map;
734 rc = virtqueue_read_next_desc(vdev, &desc, desc_pa, max, &i);
735 } while (rc == VIRTQUEUE_READ_DESC_MORE);
737 if (rc == VIRTQUEUE_READ_DESC_ERROR) {
738 goto err_undo_map;
741 /* Now copy what we have collected and mapped */
742 elem = virtqueue_alloc_element(sz, out_num, in_num);
743 elem->index = head;
744 for (i = 0; i < out_num; i++) {
745 elem->out_addr[i] = addr[i];
746 elem->out_sg[i] = iov[i];
748 for (i = 0; i < in_num; i++) {
749 elem->in_addr[i] = addr[out_num + i];
750 elem->in_sg[i] = iov[out_num + i];
753 vq->inuse++;
755 trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
756 return elem;
758 err_undo_map:
759 virtqueue_undo_map_desc(out_num, in_num, iov);
760 return NULL;
763 /* virtqueue_drop_all:
764 * @vq: The #VirtQueue
765 * Drops all queued buffers and indicates them to the guest
766 * as if they are done. Useful when buffers can not be
767 * processed but must be returned to the guest.
769 unsigned int virtqueue_drop_all(VirtQueue *vq)
771 unsigned int dropped = 0;
772 VirtQueueElement elem = {};
773 VirtIODevice *vdev = vq->vdev;
774 bool fEventIdx = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
776 if (unlikely(vdev->broken)) {
777 return 0;
780 while (!virtio_queue_empty(vq) && vq->inuse < vq->vring.num) {
781 /* works similar to virtqueue_pop but does not map buffers
782 * and does not allocate any memory */
783 smp_rmb();
784 if (!virtqueue_get_head(vq, vq->last_avail_idx, &elem.index)) {
785 break;
787 vq->inuse++;
788 vq->last_avail_idx++;
789 if (fEventIdx) {
790 vring_set_avail_event(vq, vq->last_avail_idx);
792 /* immediately push the element, nothing to unmap
793 * as both in_num and out_num are set to 0 */
794 virtqueue_push(vq, &elem, 0);
795 dropped++;
798 return dropped;
801 /* Reading and writing a structure directly to QEMUFile is *awful*, but
802 * it is what QEMU has always done by mistake. We can change it sooner
803 * or later by bumping the version number of the affected vm states.
804 * In the meanwhile, since the in-memory layout of VirtQueueElement
805 * has changed, we need to marshal to and from the layout that was
806 * used before the change.
808 typedef struct VirtQueueElementOld {
809 unsigned int index;
810 unsigned int out_num;
811 unsigned int in_num;
812 hwaddr in_addr[VIRTQUEUE_MAX_SIZE];
813 hwaddr out_addr[VIRTQUEUE_MAX_SIZE];
814 struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
815 struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
816 } VirtQueueElementOld;
818 void *qemu_get_virtqueue_element(VirtIODevice *vdev, QEMUFile *f, size_t sz)
820 VirtQueueElement *elem;
821 VirtQueueElementOld data;
822 int i;
824 qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
826 /* TODO: teach all callers that this can fail, and return failure instead
827 * of asserting here.
828 * When we do, we might be able to re-enable NDEBUG below.
830 #ifdef NDEBUG
831 #error building with NDEBUG is not supported
832 #endif
833 assert(ARRAY_SIZE(data.in_addr) >= data.in_num);
834 assert(ARRAY_SIZE(data.out_addr) >= data.out_num);
836 elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);
837 elem->index = data.index;
839 for (i = 0; i < elem->in_num; i++) {
840 elem->in_addr[i] = data.in_addr[i];
843 for (i = 0; i < elem->out_num; i++) {
844 elem->out_addr[i] = data.out_addr[i];
847 for (i = 0; i < elem->in_num; i++) {
848 /* Base is overwritten by virtqueue_map. */
849 elem->in_sg[i].iov_base = 0;
850 elem->in_sg[i].iov_len = data.in_sg[i].iov_len;
853 for (i = 0; i < elem->out_num; i++) {
854 /* Base is overwritten by virtqueue_map. */
855 elem->out_sg[i].iov_base = 0;
856 elem->out_sg[i].iov_len = data.out_sg[i].iov_len;
859 virtqueue_map(vdev, elem);
860 return elem;
863 void qemu_put_virtqueue_element(QEMUFile *f, VirtQueueElement *elem)
865 VirtQueueElementOld data;
866 int i;
868 memset(&data, 0, sizeof(data));
869 data.index = elem->index;
870 data.in_num = elem->in_num;
871 data.out_num = elem->out_num;
873 for (i = 0; i < elem->in_num; i++) {
874 data.in_addr[i] = elem->in_addr[i];
877 for (i = 0; i < elem->out_num; i++) {
878 data.out_addr[i] = elem->out_addr[i];
881 for (i = 0; i < elem->in_num; i++) {
882 /* Base is overwritten by virtqueue_map when loading. Do not
883 * save it, as it would leak the QEMU address space layout. */
884 data.in_sg[i].iov_len = elem->in_sg[i].iov_len;
887 for (i = 0; i < elem->out_num; i++) {
888 /* Do not save iov_base as above. */
889 data.out_sg[i].iov_len = elem->out_sg[i].iov_len;
891 qemu_put_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
894 /* virtio device */
895 static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
897 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
898 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
900 if (unlikely(vdev->broken)) {
901 return;
904 if (k->notify) {
905 k->notify(qbus->parent, vector);
909 void virtio_update_irq(VirtIODevice *vdev)
911 virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
914 static int virtio_validate_features(VirtIODevice *vdev)
916 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
918 if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM) &&
919 !virtio_vdev_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {
920 return -EFAULT;
923 if (k->validate_features) {
924 return k->validate_features(vdev);
925 } else {
926 return 0;
930 int virtio_set_status(VirtIODevice *vdev, uint8_t val)
932 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
933 trace_virtio_set_status(vdev, val);
935 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
936 if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
937 val & VIRTIO_CONFIG_S_FEATURES_OK) {
938 int ret = virtio_validate_features(vdev);
940 if (ret) {
941 return ret;
945 if (k->set_status) {
946 k->set_status(vdev, val);
948 vdev->status = val;
949 return 0;
952 bool target_words_bigendian(void);
953 static enum virtio_device_endian virtio_default_endian(void)
955 if (target_words_bigendian()) {
956 return VIRTIO_DEVICE_ENDIAN_BIG;
957 } else {
958 return VIRTIO_DEVICE_ENDIAN_LITTLE;
962 static enum virtio_device_endian virtio_current_cpu_endian(void)
964 CPUClass *cc = CPU_GET_CLASS(current_cpu);
966 if (cc->virtio_is_big_endian(current_cpu)) {
967 return VIRTIO_DEVICE_ENDIAN_BIG;
968 } else {
969 return VIRTIO_DEVICE_ENDIAN_LITTLE;
973 void virtio_reset(void *opaque)
975 VirtIODevice *vdev = opaque;
976 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
977 int i;
979 virtio_set_status(vdev, 0);
980 if (current_cpu) {
981 /* Guest initiated reset */
982 vdev->device_endian = virtio_current_cpu_endian();
983 } else {
984 /* System reset */
985 vdev->device_endian = virtio_default_endian();
988 if (k->reset) {
989 k->reset(vdev);
992 vdev->broken = false;
993 vdev->guest_features = 0;
994 vdev->queue_sel = 0;
995 vdev->status = 0;
996 atomic_set(&vdev->isr, 0);
997 vdev->config_vector = VIRTIO_NO_VECTOR;
998 virtio_notify_vector(vdev, vdev->config_vector);
1000 for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1001 vdev->vq[i].vring.desc = 0;
1002 vdev->vq[i].vring.avail = 0;
1003 vdev->vq[i].vring.used = 0;
1004 vdev->vq[i].last_avail_idx = 0;
1005 vdev->vq[i].shadow_avail_idx = 0;
1006 vdev->vq[i].used_idx = 0;
1007 virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
1008 vdev->vq[i].signalled_used = 0;
1009 vdev->vq[i].signalled_used_valid = false;
1010 vdev->vq[i].notification = true;
1011 vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
1012 vdev->vq[i].inuse = 0;
1016 uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
1018 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1019 uint8_t val;
1021 if (addr + sizeof(val) > vdev->config_len) {
1022 return (uint32_t)-1;
1025 k->get_config(vdev, vdev->config);
1027 val = ldub_p(vdev->config + addr);
1028 return val;
1031 uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
1033 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1034 uint16_t val;
1036 if (addr + sizeof(val) > vdev->config_len) {
1037 return (uint32_t)-1;
1040 k->get_config(vdev, vdev->config);
1042 val = lduw_p(vdev->config + addr);
1043 return val;
1046 uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
1048 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1049 uint32_t val;
1051 if (addr + sizeof(val) > vdev->config_len) {
1052 return (uint32_t)-1;
1055 k->get_config(vdev, vdev->config);
1057 val = ldl_p(vdev->config + addr);
1058 return val;
1061 void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
1063 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1064 uint8_t val = data;
1066 if (addr + sizeof(val) > vdev->config_len) {
1067 return;
1070 stb_p(vdev->config + addr, val);
1072 if (k->set_config) {
1073 k->set_config(vdev, vdev->config);
1077 void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
1079 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1080 uint16_t val = data;
1082 if (addr + sizeof(val) > vdev->config_len) {
1083 return;
1086 stw_p(vdev->config + addr, val);
1088 if (k->set_config) {
1089 k->set_config(vdev, vdev->config);
1093 void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
1095 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1096 uint32_t val = data;
1098 if (addr + sizeof(val) > vdev->config_len) {
1099 return;
1102 stl_p(vdev->config + addr, val);
1104 if (k->set_config) {
1105 k->set_config(vdev, vdev->config);
1109 uint32_t virtio_config_modern_readb(VirtIODevice *vdev, uint32_t addr)
1111 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1112 uint8_t val;
1114 if (addr + sizeof(val) > vdev->config_len) {
1115 return (uint32_t)-1;
1118 k->get_config(vdev, vdev->config);
1120 val = ldub_p(vdev->config + addr);
1121 return val;
1124 uint32_t virtio_config_modern_readw(VirtIODevice *vdev, uint32_t addr)
1126 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1127 uint16_t val;
1129 if (addr + sizeof(val) > vdev->config_len) {
1130 return (uint32_t)-1;
1133 k->get_config(vdev, vdev->config);
1135 val = lduw_le_p(vdev->config + addr);
1136 return val;
1139 uint32_t virtio_config_modern_readl(VirtIODevice *vdev, uint32_t addr)
1141 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1142 uint32_t val;
1144 if (addr + sizeof(val) > vdev->config_len) {
1145 return (uint32_t)-1;
1148 k->get_config(vdev, vdev->config);
1150 val = ldl_le_p(vdev->config + addr);
1151 return val;
1154 void virtio_config_modern_writeb(VirtIODevice *vdev,
1155 uint32_t addr, uint32_t data)
1157 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1158 uint8_t val = data;
1160 if (addr + sizeof(val) > vdev->config_len) {
1161 return;
1164 stb_p(vdev->config + addr, val);
1166 if (k->set_config) {
1167 k->set_config(vdev, vdev->config);
1171 void virtio_config_modern_writew(VirtIODevice *vdev,
1172 uint32_t addr, uint32_t data)
1174 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1175 uint16_t val = data;
1177 if (addr + sizeof(val) > vdev->config_len) {
1178 return;
1181 stw_le_p(vdev->config + addr, val);
1183 if (k->set_config) {
1184 k->set_config(vdev, vdev->config);
1188 void virtio_config_modern_writel(VirtIODevice *vdev,
1189 uint32_t addr, uint32_t data)
1191 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1192 uint32_t val = data;
1194 if (addr + sizeof(val) > vdev->config_len) {
1195 return;
1198 stl_le_p(vdev->config + addr, val);
1200 if (k->set_config) {
1201 k->set_config(vdev, vdev->config);
1205 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
1207 vdev->vq[n].vring.desc = addr;
1208 virtio_queue_update_rings(vdev, n);
1211 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
1213 return vdev->vq[n].vring.desc;
1216 void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
1217 hwaddr avail, hwaddr used)
1219 vdev->vq[n].vring.desc = desc;
1220 vdev->vq[n].vring.avail = avail;
1221 vdev->vq[n].vring.used = used;
1224 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
1226 /* Don't allow guest to flip queue between existent and
1227 * nonexistent states, or to set it to an invalid size.
1229 if (!!num != !!vdev->vq[n].vring.num ||
1230 num > VIRTQUEUE_MAX_SIZE ||
1231 num < 0) {
1232 return;
1234 vdev->vq[n].vring.num = num;
1237 VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
1239 return QLIST_FIRST(&vdev->vector_queues[vector]);
1242 VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
1244 return QLIST_NEXT(vq, node);
1247 int virtio_queue_get_num(VirtIODevice *vdev, int n)
1249 return vdev->vq[n].vring.num;
1252 int virtio_queue_get_max_num(VirtIODevice *vdev, int n)
1254 return vdev->vq[n].vring.num_default;
1257 int virtio_get_num_queues(VirtIODevice *vdev)
1259 int i;
1261 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1262 if (!virtio_queue_get_num(vdev, i)) {
1263 break;
1267 return i;
1270 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
1272 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1273 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1275 /* virtio-1 compliant devices cannot change the alignment */
1276 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1277 error_report("tried to modify queue alignment for virtio-1 device");
1278 return;
1280 /* Check that the transport told us it was going to do this
1281 * (so a buggy transport will immediately assert rather than
1282 * silently failing to migrate this state)
1284 assert(k->has_variable_vring_alignment);
1286 vdev->vq[n].vring.align = align;
1287 virtio_queue_update_rings(vdev, n);
1290 static void virtio_queue_notify_aio_vq(VirtQueue *vq)
1292 if (vq->vring.desc && vq->handle_aio_output) {
1293 VirtIODevice *vdev = vq->vdev;
1295 trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1296 vq->handle_aio_output(vdev, vq);
1300 static void virtio_queue_notify_vq(VirtQueue *vq)
1302 if (vq->vring.desc && vq->handle_output) {
1303 VirtIODevice *vdev = vq->vdev;
1305 if (unlikely(vdev->broken)) {
1306 return;
1309 trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1310 vq->handle_output(vdev, vq);
1314 void virtio_queue_notify(VirtIODevice *vdev, int n)
1316 virtio_queue_notify_vq(&vdev->vq[n]);
1319 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
1321 return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
1322 VIRTIO_NO_VECTOR;
1325 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
1327 VirtQueue *vq = &vdev->vq[n];
1329 if (n < VIRTIO_QUEUE_MAX) {
1330 if (vdev->vector_queues &&
1331 vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
1332 QLIST_REMOVE(vq, node);
1334 vdev->vq[n].vector = vector;
1335 if (vdev->vector_queues &&
1336 vector != VIRTIO_NO_VECTOR) {
1337 QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
1342 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
1343 VirtIOHandleOutput handle_output)
1345 int i;
1347 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1348 if (vdev->vq[i].vring.num == 0)
1349 break;
1352 if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
1353 abort();
1355 vdev->vq[i].vring.num = queue_size;
1356 vdev->vq[i].vring.num_default = queue_size;
1357 vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
1358 vdev->vq[i].handle_output = handle_output;
1359 vdev->vq[i].handle_aio_output = NULL;
1361 return &vdev->vq[i];
1364 void virtio_del_queue(VirtIODevice *vdev, int n)
1366 if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
1367 abort();
1370 vdev->vq[n].vring.num = 0;
1371 vdev->vq[n].vring.num_default = 0;
1374 static void virtio_set_isr(VirtIODevice *vdev, int value)
1376 uint8_t old = atomic_read(&vdev->isr);
1378 /* Do not write ISR if it does not change, so that its cacheline remains
1379 * shared in the common case where the guest does not read it.
1381 if ((old & value) != value) {
1382 atomic_or(&vdev->isr, value);
1386 bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
1388 uint16_t old, new;
1389 bool v;
1390 /* We need to expose used array entries before checking used event. */
1391 smp_mb();
1392 /* Always notify when queue is empty (when feature acknowledge) */
1393 if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1394 !vq->inuse && virtio_queue_empty(vq)) {
1395 return true;
1398 if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
1399 return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
1402 v = vq->signalled_used_valid;
1403 vq->signalled_used_valid = true;
1404 old = vq->signalled_used;
1405 new = vq->signalled_used = vq->used_idx;
1406 return !v || vring_need_event(vring_get_used_event(vq), new, old);
1409 void virtio_notify_irqfd(VirtIODevice *vdev, VirtQueue *vq)
1411 if (!virtio_should_notify(vdev, vq)) {
1412 return;
1415 trace_virtio_notify_irqfd(vdev, vq);
1418 * virtio spec 1.0 says ISR bit 0 should be ignored with MSI, but
1419 * windows drivers included in virtio-win 1.8.0 (circa 2015) are
1420 * incorrectly polling this bit during crashdump and hibernation
1421 * in MSI mode, causing a hang if this bit is never updated.
1422 * Recent releases of Windows do not really shut down, but rather
1423 * log out and hibernate to make the next startup faster. Hence,
1424 * this manifested as a more serious hang during shutdown with
1426 * Next driver release from 2016 fixed this problem, so working around it
1427 * is not a must, but it's easy to do so let's do it here.
1429 * Note: it's safe to update ISR from any thread as it was switched
1430 * to an atomic operation.
1432 virtio_set_isr(vq->vdev, 0x1);
1433 event_notifier_set(&vq->guest_notifier);
1436 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
1438 if (!virtio_should_notify(vdev, vq)) {
1439 return;
1442 trace_virtio_notify(vdev, vq);
1443 virtio_set_isr(vq->vdev, 0x1);
1444 virtio_notify_vector(vdev, vq->vector);
1447 void virtio_notify_config(VirtIODevice *vdev)
1449 if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
1450 return;
1452 virtio_set_isr(vdev, 0x3);
1453 vdev->generation++;
1454 virtio_notify_vector(vdev, vdev->config_vector);
1457 static bool virtio_device_endian_needed(void *opaque)
1459 VirtIODevice *vdev = opaque;
1461 assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
1462 if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1463 return vdev->device_endian != virtio_default_endian();
1465 /* Devices conforming to VIRTIO 1.0 or later are always LE. */
1466 return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
1469 static bool virtio_64bit_features_needed(void *opaque)
1471 VirtIODevice *vdev = opaque;
1473 return (vdev->host_features >> 32) != 0;
1476 static bool virtio_virtqueue_needed(void *opaque)
1478 VirtIODevice *vdev = opaque;
1480 return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
1483 static bool virtio_ringsize_needed(void *opaque)
1485 VirtIODevice *vdev = opaque;
1486 int i;
1488 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1489 if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
1490 return true;
1493 return false;
1496 static bool virtio_extra_state_needed(void *opaque)
1498 VirtIODevice *vdev = opaque;
1499 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1500 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1502 return k->has_extra_state &&
1503 k->has_extra_state(qbus->parent);
1506 static bool virtio_broken_needed(void *opaque)
1508 VirtIODevice *vdev = opaque;
1510 return vdev->broken;
1513 static const VMStateDescription vmstate_virtqueue = {
1514 .name = "virtqueue_state",
1515 .version_id = 1,
1516 .minimum_version_id = 1,
1517 .fields = (VMStateField[]) {
1518 VMSTATE_UINT64(vring.avail, struct VirtQueue),
1519 VMSTATE_UINT64(vring.used, struct VirtQueue),
1520 VMSTATE_END_OF_LIST()
1524 static const VMStateDescription vmstate_virtio_virtqueues = {
1525 .name = "virtio/virtqueues",
1526 .version_id = 1,
1527 .minimum_version_id = 1,
1528 .needed = &virtio_virtqueue_needed,
1529 .fields = (VMStateField[]) {
1530 VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1531 VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
1532 VMSTATE_END_OF_LIST()
1536 static const VMStateDescription vmstate_ringsize = {
1537 .name = "ringsize_state",
1538 .version_id = 1,
1539 .minimum_version_id = 1,
1540 .fields = (VMStateField[]) {
1541 VMSTATE_UINT32(vring.num_default, struct VirtQueue),
1542 VMSTATE_END_OF_LIST()
1546 static const VMStateDescription vmstate_virtio_ringsize = {
1547 .name = "virtio/ringsize",
1548 .version_id = 1,
1549 .minimum_version_id = 1,
1550 .needed = &virtio_ringsize_needed,
1551 .fields = (VMStateField[]) {
1552 VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1553 VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
1554 VMSTATE_END_OF_LIST()
1558 static int get_extra_state(QEMUFile *f, void *pv, size_t size)
1560 VirtIODevice *vdev = pv;
1561 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1562 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1564 if (!k->load_extra_state) {
1565 return -1;
1566 } else {
1567 return k->load_extra_state(qbus->parent, f);
1571 static void put_extra_state(QEMUFile *f, void *pv, size_t size)
1573 VirtIODevice *vdev = pv;
1574 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1575 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1577 k->save_extra_state(qbus->parent, f);
1580 static const VMStateInfo vmstate_info_extra_state = {
1581 .name = "virtqueue_extra_state",
1582 .get = get_extra_state,
1583 .put = put_extra_state,
1586 static const VMStateDescription vmstate_virtio_extra_state = {
1587 .name = "virtio/extra_state",
1588 .version_id = 1,
1589 .minimum_version_id = 1,
1590 .needed = &virtio_extra_state_needed,
1591 .fields = (VMStateField[]) {
1593 .name = "extra_state",
1594 .version_id = 0,
1595 .field_exists = NULL,
1596 .size = 0,
1597 .info = &vmstate_info_extra_state,
1598 .flags = VMS_SINGLE,
1599 .offset = 0,
1601 VMSTATE_END_OF_LIST()
1605 static const VMStateDescription vmstate_virtio_device_endian = {
1606 .name = "virtio/device_endian",
1607 .version_id = 1,
1608 .minimum_version_id = 1,
1609 .needed = &virtio_device_endian_needed,
1610 .fields = (VMStateField[]) {
1611 VMSTATE_UINT8(device_endian, VirtIODevice),
1612 VMSTATE_END_OF_LIST()
1616 static const VMStateDescription vmstate_virtio_64bit_features = {
1617 .name = "virtio/64bit_features",
1618 .version_id = 1,
1619 .minimum_version_id = 1,
1620 .needed = &virtio_64bit_features_needed,
1621 .fields = (VMStateField[]) {
1622 VMSTATE_UINT64(guest_features, VirtIODevice),
1623 VMSTATE_END_OF_LIST()
1627 static const VMStateDescription vmstate_virtio_broken = {
1628 .name = "virtio/broken",
1629 .version_id = 1,
1630 .minimum_version_id = 1,
1631 .needed = &virtio_broken_needed,
1632 .fields = (VMStateField[]) {
1633 VMSTATE_BOOL(broken, VirtIODevice),
1634 VMSTATE_END_OF_LIST()
1638 static const VMStateDescription vmstate_virtio = {
1639 .name = "virtio",
1640 .version_id = 1,
1641 .minimum_version_id = 1,
1642 .minimum_version_id_old = 1,
1643 .fields = (VMStateField[]) {
1644 VMSTATE_END_OF_LIST()
1646 .subsections = (const VMStateDescription*[]) {
1647 &vmstate_virtio_device_endian,
1648 &vmstate_virtio_64bit_features,
1649 &vmstate_virtio_virtqueues,
1650 &vmstate_virtio_ringsize,
1651 &vmstate_virtio_broken,
1652 &vmstate_virtio_extra_state,
1653 NULL
1657 void virtio_save(VirtIODevice *vdev, QEMUFile *f)
1659 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1660 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1661 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1662 uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
1663 int i;
1665 if (k->save_config) {
1666 k->save_config(qbus->parent, f);
1669 qemu_put_8s(f, &vdev->status);
1670 qemu_put_8s(f, &vdev->isr);
1671 qemu_put_be16s(f, &vdev->queue_sel);
1672 qemu_put_be32s(f, &guest_features_lo);
1673 qemu_put_be32(f, vdev->config_len);
1674 qemu_put_buffer(f, vdev->config, vdev->config_len);
1676 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1677 if (vdev->vq[i].vring.num == 0)
1678 break;
1681 qemu_put_be32(f, i);
1683 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1684 if (vdev->vq[i].vring.num == 0)
1685 break;
1687 qemu_put_be32(f, vdev->vq[i].vring.num);
1688 if (k->has_variable_vring_alignment) {
1689 qemu_put_be32(f, vdev->vq[i].vring.align);
1691 /* XXX virtio-1 devices */
1692 qemu_put_be64(f, vdev->vq[i].vring.desc);
1693 qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
1694 if (k->save_queue) {
1695 k->save_queue(qbus->parent, i, f);
1699 if (vdc->save != NULL) {
1700 vdc->save(vdev, f);
1703 if (vdc->vmsd) {
1704 vmstate_save_state(f, vdc->vmsd, vdev, NULL);
1707 /* Subsections */
1708 vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
1711 /* A wrapper for use as a VMState .put function */
1712 static void virtio_device_put(QEMUFile *f, void *opaque, size_t size)
1714 virtio_save(VIRTIO_DEVICE(opaque), f);
1717 /* A wrapper for use as a VMState .get function */
1718 static int virtio_device_get(QEMUFile *f, void *opaque, size_t size)
1720 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1721 DeviceClass *dc = DEVICE_CLASS(VIRTIO_DEVICE_GET_CLASS(vdev));
1723 return virtio_load(vdev, f, dc->vmsd->version_id);
1726 const VMStateInfo virtio_vmstate_info = {
1727 .name = "virtio",
1728 .get = virtio_device_get,
1729 .put = virtio_device_put,
1732 static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
1734 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1735 bool bad = (val & ~(vdev->host_features)) != 0;
1737 val &= vdev->host_features;
1738 if (k->set_features) {
1739 k->set_features(vdev, val);
1741 vdev->guest_features = val;
1742 return bad ? -1 : 0;
1745 int virtio_set_features(VirtIODevice *vdev, uint64_t val)
1748 * The driver must not attempt to set features after feature negotiation
1749 * has finished.
1751 if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
1752 return -EINVAL;
1754 return virtio_set_features_nocheck(vdev, val);
1757 int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
1759 int i, ret;
1760 int32_t config_len;
1761 uint32_t num;
1762 uint32_t features;
1763 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1764 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1765 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1768 * We poison the endianness to ensure it does not get used before
1769 * subsections have been loaded.
1771 vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
1773 if (k->load_config) {
1774 ret = k->load_config(qbus->parent, f);
1775 if (ret)
1776 return ret;
1779 qemu_get_8s(f, &vdev->status);
1780 qemu_get_8s(f, &vdev->isr);
1781 qemu_get_be16s(f, &vdev->queue_sel);
1782 if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
1783 return -1;
1785 qemu_get_be32s(f, &features);
1788 * Temporarily set guest_features low bits - needed by
1789 * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
1790 * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
1792 * Note: devices should always test host features in future - don't create
1793 * new dependencies like this.
1795 vdev->guest_features = features;
1797 config_len = qemu_get_be32(f);
1800 * There are cases where the incoming config can be bigger or smaller
1801 * than what we have; so load what we have space for, and skip
1802 * any excess that's in the stream.
1804 qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
1806 while (config_len > vdev->config_len) {
1807 qemu_get_byte(f);
1808 config_len--;
1811 num = qemu_get_be32(f);
1813 if (num > VIRTIO_QUEUE_MAX) {
1814 error_report("Invalid number of virtqueues: 0x%x", num);
1815 return -1;
1818 for (i = 0; i < num; i++) {
1819 vdev->vq[i].vring.num = qemu_get_be32(f);
1820 if (k->has_variable_vring_alignment) {
1821 vdev->vq[i].vring.align = qemu_get_be32(f);
1823 vdev->vq[i].vring.desc = qemu_get_be64(f);
1824 qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
1825 vdev->vq[i].signalled_used_valid = false;
1826 vdev->vq[i].notification = true;
1828 if (vdev->vq[i].vring.desc) {
1829 /* XXX virtio-1 devices */
1830 virtio_queue_update_rings(vdev, i);
1831 } else if (vdev->vq[i].last_avail_idx) {
1832 error_report("VQ %d address 0x0 "
1833 "inconsistent with Host index 0x%x",
1834 i, vdev->vq[i].last_avail_idx);
1835 return -1;
1837 if (k->load_queue) {
1838 ret = k->load_queue(qbus->parent, i, f);
1839 if (ret)
1840 return ret;
1844 virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
1846 if (vdc->load != NULL) {
1847 ret = vdc->load(vdev, f, version_id);
1848 if (ret) {
1849 return ret;
1853 if (vdc->vmsd) {
1854 ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id);
1855 if (ret) {
1856 return ret;
1860 /* Subsections */
1861 ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
1862 if (ret) {
1863 return ret;
1866 if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
1867 vdev->device_endian = virtio_default_endian();
1870 if (virtio_64bit_features_needed(vdev)) {
1872 * Subsection load filled vdev->guest_features. Run them
1873 * through virtio_set_features to sanity-check them against
1874 * host_features.
1876 uint64_t features64 = vdev->guest_features;
1877 if (virtio_set_features_nocheck(vdev, features64) < 0) {
1878 error_report("Features 0x%" PRIx64 " unsupported. "
1879 "Allowed features: 0x%" PRIx64,
1880 features64, vdev->host_features);
1881 return -1;
1883 } else {
1884 if (virtio_set_features_nocheck(vdev, features) < 0) {
1885 error_report("Features 0x%x unsupported. "
1886 "Allowed features: 0x%" PRIx64,
1887 features, vdev->host_features);
1888 return -1;
1892 for (i = 0; i < num; i++) {
1893 if (vdev->vq[i].vring.desc) {
1894 uint16_t nheads;
1895 nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
1896 /* Check it isn't doing strange things with descriptor numbers. */
1897 if (nheads > vdev->vq[i].vring.num) {
1898 error_report("VQ %d size 0x%x Guest index 0x%x "
1899 "inconsistent with Host index 0x%x: delta 0x%x",
1900 i, vdev->vq[i].vring.num,
1901 vring_avail_idx(&vdev->vq[i]),
1902 vdev->vq[i].last_avail_idx, nheads);
1903 return -1;
1905 vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
1906 vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
1909 * Some devices migrate VirtQueueElements that have been popped
1910 * from the avail ring but not yet returned to the used ring.
1911 * Since max ring size < UINT16_MAX it's safe to use modulo
1912 * UINT16_MAX + 1 subtraction.
1914 vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx -
1915 vdev->vq[i].used_idx);
1916 if (vdev->vq[i].inuse > vdev->vq[i].vring.num) {
1917 error_report("VQ %d size 0x%x < last_avail_idx 0x%x - "
1918 "used_idx 0x%x",
1919 i, vdev->vq[i].vring.num,
1920 vdev->vq[i].last_avail_idx,
1921 vdev->vq[i].used_idx);
1922 return -1;
1927 return 0;
1930 void virtio_cleanup(VirtIODevice *vdev)
1932 qemu_del_vm_change_state_handler(vdev->vmstate);
1933 g_free(vdev->config);
1934 g_free(vdev->vq);
1935 g_free(vdev->vector_queues);
1938 static void virtio_vmstate_change(void *opaque, int running, RunState state)
1940 VirtIODevice *vdev = opaque;
1941 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1942 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1943 bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
1944 vdev->vm_running = running;
1946 if (backend_run) {
1947 virtio_set_status(vdev, vdev->status);
1950 if (k->vmstate_change) {
1951 k->vmstate_change(qbus->parent, backend_run);
1954 if (!backend_run) {
1955 virtio_set_status(vdev, vdev->status);
1959 void virtio_instance_init_common(Object *proxy_obj, void *data,
1960 size_t vdev_size, const char *vdev_name)
1962 DeviceState *vdev = data;
1964 object_initialize(vdev, vdev_size, vdev_name);
1965 object_property_add_child(proxy_obj, "virtio-backend", OBJECT(vdev), NULL);
1966 object_unref(OBJECT(vdev));
1967 qdev_alias_all_properties(vdev, proxy_obj);
1970 void virtio_init(VirtIODevice *vdev, const char *name,
1971 uint16_t device_id, size_t config_size)
1973 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1974 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1975 int i;
1976 int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
1978 if (nvectors) {
1979 vdev->vector_queues =
1980 g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
1983 vdev->device_id = device_id;
1984 vdev->status = 0;
1985 atomic_set(&vdev->isr, 0);
1986 vdev->queue_sel = 0;
1987 vdev->config_vector = VIRTIO_NO_VECTOR;
1988 vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);
1989 vdev->vm_running = runstate_is_running();
1990 vdev->broken = false;
1991 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1992 vdev->vq[i].vector = VIRTIO_NO_VECTOR;
1993 vdev->vq[i].vdev = vdev;
1994 vdev->vq[i].queue_index = i;
1997 vdev->name = name;
1998 vdev->config_len = config_size;
1999 if (vdev->config_len) {
2000 vdev->config = g_malloc0(config_size);
2001 } else {
2002 vdev->config = NULL;
2004 vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
2005 vdev);
2006 vdev->device_endian = virtio_default_endian();
2007 vdev->use_guest_notifier_mask = true;
2010 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
2012 return vdev->vq[n].vring.desc;
2015 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
2017 return vdev->vq[n].vring.avail;
2020 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
2022 return vdev->vq[n].vring.used;
2025 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
2027 return sizeof(VRingDesc) * vdev->vq[n].vring.num;
2030 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
2032 return offsetof(VRingAvail, ring) +
2033 sizeof(uint16_t) * vdev->vq[n].vring.num;
2036 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
2038 return offsetof(VRingUsed, ring) +
2039 sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
2042 uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
2044 return vdev->vq[n].last_avail_idx;
2047 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
2049 vdev->vq[n].last_avail_idx = idx;
2050 vdev->vq[n].shadow_avail_idx = idx;
2053 void virtio_queue_update_used_idx(VirtIODevice *vdev, int n)
2055 vdev->vq[n].used_idx = vring_used_idx(&vdev->vq[n]);
2058 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
2060 vdev->vq[n].signalled_used_valid = false;
2063 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
2065 return vdev->vq + n;
2068 uint16_t virtio_get_queue_index(VirtQueue *vq)
2070 return vq->queue_index;
2073 static void virtio_queue_guest_notifier_read(EventNotifier *n)
2075 VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
2076 if (event_notifier_test_and_clear(n)) {
2077 virtio_notify_vector(vq->vdev, vq->vector);
2081 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
2082 bool with_irqfd)
2084 if (assign && !with_irqfd) {
2085 event_notifier_set_handler(&vq->guest_notifier, false,
2086 virtio_queue_guest_notifier_read);
2087 } else {
2088 event_notifier_set_handler(&vq->guest_notifier, false, NULL);
2090 if (!assign) {
2091 /* Test and clear notifier before closing it,
2092 * in case poll callback didn't have time to run. */
2093 virtio_queue_guest_notifier_read(&vq->guest_notifier);
2097 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
2099 return &vq->guest_notifier;
2102 static void virtio_queue_host_notifier_aio_read(EventNotifier *n)
2104 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2105 if (event_notifier_test_and_clear(n)) {
2106 virtio_queue_notify_aio_vq(vq);
2110 static void virtio_queue_host_notifier_aio_poll_begin(EventNotifier *n)
2112 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2114 virtio_queue_set_notification(vq, 0);
2117 static bool virtio_queue_host_notifier_aio_poll(void *opaque)
2119 EventNotifier *n = opaque;
2120 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2122 if (virtio_queue_empty(vq)) {
2123 return false;
2126 virtio_queue_notify_aio_vq(vq);
2128 /* In case the handler function re-enabled notifications */
2129 virtio_queue_set_notification(vq, 0);
2130 return true;
2133 static void virtio_queue_host_notifier_aio_poll_end(EventNotifier *n)
2135 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2137 /* Caller polls once more after this to catch requests that race with us */
2138 virtio_queue_set_notification(vq, 1);
2141 void virtio_queue_aio_set_host_notifier_handler(VirtQueue *vq, AioContext *ctx,
2142 VirtIOHandleOutput handle_output)
2144 if (handle_output) {
2145 vq->handle_aio_output = handle_output;
2146 aio_set_event_notifier(ctx, &vq->host_notifier, true,
2147 virtio_queue_host_notifier_aio_read,
2148 virtio_queue_host_notifier_aio_poll);
2149 aio_set_event_notifier_poll(ctx, &vq->host_notifier,
2150 virtio_queue_host_notifier_aio_poll_begin,
2151 virtio_queue_host_notifier_aio_poll_end);
2152 } else {
2153 aio_set_event_notifier(ctx, &vq->host_notifier, true, NULL, NULL);
2154 /* Test and clear notifier before after disabling event,
2155 * in case poll callback didn't have time to run. */
2156 virtio_queue_host_notifier_aio_read(&vq->host_notifier);
2157 vq->handle_aio_output = NULL;
2161 void virtio_queue_host_notifier_read(EventNotifier *n)
2163 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2164 if (event_notifier_test_and_clear(n)) {
2165 virtio_queue_notify_vq(vq);
2169 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
2171 return &vq->host_notifier;
2174 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
2176 g_free(vdev->bus_name);
2177 vdev->bus_name = g_strdup(bus_name);
2180 void GCC_FMT_ATTR(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
2182 va_list ap;
2184 va_start(ap, fmt);
2185 error_vreport(fmt, ap);
2186 va_end(ap);
2188 vdev->broken = true;
2190 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2191 virtio_set_status(vdev, vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET);
2192 virtio_notify_config(vdev);
2196 static void virtio_device_realize(DeviceState *dev, Error **errp)
2198 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
2199 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
2200 Error *err = NULL;
2202 /* Devices should either use vmsd or the load/save methods */
2203 assert(!vdc->vmsd || !vdc->load);
2205 if (vdc->realize != NULL) {
2206 vdc->realize(dev, &err);
2207 if (err != NULL) {
2208 error_propagate(errp, err);
2209 return;
2213 virtio_bus_device_plugged(vdev, &err);
2214 if (err != NULL) {
2215 error_propagate(errp, err);
2216 return;
2220 static void virtio_device_unrealize(DeviceState *dev, Error **errp)
2222 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
2223 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
2224 Error *err = NULL;
2226 virtio_bus_device_unplugged(vdev);
2228 if (vdc->unrealize != NULL) {
2229 vdc->unrealize(dev, &err);
2230 if (err != NULL) {
2231 error_propagate(errp, err);
2232 return;
2236 g_free(vdev->bus_name);
2237 vdev->bus_name = NULL;
2240 static Property virtio_properties[] = {
2241 DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
2242 DEFINE_PROP_END_OF_LIST(),
2245 static int virtio_device_start_ioeventfd_impl(VirtIODevice *vdev)
2247 VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
2248 int n, r, err;
2250 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
2251 VirtQueue *vq = &vdev->vq[n];
2252 if (!virtio_queue_get_num(vdev, n)) {
2253 continue;
2255 r = virtio_bus_set_host_notifier(qbus, n, true);
2256 if (r < 0) {
2257 err = r;
2258 goto assign_error;
2260 event_notifier_set_handler(&vq->host_notifier, true,
2261 virtio_queue_host_notifier_read);
2264 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
2265 /* Kick right away to begin processing requests already in vring */
2266 VirtQueue *vq = &vdev->vq[n];
2267 if (!vq->vring.num) {
2268 continue;
2270 event_notifier_set(&vq->host_notifier);
2272 return 0;
2274 assign_error:
2275 while (--n >= 0) {
2276 VirtQueue *vq = &vdev->vq[n];
2277 if (!virtio_queue_get_num(vdev, n)) {
2278 continue;
2281 event_notifier_set_handler(&vq->host_notifier, true, NULL);
2282 r = virtio_bus_set_host_notifier(qbus, n, false);
2283 assert(r >= 0);
2285 return err;
2288 int virtio_device_start_ioeventfd(VirtIODevice *vdev)
2290 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2291 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2293 return virtio_bus_start_ioeventfd(vbus);
2296 static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
2298 VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
2299 int n, r;
2301 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
2302 VirtQueue *vq = &vdev->vq[n];
2304 if (!virtio_queue_get_num(vdev, n)) {
2305 continue;
2307 event_notifier_set_handler(&vq->host_notifier, true, NULL);
2308 r = virtio_bus_set_host_notifier(qbus, n, false);
2309 assert(r >= 0);
2313 void virtio_device_stop_ioeventfd(VirtIODevice *vdev)
2315 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2316 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2318 virtio_bus_stop_ioeventfd(vbus);
2321 int virtio_device_grab_ioeventfd(VirtIODevice *vdev)
2323 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2324 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2326 return virtio_bus_grab_ioeventfd(vbus);
2329 void virtio_device_release_ioeventfd(VirtIODevice *vdev)
2331 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2332 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2334 virtio_bus_release_ioeventfd(vbus);
2337 static void virtio_device_class_init(ObjectClass *klass, void *data)
2339 /* Set the default value here. */
2340 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
2341 DeviceClass *dc = DEVICE_CLASS(klass);
2343 dc->realize = virtio_device_realize;
2344 dc->unrealize = virtio_device_unrealize;
2345 dc->bus_type = TYPE_VIRTIO_BUS;
2346 dc->props = virtio_properties;
2347 vdc->start_ioeventfd = virtio_device_start_ioeventfd_impl;
2348 vdc->stop_ioeventfd = virtio_device_stop_ioeventfd_impl;
2350 vdc->legacy_features |= VIRTIO_LEGACY_FEATURES;
2353 bool virtio_device_ioeventfd_enabled(VirtIODevice *vdev)
2355 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2356 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2358 return virtio_bus_ioeventfd_enabled(vbus);
2361 static const TypeInfo virtio_device_info = {
2362 .name = TYPE_VIRTIO_DEVICE,
2363 .parent = TYPE_DEVICE,
2364 .instance_size = sizeof(VirtIODevice),
2365 .class_init = virtio_device_class_init,
2366 .abstract = true,
2367 .class_size = sizeof(VirtioDeviceClass),
2370 static void virtio_register_types(void)
2372 type_register_static(&virtio_device_info);
2375 type_init(virtio_register_types)