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