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