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