xref: /openbmc/qemu/hw/virtio/virtio.c (revision e0c72452)
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 (vdev->vhost_started) {
2140         vhost_reset_device(k->get_vhost(vdev));
2141     }
2142 
2143     if (k->reset) {
2144         k->reset(vdev);
2145     }
2146 
2147     vdev->start_on_kick = false;
2148     vdev->started = false;
2149     vdev->broken = false;
2150     vdev->guest_features = 0;
2151     vdev->queue_sel = 0;
2152     vdev->status = 0;
2153     vdev->disabled = false;
2154     qatomic_set(&vdev->isr, 0);
2155     vdev->config_vector = VIRTIO_NO_VECTOR;
2156     virtio_notify_vector(vdev, vdev->config_vector);
2157 
2158     for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2159         __virtio_queue_reset(vdev, i);
2160     }
2161 }
2162 
2163 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
2164 {
2165     if (!vdev->vq[n].vring.num) {
2166         return;
2167     }
2168     vdev->vq[n].vring.desc = addr;
2169     virtio_queue_update_rings(vdev, n);
2170 }
2171 
2172 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
2173 {
2174     return vdev->vq[n].vring.desc;
2175 }
2176 
2177 void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
2178                             hwaddr avail, hwaddr used)
2179 {
2180     if (!vdev->vq[n].vring.num) {
2181         return;
2182     }
2183     vdev->vq[n].vring.desc = desc;
2184     vdev->vq[n].vring.avail = avail;
2185     vdev->vq[n].vring.used = used;
2186     virtio_init_region_cache(vdev, n);
2187 }
2188 
2189 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
2190 {
2191     /* Don't allow guest to flip queue between existent and
2192      * nonexistent states, or to set it to an invalid size.
2193      */
2194     if (!!num != !!vdev->vq[n].vring.num ||
2195         num > VIRTQUEUE_MAX_SIZE ||
2196         num < 0) {
2197         return;
2198     }
2199     vdev->vq[n].vring.num = num;
2200 }
2201 
2202 VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
2203 {
2204     return QLIST_FIRST(&vdev->vector_queues[vector]);
2205 }
2206 
2207 VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
2208 {
2209     return QLIST_NEXT(vq, node);
2210 }
2211 
2212 int virtio_queue_get_num(VirtIODevice *vdev, int n)
2213 {
2214     return vdev->vq[n].vring.num;
2215 }
2216 
2217 int virtio_queue_get_max_num(VirtIODevice *vdev, int n)
2218 {
2219     return vdev->vq[n].vring.num_default;
2220 }
2221 
2222 int virtio_get_num_queues(VirtIODevice *vdev)
2223 {
2224     int i;
2225 
2226     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2227         if (!virtio_queue_get_num(vdev, i)) {
2228             break;
2229         }
2230     }
2231 
2232     return i;
2233 }
2234 
2235 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
2236 {
2237     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2238     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2239 
2240     /* virtio-1 compliant devices cannot change the alignment */
2241     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2242         error_report("tried to modify queue alignment for virtio-1 device");
2243         return;
2244     }
2245     /* Check that the transport told us it was going to do this
2246      * (so a buggy transport will immediately assert rather than
2247      * silently failing to migrate this state)
2248      */
2249     assert(k->has_variable_vring_alignment);
2250 
2251     if (align) {
2252         vdev->vq[n].vring.align = align;
2253         virtio_queue_update_rings(vdev, n);
2254     }
2255 }
2256 
2257 static void virtio_queue_notify_vq(VirtQueue *vq)
2258 {
2259     if (vq->vring.desc && vq->handle_output) {
2260         VirtIODevice *vdev = vq->vdev;
2261 
2262         if (unlikely(vdev->broken)) {
2263             return;
2264         }
2265 
2266         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2267         vq->handle_output(vdev, vq);
2268 
2269         if (unlikely(vdev->start_on_kick)) {
2270             virtio_set_started(vdev, true);
2271         }
2272     }
2273 }
2274 
2275 void virtio_queue_notify(VirtIODevice *vdev, int n)
2276 {
2277     VirtQueue *vq = &vdev->vq[n];
2278 
2279     if (unlikely(!vq->vring.desc || vdev->broken)) {
2280         return;
2281     }
2282 
2283     trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2284     if (vq->host_notifier_enabled) {
2285         event_notifier_set(&vq->host_notifier);
2286     } else if (vq->handle_output) {
2287         vq->handle_output(vdev, vq);
2288 
2289         if (unlikely(vdev->start_on_kick)) {
2290             virtio_set_started(vdev, true);
2291         }
2292     }
2293 }
2294 
2295 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
2296 {
2297     return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
2298         VIRTIO_NO_VECTOR;
2299 }
2300 
2301 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
2302 {
2303     VirtQueue *vq = &vdev->vq[n];
2304 
2305     if (n < VIRTIO_QUEUE_MAX) {
2306         if (vdev->vector_queues &&
2307             vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
2308             QLIST_REMOVE(vq, node);
2309         }
2310         vdev->vq[n].vector = vector;
2311         if (vdev->vector_queues &&
2312             vector != VIRTIO_NO_VECTOR) {
2313             QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
2314         }
2315     }
2316 }
2317 
2318 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
2319                             VirtIOHandleOutput handle_output)
2320 {
2321     int i;
2322 
2323     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2324         if (vdev->vq[i].vring.num == 0)
2325             break;
2326     }
2327 
2328     if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
2329         abort();
2330 
2331     vdev->vq[i].vring.num = queue_size;
2332     vdev->vq[i].vring.num_default = queue_size;
2333     vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
2334     vdev->vq[i].handle_output = handle_output;
2335     vdev->vq[i].used_elems = g_new0(VirtQueueElement, queue_size);
2336 
2337     return &vdev->vq[i];
2338 }
2339 
2340 void virtio_delete_queue(VirtQueue *vq)
2341 {
2342     vq->vring.num = 0;
2343     vq->vring.num_default = 0;
2344     vq->handle_output = NULL;
2345     g_free(vq->used_elems);
2346     vq->used_elems = NULL;
2347     virtio_virtqueue_reset_region_cache(vq);
2348 }
2349 
2350 void virtio_del_queue(VirtIODevice *vdev, int n)
2351 {
2352     if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
2353         abort();
2354     }
2355 
2356     virtio_delete_queue(&vdev->vq[n]);
2357 }
2358 
2359 static void virtio_set_isr(VirtIODevice *vdev, int value)
2360 {
2361     uint8_t old = qatomic_read(&vdev->isr);
2362 
2363     /* Do not write ISR if it does not change, so that its cacheline remains
2364      * shared in the common case where the guest does not read it.
2365      */
2366     if ((old & value) != value) {
2367         qatomic_or(&vdev->isr, value);
2368     }
2369 }
2370 
2371 /* Called within rcu_read_lock(). */
2372 static bool virtio_split_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2373 {
2374     uint16_t old, new;
2375     bool v;
2376     /* We need to expose used array entries before checking used event. */
2377     smp_mb();
2378     /* Always notify when queue is empty (when feature acknowledge) */
2379     if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2380         !vq->inuse && virtio_queue_empty(vq)) {
2381         return true;
2382     }
2383 
2384     if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2385         return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
2386     }
2387 
2388     v = vq->signalled_used_valid;
2389     vq->signalled_used_valid = true;
2390     old = vq->signalled_used;
2391     new = vq->signalled_used = vq->used_idx;
2392     return !v || vring_need_event(vring_get_used_event(vq), new, old);
2393 }
2394 
2395 static bool vring_packed_need_event(VirtQueue *vq, bool wrap,
2396                                     uint16_t off_wrap, uint16_t new,
2397                                     uint16_t old)
2398 {
2399     int off = off_wrap & ~(1 << 15);
2400 
2401     if (wrap != off_wrap >> 15) {
2402         off -= vq->vring.num;
2403     }
2404 
2405     return vring_need_event(off, new, old);
2406 }
2407 
2408 /* Called within rcu_read_lock(). */
2409 static bool virtio_packed_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2410 {
2411     VRingPackedDescEvent e;
2412     uint16_t old, new;
2413     bool v;
2414     VRingMemoryRegionCaches *caches;
2415 
2416     caches = vring_get_region_caches(vq);
2417     if (!caches) {
2418         return false;
2419     }
2420 
2421     vring_packed_event_read(vdev, &caches->avail, &e);
2422 
2423     old = vq->signalled_used;
2424     new = vq->signalled_used = vq->used_idx;
2425     v = vq->signalled_used_valid;
2426     vq->signalled_used_valid = true;
2427 
2428     if (e.flags == VRING_PACKED_EVENT_FLAG_DISABLE) {
2429         return false;
2430     } else if (e.flags == VRING_PACKED_EVENT_FLAG_ENABLE) {
2431         return true;
2432     }
2433 
2434     return !v || vring_packed_need_event(vq, vq->used_wrap_counter,
2435                                          e.off_wrap, new, old);
2436 }
2437 
2438 /* Called within rcu_read_lock().  */
2439 static bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2440 {
2441     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
2442         return virtio_packed_should_notify(vdev, vq);
2443     } else {
2444         return virtio_split_should_notify(vdev, vq);
2445     }
2446 }
2447 
2448 void virtio_notify_irqfd(VirtIODevice *vdev, VirtQueue *vq)
2449 {
2450     WITH_RCU_READ_LOCK_GUARD() {
2451         if (!virtio_should_notify(vdev, vq)) {
2452             return;
2453         }
2454     }
2455 
2456     trace_virtio_notify_irqfd(vdev, vq);
2457 
2458     /*
2459      * virtio spec 1.0 says ISR bit 0 should be ignored with MSI, but
2460      * windows drivers included in virtio-win 1.8.0 (circa 2015) are
2461      * incorrectly polling this bit during crashdump and hibernation
2462      * in MSI mode, causing a hang if this bit is never updated.
2463      * Recent releases of Windows do not really shut down, but rather
2464      * log out and hibernate to make the next startup faster.  Hence,
2465      * this manifested as a more serious hang during shutdown with
2466      *
2467      * Next driver release from 2016 fixed this problem, so working around it
2468      * is not a must, but it's easy to do so let's do it here.
2469      *
2470      * Note: it's safe to update ISR from any thread as it was switched
2471      * to an atomic operation.
2472      */
2473     virtio_set_isr(vq->vdev, 0x1);
2474     event_notifier_set(&vq->guest_notifier);
2475 }
2476 
2477 static void virtio_irq(VirtQueue *vq)
2478 {
2479     virtio_set_isr(vq->vdev, 0x1);
2480     virtio_notify_vector(vq->vdev, vq->vector);
2481 }
2482 
2483 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
2484 {
2485     WITH_RCU_READ_LOCK_GUARD() {
2486         if (!virtio_should_notify(vdev, vq)) {
2487             return;
2488         }
2489     }
2490 
2491     trace_virtio_notify(vdev, vq);
2492     virtio_irq(vq);
2493 }
2494 
2495 void virtio_notify_config(VirtIODevice *vdev)
2496 {
2497     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
2498         return;
2499 
2500     virtio_set_isr(vdev, 0x3);
2501     vdev->generation++;
2502     virtio_notify_vector(vdev, vdev->config_vector);
2503 }
2504 
2505 static bool virtio_device_endian_needed(void *opaque)
2506 {
2507     VirtIODevice *vdev = opaque;
2508 
2509     assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
2510     if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2511         return vdev->device_endian != virtio_default_endian();
2512     }
2513     /* Devices conforming to VIRTIO 1.0 or later are always LE. */
2514     return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
2515 }
2516 
2517 static bool virtio_64bit_features_needed(void *opaque)
2518 {
2519     VirtIODevice *vdev = opaque;
2520 
2521     return (vdev->host_features >> 32) != 0;
2522 }
2523 
2524 static bool virtio_virtqueue_needed(void *opaque)
2525 {
2526     VirtIODevice *vdev = opaque;
2527 
2528     return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
2529 }
2530 
2531 static bool virtio_packed_virtqueue_needed(void *opaque)
2532 {
2533     VirtIODevice *vdev = opaque;
2534 
2535     return virtio_host_has_feature(vdev, VIRTIO_F_RING_PACKED);
2536 }
2537 
2538 static bool virtio_ringsize_needed(void *opaque)
2539 {
2540     VirtIODevice *vdev = opaque;
2541     int i;
2542 
2543     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2544         if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
2545             return true;
2546         }
2547     }
2548     return false;
2549 }
2550 
2551 static bool virtio_extra_state_needed(void *opaque)
2552 {
2553     VirtIODevice *vdev = opaque;
2554     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2555     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2556 
2557     return k->has_extra_state &&
2558         k->has_extra_state(qbus->parent);
2559 }
2560 
2561 static bool virtio_broken_needed(void *opaque)
2562 {
2563     VirtIODevice *vdev = opaque;
2564 
2565     return vdev->broken;
2566 }
2567 
2568 static bool virtio_started_needed(void *opaque)
2569 {
2570     VirtIODevice *vdev = opaque;
2571 
2572     return vdev->started;
2573 }
2574 
2575 static bool virtio_disabled_needed(void *opaque)
2576 {
2577     VirtIODevice *vdev = opaque;
2578 
2579     return vdev->disabled;
2580 }
2581 
2582 static const VMStateDescription vmstate_virtqueue = {
2583     .name = "virtqueue_state",
2584     .version_id = 1,
2585     .minimum_version_id = 1,
2586     .fields = (VMStateField[]) {
2587         VMSTATE_UINT64(vring.avail, struct VirtQueue),
2588         VMSTATE_UINT64(vring.used, struct VirtQueue),
2589         VMSTATE_END_OF_LIST()
2590     }
2591 };
2592 
2593 static const VMStateDescription vmstate_packed_virtqueue = {
2594     .name = "packed_virtqueue_state",
2595     .version_id = 1,
2596     .minimum_version_id = 1,
2597     .fields = (VMStateField[]) {
2598         VMSTATE_UINT16(last_avail_idx, struct VirtQueue),
2599         VMSTATE_BOOL(last_avail_wrap_counter, struct VirtQueue),
2600         VMSTATE_UINT16(used_idx, struct VirtQueue),
2601         VMSTATE_BOOL(used_wrap_counter, struct VirtQueue),
2602         VMSTATE_UINT32(inuse, struct VirtQueue),
2603         VMSTATE_END_OF_LIST()
2604     }
2605 };
2606 
2607 static const VMStateDescription vmstate_virtio_virtqueues = {
2608     .name = "virtio/virtqueues",
2609     .version_id = 1,
2610     .minimum_version_id = 1,
2611     .needed = &virtio_virtqueue_needed,
2612     .fields = (VMStateField[]) {
2613         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2614                       VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
2615         VMSTATE_END_OF_LIST()
2616     }
2617 };
2618 
2619 static const VMStateDescription vmstate_virtio_packed_virtqueues = {
2620     .name = "virtio/packed_virtqueues",
2621     .version_id = 1,
2622     .minimum_version_id = 1,
2623     .needed = &virtio_packed_virtqueue_needed,
2624     .fields = (VMStateField[]) {
2625         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2626                       VIRTIO_QUEUE_MAX, 0, vmstate_packed_virtqueue, VirtQueue),
2627         VMSTATE_END_OF_LIST()
2628     }
2629 };
2630 
2631 static const VMStateDescription vmstate_ringsize = {
2632     .name = "ringsize_state",
2633     .version_id = 1,
2634     .minimum_version_id = 1,
2635     .fields = (VMStateField[]) {
2636         VMSTATE_UINT32(vring.num_default, struct VirtQueue),
2637         VMSTATE_END_OF_LIST()
2638     }
2639 };
2640 
2641 static const VMStateDescription vmstate_virtio_ringsize = {
2642     .name = "virtio/ringsize",
2643     .version_id = 1,
2644     .minimum_version_id = 1,
2645     .needed = &virtio_ringsize_needed,
2646     .fields = (VMStateField[]) {
2647         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2648                       VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
2649         VMSTATE_END_OF_LIST()
2650     }
2651 };
2652 
2653 static int get_extra_state(QEMUFile *f, void *pv, size_t size,
2654                            const VMStateField *field)
2655 {
2656     VirtIODevice *vdev = pv;
2657     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2658     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2659 
2660     if (!k->load_extra_state) {
2661         return -1;
2662     } else {
2663         return k->load_extra_state(qbus->parent, f);
2664     }
2665 }
2666 
2667 static int put_extra_state(QEMUFile *f, void *pv, size_t size,
2668                            const VMStateField *field, JSONWriter *vmdesc)
2669 {
2670     VirtIODevice *vdev = pv;
2671     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2672     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2673 
2674     k->save_extra_state(qbus->parent, f);
2675     return 0;
2676 }
2677 
2678 static const VMStateInfo vmstate_info_extra_state = {
2679     .name = "virtqueue_extra_state",
2680     .get = get_extra_state,
2681     .put = put_extra_state,
2682 };
2683 
2684 static const VMStateDescription vmstate_virtio_extra_state = {
2685     .name = "virtio/extra_state",
2686     .version_id = 1,
2687     .minimum_version_id = 1,
2688     .needed = &virtio_extra_state_needed,
2689     .fields = (VMStateField[]) {
2690         {
2691             .name         = "extra_state",
2692             .version_id   = 0,
2693             .field_exists = NULL,
2694             .size         = 0,
2695             .info         = &vmstate_info_extra_state,
2696             .flags        = VMS_SINGLE,
2697             .offset       = 0,
2698         },
2699         VMSTATE_END_OF_LIST()
2700     }
2701 };
2702 
2703 static const VMStateDescription vmstate_virtio_device_endian = {
2704     .name = "virtio/device_endian",
2705     .version_id = 1,
2706     .minimum_version_id = 1,
2707     .needed = &virtio_device_endian_needed,
2708     .fields = (VMStateField[]) {
2709         VMSTATE_UINT8(device_endian, VirtIODevice),
2710         VMSTATE_END_OF_LIST()
2711     }
2712 };
2713 
2714 static const VMStateDescription vmstate_virtio_64bit_features = {
2715     .name = "virtio/64bit_features",
2716     .version_id = 1,
2717     .minimum_version_id = 1,
2718     .needed = &virtio_64bit_features_needed,
2719     .fields = (VMStateField[]) {
2720         VMSTATE_UINT64(guest_features, VirtIODevice),
2721         VMSTATE_END_OF_LIST()
2722     }
2723 };
2724 
2725 static const VMStateDescription vmstate_virtio_broken = {
2726     .name = "virtio/broken",
2727     .version_id = 1,
2728     .minimum_version_id = 1,
2729     .needed = &virtio_broken_needed,
2730     .fields = (VMStateField[]) {
2731         VMSTATE_BOOL(broken, VirtIODevice),
2732         VMSTATE_END_OF_LIST()
2733     }
2734 };
2735 
2736 static const VMStateDescription vmstate_virtio_started = {
2737     .name = "virtio/started",
2738     .version_id = 1,
2739     .minimum_version_id = 1,
2740     .needed = &virtio_started_needed,
2741     .fields = (VMStateField[]) {
2742         VMSTATE_BOOL(started, VirtIODevice),
2743         VMSTATE_END_OF_LIST()
2744     }
2745 };
2746 
2747 static const VMStateDescription vmstate_virtio_disabled = {
2748     .name = "virtio/disabled",
2749     .version_id = 1,
2750     .minimum_version_id = 1,
2751     .needed = &virtio_disabled_needed,
2752     .fields = (VMStateField[]) {
2753         VMSTATE_BOOL(disabled, VirtIODevice),
2754         VMSTATE_END_OF_LIST()
2755     }
2756 };
2757 
2758 static const VMStateDescription vmstate_virtio = {
2759     .name = "virtio",
2760     .version_id = 1,
2761     .minimum_version_id = 1,
2762     .fields = (VMStateField[]) {
2763         VMSTATE_END_OF_LIST()
2764     },
2765     .subsections = (const VMStateDescription*[]) {
2766         &vmstate_virtio_device_endian,
2767         &vmstate_virtio_64bit_features,
2768         &vmstate_virtio_virtqueues,
2769         &vmstate_virtio_ringsize,
2770         &vmstate_virtio_broken,
2771         &vmstate_virtio_extra_state,
2772         &vmstate_virtio_started,
2773         &vmstate_virtio_packed_virtqueues,
2774         &vmstate_virtio_disabled,
2775         NULL
2776     }
2777 };
2778 
2779 int virtio_save(VirtIODevice *vdev, QEMUFile *f)
2780 {
2781     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2782     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2783     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2784     uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
2785     int i;
2786 
2787     if (k->save_config) {
2788         k->save_config(qbus->parent, f);
2789     }
2790 
2791     qemu_put_8s(f, &vdev->status);
2792     qemu_put_8s(f, &vdev->isr);
2793     qemu_put_be16s(f, &vdev->queue_sel);
2794     qemu_put_be32s(f, &guest_features_lo);
2795     qemu_put_be32(f, vdev->config_len);
2796     qemu_put_buffer(f, vdev->config, vdev->config_len);
2797 
2798     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2799         if (vdev->vq[i].vring.num == 0)
2800             break;
2801     }
2802 
2803     qemu_put_be32(f, i);
2804 
2805     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2806         if (vdev->vq[i].vring.num == 0)
2807             break;
2808 
2809         qemu_put_be32(f, vdev->vq[i].vring.num);
2810         if (k->has_variable_vring_alignment) {
2811             qemu_put_be32(f, vdev->vq[i].vring.align);
2812         }
2813         /*
2814          * Save desc now, the rest of the ring addresses are saved in
2815          * subsections for VIRTIO-1 devices.
2816          */
2817         qemu_put_be64(f, vdev->vq[i].vring.desc);
2818         qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
2819         if (k->save_queue) {
2820             k->save_queue(qbus->parent, i, f);
2821         }
2822     }
2823 
2824     if (vdc->save != NULL) {
2825         vdc->save(vdev, f);
2826     }
2827 
2828     if (vdc->vmsd) {
2829         int ret = vmstate_save_state(f, vdc->vmsd, vdev, NULL);
2830         if (ret) {
2831             return ret;
2832         }
2833     }
2834 
2835     /* Subsections */
2836     return vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
2837 }
2838 
2839 /* A wrapper for use as a VMState .put function */
2840 static int virtio_device_put(QEMUFile *f, void *opaque, size_t size,
2841                               const VMStateField *field, JSONWriter *vmdesc)
2842 {
2843     return virtio_save(VIRTIO_DEVICE(opaque), f);
2844 }
2845 
2846 /* A wrapper for use as a VMState .get function */
2847 static int coroutine_mixed_fn
2848 virtio_device_get(QEMUFile *f, void *opaque, size_t size,
2849                   const VMStateField *field)
2850 {
2851     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
2852     DeviceClass *dc = DEVICE_CLASS(VIRTIO_DEVICE_GET_CLASS(vdev));
2853 
2854     return virtio_load(vdev, f, dc->vmsd->version_id);
2855 }
2856 
2857 const VMStateInfo  virtio_vmstate_info = {
2858     .name = "virtio",
2859     .get = virtio_device_get,
2860     .put = virtio_device_put,
2861 };
2862 
2863 static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
2864 {
2865     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2866     bool bad = (val & ~(vdev->host_features)) != 0;
2867 
2868     val &= vdev->host_features;
2869     if (k->set_features) {
2870         k->set_features(vdev, val);
2871     }
2872     vdev->guest_features = val;
2873     return bad ? -1 : 0;
2874 }
2875 
2876 typedef struct VirtioSetFeaturesNocheckData {
2877     Coroutine *co;
2878     VirtIODevice *vdev;
2879     uint64_t val;
2880     int ret;
2881 } VirtioSetFeaturesNocheckData;
2882 
2883 static void virtio_set_features_nocheck_bh(void *opaque)
2884 {
2885     VirtioSetFeaturesNocheckData *data = opaque;
2886 
2887     data->ret = virtio_set_features_nocheck(data->vdev, data->val);
2888     aio_co_wake(data->co);
2889 }
2890 
2891 static int coroutine_mixed_fn
2892 virtio_set_features_nocheck_maybe_co(VirtIODevice *vdev, uint64_t val)
2893 {
2894     if (qemu_in_coroutine()) {
2895         VirtioSetFeaturesNocheckData data = {
2896             .co = qemu_coroutine_self(),
2897             .vdev = vdev,
2898             .val = val,
2899         };
2900         aio_bh_schedule_oneshot(qemu_get_current_aio_context(),
2901                                 virtio_set_features_nocheck_bh, &data);
2902         qemu_coroutine_yield();
2903         return data.ret;
2904     } else {
2905         return virtio_set_features_nocheck(vdev, val);
2906     }
2907 }
2908 
2909 int virtio_set_features(VirtIODevice *vdev, uint64_t val)
2910 {
2911     int ret;
2912     /*
2913      * The driver must not attempt to set features after feature negotiation
2914      * has finished.
2915      */
2916     if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
2917         return -EINVAL;
2918     }
2919 
2920     if (val & (1ull << VIRTIO_F_BAD_FEATURE)) {
2921         qemu_log_mask(LOG_GUEST_ERROR,
2922                       "%s: guest driver for %s has enabled UNUSED(30) feature bit!\n",
2923                       __func__, vdev->name);
2924     }
2925 
2926     ret = virtio_set_features_nocheck(vdev, val);
2927     if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2928         /* VIRTIO_RING_F_EVENT_IDX changes the size of the caches.  */
2929         int i;
2930         for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2931             if (vdev->vq[i].vring.num != 0) {
2932                 virtio_init_region_cache(vdev, i);
2933             }
2934         }
2935     }
2936     if (!ret) {
2937         if (!virtio_device_started(vdev, vdev->status) &&
2938             !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2939             vdev->start_on_kick = true;
2940         }
2941     }
2942     return ret;
2943 }
2944 
2945 size_t virtio_get_config_size(const VirtIOConfigSizeParams *params,
2946                               uint64_t host_features)
2947 {
2948     size_t config_size = params->min_size;
2949     const VirtIOFeature *feature_sizes = params->feature_sizes;
2950     size_t i;
2951 
2952     for (i = 0; feature_sizes[i].flags != 0; i++) {
2953         if (host_features & feature_sizes[i].flags) {
2954             config_size = MAX(feature_sizes[i].end, config_size);
2955         }
2956     }
2957 
2958     assert(config_size <= params->max_size);
2959     return config_size;
2960 }
2961 
2962 int coroutine_mixed_fn
2963 virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
2964 {
2965     int i, ret;
2966     int32_t config_len;
2967     uint32_t num;
2968     uint32_t features;
2969     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2970     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2971     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2972 
2973     /*
2974      * We poison the endianness to ensure it does not get used before
2975      * subsections have been loaded.
2976      */
2977     vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
2978 
2979     if (k->load_config) {
2980         ret = k->load_config(qbus->parent, f);
2981         if (ret)
2982             return ret;
2983     }
2984 
2985     qemu_get_8s(f, &vdev->status);
2986     qemu_get_8s(f, &vdev->isr);
2987     qemu_get_be16s(f, &vdev->queue_sel);
2988     if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
2989         return -1;
2990     }
2991     qemu_get_be32s(f, &features);
2992 
2993     /*
2994      * Temporarily set guest_features low bits - needed by
2995      * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
2996      * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
2997      *
2998      * Note: devices should always test host features in future - don't create
2999      * new dependencies like this.
3000      */
3001     vdev->guest_features = features;
3002 
3003     config_len = qemu_get_be32(f);
3004 
3005     /*
3006      * There are cases where the incoming config can be bigger or smaller
3007      * than what we have; so load what we have space for, and skip
3008      * any excess that's in the stream.
3009      */
3010     qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
3011 
3012     while (config_len > vdev->config_len) {
3013         qemu_get_byte(f);
3014         config_len--;
3015     }
3016 
3017     num = qemu_get_be32(f);
3018 
3019     if (num > VIRTIO_QUEUE_MAX) {
3020         error_report("Invalid number of virtqueues: 0x%x", num);
3021         return -1;
3022     }
3023 
3024     for (i = 0; i < num; i++) {
3025         vdev->vq[i].vring.num = qemu_get_be32(f);
3026         if (k->has_variable_vring_alignment) {
3027             vdev->vq[i].vring.align = qemu_get_be32(f);
3028         }
3029         vdev->vq[i].vring.desc = qemu_get_be64(f);
3030         qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
3031         vdev->vq[i].signalled_used_valid = false;
3032         vdev->vq[i].notification = true;
3033 
3034         if (!vdev->vq[i].vring.desc && vdev->vq[i].last_avail_idx) {
3035             error_report("VQ %d address 0x0 "
3036                          "inconsistent with Host index 0x%x",
3037                          i, vdev->vq[i].last_avail_idx);
3038             return -1;
3039         }
3040         if (k->load_queue) {
3041             ret = k->load_queue(qbus->parent, i, f);
3042             if (ret)
3043                 return ret;
3044         }
3045     }
3046 
3047     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
3048 
3049     if (vdc->load != NULL) {
3050         ret = vdc->load(vdev, f, version_id);
3051         if (ret) {
3052             return ret;
3053         }
3054     }
3055 
3056     if (vdc->vmsd) {
3057         ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id);
3058         if (ret) {
3059             return ret;
3060         }
3061     }
3062 
3063     /* Subsections */
3064     ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
3065     if (ret) {
3066         return ret;
3067     }
3068 
3069     if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
3070         vdev->device_endian = virtio_default_endian();
3071     }
3072 
3073     if (virtio_64bit_features_needed(vdev)) {
3074         /*
3075          * Subsection load filled vdev->guest_features.  Run them
3076          * through virtio_set_features to sanity-check them against
3077          * host_features.
3078          */
3079         uint64_t features64 = vdev->guest_features;
3080         if (virtio_set_features_nocheck_maybe_co(vdev, features64) < 0) {
3081             error_report("Features 0x%" PRIx64 " unsupported. "
3082                          "Allowed features: 0x%" PRIx64,
3083                          features64, vdev->host_features);
3084             return -1;
3085         }
3086     } else {
3087         if (virtio_set_features_nocheck_maybe_co(vdev, features) < 0) {
3088             error_report("Features 0x%x unsupported. "
3089                          "Allowed features: 0x%" PRIx64,
3090                          features, vdev->host_features);
3091             return -1;
3092         }
3093     }
3094 
3095     if (!virtio_device_started(vdev, vdev->status) &&
3096         !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3097         vdev->start_on_kick = true;
3098     }
3099 
3100     RCU_READ_LOCK_GUARD();
3101     for (i = 0; i < num; i++) {
3102         if (vdev->vq[i].vring.desc) {
3103             uint16_t nheads;
3104 
3105             /*
3106              * VIRTIO-1 devices migrate desc, used, and avail ring addresses so
3107              * only the region cache needs to be set up.  Legacy devices need
3108              * to calculate used and avail ring addresses based on the desc
3109              * address.
3110              */
3111             if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3112                 virtio_init_region_cache(vdev, i);
3113             } else {
3114                 virtio_queue_update_rings(vdev, i);
3115             }
3116 
3117             if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3118                 vdev->vq[i].shadow_avail_idx = vdev->vq[i].last_avail_idx;
3119                 vdev->vq[i].shadow_avail_wrap_counter =
3120                                         vdev->vq[i].last_avail_wrap_counter;
3121                 continue;
3122             }
3123 
3124             nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
3125             /* Check it isn't doing strange things with descriptor numbers. */
3126             if (nheads > vdev->vq[i].vring.num) {
3127                 virtio_error(vdev, "VQ %d size 0x%x Guest index 0x%x "
3128                              "inconsistent with Host index 0x%x: delta 0x%x",
3129                              i, vdev->vq[i].vring.num,
3130                              vring_avail_idx(&vdev->vq[i]),
3131                              vdev->vq[i].last_avail_idx, nheads);
3132                 vdev->vq[i].used_idx = 0;
3133                 vdev->vq[i].shadow_avail_idx = 0;
3134                 vdev->vq[i].inuse = 0;
3135                 continue;
3136             }
3137             vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
3138             vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
3139 
3140             /*
3141              * Some devices migrate VirtQueueElements that have been popped
3142              * from the avail ring but not yet returned to the used ring.
3143              * Since max ring size < UINT16_MAX it's safe to use modulo
3144              * UINT16_MAX + 1 subtraction.
3145              */
3146             vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx -
3147                                 vdev->vq[i].used_idx);
3148             if (vdev->vq[i].inuse > vdev->vq[i].vring.num) {
3149                 error_report("VQ %d size 0x%x < last_avail_idx 0x%x - "
3150                              "used_idx 0x%x",
3151                              i, vdev->vq[i].vring.num,
3152                              vdev->vq[i].last_avail_idx,
3153                              vdev->vq[i].used_idx);
3154                 return -1;
3155             }
3156         }
3157     }
3158 
3159     if (vdc->post_load) {
3160         ret = vdc->post_load(vdev);
3161         if (ret) {
3162             return ret;
3163         }
3164     }
3165 
3166     return 0;
3167 }
3168 
3169 void virtio_cleanup(VirtIODevice *vdev)
3170 {
3171     qemu_del_vm_change_state_handler(vdev->vmstate);
3172 }
3173 
3174 static void virtio_vmstate_change(void *opaque, bool running, RunState state)
3175 {
3176     VirtIODevice *vdev = opaque;
3177     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3178     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3179     bool backend_run = running && virtio_device_started(vdev, vdev->status);
3180     vdev->vm_running = running;
3181 
3182     if (backend_run) {
3183         virtio_set_status(vdev, vdev->status);
3184     }
3185 
3186     if (k->vmstate_change) {
3187         k->vmstate_change(qbus->parent, backend_run);
3188     }
3189 
3190     if (!backend_run) {
3191         virtio_set_status(vdev, vdev->status);
3192     }
3193 }
3194 
3195 void virtio_instance_init_common(Object *proxy_obj, void *data,
3196                                  size_t vdev_size, const char *vdev_name)
3197 {
3198     DeviceState *vdev = data;
3199 
3200     object_initialize_child_with_props(proxy_obj, "virtio-backend", vdev,
3201                                        vdev_size, vdev_name, &error_abort,
3202                                        NULL);
3203     qdev_alias_all_properties(vdev, proxy_obj);
3204 }
3205 
3206 void virtio_init(VirtIODevice *vdev, uint16_t device_id, size_t config_size)
3207 {
3208     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3209     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3210     int i;
3211     int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
3212 
3213     if (nvectors) {
3214         vdev->vector_queues =
3215             g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
3216     }
3217 
3218     vdev->start_on_kick = false;
3219     vdev->started = false;
3220     vdev->vhost_started = false;
3221     vdev->device_id = device_id;
3222     vdev->status = 0;
3223     qatomic_set(&vdev->isr, 0);
3224     vdev->queue_sel = 0;
3225     vdev->config_vector = VIRTIO_NO_VECTOR;
3226     vdev->vq = g_new0(VirtQueue, VIRTIO_QUEUE_MAX);
3227     vdev->vm_running = runstate_is_running();
3228     vdev->broken = false;
3229     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3230         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
3231         vdev->vq[i].vdev = vdev;
3232         vdev->vq[i].queue_index = i;
3233         vdev->vq[i].host_notifier_enabled = false;
3234     }
3235 
3236     vdev->name = virtio_id_to_name(device_id);
3237     vdev->config_len = config_size;
3238     if (vdev->config_len) {
3239         vdev->config = g_malloc0(config_size);
3240     } else {
3241         vdev->config = NULL;
3242     }
3243     vdev->vmstate = qdev_add_vm_change_state_handler(DEVICE(vdev),
3244             virtio_vmstate_change, vdev);
3245     vdev->device_endian = virtio_default_endian();
3246     vdev->use_guest_notifier_mask = true;
3247 }
3248 
3249 /*
3250  * Only devices that have already been around prior to defining the virtio
3251  * standard support legacy mode; this includes devices not specified in the
3252  * standard. All newer devices conform to the virtio standard only.
3253  */
3254 bool virtio_legacy_allowed(VirtIODevice *vdev)
3255 {
3256     switch (vdev->device_id) {
3257     case VIRTIO_ID_NET:
3258     case VIRTIO_ID_BLOCK:
3259     case VIRTIO_ID_CONSOLE:
3260     case VIRTIO_ID_RNG:
3261     case VIRTIO_ID_BALLOON:
3262     case VIRTIO_ID_RPMSG:
3263     case VIRTIO_ID_SCSI:
3264     case VIRTIO_ID_9P:
3265     case VIRTIO_ID_RPROC_SERIAL:
3266     case VIRTIO_ID_CAIF:
3267         return true;
3268     default:
3269         return false;
3270     }
3271 }
3272 
3273 bool virtio_legacy_check_disabled(VirtIODevice *vdev)
3274 {
3275     return vdev->disable_legacy_check;
3276 }
3277 
3278 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
3279 {
3280     return vdev->vq[n].vring.desc;
3281 }
3282 
3283 bool virtio_queue_enabled_legacy(VirtIODevice *vdev, int n)
3284 {
3285     return virtio_queue_get_desc_addr(vdev, n) != 0;
3286 }
3287 
3288 bool virtio_queue_enabled(VirtIODevice *vdev, int n)
3289 {
3290     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3291     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3292 
3293     if (k->queue_enabled) {
3294         return k->queue_enabled(qbus->parent, n);
3295     }
3296     return virtio_queue_enabled_legacy(vdev, n);
3297 }
3298 
3299 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
3300 {
3301     return vdev->vq[n].vring.avail;
3302 }
3303 
3304 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
3305 {
3306     return vdev->vq[n].vring.used;
3307 }
3308 
3309 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
3310 {
3311     return sizeof(VRingDesc) * vdev->vq[n].vring.num;
3312 }
3313 
3314 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
3315 {
3316     int s;
3317 
3318     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3319         return sizeof(struct VRingPackedDescEvent);
3320     }
3321 
3322     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3323     return offsetof(VRingAvail, ring) +
3324         sizeof(uint16_t) * vdev->vq[n].vring.num + s;
3325 }
3326 
3327 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
3328 {
3329     int s;
3330 
3331     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3332         return sizeof(struct VRingPackedDescEvent);
3333     }
3334 
3335     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3336     return offsetof(VRingUsed, ring) +
3337         sizeof(VRingUsedElem) * vdev->vq[n].vring.num + s;
3338 }
3339 
3340 static unsigned int virtio_queue_packed_get_last_avail_idx(VirtIODevice *vdev,
3341                                                            int n)
3342 {
3343     unsigned int avail, used;
3344 
3345     avail = vdev->vq[n].last_avail_idx;
3346     avail |= ((uint16_t)vdev->vq[n].last_avail_wrap_counter) << 15;
3347 
3348     used = vdev->vq[n].used_idx;
3349     used |= ((uint16_t)vdev->vq[n].used_wrap_counter) << 15;
3350 
3351     return avail | used << 16;
3352 }
3353 
3354 static uint16_t virtio_queue_split_get_last_avail_idx(VirtIODevice *vdev,
3355                                                       int n)
3356 {
3357     return vdev->vq[n].last_avail_idx;
3358 }
3359 
3360 unsigned int virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
3361 {
3362     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3363         return virtio_queue_packed_get_last_avail_idx(vdev, n);
3364     } else {
3365         return virtio_queue_split_get_last_avail_idx(vdev, n);
3366     }
3367 }
3368 
3369 static void virtio_queue_packed_set_last_avail_idx(VirtIODevice *vdev,
3370                                                    int n, unsigned int idx)
3371 {
3372     struct VirtQueue *vq = &vdev->vq[n];
3373 
3374     vq->last_avail_idx = vq->shadow_avail_idx = idx & 0x7fff;
3375     vq->last_avail_wrap_counter =
3376         vq->shadow_avail_wrap_counter = !!(idx & 0x8000);
3377     idx >>= 16;
3378     vq->used_idx = idx & 0x7fff;
3379     vq->used_wrap_counter = !!(idx & 0x8000);
3380 }
3381 
3382 static void virtio_queue_split_set_last_avail_idx(VirtIODevice *vdev,
3383                                                   int n, unsigned int idx)
3384 {
3385         vdev->vq[n].last_avail_idx = idx;
3386         vdev->vq[n].shadow_avail_idx = idx;
3387 }
3388 
3389 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n,
3390                                      unsigned int idx)
3391 {
3392     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3393         virtio_queue_packed_set_last_avail_idx(vdev, n, idx);
3394     } else {
3395         virtio_queue_split_set_last_avail_idx(vdev, n, idx);
3396     }
3397 }
3398 
3399 static void virtio_queue_packed_restore_last_avail_idx(VirtIODevice *vdev,
3400                                                        int n)
3401 {
3402     /* We don't have a reference like avail idx in shared memory */
3403     return;
3404 }
3405 
3406 static void virtio_queue_split_restore_last_avail_idx(VirtIODevice *vdev,
3407                                                       int n)
3408 {
3409     RCU_READ_LOCK_GUARD();
3410     if (vdev->vq[n].vring.desc) {
3411         vdev->vq[n].last_avail_idx = vring_used_idx(&vdev->vq[n]);
3412         vdev->vq[n].shadow_avail_idx = vdev->vq[n].last_avail_idx;
3413     }
3414 }
3415 
3416 void virtio_queue_restore_last_avail_idx(VirtIODevice *vdev, int n)
3417 {
3418     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3419         virtio_queue_packed_restore_last_avail_idx(vdev, n);
3420     } else {
3421         virtio_queue_split_restore_last_avail_idx(vdev, n);
3422     }
3423 }
3424 
3425 static void virtio_queue_packed_update_used_idx(VirtIODevice *vdev, int n)
3426 {
3427     /* used idx was updated through set_last_avail_idx() */
3428     return;
3429 }
3430 
3431 static void virtio_split_packed_update_used_idx(VirtIODevice *vdev, int n)
3432 {
3433     RCU_READ_LOCK_GUARD();
3434     if (vdev->vq[n].vring.desc) {
3435         vdev->vq[n].used_idx = vring_used_idx(&vdev->vq[n]);
3436     }
3437 }
3438 
3439 void virtio_queue_update_used_idx(VirtIODevice *vdev, int n)
3440 {
3441     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3442         return virtio_queue_packed_update_used_idx(vdev, n);
3443     } else {
3444         return virtio_split_packed_update_used_idx(vdev, n);
3445     }
3446 }
3447 
3448 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
3449 {
3450     vdev->vq[n].signalled_used_valid = false;
3451 }
3452 
3453 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
3454 {
3455     return vdev->vq + n;
3456 }
3457 
3458 uint16_t virtio_get_queue_index(VirtQueue *vq)
3459 {
3460     return vq->queue_index;
3461 }
3462 
3463 static void virtio_queue_guest_notifier_read(EventNotifier *n)
3464 {
3465     VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
3466     if (event_notifier_test_and_clear(n)) {
3467         virtio_irq(vq);
3468     }
3469 }
3470 static void virtio_config_guest_notifier_read(EventNotifier *n)
3471 {
3472     VirtIODevice *vdev = container_of(n, VirtIODevice, config_notifier);
3473 
3474     if (event_notifier_test_and_clear(n)) {
3475         virtio_notify_config(vdev);
3476     }
3477 }
3478 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
3479                                                 bool with_irqfd)
3480 {
3481     if (assign && !with_irqfd) {
3482         event_notifier_set_handler(&vq->guest_notifier,
3483                                    virtio_queue_guest_notifier_read);
3484     } else {
3485         event_notifier_set_handler(&vq->guest_notifier, NULL);
3486     }
3487     if (!assign) {
3488         /* Test and clear notifier before closing it,
3489          * in case poll callback didn't have time to run. */
3490         virtio_queue_guest_notifier_read(&vq->guest_notifier);
3491     }
3492 }
3493 
3494 void virtio_config_set_guest_notifier_fd_handler(VirtIODevice *vdev,
3495                                                  bool assign, bool with_irqfd)
3496 {
3497     EventNotifier *n;
3498     n = &vdev->config_notifier;
3499     if (assign && !with_irqfd) {
3500         event_notifier_set_handler(n, virtio_config_guest_notifier_read);
3501     } else {
3502         event_notifier_set_handler(n, NULL);
3503     }
3504     if (!assign) {
3505         /* Test and clear notifier before closing it,*/
3506         /* in case poll callback didn't have time to run. */
3507         virtio_config_guest_notifier_read(n);
3508     }
3509 }
3510 
3511 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
3512 {
3513     return &vq->guest_notifier;
3514 }
3515 
3516 static void virtio_queue_host_notifier_aio_poll_begin(EventNotifier *n)
3517 {
3518     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3519 
3520     virtio_queue_set_notification(vq, 0);
3521 }
3522 
3523 static bool virtio_queue_host_notifier_aio_poll(void *opaque)
3524 {
3525     EventNotifier *n = opaque;
3526     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3527 
3528     return vq->vring.desc && !virtio_queue_empty(vq);
3529 }
3530 
3531 static void virtio_queue_host_notifier_aio_poll_ready(EventNotifier *n)
3532 {
3533     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3534 
3535     virtio_queue_notify_vq(vq);
3536 }
3537 
3538 static void virtio_queue_host_notifier_aio_poll_end(EventNotifier *n)
3539 {
3540     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3541 
3542     /* Caller polls once more after this to catch requests that race with us */
3543     virtio_queue_set_notification(vq, 1);
3544 }
3545 
3546 void virtio_queue_aio_attach_host_notifier(VirtQueue *vq, AioContext *ctx)
3547 {
3548     aio_set_event_notifier(ctx, &vq->host_notifier,
3549                            virtio_queue_host_notifier_read,
3550                            virtio_queue_host_notifier_aio_poll,
3551                            virtio_queue_host_notifier_aio_poll_ready);
3552     aio_set_event_notifier_poll(ctx, &vq->host_notifier,
3553                                 virtio_queue_host_notifier_aio_poll_begin,
3554                                 virtio_queue_host_notifier_aio_poll_end);
3555 }
3556 
3557 /*
3558  * Same as virtio_queue_aio_attach_host_notifier() but without polling. Use
3559  * this for rx virtqueues and similar cases where the virtqueue handler
3560  * function does not pop all elements. When the virtqueue is left non-empty
3561  * polling consumes CPU cycles and should not be used.
3562  */
3563 void virtio_queue_aio_attach_host_notifier_no_poll(VirtQueue *vq, AioContext *ctx)
3564 {
3565     aio_set_event_notifier(ctx, &vq->host_notifier,
3566                            virtio_queue_host_notifier_read,
3567                            NULL, NULL);
3568 }
3569 
3570 void virtio_queue_aio_detach_host_notifier(VirtQueue *vq, AioContext *ctx)
3571 {
3572     aio_set_event_notifier(ctx, &vq->host_notifier, NULL, NULL, NULL);
3573 }
3574 
3575 void virtio_queue_host_notifier_read(EventNotifier *n)
3576 {
3577     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3578     if (event_notifier_test_and_clear(n)) {
3579         virtio_queue_notify_vq(vq);
3580     }
3581 }
3582 
3583 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
3584 {
3585     return &vq->host_notifier;
3586 }
3587 
3588 EventNotifier *virtio_config_get_guest_notifier(VirtIODevice *vdev)
3589 {
3590     return &vdev->config_notifier;
3591 }
3592 
3593 void virtio_queue_set_host_notifier_enabled(VirtQueue *vq, bool enabled)
3594 {
3595     vq->host_notifier_enabled = enabled;
3596 }
3597 
3598 int virtio_queue_set_host_notifier_mr(VirtIODevice *vdev, int n,
3599                                       MemoryRegion *mr, bool assign)
3600 {
3601     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3602     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3603 
3604     if (k->set_host_notifier_mr) {
3605         return k->set_host_notifier_mr(qbus->parent, n, mr, assign);
3606     }
3607 
3608     return -1;
3609 }
3610 
3611 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
3612 {
3613     g_free(vdev->bus_name);
3614     vdev->bus_name = g_strdup(bus_name);
3615 }
3616 
3617 void G_GNUC_PRINTF(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
3618 {
3619     va_list ap;
3620 
3621     va_start(ap, fmt);
3622     error_vreport(fmt, ap);
3623     va_end(ap);
3624 
3625     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3626         vdev->status = vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET;
3627         virtio_notify_config(vdev);
3628     }
3629 
3630     vdev->broken = true;
3631 }
3632 
3633 static void virtio_memory_listener_commit(MemoryListener *listener)
3634 {
3635     VirtIODevice *vdev = container_of(listener, VirtIODevice, listener);
3636     int i;
3637 
3638     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3639         if (vdev->vq[i].vring.num == 0) {
3640             break;
3641         }
3642         virtio_init_region_cache(vdev, i);
3643     }
3644 }
3645 
3646 static void virtio_device_realize(DeviceState *dev, Error **errp)
3647 {
3648     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3649     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3650     Error *err = NULL;
3651 
3652     /* Devices should either use vmsd or the load/save methods */
3653     assert(!vdc->vmsd || !vdc->load);
3654 
3655     if (vdc->realize != NULL) {
3656         vdc->realize(dev, &err);
3657         if (err != NULL) {
3658             error_propagate(errp, err);
3659             return;
3660         }
3661     }
3662 
3663     virtio_bus_device_plugged(vdev, &err);
3664     if (err != NULL) {
3665         error_propagate(errp, err);
3666         vdc->unrealize(dev);
3667         return;
3668     }
3669 
3670     vdev->listener.commit = virtio_memory_listener_commit;
3671     vdev->listener.name = "virtio";
3672     memory_listener_register(&vdev->listener, vdev->dma_as);
3673 }
3674 
3675 static void virtio_device_unrealize(DeviceState *dev)
3676 {
3677     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3678     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3679 
3680     memory_listener_unregister(&vdev->listener);
3681     virtio_bus_device_unplugged(vdev);
3682 
3683     if (vdc->unrealize != NULL) {
3684         vdc->unrealize(dev);
3685     }
3686 
3687     g_free(vdev->bus_name);
3688     vdev->bus_name = NULL;
3689 }
3690 
3691 static void virtio_device_free_virtqueues(VirtIODevice *vdev)
3692 {
3693     int i;
3694     if (!vdev->vq) {
3695         return;
3696     }
3697 
3698     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3699         if (vdev->vq[i].vring.num == 0) {
3700             break;
3701         }
3702         virtio_virtqueue_reset_region_cache(&vdev->vq[i]);
3703     }
3704     g_free(vdev->vq);
3705 }
3706 
3707 static void virtio_device_instance_finalize(Object *obj)
3708 {
3709     VirtIODevice *vdev = VIRTIO_DEVICE(obj);
3710 
3711     virtio_device_free_virtqueues(vdev);
3712 
3713     g_free(vdev->config);
3714     g_free(vdev->vector_queues);
3715 }
3716 
3717 static Property virtio_properties[] = {
3718     DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
3719     DEFINE_PROP_BOOL("use-started", VirtIODevice, use_started, true),
3720     DEFINE_PROP_BOOL("use-disabled-flag", VirtIODevice, use_disabled_flag, true),
3721     DEFINE_PROP_BOOL("x-disable-legacy-check", VirtIODevice,
3722                      disable_legacy_check, false),
3723     DEFINE_PROP_END_OF_LIST(),
3724 };
3725 
3726 static int virtio_device_start_ioeventfd_impl(VirtIODevice *vdev)
3727 {
3728     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3729     int i, n, r, err;
3730 
3731     /*
3732      * Batch all the host notifiers in a single transaction to avoid
3733      * quadratic time complexity in address_space_update_ioeventfds().
3734      */
3735     memory_region_transaction_begin();
3736     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3737         VirtQueue *vq = &vdev->vq[n];
3738         if (!virtio_queue_get_num(vdev, n)) {
3739             continue;
3740         }
3741         r = virtio_bus_set_host_notifier(qbus, n, true);
3742         if (r < 0) {
3743             err = r;
3744             goto assign_error;
3745         }
3746         event_notifier_set_handler(&vq->host_notifier,
3747                                    virtio_queue_host_notifier_read);
3748     }
3749 
3750     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3751         /* Kick right away to begin processing requests already in vring */
3752         VirtQueue *vq = &vdev->vq[n];
3753         if (!vq->vring.num) {
3754             continue;
3755         }
3756         event_notifier_set(&vq->host_notifier);
3757     }
3758     memory_region_transaction_commit();
3759     return 0;
3760 
3761 assign_error:
3762     i = n; /* save n for a second iteration after transaction is committed. */
3763     while (--n >= 0) {
3764         VirtQueue *vq = &vdev->vq[n];
3765         if (!virtio_queue_get_num(vdev, n)) {
3766             continue;
3767         }
3768 
3769         event_notifier_set_handler(&vq->host_notifier, NULL);
3770         r = virtio_bus_set_host_notifier(qbus, n, false);
3771         assert(r >= 0);
3772     }
3773     /*
3774      * The transaction expects the ioeventfds to be open when it
3775      * commits. Do it now, before the cleanup loop.
3776      */
3777     memory_region_transaction_commit();
3778 
3779     while (--i >= 0) {
3780         if (!virtio_queue_get_num(vdev, i)) {
3781             continue;
3782         }
3783         virtio_bus_cleanup_host_notifier(qbus, i);
3784     }
3785     return err;
3786 }
3787 
3788 int virtio_device_start_ioeventfd(VirtIODevice *vdev)
3789 {
3790     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3791     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3792 
3793     return virtio_bus_start_ioeventfd(vbus);
3794 }
3795 
3796 static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
3797 {
3798     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3799     int n, r;
3800 
3801     /*
3802      * Batch all the host notifiers in a single transaction to avoid
3803      * quadratic time complexity in address_space_update_ioeventfds().
3804      */
3805     memory_region_transaction_begin();
3806     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3807         VirtQueue *vq = &vdev->vq[n];
3808 
3809         if (!virtio_queue_get_num(vdev, n)) {
3810             continue;
3811         }
3812         event_notifier_set_handler(&vq->host_notifier, NULL);
3813         r = virtio_bus_set_host_notifier(qbus, n, false);
3814         assert(r >= 0);
3815     }
3816     /*
3817      * The transaction expects the ioeventfds to be open when it
3818      * commits. Do it now, before the cleanup loop.
3819      */
3820     memory_region_transaction_commit();
3821 
3822     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3823         if (!virtio_queue_get_num(vdev, n)) {
3824             continue;
3825         }
3826         virtio_bus_cleanup_host_notifier(qbus, n);
3827     }
3828 }
3829 
3830 int virtio_device_grab_ioeventfd(VirtIODevice *vdev)
3831 {
3832     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3833     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3834 
3835     return virtio_bus_grab_ioeventfd(vbus);
3836 }
3837 
3838 void virtio_device_release_ioeventfd(VirtIODevice *vdev)
3839 {
3840     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3841     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3842 
3843     virtio_bus_release_ioeventfd(vbus);
3844 }
3845 
3846 static void virtio_device_class_init(ObjectClass *klass, void *data)
3847 {
3848     /* Set the default value here. */
3849     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
3850     DeviceClass *dc = DEVICE_CLASS(klass);
3851 
3852     dc->realize = virtio_device_realize;
3853     dc->unrealize = virtio_device_unrealize;
3854     dc->bus_type = TYPE_VIRTIO_BUS;
3855     device_class_set_props(dc, virtio_properties);
3856     vdc->start_ioeventfd = virtio_device_start_ioeventfd_impl;
3857     vdc->stop_ioeventfd = virtio_device_stop_ioeventfd_impl;
3858 
3859     vdc->legacy_features |= VIRTIO_LEGACY_FEATURES;
3860 }
3861 
3862 bool virtio_device_ioeventfd_enabled(VirtIODevice *vdev)
3863 {
3864     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3865     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3866 
3867     return virtio_bus_ioeventfd_enabled(vbus);
3868 }
3869 
3870 VirtQueueStatus *qmp_x_query_virtio_queue_status(const char *path,
3871                                                  uint16_t queue,
3872                                                  Error **errp)
3873 {
3874     VirtIODevice *vdev;
3875     VirtQueueStatus *status;
3876 
3877     vdev = qmp_find_virtio_device(path);
3878     if (vdev == NULL) {
3879         error_setg(errp, "Path %s is not a VirtIODevice", path);
3880         return NULL;
3881     }
3882 
3883     if (queue >= VIRTIO_QUEUE_MAX || !virtio_queue_get_num(vdev, queue)) {
3884         error_setg(errp, "Invalid virtqueue number %d", queue);
3885         return NULL;
3886     }
3887 
3888     status = g_new0(VirtQueueStatus, 1);
3889     status->name = g_strdup(vdev->name);
3890     status->queue_index = vdev->vq[queue].queue_index;
3891     status->inuse = vdev->vq[queue].inuse;
3892     status->vring_num = vdev->vq[queue].vring.num;
3893     status->vring_num_default = vdev->vq[queue].vring.num_default;
3894     status->vring_align = vdev->vq[queue].vring.align;
3895     status->vring_desc = vdev->vq[queue].vring.desc;
3896     status->vring_avail = vdev->vq[queue].vring.avail;
3897     status->vring_used = vdev->vq[queue].vring.used;
3898     status->used_idx = vdev->vq[queue].used_idx;
3899     status->signalled_used = vdev->vq[queue].signalled_used;
3900     status->signalled_used_valid = vdev->vq[queue].signalled_used_valid;
3901 
3902     if (vdev->vhost_started) {
3903         VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
3904         struct vhost_dev *hdev = vdc->get_vhost(vdev);
3905 
3906         /* check if vq index exists for vhost as well  */
3907         if (queue >= hdev->vq_index && queue < hdev->vq_index + hdev->nvqs) {
3908             status->has_last_avail_idx = true;
3909 
3910             int vhost_vq_index =
3911                 hdev->vhost_ops->vhost_get_vq_index(hdev, queue);
3912             struct vhost_vring_state state = {
3913                 .index = vhost_vq_index,
3914             };
3915 
3916             status->last_avail_idx =
3917                 hdev->vhost_ops->vhost_get_vring_base(hdev, &state);
3918         }
3919     } else {
3920         status->has_shadow_avail_idx = true;
3921         status->has_last_avail_idx = true;
3922         status->last_avail_idx = vdev->vq[queue].last_avail_idx;
3923         status->shadow_avail_idx = vdev->vq[queue].shadow_avail_idx;
3924     }
3925 
3926     return status;
3927 }
3928 
3929 static strList *qmp_decode_vring_desc_flags(uint16_t flags)
3930 {
3931     strList *list = NULL;
3932     strList *node;
3933     int i;
3934 
3935     struct {
3936         uint16_t flag;
3937         const char *value;
3938     } map[] = {
3939         { VRING_DESC_F_NEXT, "next" },
3940         { VRING_DESC_F_WRITE, "write" },
3941         { VRING_DESC_F_INDIRECT, "indirect" },
3942         { 1 << VRING_PACKED_DESC_F_AVAIL, "avail" },
3943         { 1 << VRING_PACKED_DESC_F_USED, "used" },
3944         { 0, "" }
3945     };
3946 
3947     for (i = 0; map[i].flag; i++) {
3948         if ((map[i].flag & flags) == 0) {
3949             continue;
3950         }
3951         node = g_malloc0(sizeof(strList));
3952         node->value = g_strdup(map[i].value);
3953         node->next = list;
3954         list = node;
3955     }
3956 
3957     return list;
3958 }
3959 
3960 VirtioQueueElement *qmp_x_query_virtio_queue_element(const char *path,
3961                                                      uint16_t queue,
3962                                                      bool has_index,
3963                                                      uint16_t index,
3964                                                      Error **errp)
3965 {
3966     VirtIODevice *vdev;
3967     VirtQueue *vq;
3968     VirtioQueueElement *element = NULL;
3969 
3970     vdev = qmp_find_virtio_device(path);
3971     if (vdev == NULL) {
3972         error_setg(errp, "Path %s is not a VirtIO device", path);
3973         return NULL;
3974     }
3975 
3976     if (queue >= VIRTIO_QUEUE_MAX || !virtio_queue_get_num(vdev, queue)) {
3977         error_setg(errp, "Invalid virtqueue number %d", queue);
3978         return NULL;
3979     }
3980     vq = &vdev->vq[queue];
3981 
3982     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3983         error_setg(errp, "Packed ring not supported");
3984         return NULL;
3985     } else {
3986         unsigned int head, i, max;
3987         VRingMemoryRegionCaches *caches;
3988         MemoryRegionCache indirect_desc_cache;
3989         MemoryRegionCache *desc_cache;
3990         VRingDesc desc;
3991         VirtioRingDescList *list = NULL;
3992         VirtioRingDescList *node;
3993         int rc; int ndescs;
3994 
3995         address_space_cache_init_empty(&indirect_desc_cache);
3996 
3997         RCU_READ_LOCK_GUARD();
3998 
3999         max = vq->vring.num;
4000 
4001         if (!has_index) {
4002             head = vring_avail_ring(vq, vq->last_avail_idx % vq->vring.num);
4003         } else {
4004             head = vring_avail_ring(vq, index % vq->vring.num);
4005         }
4006         i = head;
4007 
4008         caches = vring_get_region_caches(vq);
4009         if (!caches) {
4010             error_setg(errp, "Region caches not initialized");
4011             return NULL;
4012         }
4013         if (caches->desc.len < max * sizeof(VRingDesc)) {
4014             error_setg(errp, "Cannot map descriptor ring");
4015             return NULL;
4016         }
4017 
4018         desc_cache = &caches->desc;
4019         vring_split_desc_read(vdev, &desc, desc_cache, i);
4020         if (desc.flags & VRING_DESC_F_INDIRECT) {
4021             int64_t len;
4022             len = address_space_cache_init(&indirect_desc_cache, vdev->dma_as,
4023                                            desc.addr, desc.len, false);
4024             desc_cache = &indirect_desc_cache;
4025             if (len < desc.len) {
4026                 error_setg(errp, "Cannot map indirect buffer");
4027                 goto done;
4028             }
4029 
4030             max = desc.len / sizeof(VRingDesc);
4031             i = 0;
4032             vring_split_desc_read(vdev, &desc, desc_cache, i);
4033         }
4034 
4035         element = g_new0(VirtioQueueElement, 1);
4036         element->avail = g_new0(VirtioRingAvail, 1);
4037         element->used = g_new0(VirtioRingUsed, 1);
4038         element->name = g_strdup(vdev->name);
4039         element->index = head;
4040         element->avail->flags = vring_avail_flags(vq);
4041         element->avail->idx = vring_avail_idx(vq);
4042         element->avail->ring = head;
4043         element->used->flags = vring_used_flags(vq);
4044         element->used->idx = vring_used_idx(vq);
4045         ndescs = 0;
4046 
4047         do {
4048             /* A buggy driver may produce an infinite loop */
4049             if (ndescs >= max) {
4050                 break;
4051             }
4052             node = g_new0(VirtioRingDescList, 1);
4053             node->value = g_new0(VirtioRingDesc, 1);
4054             node->value->addr = desc.addr;
4055             node->value->len = desc.len;
4056             node->value->flags = qmp_decode_vring_desc_flags(desc.flags);
4057             node->next = list;
4058             list = node;
4059 
4060             ndescs++;
4061             rc = virtqueue_split_read_next_desc(vdev, &desc, desc_cache, max);
4062         } while (rc == VIRTQUEUE_READ_DESC_MORE);
4063         element->descs = list;
4064 done:
4065         address_space_cache_destroy(&indirect_desc_cache);
4066     }
4067 
4068     return element;
4069 }
4070 
4071 static const TypeInfo virtio_device_info = {
4072     .name = TYPE_VIRTIO_DEVICE,
4073     .parent = TYPE_DEVICE,
4074     .instance_size = sizeof(VirtIODevice),
4075     .class_init = virtio_device_class_init,
4076     .instance_finalize = virtio_device_instance_finalize,
4077     .abstract = true,
4078     .class_size = sizeof(VirtioDeviceClass),
4079 };
4080 
4081 static void virtio_register_types(void)
4082 {
4083     type_register_static(&virtio_device_info);
4084 }
4085 
4086 type_init(virtio_register_types)
4087