xref: /openbmc/qemu/hw/virtio/virtio.c (revision 3b894b69)
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 "qapi/qapi-commands-virtio.h"
17 #include "trace.h"
18 #include "qemu/error-report.h"
19 #include "qemu/log.h"
20 #include "qemu/main-loop.h"
21 #include "qemu/module.h"
22 #include "qom/object_interfaces.h"
23 #include "hw/core/cpu.h"
24 #include "hw/virtio/virtio.h"
25 #include "hw/virtio/vhost.h"
26 #include "migration/qemu-file-types.h"
27 #include "qemu/atomic.h"
28 #include "hw/virtio/virtio-bus.h"
29 #include "hw/qdev-properties.h"
30 #include "hw/virtio/virtio-access.h"
31 #include "sysemu/dma.h"
32 #include "sysemu/runstate.h"
33 #include "virtio-qmp.h"
34 
35 #include "standard-headers/linux/virtio_ids.h"
36 #include "standard-headers/linux/vhost_types.h"
37 #include "standard-headers/linux/virtio_blk.h"
38 #include "standard-headers/linux/virtio_console.h"
39 #include "standard-headers/linux/virtio_gpu.h"
40 #include "standard-headers/linux/virtio_net.h"
41 #include "standard-headers/linux/virtio_scsi.h"
42 #include "standard-headers/linux/virtio_i2c.h"
43 #include "standard-headers/linux/virtio_balloon.h"
44 #include "standard-headers/linux/virtio_iommu.h"
45 #include "standard-headers/linux/virtio_mem.h"
46 #include "standard-headers/linux/virtio_vsock.h"
47 
48 /*
49  * Maximum size of virtio device config space
50  */
51 #define VHOST_USER_MAX_CONFIG_SIZE 256
52 
53 /*
54  * The alignment to use between consumer and producer parts of vring.
55  * x86 pagesize again. This is the default, used by transports like PCI
56  * which don't provide a means for the guest to tell the host the alignment.
57  */
58 #define VIRTIO_PCI_VRING_ALIGN         4096
59 
60 typedef struct VRingDesc
61 {
62     uint64_t addr;
63     uint32_t len;
64     uint16_t flags;
65     uint16_t next;
66 } VRingDesc;
67 
68 typedef struct VRingPackedDesc {
69     uint64_t addr;
70     uint32_t len;
71     uint16_t id;
72     uint16_t flags;
73 } VRingPackedDesc;
74 
75 typedef struct VRingAvail
76 {
77     uint16_t flags;
78     uint16_t idx;
79     uint16_t ring[];
80 } VRingAvail;
81 
82 typedef struct VRingUsedElem
83 {
84     uint32_t id;
85     uint32_t len;
86 } VRingUsedElem;
87 
88 typedef struct VRingUsed
89 {
90     uint16_t flags;
91     uint16_t idx;
92     VRingUsedElem ring[];
93 } VRingUsed;
94 
95 typedef struct VRingMemoryRegionCaches {
96     struct rcu_head rcu;
97     MemoryRegionCache desc;
98     MemoryRegionCache avail;
99     MemoryRegionCache used;
100 } VRingMemoryRegionCaches;
101 
102 typedef struct VRing
103 {
104     unsigned int num;
105     unsigned int num_default;
106     unsigned int align;
107     hwaddr desc;
108     hwaddr avail;
109     hwaddr used;
110     VRingMemoryRegionCaches *caches;
111 } VRing;
112 
113 typedef struct VRingPackedDescEvent {
114     uint16_t off_wrap;
115     uint16_t flags;
116 } VRingPackedDescEvent ;
117 
118 struct VirtQueue
119 {
120     VRing vring;
121     VirtQueueElement *used_elems;
122 
123     /* Next head to pop */
124     uint16_t last_avail_idx;
125     bool last_avail_wrap_counter;
126 
127     /* Last avail_idx read from VQ. */
128     uint16_t shadow_avail_idx;
129     bool shadow_avail_wrap_counter;
130 
131     uint16_t used_idx;
132     bool used_wrap_counter;
133 
134     /* Last used index value we have signalled on */
135     uint16_t signalled_used;
136 
137     /* Last used index value we have signalled on */
138     bool signalled_used_valid;
139 
140     /* Notification enabled? */
141     bool notification;
142 
143     uint16_t queue_index;
144 
145     unsigned int inuse;
146 
147     uint16_t vector;
148     VirtIOHandleOutput handle_output;
149     VirtIODevice *vdev;
150     EventNotifier guest_notifier;
151     EventNotifier host_notifier;
152     bool host_notifier_enabled;
153     QLIST_ENTRY(VirtQueue) node;
154 };
155 
156 const char *virtio_device_names[] = {
157     [VIRTIO_ID_NET] = "virtio-net",
158     [VIRTIO_ID_BLOCK] = "virtio-blk",
159     [VIRTIO_ID_CONSOLE] = "virtio-serial",
160     [VIRTIO_ID_RNG] = "virtio-rng",
161     [VIRTIO_ID_BALLOON] = "virtio-balloon",
162     [VIRTIO_ID_IOMEM] = "virtio-iomem",
163     [VIRTIO_ID_RPMSG] = "virtio-rpmsg",
164     [VIRTIO_ID_SCSI] = "virtio-scsi",
165     [VIRTIO_ID_9P] = "virtio-9p",
166     [VIRTIO_ID_MAC80211_WLAN] = "virtio-mac-wlan",
167     [VIRTIO_ID_RPROC_SERIAL] = "virtio-rproc-serial",
168     [VIRTIO_ID_CAIF] = "virtio-caif",
169     [VIRTIO_ID_MEMORY_BALLOON] = "virtio-mem-balloon",
170     [VIRTIO_ID_GPU] = "virtio-gpu",
171     [VIRTIO_ID_CLOCK] = "virtio-clk",
172     [VIRTIO_ID_INPUT] = "virtio-input",
173     [VIRTIO_ID_VSOCK] = "vhost-vsock",
174     [VIRTIO_ID_CRYPTO] = "virtio-crypto",
175     [VIRTIO_ID_SIGNAL_DIST] = "virtio-signal",
176     [VIRTIO_ID_PSTORE] = "virtio-pstore",
177     [VIRTIO_ID_IOMMU] = "virtio-iommu",
178     [VIRTIO_ID_MEM] = "virtio-mem",
179     [VIRTIO_ID_SOUND] = "virtio-sound",
180     [VIRTIO_ID_FS] = "virtio-user-fs",
181     [VIRTIO_ID_PMEM] = "virtio-pmem",
182     [VIRTIO_ID_RPMB] = "virtio-rpmb",
183     [VIRTIO_ID_MAC80211_HWSIM] = "virtio-mac-hwsim",
184     [VIRTIO_ID_VIDEO_ENCODER] = "virtio-vid-encoder",
185     [VIRTIO_ID_VIDEO_DECODER] = "virtio-vid-decoder",
186     [VIRTIO_ID_SCMI] = "virtio-scmi",
187     [VIRTIO_ID_NITRO_SEC_MOD] = "virtio-nitro-sec-mod",
188     [VIRTIO_ID_I2C_ADAPTER] = "vhost-user-i2c",
189     [VIRTIO_ID_WATCHDOG] = "virtio-watchdog",
190     [VIRTIO_ID_CAN] = "virtio-can",
191     [VIRTIO_ID_DMABUF] = "virtio-dmabuf",
192     [VIRTIO_ID_PARAM_SERV] = "virtio-param-serv",
193     [VIRTIO_ID_AUDIO_POLICY] = "virtio-audio-pol",
194     [VIRTIO_ID_BT] = "virtio-bluetooth",
195     [VIRTIO_ID_GPIO] = "virtio-gpio"
196 };
197 
198 static const char *virtio_id_to_name(uint16_t device_id)
199 {
200     assert(device_id < G_N_ELEMENTS(virtio_device_names));
201     const char *name = virtio_device_names[device_id];
202     assert(name != NULL);
203     return name;
204 }
205 
206 /* Called within call_rcu().  */
207 static void virtio_free_region_cache(VRingMemoryRegionCaches *caches)
208 {
209     assert(caches != NULL);
210     address_space_cache_destroy(&caches->desc);
211     address_space_cache_destroy(&caches->avail);
212     address_space_cache_destroy(&caches->used);
213     g_free(caches);
214 }
215 
216 static void virtio_virtqueue_reset_region_cache(struct VirtQueue *vq)
217 {
218     VRingMemoryRegionCaches *caches;
219 
220     caches = qatomic_read(&vq->vring.caches);
221     qatomic_rcu_set(&vq->vring.caches, NULL);
222     if (caches) {
223         call_rcu(caches, virtio_free_region_cache, rcu);
224     }
225 }
226 
227 void virtio_init_region_cache(VirtIODevice *vdev, int n)
228 {
229     VirtQueue *vq = &vdev->vq[n];
230     VRingMemoryRegionCaches *old = vq->vring.caches;
231     VRingMemoryRegionCaches *new = NULL;
232     hwaddr addr, size;
233     int64_t len;
234     bool packed;
235 
236 
237     addr = vq->vring.desc;
238     if (!addr) {
239         goto out_no_cache;
240     }
241     new = g_new0(VRingMemoryRegionCaches, 1);
242     size = virtio_queue_get_desc_size(vdev, n);
243     packed = virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED) ?
244                                    true : false;
245     len = address_space_cache_init(&new->desc, vdev->dma_as,
246                                    addr, size, packed);
247     if (len < size) {
248         virtio_error(vdev, "Cannot map desc");
249         goto err_desc;
250     }
251 
252     size = virtio_queue_get_used_size(vdev, n);
253     len = address_space_cache_init(&new->used, vdev->dma_as,
254                                    vq->vring.used, size, true);
255     if (len < size) {
256         virtio_error(vdev, "Cannot map used");
257         goto err_used;
258     }
259 
260     size = virtio_queue_get_avail_size(vdev, n);
261     len = address_space_cache_init(&new->avail, vdev->dma_as,
262                                    vq->vring.avail, size, false);
263     if (len < size) {
264         virtio_error(vdev, "Cannot map avail");
265         goto err_avail;
266     }
267 
268     qatomic_rcu_set(&vq->vring.caches, new);
269     if (old) {
270         call_rcu(old, virtio_free_region_cache, rcu);
271     }
272     return;
273 
274 err_avail:
275     address_space_cache_destroy(&new->avail);
276 err_used:
277     address_space_cache_destroy(&new->used);
278 err_desc:
279     address_space_cache_destroy(&new->desc);
280 out_no_cache:
281     g_free(new);
282     virtio_virtqueue_reset_region_cache(vq);
283 }
284 
285 /* virt queue functions */
286 void virtio_queue_update_rings(VirtIODevice *vdev, int n)
287 {
288     VRing *vring = &vdev->vq[n].vring;
289 
290     if (!vring->num || !vring->desc || !vring->align) {
291         /* not yet setup -> nothing to do */
292         return;
293     }
294     vring->avail = vring->desc + vring->num * sizeof(VRingDesc);
295     vring->used = vring_align(vring->avail +
296                               offsetof(VRingAvail, ring[vring->num]),
297                               vring->align);
298     virtio_init_region_cache(vdev, n);
299 }
300 
301 /* Called within rcu_read_lock().  */
302 static void vring_split_desc_read(VirtIODevice *vdev, VRingDesc *desc,
303                                   MemoryRegionCache *cache, int i)
304 {
305     address_space_read_cached(cache, i * sizeof(VRingDesc),
306                               desc, sizeof(VRingDesc));
307     virtio_tswap64s(vdev, &desc->addr);
308     virtio_tswap32s(vdev, &desc->len);
309     virtio_tswap16s(vdev, &desc->flags);
310     virtio_tswap16s(vdev, &desc->next);
311 }
312 
313 static void vring_packed_event_read(VirtIODevice *vdev,
314                                     MemoryRegionCache *cache,
315                                     VRingPackedDescEvent *e)
316 {
317     hwaddr off_off = offsetof(VRingPackedDescEvent, off_wrap);
318     hwaddr off_flags = offsetof(VRingPackedDescEvent, flags);
319 
320     e->flags = virtio_lduw_phys_cached(vdev, cache, off_flags);
321     /* Make sure flags is seen before off_wrap */
322     smp_rmb();
323     e->off_wrap = virtio_lduw_phys_cached(vdev, cache, off_off);
324     virtio_tswap16s(vdev, &e->flags);
325 }
326 
327 static void vring_packed_off_wrap_write(VirtIODevice *vdev,
328                                         MemoryRegionCache *cache,
329                                         uint16_t off_wrap)
330 {
331     hwaddr off = offsetof(VRingPackedDescEvent, off_wrap);
332 
333     virtio_stw_phys_cached(vdev, cache, off, off_wrap);
334     address_space_cache_invalidate(cache, off, sizeof(off_wrap));
335 }
336 
337 static void vring_packed_flags_write(VirtIODevice *vdev,
338                                      MemoryRegionCache *cache, uint16_t flags)
339 {
340     hwaddr off = offsetof(VRingPackedDescEvent, flags);
341 
342     virtio_stw_phys_cached(vdev, cache, off, flags);
343     address_space_cache_invalidate(cache, off, sizeof(flags));
344 }
345 
346 /* Called within rcu_read_lock().  */
347 static VRingMemoryRegionCaches *vring_get_region_caches(struct VirtQueue *vq)
348 {
349     return qatomic_rcu_read(&vq->vring.caches);
350 }
351 
352 /* Called within rcu_read_lock().  */
353 static inline uint16_t vring_avail_flags(VirtQueue *vq)
354 {
355     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
356     hwaddr pa = offsetof(VRingAvail, flags);
357 
358     if (!caches) {
359         return 0;
360     }
361 
362     return virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
363 }
364 
365 /* Called within rcu_read_lock().  */
366 static inline uint16_t vring_avail_idx(VirtQueue *vq)
367 {
368     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
369     hwaddr pa = offsetof(VRingAvail, idx);
370 
371     if (!caches) {
372         return 0;
373     }
374 
375     vq->shadow_avail_idx = virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
376     return vq->shadow_avail_idx;
377 }
378 
379 /* Called within rcu_read_lock().  */
380 static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
381 {
382     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
383     hwaddr pa = offsetof(VRingAvail, ring[i]);
384 
385     if (!caches) {
386         return 0;
387     }
388 
389     return virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);
390 }
391 
392 /* Called within rcu_read_lock().  */
393 static inline uint16_t vring_get_used_event(VirtQueue *vq)
394 {
395     return vring_avail_ring(vq, vq->vring.num);
396 }
397 
398 /* Called within rcu_read_lock().  */
399 static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,
400                                     int i)
401 {
402     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
403     hwaddr pa = offsetof(VRingUsed, ring[i]);
404 
405     if (!caches) {
406         return;
407     }
408 
409     virtio_tswap32s(vq->vdev, &uelem->id);
410     virtio_tswap32s(vq->vdev, &uelem->len);
411     address_space_write_cached(&caches->used, pa, uelem, sizeof(VRingUsedElem));
412     address_space_cache_invalidate(&caches->used, pa, sizeof(VRingUsedElem));
413 }
414 
415 /* Called within rcu_read_lock(). */
416 static inline uint16_t vring_used_flags(VirtQueue *vq)
417 {
418     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
419     hwaddr pa = offsetof(VRingUsed, flags);
420 
421     if (!caches) {
422         return 0;
423     }
424 
425     return virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
426 }
427 
428 /* Called within rcu_read_lock().  */
429 static uint16_t vring_used_idx(VirtQueue *vq)
430 {
431     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
432     hwaddr pa = offsetof(VRingUsed, idx);
433 
434     if (!caches) {
435         return 0;
436     }
437 
438     return virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
439 }
440 
441 /* Called within rcu_read_lock().  */
442 static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
443 {
444     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
445     hwaddr pa = offsetof(VRingUsed, idx);
446 
447     if (caches) {
448         virtio_stw_phys_cached(vq->vdev, &caches->used, pa, val);
449         address_space_cache_invalidate(&caches->used, pa, sizeof(val));
450     }
451 
452     vq->used_idx = val;
453 }
454 
455 /* Called within rcu_read_lock().  */
456 static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
457 {
458     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
459     VirtIODevice *vdev = vq->vdev;
460     hwaddr pa = offsetof(VRingUsed, flags);
461     uint16_t flags;
462 
463     if (!caches) {
464         return;
465     }
466 
467     flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
468     virtio_stw_phys_cached(vdev, &caches->used, pa, flags | mask);
469     address_space_cache_invalidate(&caches->used, pa, sizeof(flags));
470 }
471 
472 /* Called within rcu_read_lock().  */
473 static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
474 {
475     VRingMemoryRegionCaches *caches = vring_get_region_caches(vq);
476     VirtIODevice *vdev = vq->vdev;
477     hwaddr pa = offsetof(VRingUsed, flags);
478     uint16_t flags;
479 
480     if (!caches) {
481         return;
482     }
483 
484     flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
485     virtio_stw_phys_cached(vdev, &caches->used, pa, flags & ~mask);
486     address_space_cache_invalidate(&caches->used, pa, sizeof(flags));
487 }
488 
489 /* Called within rcu_read_lock().  */
490 static inline void vring_set_avail_event(VirtQueue *vq, uint16_t val)
491 {
492     VRingMemoryRegionCaches *caches;
493     hwaddr pa;
494     if (!vq->notification) {
495         return;
496     }
497 
498     caches = vring_get_region_caches(vq);
499     if (!caches) {
500         return;
501     }
502 
503     pa = offsetof(VRingUsed, ring[vq->vring.num]);
504     virtio_stw_phys_cached(vq->vdev, &caches->used, pa, val);
505     address_space_cache_invalidate(&caches->used, pa, sizeof(val));
506 }
507 
508 static void virtio_queue_split_set_notification(VirtQueue *vq, int enable)
509 {
510     RCU_READ_LOCK_GUARD();
511 
512     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
513         vring_set_avail_event(vq, vring_avail_idx(vq));
514     } else if (enable) {
515         vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
516     } else {
517         vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
518     }
519     if (enable) {
520         /* Expose avail event/used flags before caller checks the avail idx. */
521         smp_mb();
522     }
523 }
524 
525 static void virtio_queue_packed_set_notification(VirtQueue *vq, int enable)
526 {
527     uint16_t off_wrap;
528     VRingPackedDescEvent e;
529     VRingMemoryRegionCaches *caches;
530 
531     RCU_READ_LOCK_GUARD();
532     caches = vring_get_region_caches(vq);
533     if (!caches) {
534         return;
535     }
536 
537     vring_packed_event_read(vq->vdev, &caches->used, &e);
538 
539     if (!enable) {
540         e.flags = VRING_PACKED_EVENT_FLAG_DISABLE;
541     } else if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
542         off_wrap = vq->shadow_avail_idx | vq->shadow_avail_wrap_counter << 15;
543         vring_packed_off_wrap_write(vq->vdev, &caches->used, off_wrap);
544         /* Make sure off_wrap is wrote before flags */
545         smp_wmb();
546         e.flags = VRING_PACKED_EVENT_FLAG_DESC;
547     } else {
548         e.flags = VRING_PACKED_EVENT_FLAG_ENABLE;
549     }
550 
551     vring_packed_flags_write(vq->vdev, &caches->used, e.flags);
552     if (enable) {
553         /* Expose avail event/used flags before caller checks the avail idx. */
554         smp_mb();
555     }
556 }
557 
558 bool virtio_queue_get_notification(VirtQueue *vq)
559 {
560     return vq->notification;
561 }
562 
563 void virtio_queue_set_notification(VirtQueue *vq, int enable)
564 {
565     vq->notification = enable;
566 
567     if (!vq->vring.desc) {
568         return;
569     }
570 
571     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
572         virtio_queue_packed_set_notification(vq, enable);
573     } else {
574         virtio_queue_split_set_notification(vq, enable);
575     }
576 }
577 
578 int virtio_queue_ready(VirtQueue *vq)
579 {
580     return vq->vring.avail != 0;
581 }
582 
583 static void vring_packed_desc_read_flags(VirtIODevice *vdev,
584                                          uint16_t *flags,
585                                          MemoryRegionCache *cache,
586                                          int i)
587 {
588     hwaddr off = i * sizeof(VRingPackedDesc) + offsetof(VRingPackedDesc, flags);
589 
590     *flags = virtio_lduw_phys_cached(vdev, cache, off);
591 }
592 
593 static void vring_packed_desc_read(VirtIODevice *vdev,
594                                    VRingPackedDesc *desc,
595                                    MemoryRegionCache *cache,
596                                    int i, bool strict_order)
597 {
598     hwaddr off = i * sizeof(VRingPackedDesc);
599 
600     vring_packed_desc_read_flags(vdev, &desc->flags, cache, i);
601 
602     if (strict_order) {
603         /* Make sure flags is read before the rest fields. */
604         smp_rmb();
605     }
606 
607     address_space_read_cached(cache, off + offsetof(VRingPackedDesc, addr),
608                               &desc->addr, sizeof(desc->addr));
609     address_space_read_cached(cache, off + offsetof(VRingPackedDesc, id),
610                               &desc->id, sizeof(desc->id));
611     address_space_read_cached(cache, off + offsetof(VRingPackedDesc, len),
612                               &desc->len, sizeof(desc->len));
613     virtio_tswap64s(vdev, &desc->addr);
614     virtio_tswap16s(vdev, &desc->id);
615     virtio_tswap32s(vdev, &desc->len);
616 }
617 
618 static void vring_packed_desc_write_data(VirtIODevice *vdev,
619                                          VRingPackedDesc *desc,
620                                          MemoryRegionCache *cache,
621                                          int i)
622 {
623     hwaddr off_id = i * sizeof(VRingPackedDesc) +
624                     offsetof(VRingPackedDesc, id);
625     hwaddr off_len = i * sizeof(VRingPackedDesc) +
626                     offsetof(VRingPackedDesc, len);
627 
628     virtio_tswap32s(vdev, &desc->len);
629     virtio_tswap16s(vdev, &desc->id);
630     address_space_write_cached(cache, off_id, &desc->id, sizeof(desc->id));
631     address_space_cache_invalidate(cache, off_id, sizeof(desc->id));
632     address_space_write_cached(cache, off_len, &desc->len, sizeof(desc->len));
633     address_space_cache_invalidate(cache, off_len, sizeof(desc->len));
634 }
635 
636 static void vring_packed_desc_write_flags(VirtIODevice *vdev,
637                                           VRingPackedDesc *desc,
638                                           MemoryRegionCache *cache,
639                                           int i)
640 {
641     hwaddr off = i * sizeof(VRingPackedDesc) + offsetof(VRingPackedDesc, flags);
642 
643     virtio_stw_phys_cached(vdev, cache, off, desc->flags);
644     address_space_cache_invalidate(cache, off, sizeof(desc->flags));
645 }
646 
647 static void vring_packed_desc_write(VirtIODevice *vdev,
648                                     VRingPackedDesc *desc,
649                                     MemoryRegionCache *cache,
650                                     int i, bool strict_order)
651 {
652     vring_packed_desc_write_data(vdev, desc, cache, i);
653     if (strict_order) {
654         /* Make sure data is wrote before flags. */
655         smp_wmb();
656     }
657     vring_packed_desc_write_flags(vdev, desc, cache, i);
658 }
659 
660 static inline bool is_desc_avail(uint16_t flags, bool wrap_counter)
661 {
662     bool avail, used;
663 
664     avail = !!(flags & (1 << VRING_PACKED_DESC_F_AVAIL));
665     used = !!(flags & (1 << VRING_PACKED_DESC_F_USED));
666     return (avail != used) && (avail == wrap_counter);
667 }
668 
669 /* Fetch avail_idx from VQ memory only when we really need to know if
670  * guest has added some buffers.
671  * Called within rcu_read_lock().  */
672 static int virtio_queue_empty_rcu(VirtQueue *vq)
673 {
674     if (virtio_device_disabled(vq->vdev)) {
675         return 1;
676     }
677 
678     if (unlikely(!vq->vring.avail)) {
679         return 1;
680     }
681 
682     if (vq->shadow_avail_idx != vq->last_avail_idx) {
683         return 0;
684     }
685 
686     return vring_avail_idx(vq) == vq->last_avail_idx;
687 }
688 
689 static int virtio_queue_split_empty(VirtQueue *vq)
690 {
691     bool empty;
692 
693     if (virtio_device_disabled(vq->vdev)) {
694         return 1;
695     }
696 
697     if (unlikely(!vq->vring.avail)) {
698         return 1;
699     }
700 
701     if (vq->shadow_avail_idx != vq->last_avail_idx) {
702         return 0;
703     }
704 
705     RCU_READ_LOCK_GUARD();
706     empty = vring_avail_idx(vq) == vq->last_avail_idx;
707     return empty;
708 }
709 
710 /* Called within rcu_read_lock().  */
711 static int virtio_queue_packed_empty_rcu(VirtQueue *vq)
712 {
713     struct VRingPackedDesc desc;
714     VRingMemoryRegionCaches *cache;
715 
716     if (unlikely(!vq->vring.desc)) {
717         return 1;
718     }
719 
720     cache = vring_get_region_caches(vq);
721     if (!cache) {
722         return 1;
723     }
724 
725     vring_packed_desc_read_flags(vq->vdev, &desc.flags, &cache->desc,
726                                  vq->last_avail_idx);
727 
728     return !is_desc_avail(desc.flags, vq->last_avail_wrap_counter);
729 }
730 
731 static int virtio_queue_packed_empty(VirtQueue *vq)
732 {
733     RCU_READ_LOCK_GUARD();
734     return virtio_queue_packed_empty_rcu(vq);
735 }
736 
737 int virtio_queue_empty(VirtQueue *vq)
738 {
739     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
740         return virtio_queue_packed_empty(vq);
741     } else {
742         return virtio_queue_split_empty(vq);
743     }
744 }
745 
746 static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,
747                                unsigned int len)
748 {
749     AddressSpace *dma_as = vq->vdev->dma_as;
750     unsigned int offset;
751     int i;
752 
753     offset = 0;
754     for (i = 0; i < elem->in_num; i++) {
755         size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
756 
757         dma_memory_unmap(dma_as, elem->in_sg[i].iov_base,
758                          elem->in_sg[i].iov_len,
759                          DMA_DIRECTION_FROM_DEVICE, size);
760 
761         offset += size;
762     }
763 
764     for (i = 0; i < elem->out_num; i++)
765         dma_memory_unmap(dma_as, elem->out_sg[i].iov_base,
766                          elem->out_sg[i].iov_len,
767                          DMA_DIRECTION_TO_DEVICE,
768                          elem->out_sg[i].iov_len);
769 }
770 
771 /* virtqueue_detach_element:
772  * @vq: The #VirtQueue
773  * @elem: The #VirtQueueElement
774  * @len: number of bytes written
775  *
776  * Detach the element from the virtqueue.  This function is suitable for device
777  * reset or other situations where a #VirtQueueElement is simply freed and will
778  * not be pushed or discarded.
779  */
780 void virtqueue_detach_element(VirtQueue *vq, const VirtQueueElement *elem,
781                               unsigned int len)
782 {
783     vq->inuse -= elem->ndescs;
784     virtqueue_unmap_sg(vq, elem, len);
785 }
786 
787 static void virtqueue_split_rewind(VirtQueue *vq, unsigned int num)
788 {
789     vq->last_avail_idx -= num;
790 }
791 
792 static void virtqueue_packed_rewind(VirtQueue *vq, unsigned int num)
793 {
794     if (vq->last_avail_idx < num) {
795         vq->last_avail_idx = vq->vring.num + vq->last_avail_idx - num;
796         vq->last_avail_wrap_counter ^= 1;
797     } else {
798         vq->last_avail_idx -= num;
799     }
800 }
801 
802 /* virtqueue_unpop:
803  * @vq: The #VirtQueue
804  * @elem: The #VirtQueueElement
805  * @len: number of bytes written
806  *
807  * Pretend the most recent element wasn't popped from the virtqueue.  The next
808  * call to virtqueue_pop() will refetch the element.
809  */
810 void virtqueue_unpop(VirtQueue *vq, const VirtQueueElement *elem,
811                      unsigned int len)
812 {
813 
814     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
815         virtqueue_packed_rewind(vq, 1);
816     } else {
817         virtqueue_split_rewind(vq, 1);
818     }
819 
820     virtqueue_detach_element(vq, elem, len);
821 }
822 
823 /* virtqueue_rewind:
824  * @vq: The #VirtQueue
825  * @num: Number of elements to push back
826  *
827  * Pretend that elements weren't popped from the virtqueue.  The next
828  * virtqueue_pop() will refetch the oldest element.
829  *
830  * Use virtqueue_unpop() instead if you have a VirtQueueElement.
831  *
832  * Returns: true on success, false if @num is greater than the number of in use
833  * elements.
834  */
835 bool virtqueue_rewind(VirtQueue *vq, unsigned int num)
836 {
837     if (num > vq->inuse) {
838         return false;
839     }
840 
841     vq->inuse -= num;
842     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
843         virtqueue_packed_rewind(vq, num);
844     } else {
845         virtqueue_split_rewind(vq, num);
846     }
847     return true;
848 }
849 
850 static void virtqueue_split_fill(VirtQueue *vq, const VirtQueueElement *elem,
851                     unsigned int len, unsigned int idx)
852 {
853     VRingUsedElem uelem;
854 
855     if (unlikely(!vq->vring.used)) {
856         return;
857     }
858 
859     idx = (idx + vq->used_idx) % vq->vring.num;
860 
861     uelem.id = elem->index;
862     uelem.len = len;
863     vring_used_write(vq, &uelem, idx);
864 }
865 
866 static void virtqueue_packed_fill(VirtQueue *vq, const VirtQueueElement *elem,
867                                   unsigned int len, unsigned int idx)
868 {
869     vq->used_elems[idx].index = elem->index;
870     vq->used_elems[idx].len = len;
871     vq->used_elems[idx].ndescs = elem->ndescs;
872 }
873 
874 static void virtqueue_packed_fill_desc(VirtQueue *vq,
875                                        const VirtQueueElement *elem,
876                                        unsigned int idx,
877                                        bool strict_order)
878 {
879     uint16_t head;
880     VRingMemoryRegionCaches *caches;
881     VRingPackedDesc desc = {
882         .id = elem->index,
883         .len = elem->len,
884     };
885     bool wrap_counter = vq->used_wrap_counter;
886 
887     if (unlikely(!vq->vring.desc)) {
888         return;
889     }
890 
891     head = vq->used_idx + idx;
892     if (head >= vq->vring.num) {
893         head -= vq->vring.num;
894         wrap_counter ^= 1;
895     }
896     if (wrap_counter) {
897         desc.flags |= (1 << VRING_PACKED_DESC_F_AVAIL);
898         desc.flags |= (1 << VRING_PACKED_DESC_F_USED);
899     } else {
900         desc.flags &= ~(1 << VRING_PACKED_DESC_F_AVAIL);
901         desc.flags &= ~(1 << VRING_PACKED_DESC_F_USED);
902     }
903 
904     caches = vring_get_region_caches(vq);
905     if (!caches) {
906         return;
907     }
908 
909     vring_packed_desc_write(vq->vdev, &desc, &caches->desc, head, strict_order);
910 }
911 
912 /* Called within rcu_read_lock().  */
913 void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
914                     unsigned int len, unsigned int idx)
915 {
916     trace_virtqueue_fill(vq, elem, len, idx);
917 
918     virtqueue_unmap_sg(vq, elem, len);
919 
920     if (virtio_device_disabled(vq->vdev)) {
921         return;
922     }
923 
924     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
925         virtqueue_packed_fill(vq, elem, len, idx);
926     } else {
927         virtqueue_split_fill(vq, elem, len, idx);
928     }
929 }
930 
931 /* Called within rcu_read_lock().  */
932 static void virtqueue_split_flush(VirtQueue *vq, unsigned int count)
933 {
934     uint16_t old, new;
935 
936     if (unlikely(!vq->vring.used)) {
937         return;
938     }
939 
940     /* Make sure buffer is written before we update index. */
941     smp_wmb();
942     trace_virtqueue_flush(vq, count);
943     old = vq->used_idx;
944     new = old + count;
945     vring_used_idx_set(vq, new);
946     vq->inuse -= count;
947     if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
948         vq->signalled_used_valid = false;
949 }
950 
951 static void virtqueue_packed_flush(VirtQueue *vq, unsigned int count)
952 {
953     unsigned int i, ndescs = 0;
954 
955     if (unlikely(!vq->vring.desc)) {
956         return;
957     }
958 
959     for (i = 1; i < count; i++) {
960         virtqueue_packed_fill_desc(vq, &vq->used_elems[i], i, false);
961         ndescs += vq->used_elems[i].ndescs;
962     }
963     virtqueue_packed_fill_desc(vq, &vq->used_elems[0], 0, true);
964     ndescs += vq->used_elems[0].ndescs;
965 
966     vq->inuse -= ndescs;
967     vq->used_idx += ndescs;
968     if (vq->used_idx >= vq->vring.num) {
969         vq->used_idx -= vq->vring.num;
970         vq->used_wrap_counter ^= 1;
971         vq->signalled_used_valid = false;
972     }
973 }
974 
975 void virtqueue_flush(VirtQueue *vq, unsigned int count)
976 {
977     if (virtio_device_disabled(vq->vdev)) {
978         vq->inuse -= count;
979         return;
980     }
981 
982     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
983         virtqueue_packed_flush(vq, count);
984     } else {
985         virtqueue_split_flush(vq, count);
986     }
987 }
988 
989 void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
990                     unsigned int len)
991 {
992     RCU_READ_LOCK_GUARD();
993     virtqueue_fill(vq, elem, len, 0);
994     virtqueue_flush(vq, 1);
995 }
996 
997 /* Called within rcu_read_lock().  */
998 static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
999 {
1000     uint16_t avail_idx, num_heads;
1001 
1002     /* Use shadow index whenever possible. */
1003     avail_idx = (vq->shadow_avail_idx != idx) ? vq->shadow_avail_idx
1004                                               : vring_avail_idx(vq);
1005     num_heads = avail_idx - idx;
1006 
1007     /* Check it isn't doing very strange things with descriptor numbers. */
1008     if (num_heads > vq->vring.num) {
1009         virtio_error(vq->vdev, "Guest moved used index from %u to %u",
1010                      idx, vq->shadow_avail_idx);
1011         return -EINVAL;
1012     }
1013     /*
1014      * On success, callers read a descriptor at vq->last_avail_idx.
1015      * Make sure descriptor read does not bypass avail index read.
1016      *
1017      * This is necessary even if we are using a shadow index, since
1018      * the shadow index could have been initialized by calling
1019      * vring_avail_idx() outside of this function, i.e., by a guest
1020      * memory read not accompanied by a barrier.
1021      */
1022     if (num_heads) {
1023         smp_rmb();
1024     }
1025 
1026     return num_heads;
1027 }
1028 
1029 /* Called within rcu_read_lock().  */
1030 static bool virtqueue_get_head(VirtQueue *vq, unsigned int idx,
1031                                unsigned int *head)
1032 {
1033     /* Grab the next descriptor number they're advertising, and increment
1034      * the index we've seen. */
1035     *head = vring_avail_ring(vq, idx % vq->vring.num);
1036 
1037     /* If their number is silly, that's a fatal mistake. */
1038     if (*head >= vq->vring.num) {
1039         virtio_error(vq->vdev, "Guest says index %u is available", *head);
1040         return false;
1041     }
1042 
1043     return true;
1044 }
1045 
1046 enum {
1047     VIRTQUEUE_READ_DESC_ERROR = -1,
1048     VIRTQUEUE_READ_DESC_DONE = 0,   /* end of chain */
1049     VIRTQUEUE_READ_DESC_MORE = 1,   /* more buffers in chain */
1050 };
1051 
1052 /* Reads the 'desc->next' descriptor into '*desc'. */
1053 static int virtqueue_split_read_next_desc(VirtIODevice *vdev, VRingDesc *desc,
1054                                           MemoryRegionCache *desc_cache,
1055                                           unsigned int max)
1056 {
1057     /* If this descriptor says it doesn't chain, we're done. */
1058     if (!(desc->flags & VRING_DESC_F_NEXT)) {
1059         return VIRTQUEUE_READ_DESC_DONE;
1060     }
1061 
1062     /* Check they're not leading us off end of descriptors. */
1063     if (desc->next >= max) {
1064         virtio_error(vdev, "Desc next is %u", desc->next);
1065         return VIRTQUEUE_READ_DESC_ERROR;
1066     }
1067 
1068     vring_split_desc_read(vdev, desc, desc_cache, desc->next);
1069     return VIRTQUEUE_READ_DESC_MORE;
1070 }
1071 
1072 /* Called within rcu_read_lock().  */
1073 static void virtqueue_split_get_avail_bytes(VirtQueue *vq,
1074                             unsigned int *in_bytes, unsigned int *out_bytes,
1075                             unsigned max_in_bytes, unsigned max_out_bytes,
1076                             VRingMemoryRegionCaches *caches)
1077 {
1078     VirtIODevice *vdev = vq->vdev;
1079     unsigned int idx;
1080     unsigned int total_bufs, in_total, out_total;
1081     MemoryRegionCache indirect_desc_cache;
1082     int64_t len = 0;
1083     int rc;
1084 
1085     address_space_cache_init_empty(&indirect_desc_cache);
1086 
1087     idx = vq->last_avail_idx;
1088     total_bufs = in_total = out_total = 0;
1089 
1090     while ((rc = virtqueue_num_heads(vq, idx)) > 0) {
1091         MemoryRegionCache *desc_cache = &caches->desc;
1092         unsigned int num_bufs;
1093         VRingDesc desc;
1094         unsigned int i;
1095         unsigned int max = vq->vring.num;
1096 
1097         num_bufs = total_bufs;
1098 
1099         if (!virtqueue_get_head(vq, idx++, &i)) {
1100             goto err;
1101         }
1102 
1103         vring_split_desc_read(vdev, &desc, desc_cache, i);
1104 
1105         if (desc.flags & VRING_DESC_F_INDIRECT) {
1106             if (!desc.len || (desc.len % sizeof(VRingDesc))) {
1107                 virtio_error(vdev, "Invalid size for indirect buffer table");
1108                 goto err;
1109             }
1110 
1111             /* If we've got too many, that implies a descriptor loop. */
1112             if (num_bufs >= max) {
1113                 virtio_error(vdev, "Looped descriptor");
1114                 goto err;
1115             }
1116 
1117             /* loop over the indirect descriptor table */
1118             len = address_space_cache_init(&indirect_desc_cache,
1119                                            vdev->dma_as,
1120                                            desc.addr, desc.len, false);
1121             desc_cache = &indirect_desc_cache;
1122             if (len < desc.len) {
1123                 virtio_error(vdev, "Cannot map indirect buffer");
1124                 goto err;
1125             }
1126 
1127             max = desc.len / sizeof(VRingDesc);
1128             num_bufs = i = 0;
1129             vring_split_desc_read(vdev, &desc, desc_cache, i);
1130         }
1131 
1132         do {
1133             /* If we've got too many, that implies a descriptor loop. */
1134             if (++num_bufs > max) {
1135                 virtio_error(vdev, "Looped descriptor");
1136                 goto err;
1137             }
1138 
1139             if (desc.flags & VRING_DESC_F_WRITE) {
1140                 in_total += desc.len;
1141             } else {
1142                 out_total += desc.len;
1143             }
1144             if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
1145                 goto done;
1146             }
1147 
1148             rc = virtqueue_split_read_next_desc(vdev, &desc, desc_cache, max);
1149         } while (rc == VIRTQUEUE_READ_DESC_MORE);
1150 
1151         if (rc == VIRTQUEUE_READ_DESC_ERROR) {
1152             goto err;
1153         }
1154 
1155         if (desc_cache == &indirect_desc_cache) {
1156             address_space_cache_destroy(&indirect_desc_cache);
1157             total_bufs++;
1158         } else {
1159             total_bufs = num_bufs;
1160         }
1161     }
1162 
1163     if (rc < 0) {
1164         goto err;
1165     }
1166 
1167 done:
1168     address_space_cache_destroy(&indirect_desc_cache);
1169     if (in_bytes) {
1170         *in_bytes = in_total;
1171     }
1172     if (out_bytes) {
1173         *out_bytes = out_total;
1174     }
1175     return;
1176 
1177 err:
1178     in_total = out_total = 0;
1179     goto done;
1180 }
1181 
1182 static int virtqueue_packed_read_next_desc(VirtQueue *vq,
1183                                            VRingPackedDesc *desc,
1184                                            MemoryRegionCache
1185                                            *desc_cache,
1186                                            unsigned int max,
1187                                            unsigned int *next,
1188                                            bool indirect)
1189 {
1190     /* If this descriptor says it doesn't chain, we're done. */
1191     if (!indirect && !(desc->flags & VRING_DESC_F_NEXT)) {
1192         return VIRTQUEUE_READ_DESC_DONE;
1193     }
1194 
1195     ++*next;
1196     if (*next == max) {
1197         if (indirect) {
1198             return VIRTQUEUE_READ_DESC_DONE;
1199         } else {
1200             (*next) -= vq->vring.num;
1201         }
1202     }
1203 
1204     vring_packed_desc_read(vq->vdev, desc, desc_cache, *next, false);
1205     return VIRTQUEUE_READ_DESC_MORE;
1206 }
1207 
1208 /* Called within rcu_read_lock().  */
1209 static void virtqueue_packed_get_avail_bytes(VirtQueue *vq,
1210                                              unsigned int *in_bytes,
1211                                              unsigned int *out_bytes,
1212                                              unsigned max_in_bytes,
1213                                              unsigned max_out_bytes,
1214                                              VRingMemoryRegionCaches *caches)
1215 {
1216     VirtIODevice *vdev = vq->vdev;
1217     unsigned int idx;
1218     unsigned int total_bufs, in_total, out_total;
1219     MemoryRegionCache indirect_desc_cache;
1220     MemoryRegionCache *desc_cache;
1221     int64_t len = 0;
1222     VRingPackedDesc desc;
1223     bool wrap_counter;
1224 
1225     address_space_cache_init_empty(&indirect_desc_cache);
1226 
1227     idx = vq->last_avail_idx;
1228     wrap_counter = vq->last_avail_wrap_counter;
1229     total_bufs = in_total = out_total = 0;
1230 
1231     for (;;) {
1232         unsigned int num_bufs = total_bufs;
1233         unsigned int i = idx;
1234         int rc;
1235         unsigned int max = vq->vring.num;
1236 
1237         desc_cache = &caches->desc;
1238 
1239         vring_packed_desc_read(vdev, &desc, desc_cache, idx, true);
1240         if (!is_desc_avail(desc.flags, wrap_counter)) {
1241             break;
1242         }
1243 
1244         if (desc.flags & VRING_DESC_F_INDIRECT) {
1245             if (desc.len % sizeof(VRingPackedDesc)) {
1246                 virtio_error(vdev, "Invalid size for indirect buffer table");
1247                 goto err;
1248             }
1249 
1250             /* If we've got too many, that implies a descriptor loop. */
1251             if (num_bufs >= max) {
1252                 virtio_error(vdev, "Looped descriptor");
1253                 goto err;
1254             }
1255 
1256             /* loop over the indirect descriptor table */
1257             len = address_space_cache_init(&indirect_desc_cache,
1258                                            vdev->dma_as,
1259                                            desc.addr, desc.len, false);
1260             desc_cache = &indirect_desc_cache;
1261             if (len < desc.len) {
1262                 virtio_error(vdev, "Cannot map indirect buffer");
1263                 goto err;
1264             }
1265 
1266             max = desc.len / sizeof(VRingPackedDesc);
1267             num_bufs = i = 0;
1268             vring_packed_desc_read(vdev, &desc, desc_cache, i, false);
1269         }
1270 
1271         do {
1272             /* If we've got too many, that implies a descriptor loop. */
1273             if (++num_bufs > max) {
1274                 virtio_error(vdev, "Looped descriptor");
1275                 goto err;
1276             }
1277 
1278             if (desc.flags & VRING_DESC_F_WRITE) {
1279                 in_total += desc.len;
1280             } else {
1281                 out_total += desc.len;
1282             }
1283             if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
1284                 goto done;
1285             }
1286 
1287             rc = virtqueue_packed_read_next_desc(vq, &desc, desc_cache, max,
1288                                                  &i, desc_cache ==
1289                                                  &indirect_desc_cache);
1290         } while (rc == VIRTQUEUE_READ_DESC_MORE);
1291 
1292         if (desc_cache == &indirect_desc_cache) {
1293             address_space_cache_destroy(&indirect_desc_cache);
1294             total_bufs++;
1295             idx++;
1296         } else {
1297             idx += num_bufs - total_bufs;
1298             total_bufs = num_bufs;
1299         }
1300 
1301         if (idx >= vq->vring.num) {
1302             idx -= vq->vring.num;
1303             wrap_counter ^= 1;
1304         }
1305     }
1306 
1307     /* Record the index and wrap counter for a kick we want */
1308     vq->shadow_avail_idx = idx;
1309     vq->shadow_avail_wrap_counter = wrap_counter;
1310 done:
1311     address_space_cache_destroy(&indirect_desc_cache);
1312     if (in_bytes) {
1313         *in_bytes = in_total;
1314     }
1315     if (out_bytes) {
1316         *out_bytes = out_total;
1317     }
1318     return;
1319 
1320 err:
1321     in_total = out_total = 0;
1322     goto done;
1323 }
1324 
1325 void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
1326                                unsigned int *out_bytes,
1327                                unsigned max_in_bytes, unsigned max_out_bytes)
1328 {
1329     uint16_t desc_size;
1330     VRingMemoryRegionCaches *caches;
1331 
1332     RCU_READ_LOCK_GUARD();
1333 
1334     if (unlikely(!vq->vring.desc)) {
1335         goto err;
1336     }
1337 
1338     caches = vring_get_region_caches(vq);
1339     if (!caches) {
1340         goto err;
1341     }
1342 
1343     desc_size = virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED) ?
1344                                 sizeof(VRingPackedDesc) : sizeof(VRingDesc);
1345     if (caches->desc.len < vq->vring.num * desc_size) {
1346         virtio_error(vq->vdev, "Cannot map descriptor ring");
1347         goto err;
1348     }
1349 
1350     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
1351         virtqueue_packed_get_avail_bytes(vq, in_bytes, out_bytes,
1352                                          max_in_bytes, max_out_bytes,
1353                                          caches);
1354     } else {
1355         virtqueue_split_get_avail_bytes(vq, in_bytes, out_bytes,
1356                                         max_in_bytes, max_out_bytes,
1357                                         caches);
1358     }
1359 
1360     return;
1361 err:
1362     if (in_bytes) {
1363         *in_bytes = 0;
1364     }
1365     if (out_bytes) {
1366         *out_bytes = 0;
1367     }
1368 }
1369 
1370 int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
1371                           unsigned int out_bytes)
1372 {
1373     unsigned int in_total, out_total;
1374 
1375     virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
1376     return in_bytes <= in_total && out_bytes <= out_total;
1377 }
1378 
1379 static bool virtqueue_map_desc(VirtIODevice *vdev, unsigned int *p_num_sg,
1380                                hwaddr *addr, struct iovec *iov,
1381                                unsigned int max_num_sg, bool is_write,
1382                                hwaddr pa, size_t sz)
1383 {
1384     bool ok = false;
1385     unsigned num_sg = *p_num_sg;
1386     assert(num_sg <= max_num_sg);
1387 
1388     if (!sz) {
1389         virtio_error(vdev, "virtio: zero sized buffers are not allowed");
1390         goto out;
1391     }
1392 
1393     while (sz) {
1394         hwaddr len = sz;
1395 
1396         if (num_sg == max_num_sg) {
1397             virtio_error(vdev, "virtio: too many write descriptors in "
1398                                "indirect table");
1399             goto out;
1400         }
1401 
1402         iov[num_sg].iov_base = dma_memory_map(vdev->dma_as, pa, &len,
1403                                               is_write ?
1404                                               DMA_DIRECTION_FROM_DEVICE :
1405                                               DMA_DIRECTION_TO_DEVICE,
1406                                               MEMTXATTRS_UNSPECIFIED);
1407         if (!iov[num_sg].iov_base) {
1408             virtio_error(vdev, "virtio: bogus descriptor or out of resources");
1409             goto out;
1410         }
1411 
1412         iov[num_sg].iov_len = len;
1413         addr[num_sg] = pa;
1414 
1415         sz -= len;
1416         pa += len;
1417         num_sg++;
1418     }
1419     ok = true;
1420 
1421 out:
1422     *p_num_sg = num_sg;
1423     return ok;
1424 }
1425 
1426 /* Only used by error code paths before we have a VirtQueueElement (therefore
1427  * virtqueue_unmap_sg() can't be used).  Assumes buffers weren't written to
1428  * yet.
1429  */
1430 static void virtqueue_undo_map_desc(unsigned int out_num, unsigned int in_num,
1431                                     struct iovec *iov)
1432 {
1433     unsigned int i;
1434 
1435     for (i = 0; i < out_num + in_num; i++) {
1436         int is_write = i >= out_num;
1437 
1438         cpu_physical_memory_unmap(iov->iov_base, iov->iov_len, is_write, 0);
1439         iov++;
1440     }
1441 }
1442 
1443 static void virtqueue_map_iovec(VirtIODevice *vdev, struct iovec *sg,
1444                                 hwaddr *addr, unsigned int num_sg,
1445                                 bool is_write)
1446 {
1447     unsigned int i;
1448     hwaddr len;
1449 
1450     for (i = 0; i < num_sg; i++) {
1451         len = sg[i].iov_len;
1452         sg[i].iov_base = dma_memory_map(vdev->dma_as,
1453                                         addr[i], &len, is_write ?
1454                                         DMA_DIRECTION_FROM_DEVICE :
1455                                         DMA_DIRECTION_TO_DEVICE,
1456                                         MEMTXATTRS_UNSPECIFIED);
1457         if (!sg[i].iov_base) {
1458             error_report("virtio: error trying to map MMIO memory");
1459             exit(1);
1460         }
1461         if (len != sg[i].iov_len) {
1462             error_report("virtio: unexpected memory split");
1463             exit(1);
1464         }
1465     }
1466 }
1467 
1468 void virtqueue_map(VirtIODevice *vdev, VirtQueueElement *elem)
1469 {
1470     virtqueue_map_iovec(vdev, elem->in_sg, elem->in_addr, elem->in_num, true);
1471     virtqueue_map_iovec(vdev, elem->out_sg, elem->out_addr, elem->out_num,
1472                                                                         false);
1473 }
1474 
1475 static void *virtqueue_alloc_element(size_t sz, unsigned out_num, unsigned in_num)
1476 {
1477     VirtQueueElement *elem;
1478     size_t in_addr_ofs = QEMU_ALIGN_UP(sz, __alignof__(elem->in_addr[0]));
1479     size_t out_addr_ofs = in_addr_ofs + in_num * sizeof(elem->in_addr[0]);
1480     size_t out_addr_end = out_addr_ofs + out_num * sizeof(elem->out_addr[0]);
1481     size_t in_sg_ofs = QEMU_ALIGN_UP(out_addr_end, __alignof__(elem->in_sg[0]));
1482     size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]);
1483     size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]);
1484 
1485     assert(sz >= sizeof(VirtQueueElement));
1486     elem = g_malloc(out_sg_end);
1487     trace_virtqueue_alloc_element(elem, sz, in_num, out_num);
1488     elem->out_num = out_num;
1489     elem->in_num = in_num;
1490     elem->in_addr = (void *)elem + in_addr_ofs;
1491     elem->out_addr = (void *)elem + out_addr_ofs;
1492     elem->in_sg = (void *)elem + in_sg_ofs;
1493     elem->out_sg = (void *)elem + out_sg_ofs;
1494     return elem;
1495 }
1496 
1497 static void *virtqueue_split_pop(VirtQueue *vq, size_t sz)
1498 {
1499     unsigned int i, head, max;
1500     VRingMemoryRegionCaches *caches;
1501     MemoryRegionCache indirect_desc_cache;
1502     MemoryRegionCache *desc_cache;
1503     int64_t len;
1504     VirtIODevice *vdev = vq->vdev;
1505     VirtQueueElement *elem = NULL;
1506     unsigned out_num, in_num, elem_entries;
1507     hwaddr addr[VIRTQUEUE_MAX_SIZE];
1508     struct iovec iov[VIRTQUEUE_MAX_SIZE];
1509     VRingDesc desc;
1510     int rc;
1511 
1512     address_space_cache_init_empty(&indirect_desc_cache);
1513 
1514     RCU_READ_LOCK_GUARD();
1515     if (virtio_queue_empty_rcu(vq)) {
1516         goto done;
1517     }
1518     /* Needed after virtio_queue_empty(), see comment in
1519      * virtqueue_num_heads(). */
1520     smp_rmb();
1521 
1522     /* When we start there are none of either input nor output. */
1523     out_num = in_num = elem_entries = 0;
1524 
1525     max = vq->vring.num;
1526 
1527     if (vq->inuse >= vq->vring.num) {
1528         virtio_error(vdev, "Virtqueue size exceeded");
1529         goto done;
1530     }
1531 
1532     if (!virtqueue_get_head(vq, vq->last_avail_idx++, &head)) {
1533         goto done;
1534     }
1535 
1536     if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
1537         vring_set_avail_event(vq, vq->last_avail_idx);
1538     }
1539 
1540     i = head;
1541 
1542     caches = vring_get_region_caches(vq);
1543     if (!caches) {
1544         virtio_error(vdev, "Region caches not initialized");
1545         goto done;
1546     }
1547 
1548     if (caches->desc.len < max * sizeof(VRingDesc)) {
1549         virtio_error(vdev, "Cannot map descriptor ring");
1550         goto done;
1551     }
1552 
1553     desc_cache = &caches->desc;
1554     vring_split_desc_read(vdev, &desc, desc_cache, i);
1555     if (desc.flags & VRING_DESC_F_INDIRECT) {
1556         if (!desc.len || (desc.len % sizeof(VRingDesc))) {
1557             virtio_error(vdev, "Invalid size for indirect buffer table");
1558             goto done;
1559         }
1560 
1561         /* loop over the indirect descriptor table */
1562         len = address_space_cache_init(&indirect_desc_cache, vdev->dma_as,
1563                                        desc.addr, desc.len, false);
1564         desc_cache = &indirect_desc_cache;
1565         if (len < desc.len) {
1566             virtio_error(vdev, "Cannot map indirect buffer");
1567             goto done;
1568         }
1569 
1570         max = desc.len / sizeof(VRingDesc);
1571         i = 0;
1572         vring_split_desc_read(vdev, &desc, desc_cache, i);
1573     }
1574 
1575     /* Collect all the descriptors */
1576     do {
1577         bool map_ok;
1578 
1579         if (desc.flags & VRING_DESC_F_WRITE) {
1580             map_ok = virtqueue_map_desc(vdev, &in_num, addr + out_num,
1581                                         iov + out_num,
1582                                         VIRTQUEUE_MAX_SIZE - out_num, true,
1583                                         desc.addr, desc.len);
1584         } else {
1585             if (in_num) {
1586                 virtio_error(vdev, "Incorrect order for descriptors");
1587                 goto err_undo_map;
1588             }
1589             map_ok = virtqueue_map_desc(vdev, &out_num, addr, iov,
1590                                         VIRTQUEUE_MAX_SIZE, false,
1591                                         desc.addr, desc.len);
1592         }
1593         if (!map_ok) {
1594             goto err_undo_map;
1595         }
1596 
1597         /* If we've got too many, that implies a descriptor loop. */
1598         if (++elem_entries > max) {
1599             virtio_error(vdev, "Looped descriptor");
1600             goto err_undo_map;
1601         }
1602 
1603         rc = virtqueue_split_read_next_desc(vdev, &desc, desc_cache, max);
1604     } while (rc == VIRTQUEUE_READ_DESC_MORE);
1605 
1606     if (rc == VIRTQUEUE_READ_DESC_ERROR) {
1607         goto err_undo_map;
1608     }
1609 
1610     /* Now copy what we have collected and mapped */
1611     elem = virtqueue_alloc_element(sz, out_num, in_num);
1612     elem->index = head;
1613     elem->ndescs = 1;
1614     for (i = 0; i < out_num; i++) {
1615         elem->out_addr[i] = addr[i];
1616         elem->out_sg[i] = iov[i];
1617     }
1618     for (i = 0; i < in_num; i++) {
1619         elem->in_addr[i] = addr[out_num + i];
1620         elem->in_sg[i] = iov[out_num + i];
1621     }
1622 
1623     vq->inuse++;
1624 
1625     trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
1626 done:
1627     address_space_cache_destroy(&indirect_desc_cache);
1628 
1629     return elem;
1630 
1631 err_undo_map:
1632     virtqueue_undo_map_desc(out_num, in_num, iov);
1633     goto done;
1634 }
1635 
1636 static void *virtqueue_packed_pop(VirtQueue *vq, size_t sz)
1637 {
1638     unsigned int i, max;
1639     VRingMemoryRegionCaches *caches;
1640     MemoryRegionCache indirect_desc_cache;
1641     MemoryRegionCache *desc_cache;
1642     int64_t len;
1643     VirtIODevice *vdev = vq->vdev;
1644     VirtQueueElement *elem = NULL;
1645     unsigned out_num, in_num, elem_entries;
1646     hwaddr addr[VIRTQUEUE_MAX_SIZE];
1647     struct iovec iov[VIRTQUEUE_MAX_SIZE];
1648     VRingPackedDesc desc;
1649     uint16_t id;
1650     int rc;
1651 
1652     address_space_cache_init_empty(&indirect_desc_cache);
1653 
1654     RCU_READ_LOCK_GUARD();
1655     if (virtio_queue_packed_empty_rcu(vq)) {
1656         goto done;
1657     }
1658 
1659     /* When we start there are none of either input nor output. */
1660     out_num = in_num = elem_entries = 0;
1661 
1662     max = vq->vring.num;
1663 
1664     if (vq->inuse >= vq->vring.num) {
1665         virtio_error(vdev, "Virtqueue size exceeded");
1666         goto done;
1667     }
1668 
1669     i = vq->last_avail_idx;
1670 
1671     caches = vring_get_region_caches(vq);
1672     if (!caches) {
1673         virtio_error(vdev, "Region caches not initialized");
1674         goto done;
1675     }
1676 
1677     if (caches->desc.len < max * sizeof(VRingDesc)) {
1678         virtio_error(vdev, "Cannot map descriptor ring");
1679         goto done;
1680     }
1681 
1682     desc_cache = &caches->desc;
1683     vring_packed_desc_read(vdev, &desc, desc_cache, i, true);
1684     id = desc.id;
1685     if (desc.flags & VRING_DESC_F_INDIRECT) {
1686         if (desc.len % sizeof(VRingPackedDesc)) {
1687             virtio_error(vdev, "Invalid size for indirect buffer table");
1688             goto done;
1689         }
1690 
1691         /* loop over the indirect descriptor table */
1692         len = address_space_cache_init(&indirect_desc_cache, vdev->dma_as,
1693                                        desc.addr, desc.len, false);
1694         desc_cache = &indirect_desc_cache;
1695         if (len < desc.len) {
1696             virtio_error(vdev, "Cannot map indirect buffer");
1697             goto done;
1698         }
1699 
1700         max = desc.len / sizeof(VRingPackedDesc);
1701         i = 0;
1702         vring_packed_desc_read(vdev, &desc, desc_cache, i, false);
1703     }
1704 
1705     /* Collect all the descriptors */
1706     do {
1707         bool map_ok;
1708 
1709         if (desc.flags & VRING_DESC_F_WRITE) {
1710             map_ok = virtqueue_map_desc(vdev, &in_num, addr + out_num,
1711                                         iov + out_num,
1712                                         VIRTQUEUE_MAX_SIZE - out_num, true,
1713                                         desc.addr, desc.len);
1714         } else {
1715             if (in_num) {
1716                 virtio_error(vdev, "Incorrect order for descriptors");
1717                 goto err_undo_map;
1718             }
1719             map_ok = virtqueue_map_desc(vdev, &out_num, addr, iov,
1720                                         VIRTQUEUE_MAX_SIZE, false,
1721                                         desc.addr, desc.len);
1722         }
1723         if (!map_ok) {
1724             goto err_undo_map;
1725         }
1726 
1727         /* If we've got too many, that implies a descriptor loop. */
1728         if (++elem_entries > max) {
1729             virtio_error(vdev, "Looped descriptor");
1730             goto err_undo_map;
1731         }
1732 
1733         rc = virtqueue_packed_read_next_desc(vq, &desc, desc_cache, max, &i,
1734                                              desc_cache ==
1735                                              &indirect_desc_cache);
1736     } while (rc == VIRTQUEUE_READ_DESC_MORE);
1737 
1738     /* Now copy what we have collected and mapped */
1739     elem = virtqueue_alloc_element(sz, out_num, in_num);
1740     for (i = 0; i < out_num; i++) {
1741         elem->out_addr[i] = addr[i];
1742         elem->out_sg[i] = iov[i];
1743     }
1744     for (i = 0; i < in_num; i++) {
1745         elem->in_addr[i] = addr[out_num + i];
1746         elem->in_sg[i] = iov[out_num + i];
1747     }
1748 
1749     elem->index = id;
1750     elem->ndescs = (desc_cache == &indirect_desc_cache) ? 1 : elem_entries;
1751     vq->last_avail_idx += elem->ndescs;
1752     vq->inuse += elem->ndescs;
1753 
1754     if (vq->last_avail_idx >= vq->vring.num) {
1755         vq->last_avail_idx -= vq->vring.num;
1756         vq->last_avail_wrap_counter ^= 1;
1757     }
1758 
1759     vq->shadow_avail_idx = vq->last_avail_idx;
1760     vq->shadow_avail_wrap_counter = vq->last_avail_wrap_counter;
1761 
1762     trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
1763 done:
1764     address_space_cache_destroy(&indirect_desc_cache);
1765 
1766     return elem;
1767 
1768 err_undo_map:
1769     virtqueue_undo_map_desc(out_num, in_num, iov);
1770     goto done;
1771 }
1772 
1773 void *virtqueue_pop(VirtQueue *vq, size_t sz)
1774 {
1775     if (virtio_device_disabled(vq->vdev)) {
1776         return NULL;
1777     }
1778 
1779     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_F_RING_PACKED)) {
1780         return virtqueue_packed_pop(vq, sz);
1781     } else {
1782         return virtqueue_split_pop(vq, sz);
1783     }
1784 }
1785 
1786 static unsigned int virtqueue_packed_drop_all(VirtQueue *vq)
1787 {
1788     VRingMemoryRegionCaches *caches;
1789     MemoryRegionCache *desc_cache;
1790     unsigned int dropped = 0;
1791     VirtQueueElement elem = {};
1792     VirtIODevice *vdev = vq->vdev;
1793     VRingPackedDesc desc;
1794 
1795     RCU_READ_LOCK_GUARD();
1796 
1797     caches = vring_get_region_caches(vq);
1798     if (!caches) {
1799         return 0;
1800     }
1801 
1802     desc_cache = &caches->desc;
1803 
1804     virtio_queue_set_notification(vq, 0);
1805 
1806     while (vq->inuse < vq->vring.num) {
1807         unsigned int idx = vq->last_avail_idx;
1808         /*
1809          * works similar to virtqueue_pop but does not map buffers
1810          * and does not allocate any memory.
1811          */
1812         vring_packed_desc_read(vdev, &desc, desc_cache,
1813                                vq->last_avail_idx , true);
1814         if (!is_desc_avail(desc.flags, vq->last_avail_wrap_counter)) {
1815             break;
1816         }
1817         elem.index = desc.id;
1818         elem.ndescs = 1;
1819         while (virtqueue_packed_read_next_desc(vq, &desc, desc_cache,
1820                                                vq->vring.num, &idx, false)) {
1821             ++elem.ndescs;
1822         }
1823         /*
1824          * immediately push the element, nothing to unmap
1825          * as both in_num and out_num are set to 0.
1826          */
1827         virtqueue_push(vq, &elem, 0);
1828         dropped++;
1829         vq->last_avail_idx += elem.ndescs;
1830         if (vq->last_avail_idx >= vq->vring.num) {
1831             vq->last_avail_idx -= vq->vring.num;
1832             vq->last_avail_wrap_counter ^= 1;
1833         }
1834     }
1835 
1836     return dropped;
1837 }
1838 
1839 static unsigned int virtqueue_split_drop_all(VirtQueue *vq)
1840 {
1841     unsigned int dropped = 0;
1842     VirtQueueElement elem = {};
1843     VirtIODevice *vdev = vq->vdev;
1844     bool fEventIdx = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
1845 
1846     while (!virtio_queue_empty(vq) && vq->inuse < vq->vring.num) {
1847         /* works similar to virtqueue_pop but does not map buffers
1848         * and does not allocate any memory */
1849         smp_rmb();
1850         if (!virtqueue_get_head(vq, vq->last_avail_idx, &elem.index)) {
1851             break;
1852         }
1853         vq->inuse++;
1854         vq->last_avail_idx++;
1855         if (fEventIdx) {
1856             vring_set_avail_event(vq, vq->last_avail_idx);
1857         }
1858         /* immediately push the element, nothing to unmap
1859          * as both in_num and out_num are set to 0 */
1860         virtqueue_push(vq, &elem, 0);
1861         dropped++;
1862     }
1863 
1864     return dropped;
1865 }
1866 
1867 /* virtqueue_drop_all:
1868  * @vq: The #VirtQueue
1869  * Drops all queued buffers and indicates them to the guest
1870  * as if they are done. Useful when buffers can not be
1871  * processed but must be returned to the guest.
1872  */
1873 unsigned int virtqueue_drop_all(VirtQueue *vq)
1874 {
1875     struct VirtIODevice *vdev = vq->vdev;
1876 
1877     if (virtio_device_disabled(vq->vdev)) {
1878         return 0;
1879     }
1880 
1881     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
1882         return virtqueue_packed_drop_all(vq);
1883     } else {
1884         return virtqueue_split_drop_all(vq);
1885     }
1886 }
1887 
1888 /* Reading and writing a structure directly to QEMUFile is *awful*, but
1889  * it is what QEMU has always done by mistake.  We can change it sooner
1890  * or later by bumping the version number of the affected vm states.
1891  * In the meanwhile, since the in-memory layout of VirtQueueElement
1892  * has changed, we need to marshal to and from the layout that was
1893  * used before the change.
1894  */
1895 typedef struct VirtQueueElementOld {
1896     unsigned int index;
1897     unsigned int out_num;
1898     unsigned int in_num;
1899     hwaddr in_addr[VIRTQUEUE_MAX_SIZE];
1900     hwaddr out_addr[VIRTQUEUE_MAX_SIZE];
1901     struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
1902     struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
1903 } VirtQueueElementOld;
1904 
1905 void *qemu_get_virtqueue_element(VirtIODevice *vdev, QEMUFile *f, size_t sz)
1906 {
1907     VirtQueueElement *elem;
1908     VirtQueueElementOld data;
1909     int i;
1910 
1911     qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
1912 
1913     /* TODO: teach all callers that this can fail, and return failure instead
1914      * of asserting here.
1915      * This is just one thing (there are probably more) that must be
1916      * fixed before we can allow NDEBUG compilation.
1917      */
1918     assert(ARRAY_SIZE(data.in_addr) >= data.in_num);
1919     assert(ARRAY_SIZE(data.out_addr) >= data.out_num);
1920 
1921     elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);
1922     elem->index = data.index;
1923 
1924     for (i = 0; i < elem->in_num; i++) {
1925         elem->in_addr[i] = data.in_addr[i];
1926     }
1927 
1928     for (i = 0; i < elem->out_num; i++) {
1929         elem->out_addr[i] = data.out_addr[i];
1930     }
1931 
1932     for (i = 0; i < elem->in_num; i++) {
1933         /* Base is overwritten by virtqueue_map.  */
1934         elem->in_sg[i].iov_base = 0;
1935         elem->in_sg[i].iov_len = data.in_sg[i].iov_len;
1936     }
1937 
1938     for (i = 0; i < elem->out_num; i++) {
1939         /* Base is overwritten by virtqueue_map.  */
1940         elem->out_sg[i].iov_base = 0;
1941         elem->out_sg[i].iov_len = data.out_sg[i].iov_len;
1942     }
1943 
1944     if (virtio_host_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
1945         qemu_get_be32s(f, &elem->ndescs);
1946     }
1947 
1948     virtqueue_map(vdev, elem);
1949     return elem;
1950 }
1951 
1952 void qemu_put_virtqueue_element(VirtIODevice *vdev, QEMUFile *f,
1953                                 VirtQueueElement *elem)
1954 {
1955     VirtQueueElementOld data;
1956     int i;
1957 
1958     memset(&data, 0, sizeof(data));
1959     data.index = elem->index;
1960     data.in_num = elem->in_num;
1961     data.out_num = elem->out_num;
1962 
1963     for (i = 0; i < elem->in_num; i++) {
1964         data.in_addr[i] = elem->in_addr[i];
1965     }
1966 
1967     for (i = 0; i < elem->out_num; i++) {
1968         data.out_addr[i] = elem->out_addr[i];
1969     }
1970 
1971     for (i = 0; i < elem->in_num; i++) {
1972         /* Base is overwritten by virtqueue_map when loading.  Do not
1973          * save it, as it would leak the QEMU address space layout.  */
1974         data.in_sg[i].iov_len = elem->in_sg[i].iov_len;
1975     }
1976 
1977     for (i = 0; i < elem->out_num; i++) {
1978         /* Do not save iov_base as above.  */
1979         data.out_sg[i].iov_len = elem->out_sg[i].iov_len;
1980     }
1981 
1982     if (virtio_host_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
1983         qemu_put_be32s(f, &elem->ndescs);
1984     }
1985 
1986     qemu_put_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
1987 }
1988 
1989 /* virtio device */
1990 static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
1991 {
1992     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1993     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1994 
1995     if (virtio_device_disabled(vdev)) {
1996         return;
1997     }
1998 
1999     if (k->notify) {
2000         k->notify(qbus->parent, vector);
2001     }
2002 }
2003 
2004 void virtio_update_irq(VirtIODevice *vdev)
2005 {
2006     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
2007 }
2008 
2009 static int virtio_validate_features(VirtIODevice *vdev)
2010 {
2011     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2012 
2013     if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM) &&
2014         !virtio_vdev_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {
2015         return -EFAULT;
2016     }
2017 
2018     if (k->validate_features) {
2019         return k->validate_features(vdev);
2020     } else {
2021         return 0;
2022     }
2023 }
2024 
2025 int virtio_set_status(VirtIODevice *vdev, uint8_t val)
2026 {
2027     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2028     trace_virtio_set_status(vdev, val);
2029 
2030     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2031         if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
2032             val & VIRTIO_CONFIG_S_FEATURES_OK) {
2033             int ret = virtio_validate_features(vdev);
2034 
2035             if (ret) {
2036                 return ret;
2037             }
2038         }
2039     }
2040 
2041     if ((vdev->status & VIRTIO_CONFIG_S_DRIVER_OK) !=
2042         (val & VIRTIO_CONFIG_S_DRIVER_OK)) {
2043         virtio_set_started(vdev, val & VIRTIO_CONFIG_S_DRIVER_OK);
2044     }
2045 
2046     if (k->set_status) {
2047         k->set_status(vdev, val);
2048     }
2049     vdev->status = val;
2050 
2051     return 0;
2052 }
2053 
2054 static enum virtio_device_endian virtio_default_endian(void)
2055 {
2056     if (target_words_bigendian()) {
2057         return VIRTIO_DEVICE_ENDIAN_BIG;
2058     } else {
2059         return VIRTIO_DEVICE_ENDIAN_LITTLE;
2060     }
2061 }
2062 
2063 static enum virtio_device_endian virtio_current_cpu_endian(void)
2064 {
2065     if (cpu_virtio_is_big_endian(current_cpu)) {
2066         return VIRTIO_DEVICE_ENDIAN_BIG;
2067     } else {
2068         return VIRTIO_DEVICE_ENDIAN_LITTLE;
2069     }
2070 }
2071 
2072 static void __virtio_queue_reset(VirtIODevice *vdev, uint32_t i)
2073 {
2074     vdev->vq[i].vring.desc = 0;
2075     vdev->vq[i].vring.avail = 0;
2076     vdev->vq[i].vring.used = 0;
2077     vdev->vq[i].last_avail_idx = 0;
2078     vdev->vq[i].shadow_avail_idx = 0;
2079     vdev->vq[i].used_idx = 0;
2080     vdev->vq[i].last_avail_wrap_counter = true;
2081     vdev->vq[i].shadow_avail_wrap_counter = true;
2082     vdev->vq[i].used_wrap_counter = true;
2083     virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
2084     vdev->vq[i].signalled_used = 0;
2085     vdev->vq[i].signalled_used_valid = false;
2086     vdev->vq[i].notification = true;
2087     vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
2088     vdev->vq[i].inuse = 0;
2089     virtio_virtqueue_reset_region_cache(&vdev->vq[i]);
2090 }
2091 
2092 void virtio_queue_reset(VirtIODevice *vdev, uint32_t queue_index)
2093 {
2094     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2095 
2096     if (k->queue_reset) {
2097         k->queue_reset(vdev, queue_index);
2098     }
2099 
2100     __virtio_queue_reset(vdev, queue_index);
2101 }
2102 
2103 void virtio_queue_enable(VirtIODevice *vdev, uint32_t queue_index)
2104 {
2105     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2106 
2107     /*
2108      * TODO: Seabios is currently out of spec and triggering this error.
2109      * So this needs to be fixed in Seabios, then this can
2110      * be re-enabled for new machine types only, and also after
2111      * being converted to LOG_GUEST_ERROR.
2112      *
2113     if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2114         error_report("queue_enable is only supported in devices of virtio "
2115                      "1.0 or later.");
2116     }
2117     */
2118 
2119     if (k->queue_enable) {
2120         k->queue_enable(vdev, queue_index);
2121     }
2122 }
2123 
2124 void virtio_reset(void *opaque)
2125 {
2126     VirtIODevice *vdev = opaque;
2127     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2128     int i;
2129 
2130     virtio_set_status(vdev, 0);
2131     if (current_cpu) {
2132         /* Guest initiated reset */
2133         vdev->device_endian = virtio_current_cpu_endian();
2134     } else {
2135         /* System reset */
2136         vdev->device_endian = virtio_default_endian();
2137     }
2138 
2139     if (k->reset) {
2140         k->reset(vdev);
2141     }
2142 
2143     vdev->start_on_kick = false;
2144     vdev->started = false;
2145     vdev->broken = false;
2146     vdev->guest_features = 0;
2147     vdev->queue_sel = 0;
2148     vdev->status = 0;
2149     vdev->disabled = false;
2150     qatomic_set(&vdev->isr, 0);
2151     vdev->config_vector = VIRTIO_NO_VECTOR;
2152     virtio_notify_vector(vdev, vdev->config_vector);
2153 
2154     for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2155         __virtio_queue_reset(vdev, i);
2156     }
2157 }
2158 
2159 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
2160 {
2161     if (!vdev->vq[n].vring.num) {
2162         return;
2163     }
2164     vdev->vq[n].vring.desc = addr;
2165     virtio_queue_update_rings(vdev, n);
2166 }
2167 
2168 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
2169 {
2170     return vdev->vq[n].vring.desc;
2171 }
2172 
2173 void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
2174                             hwaddr avail, hwaddr used)
2175 {
2176     if (!vdev->vq[n].vring.num) {
2177         return;
2178     }
2179     vdev->vq[n].vring.desc = desc;
2180     vdev->vq[n].vring.avail = avail;
2181     vdev->vq[n].vring.used = used;
2182     virtio_init_region_cache(vdev, n);
2183 }
2184 
2185 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
2186 {
2187     /* Don't allow guest to flip queue between existent and
2188      * nonexistent states, or to set it to an invalid size.
2189      */
2190     if (!!num != !!vdev->vq[n].vring.num ||
2191         num > VIRTQUEUE_MAX_SIZE ||
2192         num < 0) {
2193         return;
2194     }
2195     vdev->vq[n].vring.num = num;
2196 }
2197 
2198 VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
2199 {
2200     return QLIST_FIRST(&vdev->vector_queues[vector]);
2201 }
2202 
2203 VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
2204 {
2205     return QLIST_NEXT(vq, node);
2206 }
2207 
2208 int virtio_queue_get_num(VirtIODevice *vdev, int n)
2209 {
2210     return vdev->vq[n].vring.num;
2211 }
2212 
2213 int virtio_queue_get_max_num(VirtIODevice *vdev, int n)
2214 {
2215     return vdev->vq[n].vring.num_default;
2216 }
2217 
2218 int virtio_get_num_queues(VirtIODevice *vdev)
2219 {
2220     int i;
2221 
2222     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2223         if (!virtio_queue_get_num(vdev, i)) {
2224             break;
2225         }
2226     }
2227 
2228     return i;
2229 }
2230 
2231 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
2232 {
2233     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2234     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2235 
2236     /* virtio-1 compliant devices cannot change the alignment */
2237     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2238         error_report("tried to modify queue alignment for virtio-1 device");
2239         return;
2240     }
2241     /* Check that the transport told us it was going to do this
2242      * (so a buggy transport will immediately assert rather than
2243      * silently failing to migrate this state)
2244      */
2245     assert(k->has_variable_vring_alignment);
2246 
2247     if (align) {
2248         vdev->vq[n].vring.align = align;
2249         virtio_queue_update_rings(vdev, n);
2250     }
2251 }
2252 
2253 static void virtio_queue_notify_vq(VirtQueue *vq)
2254 {
2255     if (vq->vring.desc && vq->handle_output) {
2256         VirtIODevice *vdev = vq->vdev;
2257 
2258         if (unlikely(vdev->broken)) {
2259             return;
2260         }
2261 
2262         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2263         vq->handle_output(vdev, vq);
2264 
2265         if (unlikely(vdev->start_on_kick)) {
2266             virtio_set_started(vdev, true);
2267         }
2268     }
2269 }
2270 
2271 void virtio_queue_notify(VirtIODevice *vdev, int n)
2272 {
2273     VirtQueue *vq = &vdev->vq[n];
2274 
2275     if (unlikely(!vq->vring.desc || vdev->broken)) {
2276         return;
2277     }
2278 
2279     trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2280     if (vq->host_notifier_enabled) {
2281         event_notifier_set(&vq->host_notifier);
2282     } else if (vq->handle_output) {
2283         vq->handle_output(vdev, vq);
2284 
2285         if (unlikely(vdev->start_on_kick)) {
2286             virtio_set_started(vdev, true);
2287         }
2288     }
2289 }
2290 
2291 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
2292 {
2293     return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
2294         VIRTIO_NO_VECTOR;
2295 }
2296 
2297 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
2298 {
2299     VirtQueue *vq = &vdev->vq[n];
2300 
2301     if (n < VIRTIO_QUEUE_MAX) {
2302         if (vdev->vector_queues &&
2303             vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
2304             QLIST_REMOVE(vq, node);
2305         }
2306         vdev->vq[n].vector = vector;
2307         if (vdev->vector_queues &&
2308             vector != VIRTIO_NO_VECTOR) {
2309             QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
2310         }
2311     }
2312 }
2313 
2314 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
2315                             VirtIOHandleOutput handle_output)
2316 {
2317     int i;
2318 
2319     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2320         if (vdev->vq[i].vring.num == 0)
2321             break;
2322     }
2323 
2324     if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
2325         abort();
2326 
2327     vdev->vq[i].vring.num = queue_size;
2328     vdev->vq[i].vring.num_default = queue_size;
2329     vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
2330     vdev->vq[i].handle_output = handle_output;
2331     vdev->vq[i].used_elems = g_new0(VirtQueueElement, queue_size);
2332 
2333     return &vdev->vq[i];
2334 }
2335 
2336 void virtio_delete_queue(VirtQueue *vq)
2337 {
2338     vq->vring.num = 0;
2339     vq->vring.num_default = 0;
2340     vq->handle_output = NULL;
2341     g_free(vq->used_elems);
2342     vq->used_elems = NULL;
2343     virtio_virtqueue_reset_region_cache(vq);
2344 }
2345 
2346 void virtio_del_queue(VirtIODevice *vdev, int n)
2347 {
2348     if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
2349         abort();
2350     }
2351 
2352     virtio_delete_queue(&vdev->vq[n]);
2353 }
2354 
2355 static void virtio_set_isr(VirtIODevice *vdev, int value)
2356 {
2357     uint8_t old = qatomic_read(&vdev->isr);
2358 
2359     /* Do not write ISR if it does not change, so that its cacheline remains
2360      * shared in the common case where the guest does not read it.
2361      */
2362     if ((old & value) != value) {
2363         qatomic_or(&vdev->isr, value);
2364     }
2365 }
2366 
2367 /* Called within rcu_read_lock(). */
2368 static bool virtio_split_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2369 {
2370     uint16_t old, new;
2371     bool v;
2372     /* We need to expose used array entries before checking used event. */
2373     smp_mb();
2374     /* Always notify when queue is empty (when feature acknowledge) */
2375     if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2376         !vq->inuse && virtio_queue_empty(vq)) {
2377         return true;
2378     }
2379 
2380     if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2381         return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
2382     }
2383 
2384     v = vq->signalled_used_valid;
2385     vq->signalled_used_valid = true;
2386     old = vq->signalled_used;
2387     new = vq->signalled_used = vq->used_idx;
2388     return !v || vring_need_event(vring_get_used_event(vq), new, old);
2389 }
2390 
2391 static bool vring_packed_need_event(VirtQueue *vq, bool wrap,
2392                                     uint16_t off_wrap, uint16_t new,
2393                                     uint16_t old)
2394 {
2395     int off = off_wrap & ~(1 << 15);
2396 
2397     if (wrap != off_wrap >> 15) {
2398         off -= vq->vring.num;
2399     }
2400 
2401     return vring_need_event(off, new, old);
2402 }
2403 
2404 /* Called within rcu_read_lock(). */
2405 static bool virtio_packed_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2406 {
2407     VRingPackedDescEvent e;
2408     uint16_t old, new;
2409     bool v;
2410     VRingMemoryRegionCaches *caches;
2411 
2412     caches = vring_get_region_caches(vq);
2413     if (!caches) {
2414         return false;
2415     }
2416 
2417     vring_packed_event_read(vdev, &caches->avail, &e);
2418 
2419     old = vq->signalled_used;
2420     new = vq->signalled_used = vq->used_idx;
2421     v = vq->signalled_used_valid;
2422     vq->signalled_used_valid = true;
2423 
2424     if (e.flags == VRING_PACKED_EVENT_FLAG_DISABLE) {
2425         return false;
2426     } else if (e.flags == VRING_PACKED_EVENT_FLAG_ENABLE) {
2427         return true;
2428     }
2429 
2430     return !v || vring_packed_need_event(vq, vq->used_wrap_counter,
2431                                          e.off_wrap, new, old);
2432 }
2433 
2434 /* Called within rcu_read_lock().  */
2435 static bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2436 {
2437     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
2438         return virtio_packed_should_notify(vdev, vq);
2439     } else {
2440         return virtio_split_should_notify(vdev, vq);
2441     }
2442 }
2443 
2444 void virtio_notify_irqfd(VirtIODevice *vdev, VirtQueue *vq)
2445 {
2446     WITH_RCU_READ_LOCK_GUARD() {
2447         if (!virtio_should_notify(vdev, vq)) {
2448             return;
2449         }
2450     }
2451 
2452     trace_virtio_notify_irqfd(vdev, vq);
2453 
2454     /*
2455      * virtio spec 1.0 says ISR bit 0 should be ignored with MSI, but
2456      * windows drivers included in virtio-win 1.8.0 (circa 2015) are
2457      * incorrectly polling this bit during crashdump and hibernation
2458      * in MSI mode, causing a hang if this bit is never updated.
2459      * Recent releases of Windows do not really shut down, but rather
2460      * log out and hibernate to make the next startup faster.  Hence,
2461      * this manifested as a more serious hang during shutdown with
2462      *
2463      * Next driver release from 2016 fixed this problem, so working around it
2464      * is not a must, but it's easy to do so let's do it here.
2465      *
2466      * Note: it's safe to update ISR from any thread as it was switched
2467      * to an atomic operation.
2468      */
2469     virtio_set_isr(vq->vdev, 0x1);
2470     event_notifier_set(&vq->guest_notifier);
2471 }
2472 
2473 static void virtio_irq(VirtQueue *vq)
2474 {
2475     virtio_set_isr(vq->vdev, 0x1);
2476     virtio_notify_vector(vq->vdev, vq->vector);
2477 }
2478 
2479 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
2480 {
2481     WITH_RCU_READ_LOCK_GUARD() {
2482         if (!virtio_should_notify(vdev, vq)) {
2483             return;
2484         }
2485     }
2486 
2487     trace_virtio_notify(vdev, vq);
2488     virtio_irq(vq);
2489 }
2490 
2491 void virtio_notify_config(VirtIODevice *vdev)
2492 {
2493     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
2494         return;
2495 
2496     virtio_set_isr(vdev, 0x3);
2497     vdev->generation++;
2498     virtio_notify_vector(vdev, vdev->config_vector);
2499 }
2500 
2501 static bool virtio_device_endian_needed(void *opaque)
2502 {
2503     VirtIODevice *vdev = opaque;
2504 
2505     assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
2506     if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2507         return vdev->device_endian != virtio_default_endian();
2508     }
2509     /* Devices conforming to VIRTIO 1.0 or later are always LE. */
2510     return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
2511 }
2512 
2513 static bool virtio_64bit_features_needed(void *opaque)
2514 {
2515     VirtIODevice *vdev = opaque;
2516 
2517     return (vdev->host_features >> 32) != 0;
2518 }
2519 
2520 static bool virtio_virtqueue_needed(void *opaque)
2521 {
2522     VirtIODevice *vdev = opaque;
2523 
2524     return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
2525 }
2526 
2527 static bool virtio_packed_virtqueue_needed(void *opaque)
2528 {
2529     VirtIODevice *vdev = opaque;
2530 
2531     return virtio_host_has_feature(vdev, VIRTIO_F_RING_PACKED);
2532 }
2533 
2534 static bool virtio_ringsize_needed(void *opaque)
2535 {
2536     VirtIODevice *vdev = opaque;
2537     int i;
2538 
2539     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2540         if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
2541             return true;
2542         }
2543     }
2544     return false;
2545 }
2546 
2547 static bool virtio_extra_state_needed(void *opaque)
2548 {
2549     VirtIODevice *vdev = opaque;
2550     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2551     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2552 
2553     return k->has_extra_state &&
2554         k->has_extra_state(qbus->parent);
2555 }
2556 
2557 static bool virtio_broken_needed(void *opaque)
2558 {
2559     VirtIODevice *vdev = opaque;
2560 
2561     return vdev->broken;
2562 }
2563 
2564 static bool virtio_started_needed(void *opaque)
2565 {
2566     VirtIODevice *vdev = opaque;
2567 
2568     return vdev->started;
2569 }
2570 
2571 static bool virtio_disabled_needed(void *opaque)
2572 {
2573     VirtIODevice *vdev = opaque;
2574 
2575     return vdev->disabled;
2576 }
2577 
2578 static const VMStateDescription vmstate_virtqueue = {
2579     .name = "virtqueue_state",
2580     .version_id = 1,
2581     .minimum_version_id = 1,
2582     .fields = (VMStateField[]) {
2583         VMSTATE_UINT64(vring.avail, struct VirtQueue),
2584         VMSTATE_UINT64(vring.used, struct VirtQueue),
2585         VMSTATE_END_OF_LIST()
2586     }
2587 };
2588 
2589 static const VMStateDescription vmstate_packed_virtqueue = {
2590     .name = "packed_virtqueue_state",
2591     .version_id = 1,
2592     .minimum_version_id = 1,
2593     .fields = (VMStateField[]) {
2594         VMSTATE_UINT16(last_avail_idx, struct VirtQueue),
2595         VMSTATE_BOOL(last_avail_wrap_counter, struct VirtQueue),
2596         VMSTATE_UINT16(used_idx, struct VirtQueue),
2597         VMSTATE_BOOL(used_wrap_counter, struct VirtQueue),
2598         VMSTATE_UINT32(inuse, struct VirtQueue),
2599         VMSTATE_END_OF_LIST()
2600     }
2601 };
2602 
2603 static const VMStateDescription vmstate_virtio_virtqueues = {
2604     .name = "virtio/virtqueues",
2605     .version_id = 1,
2606     .minimum_version_id = 1,
2607     .needed = &virtio_virtqueue_needed,
2608     .fields = (VMStateField[]) {
2609         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2610                       VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
2611         VMSTATE_END_OF_LIST()
2612     }
2613 };
2614 
2615 static const VMStateDescription vmstate_virtio_packed_virtqueues = {
2616     .name = "virtio/packed_virtqueues",
2617     .version_id = 1,
2618     .minimum_version_id = 1,
2619     .needed = &virtio_packed_virtqueue_needed,
2620     .fields = (VMStateField[]) {
2621         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2622                       VIRTIO_QUEUE_MAX, 0, vmstate_packed_virtqueue, VirtQueue),
2623         VMSTATE_END_OF_LIST()
2624     }
2625 };
2626 
2627 static const VMStateDescription vmstate_ringsize = {
2628     .name = "ringsize_state",
2629     .version_id = 1,
2630     .minimum_version_id = 1,
2631     .fields = (VMStateField[]) {
2632         VMSTATE_UINT32(vring.num_default, struct VirtQueue),
2633         VMSTATE_END_OF_LIST()
2634     }
2635 };
2636 
2637 static const VMStateDescription vmstate_virtio_ringsize = {
2638     .name = "virtio/ringsize",
2639     .version_id = 1,
2640     .minimum_version_id = 1,
2641     .needed = &virtio_ringsize_needed,
2642     .fields = (VMStateField[]) {
2643         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2644                       VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
2645         VMSTATE_END_OF_LIST()
2646     }
2647 };
2648 
2649 static int get_extra_state(QEMUFile *f, void *pv, size_t size,
2650                            const VMStateField *field)
2651 {
2652     VirtIODevice *vdev = pv;
2653     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2654     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2655 
2656     if (!k->load_extra_state) {
2657         return -1;
2658     } else {
2659         return k->load_extra_state(qbus->parent, f);
2660     }
2661 }
2662 
2663 static int put_extra_state(QEMUFile *f, void *pv, size_t size,
2664                            const VMStateField *field, JSONWriter *vmdesc)
2665 {
2666     VirtIODevice *vdev = pv;
2667     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2668     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2669 
2670     k->save_extra_state(qbus->parent, f);
2671     return 0;
2672 }
2673 
2674 static const VMStateInfo vmstate_info_extra_state = {
2675     .name = "virtqueue_extra_state",
2676     .get = get_extra_state,
2677     .put = put_extra_state,
2678 };
2679 
2680 static const VMStateDescription vmstate_virtio_extra_state = {
2681     .name = "virtio/extra_state",
2682     .version_id = 1,
2683     .minimum_version_id = 1,
2684     .needed = &virtio_extra_state_needed,
2685     .fields = (VMStateField[]) {
2686         {
2687             .name         = "extra_state",
2688             .version_id   = 0,
2689             .field_exists = NULL,
2690             .size         = 0,
2691             .info         = &vmstate_info_extra_state,
2692             .flags        = VMS_SINGLE,
2693             .offset       = 0,
2694         },
2695         VMSTATE_END_OF_LIST()
2696     }
2697 };
2698 
2699 static const VMStateDescription vmstate_virtio_device_endian = {
2700     .name = "virtio/device_endian",
2701     .version_id = 1,
2702     .minimum_version_id = 1,
2703     .needed = &virtio_device_endian_needed,
2704     .fields = (VMStateField[]) {
2705         VMSTATE_UINT8(device_endian, VirtIODevice),
2706         VMSTATE_END_OF_LIST()
2707     }
2708 };
2709 
2710 static const VMStateDescription vmstate_virtio_64bit_features = {
2711     .name = "virtio/64bit_features",
2712     .version_id = 1,
2713     .minimum_version_id = 1,
2714     .needed = &virtio_64bit_features_needed,
2715     .fields = (VMStateField[]) {
2716         VMSTATE_UINT64(guest_features, VirtIODevice),
2717         VMSTATE_END_OF_LIST()
2718     }
2719 };
2720 
2721 static const VMStateDescription vmstate_virtio_broken = {
2722     .name = "virtio/broken",
2723     .version_id = 1,
2724     .minimum_version_id = 1,
2725     .needed = &virtio_broken_needed,
2726     .fields = (VMStateField[]) {
2727         VMSTATE_BOOL(broken, VirtIODevice),
2728         VMSTATE_END_OF_LIST()
2729     }
2730 };
2731 
2732 static const VMStateDescription vmstate_virtio_started = {
2733     .name = "virtio/started",
2734     .version_id = 1,
2735     .minimum_version_id = 1,
2736     .needed = &virtio_started_needed,
2737     .fields = (VMStateField[]) {
2738         VMSTATE_BOOL(started, VirtIODevice),
2739         VMSTATE_END_OF_LIST()
2740     }
2741 };
2742 
2743 static const VMStateDescription vmstate_virtio_disabled = {
2744     .name = "virtio/disabled",
2745     .version_id = 1,
2746     .minimum_version_id = 1,
2747     .needed = &virtio_disabled_needed,
2748     .fields = (VMStateField[]) {
2749         VMSTATE_BOOL(disabled, VirtIODevice),
2750         VMSTATE_END_OF_LIST()
2751     }
2752 };
2753 
2754 static const VMStateDescription vmstate_virtio = {
2755     .name = "virtio",
2756     .version_id = 1,
2757     .minimum_version_id = 1,
2758     .fields = (VMStateField[]) {
2759         VMSTATE_END_OF_LIST()
2760     },
2761     .subsections = (const VMStateDescription*[]) {
2762         &vmstate_virtio_device_endian,
2763         &vmstate_virtio_64bit_features,
2764         &vmstate_virtio_virtqueues,
2765         &vmstate_virtio_ringsize,
2766         &vmstate_virtio_broken,
2767         &vmstate_virtio_extra_state,
2768         &vmstate_virtio_started,
2769         &vmstate_virtio_packed_virtqueues,
2770         &vmstate_virtio_disabled,
2771         NULL
2772     }
2773 };
2774 
2775 int virtio_save(VirtIODevice *vdev, QEMUFile *f)
2776 {
2777     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2778     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2779     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2780     uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
2781     int i;
2782 
2783     if (k->save_config) {
2784         k->save_config(qbus->parent, f);
2785     }
2786 
2787     qemu_put_8s(f, &vdev->status);
2788     qemu_put_8s(f, &vdev->isr);
2789     qemu_put_be16s(f, &vdev->queue_sel);
2790     qemu_put_be32s(f, &guest_features_lo);
2791     qemu_put_be32(f, vdev->config_len);
2792     qemu_put_buffer(f, vdev->config, vdev->config_len);
2793 
2794     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2795         if (vdev->vq[i].vring.num == 0)
2796             break;
2797     }
2798 
2799     qemu_put_be32(f, i);
2800 
2801     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2802         if (vdev->vq[i].vring.num == 0)
2803             break;
2804 
2805         qemu_put_be32(f, vdev->vq[i].vring.num);
2806         if (k->has_variable_vring_alignment) {
2807             qemu_put_be32(f, vdev->vq[i].vring.align);
2808         }
2809         /*
2810          * Save desc now, the rest of the ring addresses are saved in
2811          * subsections for VIRTIO-1 devices.
2812          */
2813         qemu_put_be64(f, vdev->vq[i].vring.desc);
2814         qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
2815         if (k->save_queue) {
2816             k->save_queue(qbus->parent, i, f);
2817         }
2818     }
2819 
2820     if (vdc->save != NULL) {
2821         vdc->save(vdev, f);
2822     }
2823 
2824     if (vdc->vmsd) {
2825         int ret = vmstate_save_state(f, vdc->vmsd, vdev, NULL);
2826         if (ret) {
2827             return ret;
2828         }
2829     }
2830 
2831     /* Subsections */
2832     return vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
2833 }
2834 
2835 /* A wrapper for use as a VMState .put function */
2836 static int virtio_device_put(QEMUFile *f, void *opaque, size_t size,
2837                               const VMStateField *field, JSONWriter *vmdesc)
2838 {
2839     return virtio_save(VIRTIO_DEVICE(opaque), f);
2840 }
2841 
2842 /* A wrapper for use as a VMState .get function */
2843 static int coroutine_mixed_fn
2844 virtio_device_get(QEMUFile *f, void *opaque, size_t size,
2845                   const VMStateField *field)
2846 {
2847     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
2848     DeviceClass *dc = DEVICE_CLASS(VIRTIO_DEVICE_GET_CLASS(vdev));
2849 
2850     return virtio_load(vdev, f, dc->vmsd->version_id);
2851 }
2852 
2853 const VMStateInfo  virtio_vmstate_info = {
2854     .name = "virtio",
2855     .get = virtio_device_get,
2856     .put = virtio_device_put,
2857 };
2858 
2859 static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
2860 {
2861     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2862     bool bad = (val & ~(vdev->host_features)) != 0;
2863 
2864     val &= vdev->host_features;
2865     if (k->set_features) {
2866         k->set_features(vdev, val);
2867     }
2868     vdev->guest_features = val;
2869     return bad ? -1 : 0;
2870 }
2871 
2872 typedef struct VirtioSetFeaturesNocheckData {
2873     Coroutine *co;
2874     VirtIODevice *vdev;
2875     uint64_t val;
2876     int ret;
2877 } VirtioSetFeaturesNocheckData;
2878 
2879 static void virtio_set_features_nocheck_bh(void *opaque)
2880 {
2881     VirtioSetFeaturesNocheckData *data = opaque;
2882 
2883     data->ret = virtio_set_features_nocheck(data->vdev, data->val);
2884     aio_co_wake(data->co);
2885 }
2886 
2887 static int coroutine_mixed_fn
2888 virtio_set_features_nocheck_maybe_co(VirtIODevice *vdev, uint64_t val)
2889 {
2890     if (qemu_in_coroutine()) {
2891         VirtioSetFeaturesNocheckData data = {
2892             .co = qemu_coroutine_self(),
2893             .vdev = vdev,
2894             .val = val,
2895         };
2896         aio_bh_schedule_oneshot(qemu_get_current_aio_context(),
2897                                 virtio_set_features_nocheck_bh, &data);
2898         qemu_coroutine_yield();
2899         return data.ret;
2900     } else {
2901         return virtio_set_features_nocheck(vdev, val);
2902     }
2903 }
2904 
2905 int virtio_set_features(VirtIODevice *vdev, uint64_t val)
2906 {
2907     int ret;
2908     /*
2909      * The driver must not attempt to set features after feature negotiation
2910      * has finished.
2911      */
2912     if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
2913         return -EINVAL;
2914     }
2915 
2916     if (val & (1ull << VIRTIO_F_BAD_FEATURE)) {
2917         qemu_log_mask(LOG_GUEST_ERROR,
2918                       "%s: guest driver for %s has enabled UNUSED(30) feature bit!\n",
2919                       __func__, vdev->name);
2920     }
2921 
2922     ret = virtio_set_features_nocheck(vdev, val);
2923     if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2924         /* VIRTIO_RING_F_EVENT_IDX changes the size of the caches.  */
2925         int i;
2926         for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2927             if (vdev->vq[i].vring.num != 0) {
2928                 virtio_init_region_cache(vdev, i);
2929             }
2930         }
2931     }
2932     if (!ret) {
2933         if (!virtio_device_started(vdev, vdev->status) &&
2934             !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2935             vdev->start_on_kick = true;
2936         }
2937     }
2938     return ret;
2939 }
2940 
2941 size_t virtio_get_config_size(const VirtIOConfigSizeParams *params,
2942                               uint64_t host_features)
2943 {
2944     size_t config_size = params->min_size;
2945     const VirtIOFeature *feature_sizes = params->feature_sizes;
2946     size_t i;
2947 
2948     for (i = 0; feature_sizes[i].flags != 0; i++) {
2949         if (host_features & feature_sizes[i].flags) {
2950             config_size = MAX(feature_sizes[i].end, config_size);
2951         }
2952     }
2953 
2954     assert(config_size <= params->max_size);
2955     return config_size;
2956 }
2957 
2958 int coroutine_mixed_fn
2959 virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
2960 {
2961     int i, ret;
2962     int32_t config_len;
2963     uint32_t num;
2964     uint32_t features;
2965     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2966     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2967     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2968 
2969     /*
2970      * We poison the endianness to ensure it does not get used before
2971      * subsections have been loaded.
2972      */
2973     vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
2974 
2975     if (k->load_config) {
2976         ret = k->load_config(qbus->parent, f);
2977         if (ret)
2978             return ret;
2979     }
2980 
2981     qemu_get_8s(f, &vdev->status);
2982     qemu_get_8s(f, &vdev->isr);
2983     qemu_get_be16s(f, &vdev->queue_sel);
2984     if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
2985         return -1;
2986     }
2987     qemu_get_be32s(f, &features);
2988 
2989     /*
2990      * Temporarily set guest_features low bits - needed by
2991      * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
2992      * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
2993      *
2994      * Note: devices should always test host features in future - don't create
2995      * new dependencies like this.
2996      */
2997     vdev->guest_features = features;
2998 
2999     config_len = qemu_get_be32(f);
3000 
3001     /*
3002      * There are cases where the incoming config can be bigger or smaller
3003      * than what we have; so load what we have space for, and skip
3004      * any excess that's in the stream.
3005      */
3006     qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
3007 
3008     while (config_len > vdev->config_len) {
3009         qemu_get_byte(f);
3010         config_len--;
3011     }
3012 
3013     num = qemu_get_be32(f);
3014 
3015     if (num > VIRTIO_QUEUE_MAX) {
3016         error_report("Invalid number of virtqueues: 0x%x", num);
3017         return -1;
3018     }
3019 
3020     for (i = 0; i < num; i++) {
3021         vdev->vq[i].vring.num = qemu_get_be32(f);
3022         if (k->has_variable_vring_alignment) {
3023             vdev->vq[i].vring.align = qemu_get_be32(f);
3024         }
3025         vdev->vq[i].vring.desc = qemu_get_be64(f);
3026         qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
3027         vdev->vq[i].signalled_used_valid = false;
3028         vdev->vq[i].notification = true;
3029 
3030         if (!vdev->vq[i].vring.desc && vdev->vq[i].last_avail_idx) {
3031             error_report("VQ %d address 0x0 "
3032                          "inconsistent with Host index 0x%x",
3033                          i, vdev->vq[i].last_avail_idx);
3034             return -1;
3035         }
3036         if (k->load_queue) {
3037             ret = k->load_queue(qbus->parent, i, f);
3038             if (ret)
3039                 return ret;
3040         }
3041     }
3042 
3043     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
3044 
3045     if (vdc->load != NULL) {
3046         ret = vdc->load(vdev, f, version_id);
3047         if (ret) {
3048             return ret;
3049         }
3050     }
3051 
3052     if (vdc->vmsd) {
3053         ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id);
3054         if (ret) {
3055             return ret;
3056         }
3057     }
3058 
3059     /* Subsections */
3060     ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
3061     if (ret) {
3062         return ret;
3063     }
3064 
3065     if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
3066         vdev->device_endian = virtio_default_endian();
3067     }
3068 
3069     if (virtio_64bit_features_needed(vdev)) {
3070         /*
3071          * Subsection load filled vdev->guest_features.  Run them
3072          * through virtio_set_features to sanity-check them against
3073          * host_features.
3074          */
3075         uint64_t features64 = vdev->guest_features;
3076         if (virtio_set_features_nocheck_maybe_co(vdev, features64) < 0) {
3077             error_report("Features 0x%" PRIx64 " unsupported. "
3078                          "Allowed features: 0x%" PRIx64,
3079                          features64, vdev->host_features);
3080             return -1;
3081         }
3082     } else {
3083         if (virtio_set_features_nocheck_maybe_co(vdev, features) < 0) {
3084             error_report("Features 0x%x unsupported. "
3085                          "Allowed features: 0x%" PRIx64,
3086                          features, vdev->host_features);
3087             return -1;
3088         }
3089     }
3090 
3091     if (!virtio_device_started(vdev, vdev->status) &&
3092         !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3093         vdev->start_on_kick = true;
3094     }
3095 
3096     RCU_READ_LOCK_GUARD();
3097     for (i = 0; i < num; i++) {
3098         if (vdev->vq[i].vring.desc) {
3099             uint16_t nheads;
3100 
3101             /*
3102              * VIRTIO-1 devices migrate desc, used, and avail ring addresses so
3103              * only the region cache needs to be set up.  Legacy devices need
3104              * to calculate used and avail ring addresses based on the desc
3105              * address.
3106              */
3107             if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3108                 virtio_init_region_cache(vdev, i);
3109             } else {
3110                 virtio_queue_update_rings(vdev, i);
3111             }
3112 
3113             if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3114                 vdev->vq[i].shadow_avail_idx = vdev->vq[i].last_avail_idx;
3115                 vdev->vq[i].shadow_avail_wrap_counter =
3116                                         vdev->vq[i].last_avail_wrap_counter;
3117                 continue;
3118             }
3119 
3120             nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
3121             /* Check it isn't doing strange things with descriptor numbers. */
3122             if (nheads > vdev->vq[i].vring.num) {
3123                 virtio_error(vdev, "VQ %d size 0x%x Guest index 0x%x "
3124                              "inconsistent with Host index 0x%x: delta 0x%x",
3125                              i, vdev->vq[i].vring.num,
3126                              vring_avail_idx(&vdev->vq[i]),
3127                              vdev->vq[i].last_avail_idx, nheads);
3128                 vdev->vq[i].used_idx = 0;
3129                 vdev->vq[i].shadow_avail_idx = 0;
3130                 vdev->vq[i].inuse = 0;
3131                 continue;
3132             }
3133             vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
3134             vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
3135 
3136             /*
3137              * Some devices migrate VirtQueueElements that have been popped
3138              * from the avail ring but not yet returned to the used ring.
3139              * Since max ring size < UINT16_MAX it's safe to use modulo
3140              * UINT16_MAX + 1 subtraction.
3141              */
3142             vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx -
3143                                 vdev->vq[i].used_idx);
3144             if (vdev->vq[i].inuse > vdev->vq[i].vring.num) {
3145                 error_report("VQ %d size 0x%x < last_avail_idx 0x%x - "
3146                              "used_idx 0x%x",
3147                              i, vdev->vq[i].vring.num,
3148                              vdev->vq[i].last_avail_idx,
3149                              vdev->vq[i].used_idx);
3150                 return -1;
3151             }
3152         }
3153     }
3154 
3155     if (vdc->post_load) {
3156         ret = vdc->post_load(vdev);
3157         if (ret) {
3158             return ret;
3159         }
3160     }
3161 
3162     return 0;
3163 }
3164 
3165 void virtio_cleanup(VirtIODevice *vdev)
3166 {
3167     qemu_del_vm_change_state_handler(vdev->vmstate);
3168 }
3169 
3170 static void virtio_vmstate_change(void *opaque, bool running, RunState state)
3171 {
3172     VirtIODevice *vdev = opaque;
3173     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3174     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3175     bool backend_run = running && virtio_device_started(vdev, vdev->status);
3176     vdev->vm_running = running;
3177 
3178     if (backend_run) {
3179         virtio_set_status(vdev, vdev->status);
3180     }
3181 
3182     if (k->vmstate_change) {
3183         k->vmstate_change(qbus->parent, backend_run);
3184     }
3185 
3186     if (!backend_run) {
3187         virtio_set_status(vdev, vdev->status);
3188     }
3189 }
3190 
3191 void virtio_instance_init_common(Object *proxy_obj, void *data,
3192                                  size_t vdev_size, const char *vdev_name)
3193 {
3194     DeviceState *vdev = data;
3195 
3196     object_initialize_child_with_props(proxy_obj, "virtio-backend", vdev,
3197                                        vdev_size, vdev_name, &error_abort,
3198                                        NULL);
3199     qdev_alias_all_properties(vdev, proxy_obj);
3200 }
3201 
3202 void virtio_init(VirtIODevice *vdev, uint16_t device_id, size_t config_size)
3203 {
3204     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3205     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3206     int i;
3207     int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
3208 
3209     if (nvectors) {
3210         vdev->vector_queues =
3211             g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
3212     }
3213 
3214     vdev->start_on_kick = false;
3215     vdev->started = false;
3216     vdev->vhost_started = false;
3217     vdev->device_id = device_id;
3218     vdev->status = 0;
3219     qatomic_set(&vdev->isr, 0);
3220     vdev->queue_sel = 0;
3221     vdev->config_vector = VIRTIO_NO_VECTOR;
3222     vdev->vq = g_new0(VirtQueue, VIRTIO_QUEUE_MAX);
3223     vdev->vm_running = runstate_is_running();
3224     vdev->broken = false;
3225     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3226         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
3227         vdev->vq[i].vdev = vdev;
3228         vdev->vq[i].queue_index = i;
3229         vdev->vq[i].host_notifier_enabled = false;
3230     }
3231 
3232     vdev->name = virtio_id_to_name(device_id);
3233     vdev->config_len = config_size;
3234     if (vdev->config_len) {
3235         vdev->config = g_malloc0(config_size);
3236     } else {
3237         vdev->config = NULL;
3238     }
3239     vdev->vmstate = qdev_add_vm_change_state_handler(DEVICE(vdev),
3240             virtio_vmstate_change, vdev);
3241     vdev->device_endian = virtio_default_endian();
3242     vdev->use_guest_notifier_mask = true;
3243 }
3244 
3245 /*
3246  * Only devices that have already been around prior to defining the virtio
3247  * standard support legacy mode; this includes devices not specified in the
3248  * standard. All newer devices conform to the virtio standard only.
3249  */
3250 bool virtio_legacy_allowed(VirtIODevice *vdev)
3251 {
3252     switch (vdev->device_id) {
3253     case VIRTIO_ID_NET:
3254     case VIRTIO_ID_BLOCK:
3255     case VIRTIO_ID_CONSOLE:
3256     case VIRTIO_ID_RNG:
3257     case VIRTIO_ID_BALLOON:
3258     case VIRTIO_ID_RPMSG:
3259     case VIRTIO_ID_SCSI:
3260     case VIRTIO_ID_9P:
3261     case VIRTIO_ID_RPROC_SERIAL:
3262     case VIRTIO_ID_CAIF:
3263         return true;
3264     default:
3265         return false;
3266     }
3267 }
3268 
3269 bool virtio_legacy_check_disabled(VirtIODevice *vdev)
3270 {
3271     return vdev->disable_legacy_check;
3272 }
3273 
3274 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
3275 {
3276     return vdev->vq[n].vring.desc;
3277 }
3278 
3279 bool virtio_queue_enabled_legacy(VirtIODevice *vdev, int n)
3280 {
3281     return virtio_queue_get_desc_addr(vdev, n) != 0;
3282 }
3283 
3284 bool virtio_queue_enabled(VirtIODevice *vdev, int n)
3285 {
3286     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3287     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3288 
3289     if (k->queue_enabled) {
3290         return k->queue_enabled(qbus->parent, n);
3291     }
3292     return virtio_queue_enabled_legacy(vdev, n);
3293 }
3294 
3295 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
3296 {
3297     return vdev->vq[n].vring.avail;
3298 }
3299 
3300 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
3301 {
3302     return vdev->vq[n].vring.used;
3303 }
3304 
3305 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
3306 {
3307     return sizeof(VRingDesc) * vdev->vq[n].vring.num;
3308 }
3309 
3310 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
3311 {
3312     int s;
3313 
3314     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3315         return sizeof(struct VRingPackedDescEvent);
3316     }
3317 
3318     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3319     return offsetof(VRingAvail, ring) +
3320         sizeof(uint16_t) * vdev->vq[n].vring.num + s;
3321 }
3322 
3323 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
3324 {
3325     int s;
3326 
3327     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3328         return sizeof(struct VRingPackedDescEvent);
3329     }
3330 
3331     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3332     return offsetof(VRingUsed, ring) +
3333         sizeof(VRingUsedElem) * vdev->vq[n].vring.num + s;
3334 }
3335 
3336 static unsigned int virtio_queue_packed_get_last_avail_idx(VirtIODevice *vdev,
3337                                                            int n)
3338 {
3339     unsigned int avail, used;
3340 
3341     avail = vdev->vq[n].last_avail_idx;
3342     avail |= ((uint16_t)vdev->vq[n].last_avail_wrap_counter) << 15;
3343 
3344     used = vdev->vq[n].used_idx;
3345     used |= ((uint16_t)vdev->vq[n].used_wrap_counter) << 15;
3346 
3347     return avail | used << 16;
3348 }
3349 
3350 static uint16_t virtio_queue_split_get_last_avail_idx(VirtIODevice *vdev,
3351                                                       int n)
3352 {
3353     return vdev->vq[n].last_avail_idx;
3354 }
3355 
3356 unsigned int virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
3357 {
3358     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3359         return virtio_queue_packed_get_last_avail_idx(vdev, n);
3360     } else {
3361         return virtio_queue_split_get_last_avail_idx(vdev, n);
3362     }
3363 }
3364 
3365 static void virtio_queue_packed_set_last_avail_idx(VirtIODevice *vdev,
3366                                                    int n, unsigned int idx)
3367 {
3368     struct VirtQueue *vq = &vdev->vq[n];
3369 
3370     vq->last_avail_idx = vq->shadow_avail_idx = idx & 0x7fff;
3371     vq->last_avail_wrap_counter =
3372         vq->shadow_avail_wrap_counter = !!(idx & 0x8000);
3373     idx >>= 16;
3374     vq->used_idx = idx & 0x7fff;
3375     vq->used_wrap_counter = !!(idx & 0x8000);
3376 }
3377 
3378 static void virtio_queue_split_set_last_avail_idx(VirtIODevice *vdev,
3379                                                   int n, unsigned int idx)
3380 {
3381         vdev->vq[n].last_avail_idx = idx;
3382         vdev->vq[n].shadow_avail_idx = idx;
3383 }
3384 
3385 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n,
3386                                      unsigned int idx)
3387 {
3388     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3389         virtio_queue_packed_set_last_avail_idx(vdev, n, idx);
3390     } else {
3391         virtio_queue_split_set_last_avail_idx(vdev, n, idx);
3392     }
3393 }
3394 
3395 static void virtio_queue_packed_restore_last_avail_idx(VirtIODevice *vdev,
3396                                                        int n)
3397 {
3398     /* We don't have a reference like avail idx in shared memory */
3399     return;
3400 }
3401 
3402 static void virtio_queue_split_restore_last_avail_idx(VirtIODevice *vdev,
3403                                                       int n)
3404 {
3405     RCU_READ_LOCK_GUARD();
3406     if (vdev->vq[n].vring.desc) {
3407         vdev->vq[n].last_avail_idx = vring_used_idx(&vdev->vq[n]);
3408         vdev->vq[n].shadow_avail_idx = vdev->vq[n].last_avail_idx;
3409     }
3410 }
3411 
3412 void virtio_queue_restore_last_avail_idx(VirtIODevice *vdev, int n)
3413 {
3414     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3415         virtio_queue_packed_restore_last_avail_idx(vdev, n);
3416     } else {
3417         virtio_queue_split_restore_last_avail_idx(vdev, n);
3418     }
3419 }
3420 
3421 static void virtio_queue_packed_update_used_idx(VirtIODevice *vdev, int n)
3422 {
3423     /* used idx was updated through set_last_avail_idx() */
3424     return;
3425 }
3426 
3427 static void virtio_split_packed_update_used_idx(VirtIODevice *vdev, int n)
3428 {
3429     RCU_READ_LOCK_GUARD();
3430     if (vdev->vq[n].vring.desc) {
3431         vdev->vq[n].used_idx = vring_used_idx(&vdev->vq[n]);
3432     }
3433 }
3434 
3435 void virtio_queue_update_used_idx(VirtIODevice *vdev, int n)
3436 {
3437     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3438         return virtio_queue_packed_update_used_idx(vdev, n);
3439     } else {
3440         return virtio_split_packed_update_used_idx(vdev, n);
3441     }
3442 }
3443 
3444 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
3445 {
3446     vdev->vq[n].signalled_used_valid = false;
3447 }
3448 
3449 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
3450 {
3451     return vdev->vq + n;
3452 }
3453 
3454 uint16_t virtio_get_queue_index(VirtQueue *vq)
3455 {
3456     return vq->queue_index;
3457 }
3458 
3459 static void virtio_queue_guest_notifier_read(EventNotifier *n)
3460 {
3461     VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
3462     if (event_notifier_test_and_clear(n)) {
3463         virtio_irq(vq);
3464     }
3465 }
3466 static void virtio_config_guest_notifier_read(EventNotifier *n)
3467 {
3468     VirtIODevice *vdev = container_of(n, VirtIODevice, config_notifier);
3469 
3470     if (event_notifier_test_and_clear(n)) {
3471         virtio_notify_config(vdev);
3472     }
3473 }
3474 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
3475                                                 bool with_irqfd)
3476 {
3477     if (assign && !with_irqfd) {
3478         event_notifier_set_handler(&vq->guest_notifier,
3479                                    virtio_queue_guest_notifier_read);
3480     } else {
3481         event_notifier_set_handler(&vq->guest_notifier, NULL);
3482     }
3483     if (!assign) {
3484         /* Test and clear notifier before closing it,
3485          * in case poll callback didn't have time to run. */
3486         virtio_queue_guest_notifier_read(&vq->guest_notifier);
3487     }
3488 }
3489 
3490 void virtio_config_set_guest_notifier_fd_handler(VirtIODevice *vdev,
3491                                                  bool assign, bool with_irqfd)
3492 {
3493     EventNotifier *n;
3494     n = &vdev->config_notifier;
3495     if (assign && !with_irqfd) {
3496         event_notifier_set_handler(n, virtio_config_guest_notifier_read);
3497     } else {
3498         event_notifier_set_handler(n, NULL);
3499     }
3500     if (!assign) {
3501         /* Test and clear notifier before closing it,*/
3502         /* in case poll callback didn't have time to run. */
3503         virtio_config_guest_notifier_read(n);
3504     }
3505 }
3506 
3507 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
3508 {
3509     return &vq->guest_notifier;
3510 }
3511 
3512 static void virtio_queue_host_notifier_aio_poll_begin(EventNotifier *n)
3513 {
3514     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3515 
3516     virtio_queue_set_notification(vq, 0);
3517 }
3518 
3519 static bool virtio_queue_host_notifier_aio_poll(void *opaque)
3520 {
3521     EventNotifier *n = opaque;
3522     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3523 
3524     return vq->vring.desc && !virtio_queue_empty(vq);
3525 }
3526 
3527 static void virtio_queue_host_notifier_aio_poll_ready(EventNotifier *n)
3528 {
3529     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3530 
3531     virtio_queue_notify_vq(vq);
3532 }
3533 
3534 static void virtio_queue_host_notifier_aio_poll_end(EventNotifier *n)
3535 {
3536     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3537 
3538     /* Caller polls once more after this to catch requests that race with us */
3539     virtio_queue_set_notification(vq, 1);
3540 }
3541 
3542 void virtio_queue_aio_attach_host_notifier(VirtQueue *vq, AioContext *ctx)
3543 {
3544     aio_set_event_notifier(ctx, &vq->host_notifier,
3545                            virtio_queue_host_notifier_read,
3546                            virtio_queue_host_notifier_aio_poll,
3547                            virtio_queue_host_notifier_aio_poll_ready);
3548     aio_set_event_notifier_poll(ctx, &vq->host_notifier,
3549                                 virtio_queue_host_notifier_aio_poll_begin,
3550                                 virtio_queue_host_notifier_aio_poll_end);
3551 }
3552 
3553 /*
3554  * Same as virtio_queue_aio_attach_host_notifier() but without polling. Use
3555  * this for rx virtqueues and similar cases where the virtqueue handler
3556  * function does not pop all elements. When the virtqueue is left non-empty
3557  * polling consumes CPU cycles and should not be used.
3558  */
3559 void virtio_queue_aio_attach_host_notifier_no_poll(VirtQueue *vq, AioContext *ctx)
3560 {
3561     aio_set_event_notifier(ctx, &vq->host_notifier,
3562                            virtio_queue_host_notifier_read,
3563                            NULL, NULL);
3564 }
3565 
3566 void virtio_queue_aio_detach_host_notifier(VirtQueue *vq, AioContext *ctx)
3567 {
3568     aio_set_event_notifier(ctx, &vq->host_notifier, NULL, NULL, NULL);
3569 }
3570 
3571 void virtio_queue_host_notifier_read(EventNotifier *n)
3572 {
3573     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3574     if (event_notifier_test_and_clear(n)) {
3575         virtio_queue_notify_vq(vq);
3576     }
3577 }
3578 
3579 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
3580 {
3581     return &vq->host_notifier;
3582 }
3583 
3584 EventNotifier *virtio_config_get_guest_notifier(VirtIODevice *vdev)
3585 {
3586     return &vdev->config_notifier;
3587 }
3588 
3589 void virtio_queue_set_host_notifier_enabled(VirtQueue *vq, bool enabled)
3590 {
3591     vq->host_notifier_enabled = enabled;
3592 }
3593 
3594 int virtio_queue_set_host_notifier_mr(VirtIODevice *vdev, int n,
3595                                       MemoryRegion *mr, bool assign)
3596 {
3597     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3598     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3599 
3600     if (k->set_host_notifier_mr) {
3601         return k->set_host_notifier_mr(qbus->parent, n, mr, assign);
3602     }
3603 
3604     return -1;
3605 }
3606 
3607 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
3608 {
3609     g_free(vdev->bus_name);
3610     vdev->bus_name = g_strdup(bus_name);
3611 }
3612 
3613 void G_GNUC_PRINTF(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
3614 {
3615     va_list ap;
3616 
3617     va_start(ap, fmt);
3618     error_vreport(fmt, ap);
3619     va_end(ap);
3620 
3621     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3622         vdev->status = vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET;
3623         virtio_notify_config(vdev);
3624     }
3625 
3626     vdev->broken = true;
3627 }
3628 
3629 static void virtio_memory_listener_commit(MemoryListener *listener)
3630 {
3631     VirtIODevice *vdev = container_of(listener, VirtIODevice, listener);
3632     int i;
3633 
3634     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3635         if (vdev->vq[i].vring.num == 0) {
3636             break;
3637         }
3638         virtio_init_region_cache(vdev, i);
3639     }
3640 }
3641 
3642 static void virtio_device_realize(DeviceState *dev, Error **errp)
3643 {
3644     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3645     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3646     Error *err = NULL;
3647 
3648     /* Devices should either use vmsd or the load/save methods */
3649     assert(!vdc->vmsd || !vdc->load);
3650 
3651     if (vdc->realize != NULL) {
3652         vdc->realize(dev, &err);
3653         if (err != NULL) {
3654             error_propagate(errp, err);
3655             return;
3656         }
3657     }
3658 
3659     virtio_bus_device_plugged(vdev, &err);
3660     if (err != NULL) {
3661         error_propagate(errp, err);
3662         vdc->unrealize(dev);
3663         return;
3664     }
3665 
3666     vdev->listener.commit = virtio_memory_listener_commit;
3667     vdev->listener.name = "virtio";
3668     memory_listener_register(&vdev->listener, vdev->dma_as);
3669 }
3670 
3671 static void virtio_device_unrealize(DeviceState *dev)
3672 {
3673     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3674     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3675 
3676     memory_listener_unregister(&vdev->listener);
3677     virtio_bus_device_unplugged(vdev);
3678 
3679     if (vdc->unrealize != NULL) {
3680         vdc->unrealize(dev);
3681     }
3682 
3683     g_free(vdev->bus_name);
3684     vdev->bus_name = NULL;
3685 }
3686 
3687 static void virtio_device_free_virtqueues(VirtIODevice *vdev)
3688 {
3689     int i;
3690     if (!vdev->vq) {
3691         return;
3692     }
3693 
3694     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3695         if (vdev->vq[i].vring.num == 0) {
3696             break;
3697         }
3698         virtio_virtqueue_reset_region_cache(&vdev->vq[i]);
3699     }
3700     g_free(vdev->vq);
3701 }
3702 
3703 static void virtio_device_instance_finalize(Object *obj)
3704 {
3705     VirtIODevice *vdev = VIRTIO_DEVICE(obj);
3706 
3707     virtio_device_free_virtqueues(vdev);
3708 
3709     g_free(vdev->config);
3710     g_free(vdev->vector_queues);
3711 }
3712 
3713 static Property virtio_properties[] = {
3714     DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
3715     DEFINE_PROP_BOOL("use-started", VirtIODevice, use_started, true),
3716     DEFINE_PROP_BOOL("use-disabled-flag", VirtIODevice, use_disabled_flag, true),
3717     DEFINE_PROP_BOOL("x-disable-legacy-check", VirtIODevice,
3718                      disable_legacy_check, false),
3719     DEFINE_PROP_END_OF_LIST(),
3720 };
3721 
3722 static int virtio_device_start_ioeventfd_impl(VirtIODevice *vdev)
3723 {
3724     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3725     int i, n, r, err;
3726 
3727     /*
3728      * Batch all the host notifiers in a single transaction to avoid
3729      * quadratic time complexity in address_space_update_ioeventfds().
3730      */
3731     memory_region_transaction_begin();
3732     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3733         VirtQueue *vq = &vdev->vq[n];
3734         if (!virtio_queue_get_num(vdev, n)) {
3735             continue;
3736         }
3737         r = virtio_bus_set_host_notifier(qbus, n, true);
3738         if (r < 0) {
3739             err = r;
3740             goto assign_error;
3741         }
3742         event_notifier_set_handler(&vq->host_notifier,
3743                                    virtio_queue_host_notifier_read);
3744     }
3745 
3746     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3747         /* Kick right away to begin processing requests already in vring */
3748         VirtQueue *vq = &vdev->vq[n];
3749         if (!vq->vring.num) {
3750             continue;
3751         }
3752         event_notifier_set(&vq->host_notifier);
3753     }
3754     memory_region_transaction_commit();
3755     return 0;
3756 
3757 assign_error:
3758     i = n; /* save n for a second iteration after transaction is committed. */
3759     while (--n >= 0) {
3760         VirtQueue *vq = &vdev->vq[n];
3761         if (!virtio_queue_get_num(vdev, n)) {
3762             continue;
3763         }
3764 
3765         event_notifier_set_handler(&vq->host_notifier, NULL);
3766         r = virtio_bus_set_host_notifier(qbus, n, false);
3767         assert(r >= 0);
3768     }
3769     /*
3770      * The transaction expects the ioeventfds to be open when it
3771      * commits. Do it now, before the cleanup loop.
3772      */
3773     memory_region_transaction_commit();
3774 
3775     while (--i >= 0) {
3776         if (!virtio_queue_get_num(vdev, i)) {
3777             continue;
3778         }
3779         virtio_bus_cleanup_host_notifier(qbus, i);
3780     }
3781     return err;
3782 }
3783 
3784 int virtio_device_start_ioeventfd(VirtIODevice *vdev)
3785 {
3786     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3787     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3788 
3789     return virtio_bus_start_ioeventfd(vbus);
3790 }
3791 
3792 static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
3793 {
3794     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3795     int n, r;
3796 
3797     /*
3798      * Batch all the host notifiers in a single transaction to avoid
3799      * quadratic time complexity in address_space_update_ioeventfds().
3800      */
3801     memory_region_transaction_begin();
3802     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3803         VirtQueue *vq = &vdev->vq[n];
3804 
3805         if (!virtio_queue_get_num(vdev, n)) {
3806             continue;
3807         }
3808         event_notifier_set_handler(&vq->host_notifier, NULL);
3809         r = virtio_bus_set_host_notifier(qbus, n, false);
3810         assert(r >= 0);
3811     }
3812     /*
3813      * The transaction expects the ioeventfds to be open when it
3814      * commits. Do it now, before the cleanup loop.
3815      */
3816     memory_region_transaction_commit();
3817 
3818     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3819         if (!virtio_queue_get_num(vdev, n)) {
3820             continue;
3821         }
3822         virtio_bus_cleanup_host_notifier(qbus, n);
3823     }
3824 }
3825 
3826 int virtio_device_grab_ioeventfd(VirtIODevice *vdev)
3827 {
3828     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3829     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3830 
3831     return virtio_bus_grab_ioeventfd(vbus);
3832 }
3833 
3834 void virtio_device_release_ioeventfd(VirtIODevice *vdev)
3835 {
3836     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3837     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3838 
3839     virtio_bus_release_ioeventfd(vbus);
3840 }
3841 
3842 static void virtio_device_class_init(ObjectClass *klass, void *data)
3843 {
3844     /* Set the default value here. */
3845     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
3846     DeviceClass *dc = DEVICE_CLASS(klass);
3847 
3848     dc->realize = virtio_device_realize;
3849     dc->unrealize = virtio_device_unrealize;
3850     dc->bus_type = TYPE_VIRTIO_BUS;
3851     device_class_set_props(dc, virtio_properties);
3852     vdc->start_ioeventfd = virtio_device_start_ioeventfd_impl;
3853     vdc->stop_ioeventfd = virtio_device_stop_ioeventfd_impl;
3854 
3855     vdc->legacy_features |= VIRTIO_LEGACY_FEATURES;
3856 }
3857 
3858 bool virtio_device_ioeventfd_enabled(VirtIODevice *vdev)
3859 {
3860     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3861     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3862 
3863     return virtio_bus_ioeventfd_enabled(vbus);
3864 }
3865 
3866 VirtQueueStatus *qmp_x_query_virtio_queue_status(const char *path,
3867                                                  uint16_t queue,
3868                                                  Error **errp)
3869 {
3870     VirtIODevice *vdev;
3871     VirtQueueStatus *status;
3872 
3873     vdev = qmp_find_virtio_device(path);
3874     if (vdev == NULL) {
3875         error_setg(errp, "Path %s is not a VirtIODevice", path);
3876         return NULL;
3877     }
3878 
3879     if (queue >= VIRTIO_QUEUE_MAX || !virtio_queue_get_num(vdev, queue)) {
3880         error_setg(errp, "Invalid virtqueue number %d", queue);
3881         return NULL;
3882     }
3883 
3884     status = g_new0(VirtQueueStatus, 1);
3885     status->name = g_strdup(vdev->name);
3886     status->queue_index = vdev->vq[queue].queue_index;
3887     status->inuse = vdev->vq[queue].inuse;
3888     status->vring_num = vdev->vq[queue].vring.num;
3889     status->vring_num_default = vdev->vq[queue].vring.num_default;
3890     status->vring_align = vdev->vq[queue].vring.align;
3891     status->vring_desc = vdev->vq[queue].vring.desc;
3892     status->vring_avail = vdev->vq[queue].vring.avail;
3893     status->vring_used = vdev->vq[queue].vring.used;
3894     status->used_idx = vdev->vq[queue].used_idx;
3895     status->signalled_used = vdev->vq[queue].signalled_used;
3896     status->signalled_used_valid = vdev->vq[queue].signalled_used_valid;
3897 
3898     if (vdev->vhost_started) {
3899         VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
3900         struct vhost_dev *hdev = vdc->get_vhost(vdev);
3901 
3902         /* check if vq index exists for vhost as well  */
3903         if (queue >= hdev->vq_index && queue < hdev->vq_index + hdev->nvqs) {
3904             status->has_last_avail_idx = true;
3905 
3906             int vhost_vq_index =
3907                 hdev->vhost_ops->vhost_get_vq_index(hdev, queue);
3908             struct vhost_vring_state state = {
3909                 .index = vhost_vq_index,
3910             };
3911 
3912             status->last_avail_idx =
3913                 hdev->vhost_ops->vhost_get_vring_base(hdev, &state);
3914         }
3915     } else {
3916         status->has_shadow_avail_idx = true;
3917         status->has_last_avail_idx = true;
3918         status->last_avail_idx = vdev->vq[queue].last_avail_idx;
3919         status->shadow_avail_idx = vdev->vq[queue].shadow_avail_idx;
3920     }
3921 
3922     return status;
3923 }
3924 
3925 static strList *qmp_decode_vring_desc_flags(uint16_t flags)
3926 {
3927     strList *list = NULL;
3928     strList *node;
3929     int i;
3930 
3931     struct {
3932         uint16_t flag;
3933         const char *value;
3934     } map[] = {
3935         { VRING_DESC_F_NEXT, "next" },
3936         { VRING_DESC_F_WRITE, "write" },
3937         { VRING_DESC_F_INDIRECT, "indirect" },
3938         { 1 << VRING_PACKED_DESC_F_AVAIL, "avail" },
3939         { 1 << VRING_PACKED_DESC_F_USED, "used" },
3940         { 0, "" }
3941     };
3942 
3943     for (i = 0; map[i].flag; i++) {
3944         if ((map[i].flag & flags) == 0) {
3945             continue;
3946         }
3947         node = g_malloc0(sizeof(strList));
3948         node->value = g_strdup(map[i].value);
3949         node->next = list;
3950         list = node;
3951     }
3952 
3953     return list;
3954 }
3955 
3956 VirtioQueueElement *qmp_x_query_virtio_queue_element(const char *path,
3957                                                      uint16_t queue,
3958                                                      bool has_index,
3959                                                      uint16_t index,
3960                                                      Error **errp)
3961 {
3962     VirtIODevice *vdev;
3963     VirtQueue *vq;
3964     VirtioQueueElement *element = NULL;
3965 
3966     vdev = qmp_find_virtio_device(path);
3967     if (vdev == NULL) {
3968         error_setg(errp, "Path %s is not a VirtIO device", path);
3969         return NULL;
3970     }
3971 
3972     if (queue >= VIRTIO_QUEUE_MAX || !virtio_queue_get_num(vdev, queue)) {
3973         error_setg(errp, "Invalid virtqueue number %d", queue);
3974         return NULL;
3975     }
3976     vq = &vdev->vq[queue];
3977 
3978     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3979         error_setg(errp, "Packed ring not supported");
3980         return NULL;
3981     } else {
3982         unsigned int head, i, max;
3983         VRingMemoryRegionCaches *caches;
3984         MemoryRegionCache indirect_desc_cache;
3985         MemoryRegionCache *desc_cache;
3986         VRingDesc desc;
3987         VirtioRingDescList *list = NULL;
3988         VirtioRingDescList *node;
3989         int rc; int ndescs;
3990 
3991         address_space_cache_init_empty(&indirect_desc_cache);
3992 
3993         RCU_READ_LOCK_GUARD();
3994 
3995         max = vq->vring.num;
3996 
3997         if (!has_index) {
3998             head = vring_avail_ring(vq, vq->last_avail_idx % vq->vring.num);
3999         } else {
4000             head = vring_avail_ring(vq, index % vq->vring.num);
4001         }
4002         i = head;
4003 
4004         caches = vring_get_region_caches(vq);
4005         if (!caches) {
4006             error_setg(errp, "Region caches not initialized");
4007             return NULL;
4008         }
4009         if (caches->desc.len < max * sizeof(VRingDesc)) {
4010             error_setg(errp, "Cannot map descriptor ring");
4011             return NULL;
4012         }
4013 
4014         desc_cache = &caches->desc;
4015         vring_split_desc_read(vdev, &desc, desc_cache, i);
4016         if (desc.flags & VRING_DESC_F_INDIRECT) {
4017             int64_t len;
4018             len = address_space_cache_init(&indirect_desc_cache, vdev->dma_as,
4019                                            desc.addr, desc.len, false);
4020             desc_cache = &indirect_desc_cache;
4021             if (len < desc.len) {
4022                 error_setg(errp, "Cannot map indirect buffer");
4023                 goto done;
4024             }
4025 
4026             max = desc.len / sizeof(VRingDesc);
4027             i = 0;
4028             vring_split_desc_read(vdev, &desc, desc_cache, i);
4029         }
4030 
4031         element = g_new0(VirtioQueueElement, 1);
4032         element->avail = g_new0(VirtioRingAvail, 1);
4033         element->used = g_new0(VirtioRingUsed, 1);
4034         element->name = g_strdup(vdev->name);
4035         element->index = head;
4036         element->avail->flags = vring_avail_flags(vq);
4037         element->avail->idx = vring_avail_idx(vq);
4038         element->avail->ring = head;
4039         element->used->flags = vring_used_flags(vq);
4040         element->used->idx = vring_used_idx(vq);
4041         ndescs = 0;
4042 
4043         do {
4044             /* A buggy driver may produce an infinite loop */
4045             if (ndescs >= max) {
4046                 break;
4047             }
4048             node = g_new0(VirtioRingDescList, 1);
4049             node->value = g_new0(VirtioRingDesc, 1);
4050             node->value->addr = desc.addr;
4051             node->value->len = desc.len;
4052             node->value->flags = qmp_decode_vring_desc_flags(desc.flags);
4053             node->next = list;
4054             list = node;
4055 
4056             ndescs++;
4057             rc = virtqueue_split_read_next_desc(vdev, &desc, desc_cache, max);
4058         } while (rc == VIRTQUEUE_READ_DESC_MORE);
4059         element->descs = list;
4060 done:
4061         address_space_cache_destroy(&indirect_desc_cache);
4062     }
4063 
4064     return element;
4065 }
4066 
4067 static const TypeInfo virtio_device_info = {
4068     .name = TYPE_VIRTIO_DEVICE,
4069     .parent = TYPE_DEVICE,
4070     .instance_size = sizeof(VirtIODevice),
4071     .class_init = virtio_device_class_init,
4072     .instance_finalize = virtio_device_instance_finalize,
4073     .abstract = true,
4074     .class_size = sizeof(VirtioDeviceClass),
4075 };
4076 
4077 static void virtio_register_types(void)
4078 {
4079     type_register_static(&virtio_device_info);
4080 }
4081 
4082 type_init(virtio_register_types)
4083