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