]> git.proxmox.com Git - mirror_qemu.git/blame - hw/virtio/virtio.c
virtio: add missing region cache init in virtio_load()
[mirror_qemu.git] / hw / virtio / virtio.c
CommitLineData
967f97fa
AL
1/*
2 * Virtio Support
3 *
4 * Copyright IBM, Corp. 2007
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 */
13
9b8bfe21 14#include "qemu/osdep.h"
da34e65c 15#include "qapi/error.h"
4771d756
PB
16#include "qemu-common.h"
17#include "cpu.h"
64979a4d 18#include "trace.h"
fdfba1a2 19#include "exec/address-spaces.h"
1de7afc9 20#include "qemu/error-report.h"
0d09e41a 21#include "hw/virtio/virtio.h"
1de7afc9 22#include "qemu/atomic.h"
0d09e41a 23#include "hw/virtio/virtio-bus.h"
6b321a3d 24#include "migration/migration.h"
cee3ca00 25#include "hw/virtio/virtio-access.h"
8607f5c3 26#include "sysemu/dma.h"
967f97fa 27
6ce69d1c
PM
28/*
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.
32 */
f46f15bc
AL
33#define VIRTIO_PCI_VRING_ALIGN 4096
34
967f97fa
AL
35typedef struct VRingDesc
36{
37 uint64_t addr;
38 uint32_t len;
39 uint16_t flags;
40 uint16_t next;
41} VRingDesc;
42
43typedef struct VRingAvail
44{
45 uint16_t flags;
46 uint16_t idx;
47 uint16_t ring[0];
48} VRingAvail;
49
50typedef struct VRingUsedElem
51{
52 uint32_t id;
53 uint32_t len;
54} VRingUsedElem;
55
56typedef struct VRingUsed
57{
58 uint16_t flags;
59 uint16_t idx;
60 VRingUsedElem ring[0];
61} VRingUsed;
62
c611c764
PB
63typedef struct VRingMemoryRegionCaches {
64 struct rcu_head rcu;
65 MemoryRegionCache desc;
66 MemoryRegionCache avail;
67 MemoryRegionCache used;
68} VRingMemoryRegionCaches;
69
967f97fa
AL
70typedef struct VRing
71{
72 unsigned int num;
46c5d082 73 unsigned int num_default;
6ce69d1c 74 unsigned int align;
a8170e5e
AK
75 hwaddr desc;
76 hwaddr avail;
77 hwaddr used;
c611c764 78 VRingMemoryRegionCaches *caches;
967f97fa
AL
79} VRing;
80
81struct VirtQueue
82{
83 VRing vring;
be1fea9b
VM
84
85 /* Next head to pop */
967f97fa 86 uint16_t last_avail_idx;
b796fcd1 87
be1fea9b
VM
88 /* Last avail_idx read from VQ. */
89 uint16_t shadow_avail_idx;
90
b796fcd1
VM
91 uint16_t used_idx;
92
bcbabae8
MT
93 /* Last used index value we have signalled on */
94 uint16_t signalled_used;
95
96 /* Last used index value we have signalled on */
97 bool signalled_used_valid;
98
332fa82d
SH
99 /* Notification enabled? */
100 bool notification;
bcbabae8 101
e78a2b42
JW
102 uint16_t queue_index;
103
e66bcc40 104 unsigned int inuse;
bcbabae8 105
7055e687 106 uint16_t vector;
bf1780b0 107 VirtIOHandleOutput handle_output;
07931698 108 VirtIOHandleAIOOutput handle_aio_output;
1cbdabe2
MT
109 VirtIODevice *vdev;
110 EventNotifier guest_notifier;
111 EventNotifier host_notifier;
e0d686bf 112 QLIST_ENTRY(VirtQueue) node;
967f97fa
AL
113};
114
c611c764
PB
115static void virtio_free_region_cache(VRingMemoryRegionCaches *caches)
116{
117 if (!caches) {
118 return;
119 }
120
121 address_space_cache_destroy(&caches->desc);
122 address_space_cache_destroy(&caches->avail);
123 address_space_cache_destroy(&caches->used);
124 g_free(caches);
125}
126
127static void virtio_init_region_cache(VirtIODevice *vdev, int n)
128{
129 VirtQueue *vq = &vdev->vq[n];
130 VRingMemoryRegionCaches *old = vq->vring.caches;
131 VRingMemoryRegionCaches *new;
132 hwaddr addr, size;
133 int event_size;
134
135 event_size = virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
136
137 addr = vq->vring.desc;
138 if (!addr) {
139 return;
140 }
141 new = g_new0(VRingMemoryRegionCaches, 1);
142 size = virtio_queue_get_desc_size(vdev, n);
143 address_space_cache_init(&new->desc, vdev->dma_as,
144 addr, size, false);
145
146 size = virtio_queue_get_used_size(vdev, n) + event_size;
147 address_space_cache_init(&new->used, vdev->dma_as,
148 vq->vring.used, size, true);
149
150 size = virtio_queue_get_avail_size(vdev, n) + event_size;
151 address_space_cache_init(&new->avail, vdev->dma_as,
152 vq->vring.avail, size, false);
153
154 atomic_rcu_set(&vq->vring.caches, new);
155 if (old) {
156 call_rcu(old, virtio_free_region_cache, rcu);
157 }
158}
159
967f97fa 160/* virt queue functions */
ab223c95 161void virtio_queue_update_rings(VirtIODevice *vdev, int n)
967f97fa 162{
ab223c95 163 VRing *vring = &vdev->vq[n].vring;
53c25cea 164
ab223c95
CH
165 if (!vring->desc) {
166 /* not yet setup -> nothing to do */
167 return;
168 }
169 vring->avail = vring->desc + vring->num * sizeof(VRingDesc);
170 vring->used = vring_align(vring->avail +
171 offsetof(VRingAvail, ring[vring->num]),
172 vring->align);
c611c764 173 virtio_init_region_cache(vdev, n);
967f97fa
AL
174}
175
97cd965c 176/* Called within rcu_read_lock(). */
aa570d6f 177static void vring_desc_read(VirtIODevice *vdev, VRingDesc *desc,
5eba0404 178 MemoryRegionCache *cache, int i)
967f97fa 179{
5eba0404
PB
180 address_space_read_cached(cache, i * sizeof(VRingDesc),
181 desc, sizeof(VRingDesc));
aa570d6f
PB
182 virtio_tswap64s(vdev, &desc->addr);
183 virtio_tswap32s(vdev, &desc->len);
184 virtio_tswap16s(vdev, &desc->flags);
185 virtio_tswap16s(vdev, &desc->next);
967f97fa
AL
186}
187
97cd965c 188/* Called within rcu_read_lock(). */
967f97fa
AL
189static inline uint16_t vring_avail_flags(VirtQueue *vq)
190{
97cd965c
PB
191 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
192 hwaddr pa = offsetof(VRingAvail, flags);
193 return virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
967f97fa
AL
194}
195
97cd965c 196/* Called within rcu_read_lock(). */
967f97fa
AL
197static inline uint16_t vring_avail_idx(VirtQueue *vq)
198{
97cd965c
PB
199 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
200 hwaddr pa = offsetof(VRingAvail, idx);
201 vq->shadow_avail_idx = virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
be1fea9b 202 return vq->shadow_avail_idx;
967f97fa
AL
203}
204
97cd965c 205/* Called within rcu_read_lock(). */
967f97fa
AL
206static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
207{
97cd965c
PB
208 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
209 hwaddr pa = offsetof(VRingAvail, ring[i]);
210 return virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
967f97fa
AL
211}
212
97cd965c 213/* Called within rcu_read_lock(). */
e9600c6c 214static inline uint16_t vring_get_used_event(VirtQueue *vq)
bcbabae8
MT
215{
216 return vring_avail_ring(vq, vq->vring.num);
217}
218
97cd965c 219/* Called within rcu_read_lock(). */
1cdd2ee5
VM
220static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,
221 int i)
967f97fa 222{
97cd965c
PB
223 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
224 hwaddr pa = offsetof(VRingUsed, ring[i]);
1cdd2ee5
VM
225 virtio_tswap32s(vq->vdev, &uelem->id);
226 virtio_tswap32s(vq->vdev, &uelem->len);
97cd965c
PB
227 address_space_write_cached(&caches->used, pa, uelem, sizeof(VRingUsedElem));
228 address_space_cache_invalidate(&caches->used, pa, sizeof(VRingUsedElem));
967f97fa
AL
229}
230
97cd965c 231/* Called within rcu_read_lock(). */
967f97fa
AL
232static uint16_t vring_used_idx(VirtQueue *vq)
233{
97cd965c
PB
234 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
235 hwaddr pa = offsetof(VRingUsed, idx);
236 return virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
967f97fa
AL
237}
238
97cd965c 239/* Called within rcu_read_lock(). */
bcbabae8 240static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
967f97fa 241{
97cd965c
PB
242 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
243 hwaddr pa = offsetof(VRingUsed, idx);
244 virtio_stw_phys_cached(vq->vdev, &caches->used, pa, val);
245 address_space_cache_invalidate(&caches->used, pa, sizeof(val));
b796fcd1 246 vq->used_idx = val;
967f97fa
AL
247}
248
97cd965c 249/* Called within rcu_read_lock(). */
967f97fa
AL
250static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
251{
97cd965c 252 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
cee3ca00 253 VirtIODevice *vdev = vq->vdev;
97cd965c
PB
254 hwaddr pa = offsetof(VRingUsed, flags);
255 uint16_t flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
256
257 virtio_stw_phys_cached(vdev, &caches->used, pa, flags | mask);
258 address_space_cache_invalidate(&caches->used, pa, sizeof(flags));
967f97fa
AL
259}
260
97cd965c 261/* Called within rcu_read_lock(). */
967f97fa
AL
262static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
263{
97cd965c 264 VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
cee3ca00 265 VirtIODevice *vdev = vq->vdev;
97cd965c
PB
266 hwaddr pa = offsetof(VRingUsed, flags);
267 uint16_t flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
268
269 virtio_stw_phys_cached(vdev, &caches->used, pa, flags & ~mask);
270 address_space_cache_invalidate(&caches->used, pa, sizeof(flags));
967f97fa
AL
271}
272
97cd965c 273/* Called within rcu_read_lock(). */
e9600c6c 274static inline void vring_set_avail_event(VirtQueue *vq, uint16_t val)
bcbabae8 275{
97cd965c 276 VRingMemoryRegionCaches *caches;
a8170e5e 277 hwaddr pa;
332fa82d 278 if (!vq->notification) {
bcbabae8
MT
279 return;
280 }
97cd965c
PB
281
282 caches = atomic_rcu_read(&vq->vring.caches);
283 pa = offsetof(VRingUsed, ring[vq->vring.num]);
284 virtio_stw_phys_cached(vq->vdev, &caches->used, pa, val);
3cdf8473 285 address_space_cache_invalidate(&caches->used, pa, sizeof(val));
bcbabae8
MT
286}
287
967f97fa
AL
288void virtio_queue_set_notification(VirtQueue *vq, int enable)
289{
332fa82d 290 vq->notification = enable;
97cd965c 291
34c6bf22
CH
292 if (!vq->vring.desc) {
293 return;
294 }
295
97cd965c 296 rcu_read_lock();
95129d6f 297 if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
e9600c6c 298 vring_set_avail_event(vq, vring_avail_idx(vq));
bcbabae8 299 } else if (enable) {
967f97fa 300 vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
bcbabae8 301 } else {
967f97fa 302 vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
bcbabae8 303 }
92045d80
MT
304 if (enable) {
305 /* Expose avail event/used flags before caller checks the avail idx. */
306 smp_mb();
307 }
97cd965c 308 rcu_read_unlock();
967f97fa
AL
309}
310
311int virtio_queue_ready(VirtQueue *vq)
312{
313 return vq->vring.avail != 0;
314}
315
be1fea9b 316/* Fetch avail_idx from VQ memory only when we really need to know if
97cd965c
PB
317 * guest has added some buffers.
318 * Called within rcu_read_lock(). */
319static int virtio_queue_empty_rcu(VirtQueue *vq)
967f97fa 320{
be1fea9b
VM
321 if (vq->shadow_avail_idx != vq->last_avail_idx) {
322 return 0;
323 }
324
967f97fa
AL
325 return vring_avail_idx(vq) == vq->last_avail_idx;
326}
327
97cd965c
PB
328int virtio_queue_empty(VirtQueue *vq)
329{
330 bool empty;
331
332 if (vq->shadow_avail_idx != vq->last_avail_idx) {
333 return 0;
334 }
335
336 rcu_read_lock();
337 empty = vring_avail_idx(vq) == vq->last_avail_idx;
338 rcu_read_unlock();
339 return empty;
340}
341
ce317461
JW
342static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,
343 unsigned int len)
967f97fa 344{
8607f5c3 345 AddressSpace *dma_as = vq->vdev->dma_as;
967f97fa
AL
346 unsigned int offset;
347 int i;
348
967f97fa
AL
349 offset = 0;
350 for (i = 0; i < elem->in_num; i++) {
351 size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
352
8607f5c3
JW
353 dma_memory_unmap(dma_as, elem->in_sg[i].iov_base,
354 elem->in_sg[i].iov_len,
355 DMA_DIRECTION_FROM_DEVICE, size);
967f97fa 356
0cea71a2 357 offset += size;
967f97fa
AL
358 }
359
26b258e1 360 for (i = 0; i < elem->out_num; i++)
8607f5c3
JW
361 dma_memory_unmap(dma_as, elem->out_sg[i].iov_base,
362 elem->out_sg[i].iov_len,
363 DMA_DIRECTION_TO_DEVICE,
364 elem->out_sg[i].iov_len);
ce317461
JW
365}
366
2640d2a5
SH
367/* virtqueue_detach_element:
368 * @vq: The #VirtQueue
369 * @elem: The #VirtQueueElement
370 * @len: number of bytes written
371 *
372 * Detach the element from the virtqueue. This function is suitable for device
373 * reset or other situations where a #VirtQueueElement is simply freed and will
374 * not be pushed or discarded.
375 */
376void virtqueue_detach_element(VirtQueue *vq, const VirtQueueElement *elem,
377 unsigned int len)
378{
379 vq->inuse--;
380 virtqueue_unmap_sg(vq, elem, len);
381}
382
27e57efe 383/* virtqueue_unpop:
2640d2a5
SH
384 * @vq: The #VirtQueue
385 * @elem: The #VirtQueueElement
386 * @len: number of bytes written
387 *
388 * Pretend the most recent element wasn't popped from the virtqueue. The next
389 * call to virtqueue_pop() will refetch the element.
390 */
27e57efe
LP
391void virtqueue_unpop(VirtQueue *vq, const VirtQueueElement *elem,
392 unsigned int len)
29b9f5ef
JW
393{
394 vq->last_avail_idx--;
2640d2a5 395 virtqueue_detach_element(vq, elem, len);
29b9f5ef
JW
396}
397
297a75e6
SH
398/* virtqueue_rewind:
399 * @vq: The #VirtQueue
400 * @num: Number of elements to push back
401 *
402 * Pretend that elements weren't popped from the virtqueue. The next
403 * virtqueue_pop() will refetch the oldest element.
404 *
27e57efe 405 * Use virtqueue_unpop() instead if you have a VirtQueueElement.
297a75e6
SH
406 *
407 * Returns: true on success, false if @num is greater than the number of in use
408 * elements.
409 */
410bool virtqueue_rewind(VirtQueue *vq, unsigned int num)
411{
412 if (num > vq->inuse) {
413 return false;
414 }
415 vq->last_avail_idx -= num;
416 vq->inuse -= num;
417 return true;
418}
419
97cd965c 420/* Called within rcu_read_lock(). */
ce317461
JW
421void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
422 unsigned int len, unsigned int idx)
423{
1cdd2ee5
VM
424 VRingUsedElem uelem;
425
ce317461
JW
426 trace_virtqueue_fill(vq, elem, len, idx);
427
428 virtqueue_unmap_sg(vq, elem, len);
26b258e1 429
f5ed3663
SH
430 if (unlikely(vq->vdev->broken)) {
431 return;
432 }
433
b796fcd1 434 idx = (idx + vq->used_idx) % vq->vring.num;
967f97fa 435
1cdd2ee5
VM
436 uelem.id = elem->index;
437 uelem.len = len;
438 vring_used_write(vq, &uelem, idx);
967f97fa
AL
439}
440
97cd965c 441/* Called within rcu_read_lock(). */
967f97fa
AL
442void virtqueue_flush(VirtQueue *vq, unsigned int count)
443{
bcbabae8 444 uint16_t old, new;
f5ed3663
SH
445
446 if (unlikely(vq->vdev->broken)) {
447 vq->inuse -= count;
448 return;
449 }
450
967f97fa 451 /* Make sure buffer is written before we update index. */
b90d2f35 452 smp_wmb();
64979a4d 453 trace_virtqueue_flush(vq, count);
b796fcd1 454 old = vq->used_idx;
bcbabae8
MT
455 new = old + count;
456 vring_used_idx_set(vq, new);
967f97fa 457 vq->inuse -= count;
bcbabae8
MT
458 if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
459 vq->signalled_used_valid = false;
967f97fa
AL
460}
461
462void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
463 unsigned int len)
464{
97cd965c 465 rcu_read_lock();
967f97fa
AL
466 virtqueue_fill(vq, elem, len, 0);
467 virtqueue_flush(vq, 1);
97cd965c 468 rcu_read_unlock();
967f97fa
AL
469}
470
97cd965c 471/* Called within rcu_read_lock(). */
967f97fa
AL
472static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
473{
474 uint16_t num_heads = vring_avail_idx(vq) - idx;
475
476 /* Check it isn't doing very strange things with descriptor numbers. */
bb6834cf 477 if (num_heads > vq->vring.num) {
4355c1ab 478 virtio_error(vq->vdev, "Guest moved used index from %u to %u",
be1fea9b 479 idx, vq->shadow_avail_idx);
4355c1ab 480 return -EINVAL;
bb6834cf 481 }
a821ce59
MT
482 /* On success, callers read a descriptor at vq->last_avail_idx.
483 * Make sure descriptor read does not bypass avail index read. */
484 if (num_heads) {
485 smp_rmb();
486 }
967f97fa
AL
487
488 return num_heads;
489}
490
97cd965c 491/* Called within rcu_read_lock(). */
fb1131b6
SH
492static bool virtqueue_get_head(VirtQueue *vq, unsigned int idx,
493 unsigned int *head)
967f97fa 494{
967f97fa
AL
495 /* Grab the next descriptor number they're advertising, and increment
496 * the index we've seen. */
fb1131b6 497 *head = vring_avail_ring(vq, idx % vq->vring.num);
967f97fa
AL
498
499 /* If their number is silly, that's a fatal mistake. */
fb1131b6
SH
500 if (*head >= vq->vring.num) {
501 virtio_error(vq->vdev, "Guest says index %u is available", *head);
502 return false;
bb6834cf 503 }
967f97fa 504
fb1131b6 505 return true;
967f97fa
AL
506}
507
412e0e81
SH
508enum {
509 VIRTQUEUE_READ_DESC_ERROR = -1,
510 VIRTQUEUE_READ_DESC_DONE = 0, /* end of chain */
511 VIRTQUEUE_READ_DESC_MORE = 1, /* more buffers in chain */
512};
967f97fa 513
412e0e81 514static int virtqueue_read_next_desc(VirtIODevice *vdev, VRingDesc *desc,
5eba0404 515 MemoryRegionCache *desc_cache, unsigned int max,
412e0e81
SH
516 unsigned int *next)
517{
967f97fa 518 /* If this descriptor says it doesn't chain, we're done. */
aa570d6f 519 if (!(desc->flags & VRING_DESC_F_NEXT)) {
412e0e81 520 return VIRTQUEUE_READ_DESC_DONE;
cee3ca00 521 }
967f97fa
AL
522
523 /* Check they're not leading us off end of descriptors. */
412e0e81 524 *next = desc->next;
967f97fa 525 /* Make sure compiler knows to grab that: we don't want it changing! */
b90d2f35 526 smp_wmb();
967f97fa 527
412e0e81
SH
528 if (*next >= max) {
529 virtio_error(vdev, "Desc next is %u", *next);
530 return VIRTQUEUE_READ_DESC_ERROR;
bb6834cf 531 }
967f97fa 532
5eba0404 533 vring_desc_read(vdev, desc, desc_cache, *next);
412e0e81 534 return VIRTQUEUE_READ_DESC_MORE;
967f97fa
AL
535}
536
0d8d7690 537void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
e1f7b481
MT
538 unsigned int *out_bytes,
539 unsigned max_in_bytes, unsigned max_out_bytes)
967f97fa 540{
9796d0ac
PB
541 VirtIODevice *vdev = vq->vdev;
542 unsigned int max, idx;
385ce95d 543 unsigned int total_bufs, in_total, out_total;
991976f7 544 VRingMemoryRegionCaches *caches;
5eba0404
PB
545 MemoryRegionCache indirect_desc_cache = MEMORY_REGION_CACHE_INVALID;
546 int64_t len = 0;
412e0e81 547 int rc;
967f97fa 548
991976f7 549 rcu_read_lock();
967f97fa 550 idx = vq->last_avail_idx;
efeea6d0 551 total_bufs = in_total = out_total = 0;
9796d0ac
PB
552
553 max = vq->vring.num;
991976f7
PB
554 caches = atomic_rcu_read(&vq->vring.caches);
555 if (caches->desc.len < max * sizeof(VRingDesc)) {
9796d0ac
PB
556 virtio_error(vdev, "Cannot map descriptor ring");
557 goto err;
558 }
559
4355c1ab 560 while ((rc = virtqueue_num_heads(vq, idx)) > 0) {
991976f7 561 MemoryRegionCache *desc_cache = &caches->desc;
9796d0ac 562 unsigned int num_bufs;
aa570d6f 563 VRingDesc desc;
b1c7c07f 564 unsigned int i;
967f97fa 565
efeea6d0 566 num_bufs = total_bufs;
fb1131b6
SH
567
568 if (!virtqueue_get_head(vq, idx++, &i)) {
569 goto err;
570 }
571
5eba0404 572 vring_desc_read(vdev, &desc, desc_cache, i);
efeea6d0 573
aa570d6f
PB
574 if (desc.flags & VRING_DESC_F_INDIRECT) {
575 if (desc.len % sizeof(VRingDesc)) {
d65abf85
SH
576 virtio_error(vdev, "Invalid size for indirect buffer table");
577 goto err;
efeea6d0
MM
578 }
579
580 /* If we've got too many, that implies a descriptor loop. */
581 if (num_bufs >= max) {
d65abf85
SH
582 virtio_error(vdev, "Looped descriptor");
583 goto err;
efeea6d0
MM
584 }
585
586 /* loop over the indirect descriptor table */
5eba0404
PB
587 len = address_space_cache_init(&indirect_desc_cache,
588 vdev->dma_as,
589 desc.addr, desc.len, false);
590 desc_cache = &indirect_desc_cache;
9796d0ac
PB
591 if (len < desc.len) {
592 virtio_error(vdev, "Cannot map indirect buffer");
593 goto err;
594 }
595
aa570d6f 596 max = desc.len / sizeof(VRingDesc);
1ae2757c 597 num_bufs = i = 0;
5eba0404 598 vring_desc_read(vdev, &desc, desc_cache, i);
efeea6d0
MM
599 }
600
967f97fa
AL
601 do {
602 /* If we've got too many, that implies a descriptor loop. */
5774cf98 603 if (++num_bufs > max) {
d65abf85
SH
604 virtio_error(vdev, "Looped descriptor");
605 goto err;
bb6834cf 606 }
967f97fa 607
aa570d6f
PB
608 if (desc.flags & VRING_DESC_F_WRITE) {
609 in_total += desc.len;
967f97fa 610 } else {
aa570d6f 611 out_total += desc.len;
967f97fa 612 }
e1f7b481
MT
613 if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
614 goto done;
615 }
412e0e81 616
5eba0404 617 rc = virtqueue_read_next_desc(vdev, &desc, desc_cache, max, &i);
412e0e81
SH
618 } while (rc == VIRTQUEUE_READ_DESC_MORE);
619
620 if (rc == VIRTQUEUE_READ_DESC_ERROR) {
621 goto err;
622 }
efeea6d0 623
5eba0404
PB
624 if (desc_cache == &indirect_desc_cache) {
625 address_space_cache_destroy(&indirect_desc_cache);
efeea6d0 626 total_bufs++;
9796d0ac
PB
627 } else {
628 total_bufs = num_bufs;
629 }
967f97fa 630 }
4355c1ab
SH
631
632 if (rc < 0) {
633 goto err;
634 }
635
e1f7b481 636done:
5eba0404 637 address_space_cache_destroy(&indirect_desc_cache);
0d8d7690
AS
638 if (in_bytes) {
639 *in_bytes = in_total;
640 }
641 if (out_bytes) {
642 *out_bytes = out_total;
643 }
991976f7 644 rcu_read_unlock();
d65abf85
SH
645 return;
646
647err:
648 in_total = out_total = 0;
649 goto done;
0d8d7690 650}
967f97fa 651
0d8d7690
AS
652int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
653 unsigned int out_bytes)
654{
655 unsigned int in_total, out_total;
656
e1f7b481
MT
657 virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
658 return in_bytes <= in_total && out_bytes <= out_total;
967f97fa
AL
659}
660
ec55da19
SH
661static bool virtqueue_map_desc(VirtIODevice *vdev, unsigned int *p_num_sg,
662 hwaddr *addr, struct iovec *iov,
3b3b0628
PB
663 unsigned int max_num_sg, bool is_write,
664 hwaddr pa, size_t sz)
665{
ec55da19 666 bool ok = false;
3b3b0628
PB
667 unsigned num_sg = *p_num_sg;
668 assert(num_sg <= max_num_sg);
669
1e7aed70 670 if (!sz) {
ec55da19
SH
671 virtio_error(vdev, "virtio: zero sized buffers are not allowed");
672 goto out;
1e7aed70
PP
673 }
674
3b3b0628
PB
675 while (sz) {
676 hwaddr len = sz;
677
678 if (num_sg == max_num_sg) {
ec55da19
SH
679 virtio_error(vdev, "virtio: too many write descriptors in "
680 "indirect table");
681 goto out;
3b3b0628
PB
682 }
683
8607f5c3
JW
684 iov[num_sg].iov_base = dma_memory_map(vdev->dma_as, pa, &len,
685 is_write ?
686 DMA_DIRECTION_FROM_DEVICE :
687 DMA_DIRECTION_TO_DEVICE);
973e7170 688 if (!iov[num_sg].iov_base) {
ec55da19
SH
689 virtio_error(vdev, "virtio: bogus descriptor or out of resources");
690 goto out;
973e7170
PP
691 }
692
3b3b0628
PB
693 iov[num_sg].iov_len = len;
694 addr[num_sg] = pa;
695
696 sz -= len;
697 pa += len;
698 num_sg++;
699 }
ec55da19
SH
700 ok = true;
701
702out:
3b3b0628 703 *p_num_sg = num_sg;
ec55da19
SH
704 return ok;
705}
706
707/* Only used by error code paths before we have a VirtQueueElement (therefore
708 * virtqueue_unmap_sg() can't be used). Assumes buffers weren't written to
709 * yet.
710 */
711static void virtqueue_undo_map_desc(unsigned int out_num, unsigned int in_num,
712 struct iovec *iov)
713{
714 unsigned int i;
715
716 for (i = 0; i < out_num + in_num; i++) {
717 int is_write = i >= out_num;
718
719 cpu_physical_memory_unmap(iov->iov_base, iov->iov_len, is_write, 0);
720 iov++;
721 }
3b3b0628
PB
722}
723
8607f5c3
JW
724static void virtqueue_map_iovec(VirtIODevice *vdev, struct iovec *sg,
725 hwaddr *addr, unsigned int *num_sg,
6bdc21c0 726 int is_write)
42fb2e07
KW
727{
728 unsigned int i;
a8170e5e 729 hwaddr len;
42fb2e07 730
8059feee 731 for (i = 0; i < *num_sg; i++) {
42fb2e07 732 len = sg[i].iov_len;
8607f5c3
JW
733 sg[i].iov_base = dma_memory_map(vdev->dma_as,
734 addr[i], &len, is_write ?
735 DMA_DIRECTION_FROM_DEVICE :
736 DMA_DIRECTION_TO_DEVICE);
8059feee 737 if (!sg[i].iov_base) {
1a285899 738 error_report("virtio: error trying to map MMIO memory");
42fb2e07
KW
739 exit(1);
740 }
3b3b0628
PB
741 if (len != sg[i].iov_len) {
742 error_report("virtio: unexpected memory split");
8059feee
MT
743 exit(1);
744 }
42fb2e07
KW
745 }
746}
747
8607f5c3 748void virtqueue_map(VirtIODevice *vdev, VirtQueueElement *elem)
8059feee 749{
6bdc21c0
MT
750 virtqueue_map_iovec(vdev, elem->in_sg, elem->in_addr, &elem->in_num, 1);
751 virtqueue_map_iovec(vdev, elem->out_sg, elem->out_addr, &elem->out_num, 0);
3724650d
PB
752}
753
bf91bd27 754static void *virtqueue_alloc_element(size_t sz, unsigned out_num, unsigned in_num)
3724650d
PB
755{
756 VirtQueueElement *elem;
757 size_t in_addr_ofs = QEMU_ALIGN_UP(sz, __alignof__(elem->in_addr[0]));
758 size_t out_addr_ofs = in_addr_ofs + in_num * sizeof(elem->in_addr[0]);
759 size_t out_addr_end = out_addr_ofs + out_num * sizeof(elem->out_addr[0]);
760 size_t in_sg_ofs = QEMU_ALIGN_UP(out_addr_end, __alignof__(elem->in_sg[0]));
761 size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]);
762 size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]);
763
764 assert(sz >= sizeof(VirtQueueElement));
765 elem = g_malloc(out_sg_end);
766 elem->out_num = out_num;
767 elem->in_num = in_num;
768 elem->in_addr = (void *)elem + in_addr_ofs;
769 elem->out_addr = (void *)elem + out_addr_ofs;
770 elem->in_sg = (void *)elem + in_sg_ofs;
771 elem->out_sg = (void *)elem + out_sg_ofs;
772 return elem;
8059feee
MT
773}
774
51b19ebe 775void *virtqueue_pop(VirtQueue *vq, size_t sz)
967f97fa 776{
5774cf98 777 unsigned int i, head, max;
991976f7 778 VRingMemoryRegionCaches *caches;
5eba0404
PB
779 MemoryRegionCache indirect_desc_cache = MEMORY_REGION_CACHE_INVALID;
780 MemoryRegionCache *desc_cache;
781 int64_t len;
cee3ca00 782 VirtIODevice *vdev = vq->vdev;
9796d0ac 783 VirtQueueElement *elem = NULL;
3b3b0628
PB
784 unsigned out_num, in_num;
785 hwaddr addr[VIRTQUEUE_MAX_SIZE];
786 struct iovec iov[VIRTQUEUE_MAX_SIZE];
aa570d6f 787 VRingDesc desc;
412e0e81 788 int rc;
967f97fa 789
f5ed3663
SH
790 if (unlikely(vdev->broken)) {
791 return NULL;
792 }
97cd965c
PB
793 rcu_read_lock();
794 if (virtio_queue_empty_rcu(vq)) {
795 goto done;
51b19ebe 796 }
be1fea9b
VM
797 /* Needed after virtio_queue_empty(), see comment in
798 * virtqueue_num_heads(). */
799 smp_rmb();
967f97fa
AL
800
801 /* When we start there are none of either input nor output. */
3b3b0628 802 out_num = in_num = 0;
967f97fa 803
5774cf98
MM
804 max = vq->vring.num;
805
afd9096e 806 if (vq->inuse >= vq->vring.num) {
ec55da19 807 virtio_error(vdev, "Virtqueue size exceeded");
97cd965c 808 goto done;
afd9096e
SH
809 }
810
fb1131b6 811 if (!virtqueue_get_head(vq, vq->last_avail_idx++, &head)) {
97cd965c 812 goto done;
fb1131b6
SH
813 }
814
95129d6f 815 if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
e9600c6c 816 vring_set_avail_event(vq, vq->last_avail_idx);
bcbabae8 817 }
efeea6d0 818
fb1131b6 819 i = head;
9796d0ac 820
991976f7
PB
821 caches = atomic_rcu_read(&vq->vring.caches);
822 if (caches->desc.len < max * sizeof(VRingDesc)) {
9796d0ac
PB
823 virtio_error(vdev, "Cannot map descriptor ring");
824 goto done;
825 }
826
991976f7 827 desc_cache = &caches->desc;
5eba0404 828 vring_desc_read(vdev, &desc, desc_cache, i);
aa570d6f
PB
829 if (desc.flags & VRING_DESC_F_INDIRECT) {
830 if (desc.len % sizeof(VRingDesc)) {
ec55da19 831 virtio_error(vdev, "Invalid size for indirect buffer table");
9796d0ac 832 goto done;
efeea6d0
MM
833 }
834
835 /* loop over the indirect descriptor table */
5eba0404
PB
836 len = address_space_cache_init(&indirect_desc_cache, vdev->dma_as,
837 desc.addr, desc.len, false);
838 desc_cache = &indirect_desc_cache;
9796d0ac
PB
839 if (len < desc.len) {
840 virtio_error(vdev, "Cannot map indirect buffer");
841 goto done;
842 }
843
aa570d6f 844 max = desc.len / sizeof(VRingDesc);
efeea6d0 845 i = 0;
5eba0404 846 vring_desc_read(vdev, &desc, desc_cache, i);
efeea6d0
MM
847 }
848
42fb2e07 849 /* Collect all the descriptors */
967f97fa 850 do {
ec55da19
SH
851 bool map_ok;
852
aa570d6f 853 if (desc.flags & VRING_DESC_F_WRITE) {
ec55da19
SH
854 map_ok = virtqueue_map_desc(vdev, &in_num, addr + out_num,
855 iov + out_num,
856 VIRTQUEUE_MAX_SIZE - out_num, true,
857 desc.addr, desc.len);
42fb2e07 858 } else {
3b3b0628 859 if (in_num) {
ec55da19
SH
860 virtio_error(vdev, "Incorrect order for descriptors");
861 goto err_undo_map;
c8eac1cf 862 }
ec55da19
SH
863 map_ok = virtqueue_map_desc(vdev, &out_num, addr, iov,
864 VIRTQUEUE_MAX_SIZE, false,
865 desc.addr, desc.len);
866 }
867 if (!map_ok) {
868 goto err_undo_map;
42fb2e07 869 }
967f97fa 870
967f97fa 871 /* If we've got too many, that implies a descriptor loop. */
3b3b0628 872 if ((in_num + out_num) > max) {
ec55da19
SH
873 virtio_error(vdev, "Looped descriptor");
874 goto err_undo_map;
bb6834cf 875 }
412e0e81 876
5eba0404 877 rc = virtqueue_read_next_desc(vdev, &desc, desc_cache, max, &i);
412e0e81
SH
878 } while (rc == VIRTQUEUE_READ_DESC_MORE);
879
880 if (rc == VIRTQUEUE_READ_DESC_ERROR) {
881 goto err_undo_map;
882 }
967f97fa 883
3b3b0628
PB
884 /* Now copy what we have collected and mapped */
885 elem = virtqueue_alloc_element(sz, out_num, in_num);
967f97fa 886 elem->index = head;
3b3b0628
PB
887 for (i = 0; i < out_num; i++) {
888 elem->out_addr[i] = addr[i];
889 elem->out_sg[i] = iov[i];
890 }
891 for (i = 0; i < in_num; i++) {
892 elem->in_addr[i] = addr[out_num + i];
893 elem->in_sg[i] = iov[out_num + i];
894 }
967f97fa
AL
895
896 vq->inuse++;
897
64979a4d 898 trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
9796d0ac 899done:
5eba0404 900 address_space_cache_destroy(&indirect_desc_cache);
991976f7 901 rcu_read_unlock();
9796d0ac 902
51b19ebe 903 return elem;
ec55da19
SH
904
905err_undo_map:
906 virtqueue_undo_map_desc(out_num, in_num, iov);
9796d0ac 907 goto done;
967f97fa
AL
908}
909
54e17709
YB
910/* virtqueue_drop_all:
911 * @vq: The #VirtQueue
912 * Drops all queued buffers and indicates them to the guest
913 * as if they are done. Useful when buffers can not be
914 * processed but must be returned to the guest.
915 */
916unsigned int virtqueue_drop_all(VirtQueue *vq)
917{
918 unsigned int dropped = 0;
919 VirtQueueElement elem = {};
920 VirtIODevice *vdev = vq->vdev;
921 bool fEventIdx = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
922
923 if (unlikely(vdev->broken)) {
924 return 0;
925 }
926
927 while (!virtio_queue_empty(vq) && vq->inuse < vq->vring.num) {
928 /* works similar to virtqueue_pop but does not map buffers
929 * and does not allocate any memory */
930 smp_rmb();
931 if (!virtqueue_get_head(vq, vq->last_avail_idx, &elem.index)) {
932 break;
933 }
934 vq->inuse++;
935 vq->last_avail_idx++;
936 if (fEventIdx) {
937 vring_set_avail_event(vq, vq->last_avail_idx);
938 }
939 /* immediately push the element, nothing to unmap
940 * as both in_num and out_num are set to 0 */
941 virtqueue_push(vq, &elem, 0);
942 dropped++;
943 }
944
945 return dropped;
946}
947
3724650d
PB
948/* Reading and writing a structure directly to QEMUFile is *awful*, but
949 * it is what QEMU has always done by mistake. We can change it sooner
950 * or later by bumping the version number of the affected vm states.
951 * In the meanwhile, since the in-memory layout of VirtQueueElement
952 * has changed, we need to marshal to and from the layout that was
953 * used before the change.
954 */
955typedef struct VirtQueueElementOld {
956 unsigned int index;
957 unsigned int out_num;
958 unsigned int in_num;
959 hwaddr in_addr[VIRTQUEUE_MAX_SIZE];
960 hwaddr out_addr[VIRTQUEUE_MAX_SIZE];
961 struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
962 struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
963} VirtQueueElementOld;
964
8607f5c3 965void *qemu_get_virtqueue_element(VirtIODevice *vdev, QEMUFile *f, size_t sz)
ab281c17 966{
3724650d
PB
967 VirtQueueElement *elem;
968 VirtQueueElementOld data;
969 int i;
970
971 qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
972
6bdc21c0
MT
973 /* TODO: teach all callers that this can fail, and return failure instead
974 * of asserting here.
975 * When we do, we might be able to re-enable NDEBUG below.
976 */
977#ifdef NDEBUG
978#error building with NDEBUG is not supported
979#endif
980 assert(ARRAY_SIZE(data.in_addr) >= data.in_num);
981 assert(ARRAY_SIZE(data.out_addr) >= data.out_num);
982
3724650d
PB
983 elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);
984 elem->index = data.index;
985
986 for (i = 0; i < elem->in_num; i++) {
987 elem->in_addr[i] = data.in_addr[i];
988 }
989
990 for (i = 0; i < elem->out_num; i++) {
991 elem->out_addr[i] = data.out_addr[i];
992 }
993
994 for (i = 0; i < elem->in_num; i++) {
995 /* Base is overwritten by virtqueue_map. */
996 elem->in_sg[i].iov_base = 0;
997 elem->in_sg[i].iov_len = data.in_sg[i].iov_len;
998 }
999
1000 for (i = 0; i < elem->out_num; i++) {
1001 /* Base is overwritten by virtqueue_map. */
1002 elem->out_sg[i].iov_base = 0;
1003 elem->out_sg[i].iov_len = data.out_sg[i].iov_len;
1004 }
1005
8607f5c3 1006 virtqueue_map(vdev, elem);
ab281c17
PB
1007 return elem;
1008}
1009
1010void qemu_put_virtqueue_element(QEMUFile *f, VirtQueueElement *elem)
1011{
3724650d
PB
1012 VirtQueueElementOld data;
1013 int i;
1014
1015 memset(&data, 0, sizeof(data));
1016 data.index = elem->index;
1017 data.in_num = elem->in_num;
1018 data.out_num = elem->out_num;
1019
1020 for (i = 0; i < elem->in_num; i++) {
1021 data.in_addr[i] = elem->in_addr[i];
1022 }
1023
1024 for (i = 0; i < elem->out_num; i++) {
1025 data.out_addr[i] = elem->out_addr[i];
1026 }
1027
1028 for (i = 0; i < elem->in_num; i++) {
1029 /* Base is overwritten by virtqueue_map when loading. Do not
1030 * save it, as it would leak the QEMU address space layout. */
1031 data.in_sg[i].iov_len = elem->in_sg[i].iov_len;
1032 }
1033
1034 for (i = 0; i < elem->out_num; i++) {
1035 /* Do not save iov_base as above. */
1036 data.out_sg[i].iov_len = elem->out_sg[i].iov_len;
1037 }
1038 qemu_put_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
ab281c17
PB
1039}
1040
967f97fa 1041/* virtio device */
7055e687
MT
1042static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
1043{
1c819449
FK
1044 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1045 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1046
f5ed3663
SH
1047 if (unlikely(vdev->broken)) {
1048 return;
1049 }
1050
1c819449
FK
1051 if (k->notify) {
1052 k->notify(qbus->parent, vector);
7055e687
MT
1053 }
1054}
967f97fa 1055
53c25cea 1056void virtio_update_irq(VirtIODevice *vdev)
967f97fa 1057{
7055e687 1058 virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
967f97fa
AL
1059}
1060
0b352fd6
CH
1061static int virtio_validate_features(VirtIODevice *vdev)
1062{
1063 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1064
8607f5c3
JW
1065 if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM) &&
1066 !virtio_vdev_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {
1067 return -EFAULT;
1068 }
1069
0b352fd6
CH
1070 if (k->validate_features) {
1071 return k->validate_features(vdev);
1072 } else {
1073 return 0;
1074 }
1075}
1076
1077int virtio_set_status(VirtIODevice *vdev, uint8_t val)
4e1837f8 1078{
181103cd 1079 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
4e1837f8
SH
1080 trace_virtio_set_status(vdev, val);
1081
95129d6f 1082 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
0b352fd6
CH
1083 if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
1084 val & VIRTIO_CONFIG_S_FEATURES_OK) {
1085 int ret = virtio_validate_features(vdev);
1086
1087 if (ret) {
1088 return ret;
1089 }
1090 }
1091 }
181103cd
FK
1092 if (k->set_status) {
1093 k->set_status(vdev, val);
4e1837f8
SH
1094 }
1095 vdev->status = val;
0b352fd6 1096 return 0;
4e1837f8
SH
1097}
1098
616a6552
GK
1099bool target_words_bigendian(void);
1100static enum virtio_device_endian virtio_default_endian(void)
1101{
1102 if (target_words_bigendian()) {
1103 return VIRTIO_DEVICE_ENDIAN_BIG;
1104 } else {
1105 return VIRTIO_DEVICE_ENDIAN_LITTLE;
1106 }
1107}
1108
1109static enum virtio_device_endian virtio_current_cpu_endian(void)
1110{
1111 CPUClass *cc = CPU_GET_CLASS(current_cpu);
1112
1113 if (cc->virtio_is_big_endian(current_cpu)) {
1114 return VIRTIO_DEVICE_ENDIAN_BIG;
1115 } else {
1116 return VIRTIO_DEVICE_ENDIAN_LITTLE;
1117 }
1118}
1119
53c25cea 1120void virtio_reset(void *opaque)
967f97fa
AL
1121{
1122 VirtIODevice *vdev = opaque;
181103cd 1123 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1124 int i;
1125
e0c472d8 1126 virtio_set_status(vdev, 0);
616a6552
GK
1127 if (current_cpu) {
1128 /* Guest initiated reset */
1129 vdev->device_endian = virtio_current_cpu_endian();
1130 } else {
1131 /* System reset */
1132 vdev->device_endian = virtio_default_endian();
1133 }
e0c472d8 1134
181103cd
FK
1135 if (k->reset) {
1136 k->reset(vdev);
1137 }
967f97fa 1138
f5ed3663 1139 vdev->broken = false;
704a76fc 1140 vdev->guest_features = 0;
967f97fa
AL
1141 vdev->queue_sel = 0;
1142 vdev->status = 0;
0687c37c 1143 atomic_set(&vdev->isr, 0);
7055e687
MT
1144 vdev->config_vector = VIRTIO_NO_VECTOR;
1145 virtio_notify_vector(vdev, vdev->config_vector);
967f97fa 1146
87b3bd1c 1147 for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
967f97fa
AL
1148 vdev->vq[i].vring.desc = 0;
1149 vdev->vq[i].vring.avail = 0;
1150 vdev->vq[i].vring.used = 0;
1151 vdev->vq[i].last_avail_idx = 0;
be1fea9b 1152 vdev->vq[i].shadow_avail_idx = 0;
b796fcd1 1153 vdev->vq[i].used_idx = 0;
e0d686bf 1154 virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
bcbabae8
MT
1155 vdev->vq[i].signalled_used = 0;
1156 vdev->vq[i].signalled_used_valid = false;
332fa82d 1157 vdev->vq[i].notification = true;
46c5d082 1158 vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
4b7f91ed 1159 vdev->vq[i].inuse = 0;
967f97fa
AL
1160 }
1161}
1162
53c25cea 1163uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
967f97fa 1164{
181103cd 1165 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1166 uint8_t val;
1167
5f5a1318 1168 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1169 return (uint32_t)-1;
5f5a1318
JW
1170 }
1171
1172 k->get_config(vdev, vdev->config);
967f97fa 1173
06dbfc6f 1174 val = ldub_p(vdev->config + addr);
967f97fa
AL
1175 return val;
1176}
1177
53c25cea 1178uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
967f97fa 1179{
181103cd 1180 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1181 uint16_t val;
1182
5f5a1318 1183 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1184 return (uint32_t)-1;
5f5a1318
JW
1185 }
1186
1187 k->get_config(vdev, vdev->config);
967f97fa 1188
06dbfc6f 1189 val = lduw_p(vdev->config + addr);
967f97fa
AL
1190 return val;
1191}
1192
53c25cea 1193uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
967f97fa 1194{
181103cd 1195 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1196 uint32_t val;
1197
5f5a1318 1198 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1199 return (uint32_t)-1;
5f5a1318
JW
1200 }
1201
1202 k->get_config(vdev, vdev->config);
967f97fa 1203
06dbfc6f 1204 val = ldl_p(vdev->config + addr);
967f97fa
AL
1205 return val;
1206}
1207
53c25cea 1208void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
967f97fa 1209{
181103cd 1210 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1211 uint8_t val = data;
1212
5f5a1318 1213 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1214 return;
5f5a1318 1215 }
967f97fa 1216
06dbfc6f 1217 stb_p(vdev->config + addr, val);
967f97fa 1218
181103cd
FK
1219 if (k->set_config) {
1220 k->set_config(vdev, vdev->config);
1221 }
967f97fa
AL
1222}
1223
53c25cea 1224void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
967f97fa 1225{
181103cd 1226 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1227 uint16_t val = data;
1228
5f5a1318 1229 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1230 return;
5f5a1318 1231 }
967f97fa 1232
06dbfc6f 1233 stw_p(vdev->config + addr, val);
967f97fa 1234
181103cd
FK
1235 if (k->set_config) {
1236 k->set_config(vdev, vdev->config);
1237 }
967f97fa
AL
1238}
1239
53c25cea 1240void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
967f97fa 1241{
181103cd 1242 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa
AL
1243 uint32_t val = data;
1244
5f5a1318 1245 if (addr + sizeof(val) > vdev->config_len) {
967f97fa 1246 return;
5f5a1318 1247 }
967f97fa 1248
06dbfc6f 1249 stl_p(vdev->config + addr, val);
967f97fa 1250
181103cd
FK
1251 if (k->set_config) {
1252 k->set_config(vdev, vdev->config);
1253 }
967f97fa
AL
1254}
1255
adfb743c
MT
1256uint32_t virtio_config_modern_readb(VirtIODevice *vdev, uint32_t addr)
1257{
1258 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1259 uint8_t val;
1260
1261 if (addr + sizeof(val) > vdev->config_len) {
1262 return (uint32_t)-1;
1263 }
1264
1265 k->get_config(vdev, vdev->config);
1266
1267 val = ldub_p(vdev->config + addr);
1268 return val;
1269}
1270
1271uint32_t virtio_config_modern_readw(VirtIODevice *vdev, uint32_t addr)
1272{
1273 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1274 uint16_t val;
1275
1276 if (addr + sizeof(val) > vdev->config_len) {
1277 return (uint32_t)-1;
1278 }
1279
1280 k->get_config(vdev, vdev->config);
1281
1282 val = lduw_le_p(vdev->config + addr);
1283 return val;
1284}
1285
1286uint32_t virtio_config_modern_readl(VirtIODevice *vdev, uint32_t addr)
1287{
1288 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1289 uint32_t val;
1290
1291 if (addr + sizeof(val) > vdev->config_len) {
1292 return (uint32_t)-1;
1293 }
1294
1295 k->get_config(vdev, vdev->config);
1296
1297 val = ldl_le_p(vdev->config + addr);
1298 return val;
1299}
1300
1301void virtio_config_modern_writeb(VirtIODevice *vdev,
1302 uint32_t addr, uint32_t data)
1303{
1304 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1305 uint8_t val = data;
1306
1307 if (addr + sizeof(val) > vdev->config_len) {
1308 return;
1309 }
1310
1311 stb_p(vdev->config + addr, val);
1312
1313 if (k->set_config) {
1314 k->set_config(vdev, vdev->config);
1315 }
1316}
1317
1318void virtio_config_modern_writew(VirtIODevice *vdev,
1319 uint32_t addr, uint32_t data)
1320{
1321 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1322 uint16_t val = data;
1323
1324 if (addr + sizeof(val) > vdev->config_len) {
1325 return;
1326 }
1327
1328 stw_le_p(vdev->config + addr, val);
1329
1330 if (k->set_config) {
1331 k->set_config(vdev, vdev->config);
1332 }
1333}
1334
1335void virtio_config_modern_writel(VirtIODevice *vdev,
1336 uint32_t addr, uint32_t data)
1337{
1338 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1339 uint32_t val = data;
1340
1341 if (addr + sizeof(val) > vdev->config_len) {
1342 return;
1343 }
1344
1345 stl_le_p(vdev->config + addr, val);
1346
1347 if (k->set_config) {
1348 k->set_config(vdev, vdev->config);
1349 }
1350}
1351
a8170e5e 1352void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
967f97fa 1353{
ab223c95
CH
1354 vdev->vq[n].vring.desc = addr;
1355 virtio_queue_update_rings(vdev, n);
53c25cea
PB
1356}
1357
a8170e5e 1358hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
53c25cea 1359{
ab223c95
CH
1360 return vdev->vq[n].vring.desc;
1361}
1362
1363void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
1364 hwaddr avail, hwaddr used)
1365{
1366 vdev->vq[n].vring.desc = desc;
1367 vdev->vq[n].vring.avail = avail;
1368 vdev->vq[n].vring.used = used;
c611c764 1369 virtio_init_region_cache(vdev, n);
53c25cea
PB
1370}
1371
e63c0ba1
PM
1372void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
1373{
f6049f44
PM
1374 /* Don't allow guest to flip queue between existent and
1375 * nonexistent states, or to set it to an invalid size.
1376 */
1377 if (!!num != !!vdev->vq[n].vring.num ||
1378 num > VIRTQUEUE_MAX_SIZE ||
1379 num < 0) {
1380 return;
e63c0ba1 1381 }
f6049f44 1382 vdev->vq[n].vring.num = num;
e63c0ba1
PM
1383}
1384
e0d686bf
JW
1385VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
1386{
1387 return QLIST_FIRST(&vdev->vector_queues[vector]);
1388}
1389
1390VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
1391{
1392 return QLIST_NEXT(vq, node);
1393}
1394
53c25cea
PB
1395int virtio_queue_get_num(VirtIODevice *vdev, int n)
1396{
1397 return vdev->vq[n].vring.num;
1398}
967f97fa 1399
8c797e75
MT
1400int virtio_queue_get_max_num(VirtIODevice *vdev, int n)
1401{
1402 return vdev->vq[n].vring.num_default;
1403}
1404
8ad176aa
JW
1405int virtio_get_num_queues(VirtIODevice *vdev)
1406{
1407 int i;
1408
87b3bd1c 1409 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
8ad176aa
JW
1410 if (!virtio_queue_get_num(vdev, i)) {
1411 break;
1412 }
1413 }
1414
1415 return i;
1416}
1417
6ce69d1c
PM
1418void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
1419{
1420 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1421 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1422
ab223c95 1423 /* virtio-1 compliant devices cannot change the alignment */
95129d6f 1424 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
ab223c95
CH
1425 error_report("tried to modify queue alignment for virtio-1 device");
1426 return;
1427 }
6ce69d1c
PM
1428 /* Check that the transport told us it was going to do this
1429 * (so a buggy transport will immediately assert rather than
1430 * silently failing to migrate this state)
1431 */
1432 assert(k->has_variable_vring_alignment);
1433
1434 vdev->vq[n].vring.align = align;
ab223c95 1435 virtio_queue_update_rings(vdev, n);
6ce69d1c
PM
1436}
1437
07931698 1438static bool virtio_queue_notify_aio_vq(VirtQueue *vq)
344dc16f
MT
1439{
1440 if (vq->vring.desc && vq->handle_aio_output) {
1441 VirtIODevice *vdev = vq->vdev;
1442
1443 trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
07931698 1444 return vq->handle_aio_output(vdev, vq);
344dc16f 1445 }
07931698
FZ
1446
1447 return false;
344dc16f
MT
1448}
1449
2b2cbcad 1450static void virtio_queue_notify_vq(VirtQueue *vq)
25db9ebe 1451{
9e0f5b81 1452 if (vq->vring.desc && vq->handle_output) {
25db9ebe 1453 VirtIODevice *vdev = vq->vdev;
9e0f5b81 1454
f5ed3663
SH
1455 if (unlikely(vdev->broken)) {
1456 return;
1457 }
1458
25db9ebe
SH
1459 trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1460 vq->handle_output(vdev, vq);
1461 }
1462}
1463
53c25cea
PB
1464void virtio_queue_notify(VirtIODevice *vdev, int n)
1465{
7157e2e2 1466 virtio_queue_notify_vq(&vdev->vq[n]);
967f97fa
AL
1467}
1468
7055e687
MT
1469uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
1470{
87b3bd1c 1471 return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
7055e687
MT
1472 VIRTIO_NO_VECTOR;
1473}
1474
1475void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
1476{
e0d686bf
JW
1477 VirtQueue *vq = &vdev->vq[n];
1478
87b3bd1c 1479 if (n < VIRTIO_QUEUE_MAX) {
e0d686bf
JW
1480 if (vdev->vector_queues &&
1481 vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
1482 QLIST_REMOVE(vq, node);
1483 }
7055e687 1484 vdev->vq[n].vector = vector;
e0d686bf
JW
1485 if (vdev->vector_queues &&
1486 vector != VIRTIO_NO_VECTOR) {
1487 QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
1488 }
1489 }
7055e687
MT
1490}
1491
f1ac6a55
PB
1492VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
1493 VirtIOHandleOutput handle_output)
967f97fa
AL
1494{
1495 int i;
1496
87b3bd1c 1497 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
967f97fa
AL
1498 if (vdev->vq[i].vring.num == 0)
1499 break;
1500 }
1501
87b3bd1c 1502 if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
967f97fa
AL
1503 abort();
1504
1505 vdev->vq[i].vring.num = queue_size;
46c5d082 1506 vdev->vq[i].vring.num_default = queue_size;
6ce69d1c 1507 vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
967f97fa 1508 vdev->vq[i].handle_output = handle_output;
344dc16f 1509 vdev->vq[i].handle_aio_output = NULL;
967f97fa
AL
1510
1511 return &vdev->vq[i];
1512}
1513
f23fd811
JW
1514void virtio_del_queue(VirtIODevice *vdev, int n)
1515{
87b3bd1c 1516 if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
f23fd811
JW
1517 abort();
1518 }
1519
1520 vdev->vq[n].vring.num = 0;
46c5d082 1521 vdev->vq[n].vring.num_default = 0;
f23fd811
JW
1522}
1523
0687c37c
PB
1524static void virtio_set_isr(VirtIODevice *vdev, int value)
1525{
1526 uint8_t old = atomic_read(&vdev->isr);
1527
1528 /* Do not write ISR if it does not change, so that its cacheline remains
1529 * shared in the common case where the guest does not read it.
1530 */
1531 if ((old & value) != value) {
1532 atomic_or(&vdev->isr, value);
1533 }
1534}
1535
97cd965c 1536/* Called within rcu_read_lock(). */
c25d97c4 1537static bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
bcbabae8
MT
1538{
1539 uint16_t old, new;
1540 bool v;
a281ebc1
MT
1541 /* We need to expose used array entries before checking used event. */
1542 smp_mb();
97b83deb 1543 /* Always notify when queue is empty (when feature acknowledge) */
95129d6f 1544 if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
be1fea9b 1545 !vq->inuse && virtio_queue_empty(vq)) {
bcbabae8
MT
1546 return true;
1547 }
1548
95129d6f 1549 if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
bcbabae8
MT
1550 return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
1551 }
1552
1553 v = vq->signalled_used_valid;
1554 vq->signalled_used_valid = true;
1555 old = vq->signalled_used;
b796fcd1 1556 new = vq->signalled_used = vq->used_idx;
e9600c6c 1557 return !v || vring_need_event(vring_get_used_event(vq), new, old);
bcbabae8
MT
1558}
1559
83d768b5
PB
1560void virtio_notify_irqfd(VirtIODevice *vdev, VirtQueue *vq)
1561{
97cd965c
PB
1562 bool should_notify;
1563 rcu_read_lock();
1564 should_notify = virtio_should_notify(vdev, vq);
1565 rcu_read_unlock();
1566
1567 if (!should_notify) {
83d768b5
PB
1568 return;
1569 }
1570
1571 trace_virtio_notify_irqfd(vdev, vq);
1572
1573 /*
1574 * virtio spec 1.0 says ISR bit 0 should be ignored with MSI, but
1575 * windows drivers included in virtio-win 1.8.0 (circa 2015) are
1576 * incorrectly polling this bit during crashdump and hibernation
1577 * in MSI mode, causing a hang if this bit is never updated.
1578 * Recent releases of Windows do not really shut down, but rather
1579 * log out and hibernate to make the next startup faster. Hence,
1580 * this manifested as a more serious hang during shutdown with
1581 *
1582 * Next driver release from 2016 fixed this problem, so working around it
1583 * is not a must, but it's easy to do so let's do it here.
1584 *
1585 * Note: it's safe to update ISR from any thread as it was switched
1586 * to an atomic operation.
1587 */
1588 virtio_set_isr(vq->vdev, 0x1);
1589 event_notifier_set(&vq->guest_notifier);
1590}
1591
b4b9862b
MT
1592static void virtio_irq(VirtQueue *vq)
1593{
1594 virtio_set_isr(vq->vdev, 0x1);
1595 virtio_notify_vector(vq->vdev, vq->vector);
1596}
1597
bcbabae8
MT
1598void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
1599{
97cd965c
PB
1600 bool should_notify;
1601 rcu_read_lock();
1602 should_notify = virtio_should_notify(vdev, vq);
1603 rcu_read_unlock();
1604
1605 if (!should_notify) {
967f97fa 1606 return;
bcbabae8 1607 }
967f97fa 1608
64979a4d 1609 trace_virtio_notify(vdev, vq);
b4b9862b 1610 virtio_irq(vq);
967f97fa
AL
1611}
1612
1613void virtio_notify_config(VirtIODevice *vdev)
1614{
7625162c
AL
1615 if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
1616 return;
1617
0687c37c 1618 virtio_set_isr(vdev, 0x3);
b8f05908 1619 vdev->generation++;
7055e687 1620 virtio_notify_vector(vdev, vdev->config_vector);
967f97fa
AL
1621}
1622
616a6552
GK
1623static bool virtio_device_endian_needed(void *opaque)
1624{
1625 VirtIODevice *vdev = opaque;
1626
1627 assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
95129d6f 1628 if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3c185597
CH
1629 return vdev->device_endian != virtio_default_endian();
1630 }
1631 /* Devices conforming to VIRTIO 1.0 or later are always LE. */
1632 return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
616a6552
GK
1633}
1634
019a3edb
GH
1635static bool virtio_64bit_features_needed(void *opaque)
1636{
1637 VirtIODevice *vdev = opaque;
1638
1639 return (vdev->host_features >> 32) != 0;
1640}
1641
74aae7b2
JW
1642static bool virtio_virtqueue_needed(void *opaque)
1643{
1644 VirtIODevice *vdev = opaque;
1645
1646 return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
1647}
1648
46c5d082
CH
1649static bool virtio_ringsize_needed(void *opaque)
1650{
1651 VirtIODevice *vdev = opaque;
1652 int i;
1653
1654 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1655 if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
1656 return true;
1657 }
1658 }
1659 return false;
1660}
1661
a6df8adf
JW
1662static bool virtio_extra_state_needed(void *opaque)
1663{
1664 VirtIODevice *vdev = opaque;
1665 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1666 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1667
1668 return k->has_extra_state &&
1669 k->has_extra_state(qbus->parent);
1670}
1671
791b1daf
SH
1672static bool virtio_broken_needed(void *opaque)
1673{
1674 VirtIODevice *vdev = opaque;
1675
1676 return vdev->broken;
1677}
1678
50e5ae4d 1679static const VMStateDescription vmstate_virtqueue = {
74aae7b2 1680 .name = "virtqueue_state",
50e5ae4d
DDAG
1681 .version_id = 1,
1682 .minimum_version_id = 1,
1683 .fields = (VMStateField[]) {
1684 VMSTATE_UINT64(vring.avail, struct VirtQueue),
1685 VMSTATE_UINT64(vring.used, struct VirtQueue),
1686 VMSTATE_END_OF_LIST()
1687 }
74aae7b2
JW
1688};
1689
1690static const VMStateDescription vmstate_virtio_virtqueues = {
1691 .name = "virtio/virtqueues",
1692 .version_id = 1,
1693 .minimum_version_id = 1,
1694 .needed = &virtio_virtqueue_needed,
1695 .fields = (VMStateField[]) {
3e996cc5
DDAG
1696 VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1697 VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
74aae7b2
JW
1698 VMSTATE_END_OF_LIST()
1699 }
1700};
1701
50e5ae4d 1702static const VMStateDescription vmstate_ringsize = {
46c5d082 1703 .name = "ringsize_state",
50e5ae4d
DDAG
1704 .version_id = 1,
1705 .minimum_version_id = 1,
1706 .fields = (VMStateField[]) {
1707 VMSTATE_UINT32(vring.num_default, struct VirtQueue),
1708 VMSTATE_END_OF_LIST()
1709 }
46c5d082
CH
1710};
1711
1712static const VMStateDescription vmstate_virtio_ringsize = {
1713 .name = "virtio/ringsize",
1714 .version_id = 1,
1715 .minimum_version_id = 1,
1716 .needed = &virtio_ringsize_needed,
1717 .fields = (VMStateField[]) {
3e996cc5
DDAG
1718 VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1719 VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
46c5d082
CH
1720 VMSTATE_END_OF_LIST()
1721 }
1722};
1723
2c21ee76
JD
1724static int get_extra_state(QEMUFile *f, void *pv, size_t size,
1725 VMStateField *field)
a6df8adf
JW
1726{
1727 VirtIODevice *vdev = pv;
1728 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1729 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1730
1731 if (!k->load_extra_state) {
1732 return -1;
1733 } else {
1734 return k->load_extra_state(qbus->parent, f);
1735 }
1736}
1737
2c21ee76
JD
1738static int put_extra_state(QEMUFile *f, void *pv, size_t size,
1739 VMStateField *field, QJSON *vmdesc)
a6df8adf
JW
1740{
1741 VirtIODevice *vdev = pv;
1742 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1743 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1744
1745 k->save_extra_state(qbus->parent, f);
2c21ee76 1746 return 0;
a6df8adf
JW
1747}
1748
1749static const VMStateInfo vmstate_info_extra_state = {
1750 .name = "virtqueue_extra_state",
1751 .get = get_extra_state,
1752 .put = put_extra_state,
1753};
1754
1755static const VMStateDescription vmstate_virtio_extra_state = {
1756 .name = "virtio/extra_state",
1757 .version_id = 1,
1758 .minimum_version_id = 1,
1759 .needed = &virtio_extra_state_needed,
1760 .fields = (VMStateField[]) {
1761 {
1762 .name = "extra_state",
1763 .version_id = 0,
1764 .field_exists = NULL,
1765 .size = 0,
1766 .info = &vmstate_info_extra_state,
1767 .flags = VMS_SINGLE,
1768 .offset = 0,
1769 },
1770 VMSTATE_END_OF_LIST()
1771 }
1772};
1773
616a6552
GK
1774static const VMStateDescription vmstate_virtio_device_endian = {
1775 .name = "virtio/device_endian",
1776 .version_id = 1,
1777 .minimum_version_id = 1,
5cd8cada 1778 .needed = &virtio_device_endian_needed,
616a6552
GK
1779 .fields = (VMStateField[]) {
1780 VMSTATE_UINT8(device_endian, VirtIODevice),
1781 VMSTATE_END_OF_LIST()
1782 }
1783};
1784
019a3edb
GH
1785static const VMStateDescription vmstate_virtio_64bit_features = {
1786 .name = "virtio/64bit_features",
1787 .version_id = 1,
1788 .minimum_version_id = 1,
5cd8cada 1789 .needed = &virtio_64bit_features_needed,
019a3edb
GH
1790 .fields = (VMStateField[]) {
1791 VMSTATE_UINT64(guest_features, VirtIODevice),
1792 VMSTATE_END_OF_LIST()
1793 }
1794};
1795
791b1daf
SH
1796static const VMStateDescription vmstate_virtio_broken = {
1797 .name = "virtio/broken",
1798 .version_id = 1,
1799 .minimum_version_id = 1,
1800 .needed = &virtio_broken_needed,
1801 .fields = (VMStateField[]) {
1802 VMSTATE_BOOL(broken, VirtIODevice),
1803 VMSTATE_END_OF_LIST()
1804 }
1805};
1806
6b321a3d
GK
1807static const VMStateDescription vmstate_virtio = {
1808 .name = "virtio",
1809 .version_id = 1,
1810 .minimum_version_id = 1,
1811 .minimum_version_id_old = 1,
1812 .fields = (VMStateField[]) {
1813 VMSTATE_END_OF_LIST()
616a6552 1814 },
5cd8cada
JQ
1815 .subsections = (const VMStateDescription*[]) {
1816 &vmstate_virtio_device_endian,
1817 &vmstate_virtio_64bit_features,
74aae7b2 1818 &vmstate_virtio_virtqueues,
46c5d082 1819 &vmstate_virtio_ringsize,
791b1daf 1820 &vmstate_virtio_broken,
a6df8adf 1821 &vmstate_virtio_extra_state,
5cd8cada 1822 NULL
6b321a3d
GK
1823 }
1824};
1825
967f97fa
AL
1826void virtio_save(VirtIODevice *vdev, QEMUFile *f)
1827{
1c819449
FK
1828 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1829 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1b5fc0de 1830 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
019a3edb 1831 uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
967f97fa
AL
1832 int i;
1833
1c819449
FK
1834 if (k->save_config) {
1835 k->save_config(qbus->parent, f);
1836 }
967f97fa 1837
967f97fa
AL
1838 qemu_put_8s(f, &vdev->status);
1839 qemu_put_8s(f, &vdev->isr);
1840 qemu_put_be16s(f, &vdev->queue_sel);
019a3edb 1841 qemu_put_be32s(f, &guest_features_lo);
967f97fa
AL
1842 qemu_put_be32(f, vdev->config_len);
1843 qemu_put_buffer(f, vdev->config, vdev->config_len);
1844
87b3bd1c 1845 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
967f97fa
AL
1846 if (vdev->vq[i].vring.num == 0)
1847 break;
1848 }
1849
1850 qemu_put_be32(f, i);
1851
87b3bd1c 1852 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
967f97fa
AL
1853 if (vdev->vq[i].vring.num == 0)
1854 break;
1855
1856 qemu_put_be32(f, vdev->vq[i].vring.num);
6ce69d1c
PM
1857 if (k->has_variable_vring_alignment) {
1858 qemu_put_be32(f, vdev->vq[i].vring.align);
1859 }
874adf45
SH
1860 /*
1861 * Save desc now, the rest of the ring addresses are saved in
1862 * subsections for VIRTIO-1 devices.
1863 */
ab223c95 1864 qemu_put_be64(f, vdev->vq[i].vring.desc);
967f97fa 1865 qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
1c819449
FK
1866 if (k->save_queue) {
1867 k->save_queue(qbus->parent, i, f);
1868 }
967f97fa 1869 }
1b5fc0de
GK
1870
1871 if (vdc->save != NULL) {
1872 vdc->save(vdev, f);
1873 }
6b321a3d 1874
ea43e259
DDAG
1875 if (vdc->vmsd) {
1876 vmstate_save_state(f, vdc->vmsd, vdev, NULL);
1877 }
1878
6b321a3d 1879 /* Subsections */
8118f095 1880 vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
967f97fa
AL
1881}
1882
1a665855 1883/* A wrapper for use as a VMState .put function */
2c21ee76
JD
1884static int virtio_device_put(QEMUFile *f, void *opaque, size_t size,
1885 VMStateField *field, QJSON *vmdesc)
1a665855
HP
1886{
1887 virtio_save(VIRTIO_DEVICE(opaque), f);
2c21ee76
JD
1888
1889 return 0;
1a665855
HP
1890}
1891
1892/* A wrapper for use as a VMState .get function */
2c21ee76
JD
1893static int virtio_device_get(QEMUFile *f, void *opaque, size_t size,
1894 VMStateField *field)
1a665855
HP
1895{
1896 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1897 DeviceClass *dc = DEVICE_CLASS(VIRTIO_DEVICE_GET_CLASS(vdev));
1898
1899 return virtio_load(vdev, f, dc->vmsd->version_id);
1900}
1901
1902const VMStateInfo virtio_vmstate_info = {
1903 .name = "virtio",
1904 .get = virtio_device_get,
1905 .put = virtio_device_put,
1906};
1907
6c0196d7 1908static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
ad0c9332 1909{
181103cd 1910 VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
6b8f1020 1911 bool bad = (val & ~(vdev->host_features)) != 0;
ad0c9332 1912
6b8f1020 1913 val &= vdev->host_features;
181103cd
FK
1914 if (k->set_features) {
1915 k->set_features(vdev, val);
ad0c9332
PB
1916 }
1917 vdev->guest_features = val;
1918 return bad ? -1 : 0;
1919}
1920
6c0196d7
CH
1921int virtio_set_features(VirtIODevice *vdev, uint64_t val)
1922{
1923 /*
1924 * The driver must not attempt to set features after feature negotiation
1925 * has finished.
1926 */
1927 if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
1928 return -EINVAL;
1929 }
1930 return virtio_set_features_nocheck(vdev, val);
1931}
1932
1b5fc0de 1933int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
967f97fa 1934{
cc459952 1935 int i, ret;
a890a2f9 1936 int32_t config_len;
cc459952 1937 uint32_t num;
6d74ca5a 1938 uint32_t features;
1c819449
FK
1939 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1940 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1b5fc0de 1941 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
967f97fa 1942
616a6552
GK
1943 /*
1944 * We poison the endianness to ensure it does not get used before
1945 * subsections have been loaded.
1946 */
1947 vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
1948
1c819449
FK
1949 if (k->load_config) {
1950 ret = k->load_config(qbus->parent, f);
ff24bd58
MT
1951 if (ret)
1952 return ret;
1953 }
967f97fa 1954
967f97fa
AL
1955 qemu_get_8s(f, &vdev->status);
1956 qemu_get_8s(f, &vdev->isr);
1957 qemu_get_be16s(f, &vdev->queue_sel);
87b3bd1c 1958 if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
4b53c2c7
MR
1959 return -1;
1960 }
6d74ca5a 1961 qemu_get_be32s(f, &features);
ad0c9332 1962
62cee1a2
MT
1963 /*
1964 * Temporarily set guest_features low bits - needed by
1965 * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
1966 * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
1967 *
1968 * Note: devices should always test host features in future - don't create
1969 * new dependencies like this.
1970 */
1971 vdev->guest_features = features;
1972
a890a2f9 1973 config_len = qemu_get_be32(f);
2f5732e9
DDAG
1974
1975 /*
1976 * There are cases where the incoming config can be bigger or smaller
1977 * than what we have; so load what we have space for, and skip
1978 * any excess that's in the stream.
1979 */
1980 qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
1981
1982 while (config_len > vdev->config_len) {
1983 qemu_get_byte(f);
1984 config_len--;
a890a2f9 1985 }
967f97fa
AL
1986
1987 num = qemu_get_be32(f);
1988
87b3bd1c 1989 if (num > VIRTIO_QUEUE_MAX) {
8a1be662 1990 error_report("Invalid number of virtqueues: 0x%x", num);
cc459952
MT
1991 return -1;
1992 }
1993
967f97fa
AL
1994 for (i = 0; i < num; i++) {
1995 vdev->vq[i].vring.num = qemu_get_be32(f);
6ce69d1c
PM
1996 if (k->has_variable_vring_alignment) {
1997 vdev->vq[i].vring.align = qemu_get_be32(f);
1998 }
ab223c95 1999 vdev->vq[i].vring.desc = qemu_get_be64(f);
967f97fa 2000 qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
bcbabae8 2001 vdev->vq[i].signalled_used_valid = false;
332fa82d 2002 vdev->vq[i].notification = true;
967f97fa 2003
874adf45 2004 if (!vdev->vq[i].vring.desc && vdev->vq[i].last_avail_idx) {
1abeb5a6 2005 error_report("VQ %d address 0x0 "
6daf194d 2006 "inconsistent with Host index 0x%x",
1abeb5a6 2007 i, vdev->vq[i].last_avail_idx);
874adf45 2008 return -1;
8275e2f6 2009 }
1c819449
FK
2010 if (k->load_queue) {
2011 ret = k->load_queue(qbus->parent, i, f);
ff24bd58
MT
2012 if (ret)
2013 return ret;
7055e687 2014 }
967f97fa
AL
2015 }
2016
7055e687 2017 virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
1b5fc0de
GK
2018
2019 if (vdc->load != NULL) {
6b321a3d
GK
2020 ret = vdc->load(vdev, f, version_id);
2021 if (ret) {
2022 return ret;
2023 }
1b5fc0de
GK
2024 }
2025
ea43e259
DDAG
2026 if (vdc->vmsd) {
2027 ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id);
2028 if (ret) {
2029 return ret;
2030 }
2031 }
2032
616a6552
GK
2033 /* Subsections */
2034 ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
2035 if (ret) {
2036 return ret;
2037 }
2038
2039 if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
2040 vdev->device_endian = virtio_default_endian();
2041 }
2042
019a3edb
GH
2043 if (virtio_64bit_features_needed(vdev)) {
2044 /*
2045 * Subsection load filled vdev->guest_features. Run them
2046 * through virtio_set_features to sanity-check them against
2047 * host_features.
2048 */
2049 uint64_t features64 = vdev->guest_features;
6c0196d7 2050 if (virtio_set_features_nocheck(vdev, features64) < 0) {
019a3edb
GH
2051 error_report("Features 0x%" PRIx64 " unsupported. "
2052 "Allowed features: 0x%" PRIx64,
2053 features64, vdev->host_features);
2054 return -1;
2055 }
2056 } else {
6c0196d7 2057 if (virtio_set_features_nocheck(vdev, features) < 0) {
019a3edb
GH
2058 error_report("Features 0x%x unsupported. "
2059 "Allowed features: 0x%" PRIx64,
2060 features, vdev->host_features);
2061 return -1;
2062 }
2063 }
2064
97cd965c 2065 rcu_read_lock();
616a6552 2066 for (i = 0; i < num; i++) {
ab223c95 2067 if (vdev->vq[i].vring.desc) {
616a6552 2068 uint16_t nheads;
874adf45
SH
2069
2070 /*
2071 * VIRTIO-1 devices migrate desc, used, and avail ring addresses so
2072 * only the region cache needs to be set up. Legacy devices need
2073 * to calculate used and avail ring addresses based on the desc
2074 * address.
2075 */
2076 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2077 virtio_init_region_cache(vdev, i);
2078 } else {
2079 virtio_queue_update_rings(vdev, i);
2080 }
2081
616a6552
GK
2082 nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
2083 /* Check it isn't doing strange things with descriptor numbers. */
2084 if (nheads > vdev->vq[i].vring.num) {
2085 error_report("VQ %d size 0x%x Guest index 0x%x "
2086 "inconsistent with Host index 0x%x: delta 0x%x",
2087 i, vdev->vq[i].vring.num,
2088 vring_avail_idx(&vdev->vq[i]),
2089 vdev->vq[i].last_avail_idx, nheads);
2090 return -1;
2091 }
b796fcd1 2092 vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
be1fea9b 2093 vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
bccdef6b
SH
2094
2095 /*
2096 * Some devices migrate VirtQueueElements that have been popped
2097 * from the avail ring but not yet returned to the used ring.
e66bcc40
HP
2098 * Since max ring size < UINT16_MAX it's safe to use modulo
2099 * UINT16_MAX + 1 subtraction.
bccdef6b 2100 */
e66bcc40
HP
2101 vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx -
2102 vdev->vq[i].used_idx);
bccdef6b
SH
2103 if (vdev->vq[i].inuse > vdev->vq[i].vring.num) {
2104 error_report("VQ %d size 0x%x < last_avail_idx 0x%x - "
2105 "used_idx 0x%x",
2106 i, vdev->vq[i].vring.num,
2107 vdev->vq[i].last_avail_idx,
2108 vdev->vq[i].used_idx);
2109 return -1;
2110 }
616a6552
GK
2111 }
2112 }
97cd965c 2113 rcu_read_unlock();
616a6552
GK
2114
2115 return 0;
967f97fa
AL
2116}
2117
6a1a8cc7 2118void virtio_cleanup(VirtIODevice *vdev)
b946a153 2119{
85cf2a8d 2120 qemu_del_vm_change_state_handler(vdev->vmstate);
8e05db92
FK
2121}
2122
1dfb4dd9 2123static void virtio_vmstate_change(void *opaque, int running, RunState state)
85cf2a8d
MT
2124{
2125 VirtIODevice *vdev = opaque;
1c819449
FK
2126 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2127 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
85cf2a8d 2128 bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
9e8e8c48 2129 vdev->vm_running = running;
85cf2a8d
MT
2130
2131 if (backend_run) {
2132 virtio_set_status(vdev, vdev->status);
2133 }
2134
1c819449
FK
2135 if (k->vmstate_change) {
2136 k->vmstate_change(qbus->parent, backend_run);
85cf2a8d
MT
2137 }
2138
2139 if (!backend_run) {
2140 virtio_set_status(vdev, vdev->status);
2141 }
2142}
2143
c8075caf
GA
2144void virtio_instance_init_common(Object *proxy_obj, void *data,
2145 size_t vdev_size, const char *vdev_name)
2146{
2147 DeviceState *vdev = data;
2148
2149 object_initialize(vdev, vdev_size, vdev_name);
2150 object_property_add_child(proxy_obj, "virtio-backend", OBJECT(vdev), NULL);
2151 object_unref(OBJECT(vdev));
2152 qdev_alias_all_properties(vdev, proxy_obj);
2153}
2154
8e05db92
FK
2155void virtio_init(VirtIODevice *vdev, const char *name,
2156 uint16_t device_id, size_t config_size)
967f97fa 2157{
e0d686bf
JW
2158 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2159 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
b8193adb 2160 int i;
e0d686bf
JW
2161 int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
2162
2163 if (nvectors) {
2164 vdev->vector_queues =
2165 g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
2166 }
2167
53c25cea 2168 vdev->device_id = device_id;
967f97fa 2169 vdev->status = 0;
0687c37c 2170 atomic_set(&vdev->isr, 0);
967f97fa 2171 vdev->queue_sel = 0;
7055e687 2172 vdev->config_vector = VIRTIO_NO_VECTOR;
87b3bd1c 2173 vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);
1354869c 2174 vdev->vm_running = runstate_is_running();
f5ed3663 2175 vdev->broken = false;
87b3bd1c 2176 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
b8193adb 2177 vdev->vq[i].vector = VIRTIO_NO_VECTOR;
1cbdabe2 2178 vdev->vq[i].vdev = vdev;
e78a2b42 2179 vdev->vq[i].queue_index = i;
1cbdabe2 2180 }
967f97fa 2181
967f97fa
AL
2182 vdev->name = name;
2183 vdev->config_len = config_size;
8e05db92 2184 if (vdev->config_len) {
7267c094 2185 vdev->config = g_malloc0(config_size);
8e05db92 2186 } else {
967f97fa 2187 vdev->config = NULL;
8e05db92
FK
2188 }
2189 vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
2190 vdev);
616a6552 2191 vdev->device_endian = virtio_default_endian();
5669655a 2192 vdev->use_guest_notifier_mask = true;
8e05db92 2193}
967f97fa 2194
a8170e5e 2195hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
1cbdabe2
MT
2196{
2197 return vdev->vq[n].vring.desc;
2198}
2199
a8170e5e 2200hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
1cbdabe2
MT
2201{
2202 return vdev->vq[n].vring.avail;
2203}
2204
a8170e5e 2205hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
1cbdabe2
MT
2206{
2207 return vdev->vq[n].vring.used;
2208}
2209
a8170e5e 2210hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
1cbdabe2
MT
2211{
2212 return sizeof(VRingDesc) * vdev->vq[n].vring.num;
2213}
2214
a8170e5e 2215hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
1cbdabe2
MT
2216{
2217 return offsetof(VRingAvail, ring) +
50764fc8 2218 sizeof(uint16_t) * vdev->vq[n].vring.num;
1cbdabe2
MT
2219}
2220
a8170e5e 2221hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
1cbdabe2
MT
2222{
2223 return offsetof(VRingUsed, ring) +
2224 sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
2225}
2226
1cbdabe2
MT
2227uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
2228{
2229 return vdev->vq[n].last_avail_idx;
2230}
2231
2232void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
2233{
2234 vdev->vq[n].last_avail_idx = idx;
be1fea9b 2235 vdev->vq[n].shadow_avail_idx = idx;
1cbdabe2
MT
2236}
2237
312d3b35
YB
2238void virtio_queue_update_used_idx(VirtIODevice *vdev, int n)
2239{
97cd965c 2240 rcu_read_lock();
ca0176ad
PB
2241 if (vdev->vq[n].vring.desc) {
2242 vdev->vq[n].used_idx = vring_used_idx(&vdev->vq[n]);
2243 }
97cd965c 2244 rcu_read_unlock();
312d3b35
YB
2245}
2246
6793dfd1
SH
2247void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
2248{
2249 vdev->vq[n].signalled_used_valid = false;
2250}
2251
1cbdabe2
MT
2252VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
2253{
2254 return vdev->vq + n;
2255}
2256
e78a2b42
JW
2257uint16_t virtio_get_queue_index(VirtQueue *vq)
2258{
2259 return vq->queue_index;
2260}
2261
15b2bd18
PB
2262static void virtio_queue_guest_notifier_read(EventNotifier *n)
2263{
2264 VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
2265 if (event_notifier_test_and_clear(n)) {
b4b9862b 2266 virtio_irq(vq);
15b2bd18
PB
2267 }
2268}
2269
2270void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
2271 bool with_irqfd)
2272{
2273 if (assign && !with_irqfd) {
d6da1e9e 2274 event_notifier_set_handler(&vq->guest_notifier,
15b2bd18
PB
2275 virtio_queue_guest_notifier_read);
2276 } else {
d6da1e9e 2277 event_notifier_set_handler(&vq->guest_notifier, NULL);
15b2bd18
PB
2278 }
2279 if (!assign) {
2280 /* Test and clear notifier before closing it,
2281 * in case poll callback didn't have time to run. */
2282 virtio_queue_guest_notifier_read(&vq->guest_notifier);
2283 }
2284}
2285
1cbdabe2
MT
2286EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
2287{
2288 return &vq->guest_notifier;
2289}
b1f416aa 2290
344dc16f 2291static void virtio_queue_host_notifier_aio_read(EventNotifier *n)
b1f416aa
PB
2292{
2293 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2294 if (event_notifier_test_and_clear(n)) {
344dc16f 2295 virtio_queue_notify_aio_vq(vq);
b1f416aa
PB
2296 }
2297}
2298
a7c8215e
SH
2299static void virtio_queue_host_notifier_aio_poll_begin(EventNotifier *n)
2300{
2301 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2302
2303 virtio_queue_set_notification(vq, 0);
2304}
2305
0062ea0f
SH
2306static bool virtio_queue_host_notifier_aio_poll(void *opaque)
2307{
2308 EventNotifier *n = opaque;
2309 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
07931698 2310 bool progress;
0062ea0f 2311
dd3dd4ba 2312 if (!vq->vring.desc || virtio_queue_empty(vq)) {
0062ea0f
SH
2313 return false;
2314 }
2315
07931698 2316 progress = virtio_queue_notify_aio_vq(vq);
1448c133
SH
2317
2318 /* In case the handler function re-enabled notifications */
2319 virtio_queue_set_notification(vq, 0);
07931698 2320 return progress;
0062ea0f
SH
2321}
2322
a7c8215e
SH
2323static void virtio_queue_host_notifier_aio_poll_end(EventNotifier *n)
2324{
2325 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2326
2327 /* Caller polls once more after this to catch requests that race with us */
2328 virtio_queue_set_notification(vq, 1);
2329}
2330
a1afb606 2331void virtio_queue_aio_set_host_notifier_handler(VirtQueue *vq, AioContext *ctx,
07931698 2332 VirtIOHandleAIOOutput handle_output)
a1afb606 2333{
a378b49a
PB
2334 if (handle_output) {
2335 vq->handle_aio_output = handle_output;
a1afb606 2336 aio_set_event_notifier(ctx, &vq->host_notifier, true,
0062ea0f
SH
2337 virtio_queue_host_notifier_aio_read,
2338 virtio_queue_host_notifier_aio_poll);
a7c8215e
SH
2339 aio_set_event_notifier_poll(ctx, &vq->host_notifier,
2340 virtio_queue_host_notifier_aio_poll_begin,
2341 virtio_queue_host_notifier_aio_poll_end);
a1afb606 2342 } else {
f6a51c84 2343 aio_set_event_notifier(ctx, &vq->host_notifier, true, NULL, NULL);
a1afb606
PB
2344 /* Test and clear notifier before after disabling event,
2345 * in case poll callback didn't have time to run. */
344dc16f 2346 virtio_queue_host_notifier_aio_read(&vq->host_notifier);
a378b49a 2347 vq->handle_aio_output = NULL;
344dc16f
MT
2348 }
2349}
2350
fa283a4a 2351void virtio_queue_host_notifier_read(EventNotifier *n)
344dc16f
MT
2352{
2353 VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
2354 if (event_notifier_test_and_clear(n)) {
2355 virtio_queue_notify_vq(vq);
a1afb606
PB
2356 }
2357}
2358
1cbdabe2
MT
2359EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
2360{
2361 return &vq->host_notifier;
2362}
8e05db92 2363
1034e9cf
FK
2364void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
2365{
9e288406 2366 g_free(vdev->bus_name);
80e0090a 2367 vdev->bus_name = g_strdup(bus_name);
1034e9cf
FK
2368}
2369
f5ed3663
SH
2370void GCC_FMT_ATTR(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
2371{
2372 va_list ap;
2373
2374 va_start(ap, fmt);
2375 error_vreport(fmt, ap);
2376 va_end(ap);
2377
2378 vdev->broken = true;
2379
2380 if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2381 virtio_set_status(vdev, vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET);
2382 virtio_notify_config(vdev);
2383 }
2384}
2385
c611c764
PB
2386static void virtio_memory_listener_commit(MemoryListener *listener)
2387{
2388 VirtIODevice *vdev = container_of(listener, VirtIODevice, listener);
2389 int i;
2390
2391 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2392 if (vdev->vq[i].vring.num == 0) {
2393 break;
2394 }
2395 virtio_init_region_cache(vdev, i);
2396 }
2397}
2398
1d244b42
AF
2399static void virtio_device_realize(DeviceState *dev, Error **errp)
2400{
2401 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
2402 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
2403 Error *err = NULL;
2404
ea43e259
DDAG
2405 /* Devices should either use vmsd or the load/save methods */
2406 assert(!vdc->vmsd || !vdc->load);
2407
1d244b42
AF
2408 if (vdc->realize != NULL) {
2409 vdc->realize(dev, &err);
2410 if (err != NULL) {
2411 error_propagate(errp, err);
2412 return;
2413 }
8e05db92 2414 }
e8398045
JW
2415
2416 virtio_bus_device_plugged(vdev, &err);
2417 if (err != NULL) {
2418 error_propagate(errp, err);
2419 return;
2420 }
c611c764
PB
2421
2422 vdev->listener.commit = virtio_memory_listener_commit;
2423 memory_listener_register(&vdev->listener, vdev->dma_as);
8e05db92
FK
2424}
2425
1d244b42 2426static void virtio_device_unrealize(DeviceState *dev, Error **errp)
1034e9cf 2427{
1d244b42 2428 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
306ec6c3
AF
2429 VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
2430 Error *err = NULL;
1d244b42 2431
83d07047
PB
2432 virtio_bus_device_unplugged(vdev);
2433
306ec6c3
AF
2434 if (vdc->unrealize != NULL) {
2435 vdc->unrealize(dev, &err);
2436 if (err != NULL) {
2437 error_propagate(errp, err);
2438 return;
2439 }
5e96f5d2 2440 }
1d244b42 2441
9e288406
MA
2442 g_free(vdev->bus_name);
2443 vdev->bus_name = NULL;
1034e9cf
FK
2444}
2445
c611c764
PB
2446static void virtio_device_free_virtqueues(VirtIODevice *vdev)
2447{
2448 int i;
2449 if (!vdev->vq) {
2450 return;
2451 }
2452
2453 for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2454 VRingMemoryRegionCaches *caches;
2455 if (vdev->vq[i].vring.num == 0) {
2456 break;
2457 }
2458 caches = atomic_read(&vdev->vq[i].vring.caches);
2459 atomic_set(&vdev->vq[i].vring.caches, NULL);
2460 virtio_free_region_cache(caches);
2461 }
2462 g_free(vdev->vq);
2463}
2464
2465static void virtio_device_instance_finalize(Object *obj)
2466{
2467 VirtIODevice *vdev = VIRTIO_DEVICE(obj);
2468
2469 memory_listener_unregister(&vdev->listener);
2470 virtio_device_free_virtqueues(vdev);
2471
2472 g_free(vdev->config);
2473 g_free(vdev->vector_queues);
2474}
2475
6b8f1020
CH
2476static Property virtio_properties[] = {
2477 DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
2478 DEFINE_PROP_END_OF_LIST(),
2479};
2480
ff4c07df
PB
2481static int virtio_device_start_ioeventfd_impl(VirtIODevice *vdev)
2482{
2483 VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
ff4c07df
PB
2484 int n, r, err;
2485
2486 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
fa283a4a 2487 VirtQueue *vq = &vdev->vq[n];
ff4c07df
PB
2488 if (!virtio_queue_get_num(vdev, n)) {
2489 continue;
2490 }
ed08a2a0 2491 r = virtio_bus_set_host_notifier(qbus, n, true);
ff4c07df
PB
2492 if (r < 0) {
2493 err = r;
2494 goto assign_error;
2495 }
d6da1e9e 2496 event_notifier_set_handler(&vq->host_notifier,
fa283a4a 2497 virtio_queue_host_notifier_read);
6019f3b9
PB
2498 }
2499
2500 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
2501 /* Kick right away to begin processing requests already in vring */
2502 VirtQueue *vq = &vdev->vq[n];
2503 if (!vq->vring.num) {
2504 continue;
2505 }
2506 event_notifier_set(&vq->host_notifier);
ff4c07df
PB
2507 }
2508 return 0;
2509
2510assign_error:
2511 while (--n >= 0) {
fa283a4a 2512 VirtQueue *vq = &vdev->vq[n];
ff4c07df
PB
2513 if (!virtio_queue_get_num(vdev, n)) {
2514 continue;
2515 }
2516
d6da1e9e 2517 event_notifier_set_handler(&vq->host_notifier, NULL);
ed08a2a0 2518 r = virtio_bus_set_host_notifier(qbus, n, false);
ff4c07df
PB
2519 assert(r >= 0);
2520 }
2521 return err;
2522}
2523
2524int virtio_device_start_ioeventfd(VirtIODevice *vdev)
2525{
2526 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2527 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2528
2529 return virtio_bus_start_ioeventfd(vbus);
2530}
2531
2532static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
2533{
2534 VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
ff4c07df
PB
2535 int n, r;
2536
2537 for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
fa283a4a
PB
2538 VirtQueue *vq = &vdev->vq[n];
2539
ff4c07df
PB
2540 if (!virtio_queue_get_num(vdev, n)) {
2541 continue;
2542 }
d6da1e9e 2543 event_notifier_set_handler(&vq->host_notifier, NULL);
ed08a2a0 2544 r = virtio_bus_set_host_notifier(qbus, n, false);
ff4c07df
PB
2545 assert(r >= 0);
2546 }
2547}
2548
2549void virtio_device_stop_ioeventfd(VirtIODevice *vdev)
2550{
2551 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2552 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2553
2554 virtio_bus_stop_ioeventfd(vbus);
2555}
2556
310837de
PB
2557int virtio_device_grab_ioeventfd(VirtIODevice *vdev)
2558{
2559 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2560 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2561
2562 return virtio_bus_grab_ioeventfd(vbus);
2563}
2564
2565void virtio_device_release_ioeventfd(VirtIODevice *vdev)
2566{
2567 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2568 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2569
2570 virtio_bus_release_ioeventfd(vbus);
2571}
2572
8e05db92
FK
2573static void virtio_device_class_init(ObjectClass *klass, void *data)
2574{
2575 /* Set the default value here. */
ff4c07df 2576 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
8e05db92 2577 DeviceClass *dc = DEVICE_CLASS(klass);
1d244b42
AF
2578
2579 dc->realize = virtio_device_realize;
2580 dc->unrealize = virtio_device_unrealize;
8e05db92 2581 dc->bus_type = TYPE_VIRTIO_BUS;
6b8f1020 2582 dc->props = virtio_properties;
ff4c07df
PB
2583 vdc->start_ioeventfd = virtio_device_start_ioeventfd_impl;
2584 vdc->stop_ioeventfd = virtio_device_stop_ioeventfd_impl;
9b706dbb
MT
2585
2586 vdc->legacy_features |= VIRTIO_LEGACY_FEATURES;
8e05db92
FK
2587}
2588
8e93cef1
PB
2589bool virtio_device_ioeventfd_enabled(VirtIODevice *vdev)
2590{
2591 BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2592 VirtioBusState *vbus = VIRTIO_BUS(qbus);
2593
2594 return virtio_bus_ioeventfd_enabled(vbus);
2595}
2596
8e05db92
FK
2597static const TypeInfo virtio_device_info = {
2598 .name = TYPE_VIRTIO_DEVICE,
2599 .parent = TYPE_DEVICE,
2600 .instance_size = sizeof(VirtIODevice),
2601 .class_init = virtio_device_class_init,
c611c764 2602 .instance_finalize = virtio_device_instance_finalize,
8e05db92
FK
2603 .abstract = true,
2604 .class_size = sizeof(VirtioDeviceClass),
2605};
2606
2607static void virtio_register_types(void)
2608{
2609 type_register_static(&virtio_device_info);
2610}
2611
2612type_init(virtio_register_types)