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