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