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