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