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