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