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