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