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