xref: /openbmc/qemu/hw/virtio/virtio.c (revision e615c157)
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 (unlikely(vq->vdev->broken)) {
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 (unlikely(vq->vdev->broken)) {
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 (unlikely(vq->vdev->broken)) {
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 (unlikely(vq->vdev->broken)) {
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 (unlikely(vq->vdev->broken)) {
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 (unlikely(vdev->broken)) {
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 (unlikely(vdev->broken)) {
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     atomic_set(&vdev->isr, 0);
1924     vdev->config_vector = VIRTIO_NO_VECTOR;
1925     virtio_notify_vector(vdev, vdev->config_vector);
1926 
1927     for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1928         vdev->vq[i].vring.desc = 0;
1929         vdev->vq[i].vring.avail = 0;
1930         vdev->vq[i].vring.used = 0;
1931         vdev->vq[i].last_avail_idx = 0;
1932         vdev->vq[i].shadow_avail_idx = 0;
1933         vdev->vq[i].used_idx = 0;
1934         vdev->vq[i].last_avail_wrap_counter = true;
1935         vdev->vq[i].shadow_avail_wrap_counter = true;
1936         vdev->vq[i].used_wrap_counter = true;
1937         virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
1938         vdev->vq[i].signalled_used = 0;
1939         vdev->vq[i].signalled_used_valid = false;
1940         vdev->vq[i].notification = true;
1941         vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
1942         vdev->vq[i].inuse = 0;
1943         virtio_virtqueue_reset_region_cache(&vdev->vq[i]);
1944     }
1945 }
1946 
1947 uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
1948 {
1949     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1950     uint8_t val;
1951 
1952     if (addr + sizeof(val) > vdev->config_len) {
1953         return (uint32_t)-1;
1954     }
1955 
1956     k->get_config(vdev, vdev->config);
1957 
1958     val = ldub_p(vdev->config + addr);
1959     return val;
1960 }
1961 
1962 uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
1963 {
1964     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1965     uint16_t val;
1966 
1967     if (addr + sizeof(val) > vdev->config_len) {
1968         return (uint32_t)-1;
1969     }
1970 
1971     k->get_config(vdev, vdev->config);
1972 
1973     val = lduw_p(vdev->config + addr);
1974     return val;
1975 }
1976 
1977 uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
1978 {
1979     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1980     uint32_t val;
1981 
1982     if (addr + sizeof(val) > vdev->config_len) {
1983         return (uint32_t)-1;
1984     }
1985 
1986     k->get_config(vdev, vdev->config);
1987 
1988     val = ldl_p(vdev->config + addr);
1989     return val;
1990 }
1991 
1992 void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
1993 {
1994     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1995     uint8_t val = data;
1996 
1997     if (addr + sizeof(val) > vdev->config_len) {
1998         return;
1999     }
2000 
2001     stb_p(vdev->config + addr, val);
2002 
2003     if (k->set_config) {
2004         k->set_config(vdev, vdev->config);
2005     }
2006 }
2007 
2008 void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
2009 {
2010     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2011     uint16_t val = data;
2012 
2013     if (addr + sizeof(val) > vdev->config_len) {
2014         return;
2015     }
2016 
2017     stw_p(vdev->config + addr, val);
2018 
2019     if (k->set_config) {
2020         k->set_config(vdev, vdev->config);
2021     }
2022 }
2023 
2024 void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
2025 {
2026     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2027     uint32_t val = data;
2028 
2029     if (addr + sizeof(val) > vdev->config_len) {
2030         return;
2031     }
2032 
2033     stl_p(vdev->config + addr, val);
2034 
2035     if (k->set_config) {
2036         k->set_config(vdev, vdev->config);
2037     }
2038 }
2039 
2040 uint32_t virtio_config_modern_readb(VirtIODevice *vdev, uint32_t addr)
2041 {
2042     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2043     uint8_t val;
2044 
2045     if (addr + sizeof(val) > vdev->config_len) {
2046         return (uint32_t)-1;
2047     }
2048 
2049     k->get_config(vdev, vdev->config);
2050 
2051     val = ldub_p(vdev->config + addr);
2052     return val;
2053 }
2054 
2055 uint32_t virtio_config_modern_readw(VirtIODevice *vdev, uint32_t addr)
2056 {
2057     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2058     uint16_t val;
2059 
2060     if (addr + sizeof(val) > vdev->config_len) {
2061         return (uint32_t)-1;
2062     }
2063 
2064     k->get_config(vdev, vdev->config);
2065 
2066     val = lduw_le_p(vdev->config + addr);
2067     return val;
2068 }
2069 
2070 uint32_t virtio_config_modern_readl(VirtIODevice *vdev, uint32_t addr)
2071 {
2072     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2073     uint32_t val;
2074 
2075     if (addr + sizeof(val) > vdev->config_len) {
2076         return (uint32_t)-1;
2077     }
2078 
2079     k->get_config(vdev, vdev->config);
2080 
2081     val = ldl_le_p(vdev->config + addr);
2082     return val;
2083 }
2084 
2085 void virtio_config_modern_writeb(VirtIODevice *vdev,
2086                                  uint32_t addr, uint32_t data)
2087 {
2088     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2089     uint8_t val = data;
2090 
2091     if (addr + sizeof(val) > vdev->config_len) {
2092         return;
2093     }
2094 
2095     stb_p(vdev->config + addr, val);
2096 
2097     if (k->set_config) {
2098         k->set_config(vdev, vdev->config);
2099     }
2100 }
2101 
2102 void virtio_config_modern_writew(VirtIODevice *vdev,
2103                                  uint32_t addr, uint32_t data)
2104 {
2105     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2106     uint16_t val = data;
2107 
2108     if (addr + sizeof(val) > vdev->config_len) {
2109         return;
2110     }
2111 
2112     stw_le_p(vdev->config + addr, val);
2113 
2114     if (k->set_config) {
2115         k->set_config(vdev, vdev->config);
2116     }
2117 }
2118 
2119 void virtio_config_modern_writel(VirtIODevice *vdev,
2120                                  uint32_t addr, uint32_t data)
2121 {
2122     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2123     uint32_t val = data;
2124 
2125     if (addr + sizeof(val) > vdev->config_len) {
2126         return;
2127     }
2128 
2129     stl_le_p(vdev->config + addr, val);
2130 
2131     if (k->set_config) {
2132         k->set_config(vdev, vdev->config);
2133     }
2134 }
2135 
2136 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
2137 {
2138     if (!vdev->vq[n].vring.num) {
2139         return;
2140     }
2141     vdev->vq[n].vring.desc = addr;
2142     virtio_queue_update_rings(vdev, n);
2143 }
2144 
2145 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
2146 {
2147     return vdev->vq[n].vring.desc;
2148 }
2149 
2150 void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
2151                             hwaddr avail, hwaddr used)
2152 {
2153     if (!vdev->vq[n].vring.num) {
2154         return;
2155     }
2156     vdev->vq[n].vring.desc = desc;
2157     vdev->vq[n].vring.avail = avail;
2158     vdev->vq[n].vring.used = used;
2159     virtio_init_region_cache(vdev, n);
2160 }
2161 
2162 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
2163 {
2164     /* Don't allow guest to flip queue between existent and
2165      * nonexistent states, or to set it to an invalid size.
2166      */
2167     if (!!num != !!vdev->vq[n].vring.num ||
2168         num > VIRTQUEUE_MAX_SIZE ||
2169         num < 0) {
2170         return;
2171     }
2172     vdev->vq[n].vring.num = num;
2173 }
2174 
2175 VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
2176 {
2177     return QLIST_FIRST(&vdev->vector_queues[vector]);
2178 }
2179 
2180 VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
2181 {
2182     return QLIST_NEXT(vq, node);
2183 }
2184 
2185 int virtio_queue_get_num(VirtIODevice *vdev, int n)
2186 {
2187     return vdev->vq[n].vring.num;
2188 }
2189 
2190 int virtio_queue_get_max_num(VirtIODevice *vdev, int n)
2191 {
2192     return vdev->vq[n].vring.num_default;
2193 }
2194 
2195 int virtio_get_num_queues(VirtIODevice *vdev)
2196 {
2197     int i;
2198 
2199     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2200         if (!virtio_queue_get_num(vdev, i)) {
2201             break;
2202         }
2203     }
2204 
2205     return i;
2206 }
2207 
2208 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
2209 {
2210     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2211     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2212 
2213     /* virtio-1 compliant devices cannot change the alignment */
2214     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2215         error_report("tried to modify queue alignment for virtio-1 device");
2216         return;
2217     }
2218     /* Check that the transport told us it was going to do this
2219      * (so a buggy transport will immediately assert rather than
2220      * silently failing to migrate this state)
2221      */
2222     assert(k->has_variable_vring_alignment);
2223 
2224     if (align) {
2225         vdev->vq[n].vring.align = align;
2226         virtio_queue_update_rings(vdev, n);
2227     }
2228 }
2229 
2230 static bool virtio_queue_notify_aio_vq(VirtQueue *vq)
2231 {
2232     bool ret = false;
2233 
2234     if (vq->vring.desc && vq->handle_aio_output) {
2235         VirtIODevice *vdev = vq->vdev;
2236 
2237         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2238         ret = vq->handle_aio_output(vdev, vq);
2239 
2240         if (unlikely(vdev->start_on_kick)) {
2241             virtio_set_started(vdev, true);
2242         }
2243     }
2244 
2245     return ret;
2246 }
2247 
2248 static void virtio_queue_notify_vq(VirtQueue *vq)
2249 {
2250     if (vq->vring.desc && vq->handle_output) {
2251         VirtIODevice *vdev = vq->vdev;
2252 
2253         if (unlikely(vdev->broken)) {
2254             return;
2255         }
2256 
2257         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2258         vq->handle_output(vdev, vq);
2259 
2260         if (unlikely(vdev->start_on_kick)) {
2261             virtio_set_started(vdev, true);
2262         }
2263     }
2264 }
2265 
2266 void virtio_queue_notify(VirtIODevice *vdev, int n)
2267 {
2268     VirtQueue *vq = &vdev->vq[n];
2269 
2270     if (unlikely(!vq->vring.desc || vdev->broken)) {
2271         return;
2272     }
2273 
2274     trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
2275     if (vq->host_notifier_enabled) {
2276         event_notifier_set(&vq->host_notifier);
2277     } else if (vq->handle_output) {
2278         vq->handle_output(vdev, vq);
2279 
2280         if (unlikely(vdev->start_on_kick)) {
2281             virtio_set_started(vdev, true);
2282         }
2283     }
2284 }
2285 
2286 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
2287 {
2288     return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
2289         VIRTIO_NO_VECTOR;
2290 }
2291 
2292 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
2293 {
2294     VirtQueue *vq = &vdev->vq[n];
2295 
2296     if (n < VIRTIO_QUEUE_MAX) {
2297         if (vdev->vector_queues &&
2298             vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
2299             QLIST_REMOVE(vq, node);
2300         }
2301         vdev->vq[n].vector = vector;
2302         if (vdev->vector_queues &&
2303             vector != VIRTIO_NO_VECTOR) {
2304             QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
2305         }
2306     }
2307 }
2308 
2309 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
2310                             VirtIOHandleOutput handle_output)
2311 {
2312     int i;
2313 
2314     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2315         if (vdev->vq[i].vring.num == 0)
2316             break;
2317     }
2318 
2319     if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
2320         abort();
2321 
2322     vdev->vq[i].vring.num = queue_size;
2323     vdev->vq[i].vring.num_default = queue_size;
2324     vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
2325     vdev->vq[i].handle_output = handle_output;
2326     vdev->vq[i].handle_aio_output = NULL;
2327     vdev->vq[i].used_elems = g_malloc0(sizeof(VirtQueueElement) *
2328                                        queue_size);
2329 
2330     return &vdev->vq[i];
2331 }
2332 
2333 void virtio_delete_queue(VirtQueue *vq)
2334 {
2335     vq->vring.num = 0;
2336     vq->vring.num_default = 0;
2337     vq->handle_output = NULL;
2338     vq->handle_aio_output = NULL;
2339     g_free(vq->used_elems);
2340     vq->used_elems = NULL;
2341 }
2342 
2343 void virtio_del_queue(VirtIODevice *vdev, int n)
2344 {
2345     if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
2346         abort();
2347     }
2348 
2349     virtio_delete_queue(&vdev->vq[n]);
2350 }
2351 
2352 static void virtio_set_isr(VirtIODevice *vdev, int value)
2353 {
2354     uint8_t old = atomic_read(&vdev->isr);
2355 
2356     /* Do not write ISR if it does not change, so that its cacheline remains
2357      * shared in the common case where the guest does not read it.
2358      */
2359     if ((old & value) != value) {
2360         atomic_or(&vdev->isr, value);
2361     }
2362 }
2363 
2364 static bool virtio_split_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2365 {
2366     uint16_t old, new;
2367     bool v;
2368     /* We need to expose used array entries before checking used event. */
2369     smp_mb();
2370     /* Always notify when queue is empty (when feature acknowledge) */
2371     if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2372         !vq->inuse && virtio_queue_empty(vq)) {
2373         return true;
2374     }
2375 
2376     if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2377         return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
2378     }
2379 
2380     v = vq->signalled_used_valid;
2381     vq->signalled_used_valid = true;
2382     old = vq->signalled_used;
2383     new = vq->signalled_used = vq->used_idx;
2384     return !v || vring_need_event(vring_get_used_event(vq), new, old);
2385 }
2386 
2387 static bool vring_packed_need_event(VirtQueue *vq, bool wrap,
2388                                     uint16_t off_wrap, uint16_t new,
2389                                     uint16_t old)
2390 {
2391     int off = off_wrap & ~(1 << 15);
2392 
2393     if (wrap != off_wrap >> 15) {
2394         off -= vq->vring.num;
2395     }
2396 
2397     return vring_need_event(off, new, old);
2398 }
2399 
2400 static bool virtio_packed_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2401 {
2402     VRingPackedDescEvent e;
2403     uint16_t old, new;
2404     bool v;
2405     VRingMemoryRegionCaches *caches;
2406 
2407     caches = vring_get_region_caches(vq);
2408     vring_packed_event_read(vdev, &caches->avail, &e);
2409 
2410     old = vq->signalled_used;
2411     new = vq->signalled_used = vq->used_idx;
2412     v = vq->signalled_used_valid;
2413     vq->signalled_used_valid = true;
2414 
2415     if (e.flags == VRING_PACKED_EVENT_FLAG_DISABLE) {
2416         return false;
2417     } else if (e.flags == VRING_PACKED_EVENT_FLAG_ENABLE) {
2418         return true;
2419     }
2420 
2421     return !v || vring_packed_need_event(vq, vq->used_wrap_counter,
2422                                          e.off_wrap, new, old);
2423 }
2424 
2425 /* Called within rcu_read_lock().  */
2426 static bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
2427 {
2428     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
2429         return virtio_packed_should_notify(vdev, vq);
2430     } else {
2431         return virtio_split_should_notify(vdev, vq);
2432     }
2433 }
2434 
2435 void virtio_notify_irqfd(VirtIODevice *vdev, VirtQueue *vq)
2436 {
2437     WITH_RCU_READ_LOCK_GUARD() {
2438         if (!virtio_should_notify(vdev, vq)) {
2439             return;
2440         }
2441     }
2442 
2443     trace_virtio_notify_irqfd(vdev, vq);
2444 
2445     /*
2446      * virtio spec 1.0 says ISR bit 0 should be ignored with MSI, but
2447      * windows drivers included in virtio-win 1.8.0 (circa 2015) are
2448      * incorrectly polling this bit during crashdump and hibernation
2449      * in MSI mode, causing a hang if this bit is never updated.
2450      * Recent releases of Windows do not really shut down, but rather
2451      * log out and hibernate to make the next startup faster.  Hence,
2452      * this manifested as a more serious hang during shutdown with
2453      *
2454      * Next driver release from 2016 fixed this problem, so working around it
2455      * is not a must, but it's easy to do so let's do it here.
2456      *
2457      * Note: it's safe to update ISR from any thread as it was switched
2458      * to an atomic operation.
2459      */
2460     virtio_set_isr(vq->vdev, 0x1);
2461     event_notifier_set(&vq->guest_notifier);
2462 }
2463 
2464 static void virtio_irq(VirtQueue *vq)
2465 {
2466     virtio_set_isr(vq->vdev, 0x1);
2467     virtio_notify_vector(vq->vdev, vq->vector);
2468 }
2469 
2470 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
2471 {
2472     WITH_RCU_READ_LOCK_GUARD() {
2473         if (!virtio_should_notify(vdev, vq)) {
2474             return;
2475         }
2476     }
2477 
2478     trace_virtio_notify(vdev, vq);
2479     virtio_irq(vq);
2480 }
2481 
2482 void virtio_notify_config(VirtIODevice *vdev)
2483 {
2484     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
2485         return;
2486 
2487     virtio_set_isr(vdev, 0x3);
2488     vdev->generation++;
2489     virtio_notify_vector(vdev, vdev->config_vector);
2490 }
2491 
2492 static bool virtio_device_endian_needed(void *opaque)
2493 {
2494     VirtIODevice *vdev = opaque;
2495 
2496     assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
2497     if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2498         return vdev->device_endian != virtio_default_endian();
2499     }
2500     /* Devices conforming to VIRTIO 1.0 or later are always LE. */
2501     return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
2502 }
2503 
2504 static bool virtio_64bit_features_needed(void *opaque)
2505 {
2506     VirtIODevice *vdev = opaque;
2507 
2508     return (vdev->host_features >> 32) != 0;
2509 }
2510 
2511 static bool virtio_virtqueue_needed(void *opaque)
2512 {
2513     VirtIODevice *vdev = opaque;
2514 
2515     return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
2516 }
2517 
2518 static bool virtio_packed_virtqueue_needed(void *opaque)
2519 {
2520     VirtIODevice *vdev = opaque;
2521 
2522     return virtio_host_has_feature(vdev, VIRTIO_F_RING_PACKED);
2523 }
2524 
2525 static bool virtio_ringsize_needed(void *opaque)
2526 {
2527     VirtIODevice *vdev = opaque;
2528     int i;
2529 
2530     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2531         if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
2532             return true;
2533         }
2534     }
2535     return false;
2536 }
2537 
2538 static bool virtio_extra_state_needed(void *opaque)
2539 {
2540     VirtIODevice *vdev = opaque;
2541     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2542     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2543 
2544     return k->has_extra_state &&
2545         k->has_extra_state(qbus->parent);
2546 }
2547 
2548 static bool virtio_broken_needed(void *opaque)
2549 {
2550     VirtIODevice *vdev = opaque;
2551 
2552     return vdev->broken;
2553 }
2554 
2555 static bool virtio_started_needed(void *opaque)
2556 {
2557     VirtIODevice *vdev = opaque;
2558 
2559     return vdev->started;
2560 }
2561 
2562 static const VMStateDescription vmstate_virtqueue = {
2563     .name = "virtqueue_state",
2564     .version_id = 1,
2565     .minimum_version_id = 1,
2566     .fields = (VMStateField[]) {
2567         VMSTATE_UINT64(vring.avail, struct VirtQueue),
2568         VMSTATE_UINT64(vring.used, struct VirtQueue),
2569         VMSTATE_END_OF_LIST()
2570     }
2571 };
2572 
2573 static const VMStateDescription vmstate_packed_virtqueue = {
2574     .name = "packed_virtqueue_state",
2575     .version_id = 1,
2576     .minimum_version_id = 1,
2577     .fields = (VMStateField[]) {
2578         VMSTATE_UINT16(last_avail_idx, struct VirtQueue),
2579         VMSTATE_BOOL(last_avail_wrap_counter, struct VirtQueue),
2580         VMSTATE_UINT16(used_idx, struct VirtQueue),
2581         VMSTATE_BOOL(used_wrap_counter, struct VirtQueue),
2582         VMSTATE_UINT32(inuse, struct VirtQueue),
2583         VMSTATE_END_OF_LIST()
2584     }
2585 };
2586 
2587 static const VMStateDescription vmstate_virtio_virtqueues = {
2588     .name = "virtio/virtqueues",
2589     .version_id = 1,
2590     .minimum_version_id = 1,
2591     .needed = &virtio_virtqueue_needed,
2592     .fields = (VMStateField[]) {
2593         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2594                       VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
2595         VMSTATE_END_OF_LIST()
2596     }
2597 };
2598 
2599 static const VMStateDescription vmstate_virtio_packed_virtqueues = {
2600     .name = "virtio/packed_virtqueues",
2601     .version_id = 1,
2602     .minimum_version_id = 1,
2603     .needed = &virtio_packed_virtqueue_needed,
2604     .fields = (VMStateField[]) {
2605         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2606                       VIRTIO_QUEUE_MAX, 0, vmstate_packed_virtqueue, VirtQueue),
2607         VMSTATE_END_OF_LIST()
2608     }
2609 };
2610 
2611 static const VMStateDescription vmstate_ringsize = {
2612     .name = "ringsize_state",
2613     .version_id = 1,
2614     .minimum_version_id = 1,
2615     .fields = (VMStateField[]) {
2616         VMSTATE_UINT32(vring.num_default, struct VirtQueue),
2617         VMSTATE_END_OF_LIST()
2618     }
2619 };
2620 
2621 static const VMStateDescription vmstate_virtio_ringsize = {
2622     .name = "virtio/ringsize",
2623     .version_id = 1,
2624     .minimum_version_id = 1,
2625     .needed = &virtio_ringsize_needed,
2626     .fields = (VMStateField[]) {
2627         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
2628                       VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
2629         VMSTATE_END_OF_LIST()
2630     }
2631 };
2632 
2633 static int get_extra_state(QEMUFile *f, void *pv, size_t size,
2634                            const VMStateField *field)
2635 {
2636     VirtIODevice *vdev = pv;
2637     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2638     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2639 
2640     if (!k->load_extra_state) {
2641         return -1;
2642     } else {
2643         return k->load_extra_state(qbus->parent, f);
2644     }
2645 }
2646 
2647 static int put_extra_state(QEMUFile *f, void *pv, size_t size,
2648                            const VMStateField *field, QJSON *vmdesc)
2649 {
2650     VirtIODevice *vdev = pv;
2651     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2652     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2653 
2654     k->save_extra_state(qbus->parent, f);
2655     return 0;
2656 }
2657 
2658 static const VMStateInfo vmstate_info_extra_state = {
2659     .name = "virtqueue_extra_state",
2660     .get = get_extra_state,
2661     .put = put_extra_state,
2662 };
2663 
2664 static const VMStateDescription vmstate_virtio_extra_state = {
2665     .name = "virtio/extra_state",
2666     .version_id = 1,
2667     .minimum_version_id = 1,
2668     .needed = &virtio_extra_state_needed,
2669     .fields = (VMStateField[]) {
2670         {
2671             .name         = "extra_state",
2672             .version_id   = 0,
2673             .field_exists = NULL,
2674             .size         = 0,
2675             .info         = &vmstate_info_extra_state,
2676             .flags        = VMS_SINGLE,
2677             .offset       = 0,
2678         },
2679         VMSTATE_END_OF_LIST()
2680     }
2681 };
2682 
2683 static const VMStateDescription vmstate_virtio_device_endian = {
2684     .name = "virtio/device_endian",
2685     .version_id = 1,
2686     .minimum_version_id = 1,
2687     .needed = &virtio_device_endian_needed,
2688     .fields = (VMStateField[]) {
2689         VMSTATE_UINT8(device_endian, VirtIODevice),
2690         VMSTATE_END_OF_LIST()
2691     }
2692 };
2693 
2694 static const VMStateDescription vmstate_virtio_64bit_features = {
2695     .name = "virtio/64bit_features",
2696     .version_id = 1,
2697     .minimum_version_id = 1,
2698     .needed = &virtio_64bit_features_needed,
2699     .fields = (VMStateField[]) {
2700         VMSTATE_UINT64(guest_features, VirtIODevice),
2701         VMSTATE_END_OF_LIST()
2702     }
2703 };
2704 
2705 static const VMStateDescription vmstate_virtio_broken = {
2706     .name = "virtio/broken",
2707     .version_id = 1,
2708     .minimum_version_id = 1,
2709     .needed = &virtio_broken_needed,
2710     .fields = (VMStateField[]) {
2711         VMSTATE_BOOL(broken, VirtIODevice),
2712         VMSTATE_END_OF_LIST()
2713     }
2714 };
2715 
2716 static const VMStateDescription vmstate_virtio_started = {
2717     .name = "virtio/started",
2718     .version_id = 1,
2719     .minimum_version_id = 1,
2720     .needed = &virtio_started_needed,
2721     .fields = (VMStateField[]) {
2722         VMSTATE_BOOL(started, VirtIODevice),
2723         VMSTATE_END_OF_LIST()
2724     }
2725 };
2726 
2727 static const VMStateDescription vmstate_virtio = {
2728     .name = "virtio",
2729     .version_id = 1,
2730     .minimum_version_id = 1,
2731     .minimum_version_id_old = 1,
2732     .fields = (VMStateField[]) {
2733         VMSTATE_END_OF_LIST()
2734     },
2735     .subsections = (const VMStateDescription*[]) {
2736         &vmstate_virtio_device_endian,
2737         &vmstate_virtio_64bit_features,
2738         &vmstate_virtio_virtqueues,
2739         &vmstate_virtio_ringsize,
2740         &vmstate_virtio_broken,
2741         &vmstate_virtio_extra_state,
2742         &vmstate_virtio_started,
2743         &vmstate_virtio_packed_virtqueues,
2744         NULL
2745     }
2746 };
2747 
2748 int virtio_save(VirtIODevice *vdev, QEMUFile *f)
2749 {
2750     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2751     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2752     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2753     uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
2754     int i;
2755 
2756     if (k->save_config) {
2757         k->save_config(qbus->parent, f);
2758     }
2759 
2760     qemu_put_8s(f, &vdev->status);
2761     qemu_put_8s(f, &vdev->isr);
2762     qemu_put_be16s(f, &vdev->queue_sel);
2763     qemu_put_be32s(f, &guest_features_lo);
2764     qemu_put_be32(f, vdev->config_len);
2765     qemu_put_buffer(f, vdev->config, vdev->config_len);
2766 
2767     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2768         if (vdev->vq[i].vring.num == 0)
2769             break;
2770     }
2771 
2772     qemu_put_be32(f, i);
2773 
2774     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2775         if (vdev->vq[i].vring.num == 0)
2776             break;
2777 
2778         qemu_put_be32(f, vdev->vq[i].vring.num);
2779         if (k->has_variable_vring_alignment) {
2780             qemu_put_be32(f, vdev->vq[i].vring.align);
2781         }
2782         /*
2783          * Save desc now, the rest of the ring addresses are saved in
2784          * subsections for VIRTIO-1 devices.
2785          */
2786         qemu_put_be64(f, vdev->vq[i].vring.desc);
2787         qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
2788         if (k->save_queue) {
2789             k->save_queue(qbus->parent, i, f);
2790         }
2791     }
2792 
2793     if (vdc->save != NULL) {
2794         vdc->save(vdev, f);
2795     }
2796 
2797     if (vdc->vmsd) {
2798         int ret = vmstate_save_state(f, vdc->vmsd, vdev, NULL);
2799         if (ret) {
2800             return ret;
2801         }
2802     }
2803 
2804     /* Subsections */
2805     return vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
2806 }
2807 
2808 /* A wrapper for use as a VMState .put function */
2809 static int virtio_device_put(QEMUFile *f, void *opaque, size_t size,
2810                               const VMStateField *field, QJSON *vmdesc)
2811 {
2812     return virtio_save(VIRTIO_DEVICE(opaque), f);
2813 }
2814 
2815 /* A wrapper for use as a VMState .get function */
2816 static int virtio_device_get(QEMUFile *f, void *opaque, size_t size,
2817                              const VMStateField *field)
2818 {
2819     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
2820     DeviceClass *dc = DEVICE_CLASS(VIRTIO_DEVICE_GET_CLASS(vdev));
2821 
2822     return virtio_load(vdev, f, dc->vmsd->version_id);
2823 }
2824 
2825 const VMStateInfo  virtio_vmstate_info = {
2826     .name = "virtio",
2827     .get = virtio_device_get,
2828     .put = virtio_device_put,
2829 };
2830 
2831 static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
2832 {
2833     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
2834     bool bad = (val & ~(vdev->host_features)) != 0;
2835 
2836     val &= vdev->host_features;
2837     if (k->set_features) {
2838         k->set_features(vdev, val);
2839     }
2840     vdev->guest_features = val;
2841     return bad ? -1 : 0;
2842 }
2843 
2844 int virtio_set_features(VirtIODevice *vdev, uint64_t val)
2845 {
2846     int ret;
2847     /*
2848      * The driver must not attempt to set features after feature negotiation
2849      * has finished.
2850      */
2851     if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
2852         return -EINVAL;
2853     }
2854     ret = virtio_set_features_nocheck(vdev, val);
2855     if (!ret) {
2856         if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
2857             /* VIRTIO_RING_F_EVENT_IDX changes the size of the caches.  */
2858             int i;
2859             for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2860                 if (vdev->vq[i].vring.num != 0) {
2861                     virtio_init_region_cache(vdev, i);
2862                 }
2863             }
2864         }
2865 
2866         if (!virtio_device_started(vdev, vdev->status) &&
2867             !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2868             vdev->start_on_kick = true;
2869         }
2870     }
2871     return ret;
2872 }
2873 
2874 size_t virtio_feature_get_config_size(VirtIOFeature *feature_sizes,
2875                                       uint64_t host_features)
2876 {
2877     size_t config_size = 0;
2878     int i;
2879 
2880     for (i = 0; feature_sizes[i].flags != 0; i++) {
2881         if (host_features & feature_sizes[i].flags) {
2882             config_size = MAX(feature_sizes[i].end, config_size);
2883         }
2884     }
2885 
2886     return config_size;
2887 }
2888 
2889 int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
2890 {
2891     int i, ret;
2892     int32_t config_len;
2893     uint32_t num;
2894     uint32_t features;
2895     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
2896     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
2897     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
2898 
2899     /*
2900      * We poison the endianness to ensure it does not get used before
2901      * subsections have been loaded.
2902      */
2903     vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
2904 
2905     if (k->load_config) {
2906         ret = k->load_config(qbus->parent, f);
2907         if (ret)
2908             return ret;
2909     }
2910 
2911     qemu_get_8s(f, &vdev->status);
2912     qemu_get_8s(f, &vdev->isr);
2913     qemu_get_be16s(f, &vdev->queue_sel);
2914     if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
2915         return -1;
2916     }
2917     qemu_get_be32s(f, &features);
2918 
2919     /*
2920      * Temporarily set guest_features low bits - needed by
2921      * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
2922      * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
2923      *
2924      * Note: devices should always test host features in future - don't create
2925      * new dependencies like this.
2926      */
2927     vdev->guest_features = features;
2928 
2929     config_len = qemu_get_be32(f);
2930 
2931     /*
2932      * There are cases where the incoming config can be bigger or smaller
2933      * than what we have; so load what we have space for, and skip
2934      * any excess that's in the stream.
2935      */
2936     qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
2937 
2938     while (config_len > vdev->config_len) {
2939         qemu_get_byte(f);
2940         config_len--;
2941     }
2942 
2943     num = qemu_get_be32(f);
2944 
2945     if (num > VIRTIO_QUEUE_MAX) {
2946         error_report("Invalid number of virtqueues: 0x%x", num);
2947         return -1;
2948     }
2949 
2950     for (i = 0; i < num; i++) {
2951         vdev->vq[i].vring.num = qemu_get_be32(f);
2952         if (k->has_variable_vring_alignment) {
2953             vdev->vq[i].vring.align = qemu_get_be32(f);
2954         }
2955         vdev->vq[i].vring.desc = qemu_get_be64(f);
2956         qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
2957         vdev->vq[i].signalled_used_valid = false;
2958         vdev->vq[i].notification = true;
2959 
2960         if (!vdev->vq[i].vring.desc && vdev->vq[i].last_avail_idx) {
2961             error_report("VQ %d address 0x0 "
2962                          "inconsistent with Host index 0x%x",
2963                          i, vdev->vq[i].last_avail_idx);
2964             return -1;
2965         }
2966         if (k->load_queue) {
2967             ret = k->load_queue(qbus->parent, i, f);
2968             if (ret)
2969                 return ret;
2970         }
2971     }
2972 
2973     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
2974 
2975     if (vdc->load != NULL) {
2976         ret = vdc->load(vdev, f, version_id);
2977         if (ret) {
2978             return ret;
2979         }
2980     }
2981 
2982     if (vdc->vmsd) {
2983         ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id);
2984         if (ret) {
2985             return ret;
2986         }
2987     }
2988 
2989     /* Subsections */
2990     ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
2991     if (ret) {
2992         return ret;
2993     }
2994 
2995     if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
2996         vdev->device_endian = virtio_default_endian();
2997     }
2998 
2999     if (virtio_64bit_features_needed(vdev)) {
3000         /*
3001          * Subsection load filled vdev->guest_features.  Run them
3002          * through virtio_set_features to sanity-check them against
3003          * host_features.
3004          */
3005         uint64_t features64 = vdev->guest_features;
3006         if (virtio_set_features_nocheck(vdev, features64) < 0) {
3007             error_report("Features 0x%" PRIx64 " unsupported. "
3008                          "Allowed features: 0x%" PRIx64,
3009                          features64, vdev->host_features);
3010             return -1;
3011         }
3012     } else {
3013         if (virtio_set_features_nocheck(vdev, features) < 0) {
3014             error_report("Features 0x%x unsupported. "
3015                          "Allowed features: 0x%" PRIx64,
3016                          features, vdev->host_features);
3017             return -1;
3018         }
3019     }
3020 
3021     if (!virtio_device_started(vdev, vdev->status) &&
3022         !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3023         vdev->start_on_kick = true;
3024     }
3025 
3026     RCU_READ_LOCK_GUARD();
3027     for (i = 0; i < num; i++) {
3028         if (vdev->vq[i].vring.desc) {
3029             uint16_t nheads;
3030 
3031             /*
3032              * VIRTIO-1 devices migrate desc, used, and avail ring addresses so
3033              * only the region cache needs to be set up.  Legacy devices need
3034              * to calculate used and avail ring addresses based on the desc
3035              * address.
3036              */
3037             if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3038                 virtio_init_region_cache(vdev, i);
3039             } else {
3040                 virtio_queue_update_rings(vdev, i);
3041             }
3042 
3043             if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3044                 vdev->vq[i].shadow_avail_idx = vdev->vq[i].last_avail_idx;
3045                 vdev->vq[i].shadow_avail_wrap_counter =
3046                                         vdev->vq[i].last_avail_wrap_counter;
3047                 continue;
3048             }
3049 
3050             nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
3051             /* Check it isn't doing strange things with descriptor numbers. */
3052             if (nheads > vdev->vq[i].vring.num) {
3053                 error_report("VQ %d size 0x%x Guest index 0x%x "
3054                              "inconsistent with Host index 0x%x: delta 0x%x",
3055                              i, vdev->vq[i].vring.num,
3056                              vring_avail_idx(&vdev->vq[i]),
3057                              vdev->vq[i].last_avail_idx, nheads);
3058                 return -1;
3059             }
3060             vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
3061             vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
3062 
3063             /*
3064              * Some devices migrate VirtQueueElements that have been popped
3065              * from the avail ring but not yet returned to the used ring.
3066              * Since max ring size < UINT16_MAX it's safe to use modulo
3067              * UINT16_MAX + 1 subtraction.
3068              */
3069             vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx -
3070                                 vdev->vq[i].used_idx);
3071             if (vdev->vq[i].inuse > vdev->vq[i].vring.num) {
3072                 error_report("VQ %d size 0x%x < last_avail_idx 0x%x - "
3073                              "used_idx 0x%x",
3074                              i, vdev->vq[i].vring.num,
3075                              vdev->vq[i].last_avail_idx,
3076                              vdev->vq[i].used_idx);
3077                 return -1;
3078             }
3079         }
3080     }
3081 
3082     if (vdc->post_load) {
3083         ret = vdc->post_load(vdev);
3084         if (ret) {
3085             return ret;
3086         }
3087     }
3088 
3089     return 0;
3090 }
3091 
3092 void virtio_cleanup(VirtIODevice *vdev)
3093 {
3094     qemu_del_vm_change_state_handler(vdev->vmstate);
3095 }
3096 
3097 static void virtio_vmstate_change(void *opaque, int running, RunState state)
3098 {
3099     VirtIODevice *vdev = opaque;
3100     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3101     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3102     bool backend_run = running && virtio_device_started(vdev, vdev->status);
3103     vdev->vm_running = running;
3104 
3105     if (backend_run) {
3106         virtio_set_status(vdev, vdev->status);
3107     }
3108 
3109     if (k->vmstate_change) {
3110         k->vmstate_change(qbus->parent, backend_run);
3111     }
3112 
3113     if (!backend_run) {
3114         virtio_set_status(vdev, vdev->status);
3115     }
3116 }
3117 
3118 void virtio_instance_init_common(Object *proxy_obj, void *data,
3119                                  size_t vdev_size, const char *vdev_name)
3120 {
3121     DeviceState *vdev = data;
3122 
3123     object_initialize_child(proxy_obj, "virtio-backend", vdev, vdev_size,
3124                             vdev_name, &error_abort, NULL);
3125     qdev_alias_all_properties(vdev, proxy_obj);
3126 }
3127 
3128 void virtio_init(VirtIODevice *vdev, const char *name,
3129                  uint16_t device_id, size_t config_size)
3130 {
3131     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3132     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3133     int i;
3134     int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
3135 
3136     if (nvectors) {
3137         vdev->vector_queues =
3138             g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
3139     }
3140 
3141     vdev->start_on_kick = false;
3142     vdev->started = false;
3143     vdev->device_id = device_id;
3144     vdev->status = 0;
3145     atomic_set(&vdev->isr, 0);
3146     vdev->queue_sel = 0;
3147     vdev->config_vector = VIRTIO_NO_VECTOR;
3148     vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);
3149     vdev->vm_running = runstate_is_running();
3150     vdev->broken = false;
3151     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3152         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
3153         vdev->vq[i].vdev = vdev;
3154         vdev->vq[i].queue_index = i;
3155         vdev->vq[i].host_notifier_enabled = false;
3156     }
3157 
3158     vdev->name = name;
3159     vdev->config_len = config_size;
3160     if (vdev->config_len) {
3161         vdev->config = g_malloc0(config_size);
3162     } else {
3163         vdev->config = NULL;
3164     }
3165     vdev->vmstate = qdev_add_vm_change_state_handler(DEVICE(vdev),
3166             virtio_vmstate_change, vdev);
3167     vdev->device_endian = virtio_default_endian();
3168     vdev->use_guest_notifier_mask = true;
3169 }
3170 
3171 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
3172 {
3173     return vdev->vq[n].vring.desc;
3174 }
3175 
3176 bool virtio_queue_enabled(VirtIODevice *vdev, int n)
3177 {
3178     return virtio_queue_get_desc_addr(vdev, n) != 0;
3179 }
3180 
3181 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
3182 {
3183     return vdev->vq[n].vring.avail;
3184 }
3185 
3186 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
3187 {
3188     return vdev->vq[n].vring.used;
3189 }
3190 
3191 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
3192 {
3193     return sizeof(VRingDesc) * vdev->vq[n].vring.num;
3194 }
3195 
3196 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
3197 {
3198     int s;
3199 
3200     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3201         return sizeof(struct VRingPackedDescEvent);
3202     }
3203 
3204     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3205     return offsetof(VRingAvail, ring) +
3206         sizeof(uint16_t) * vdev->vq[n].vring.num + s;
3207 }
3208 
3209 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
3210 {
3211     int s;
3212 
3213     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3214         return sizeof(struct VRingPackedDescEvent);
3215     }
3216 
3217     s = virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
3218     return offsetof(VRingUsed, ring) +
3219         sizeof(VRingUsedElem) * vdev->vq[n].vring.num + s;
3220 }
3221 
3222 static unsigned int virtio_queue_packed_get_last_avail_idx(VirtIODevice *vdev,
3223                                                            int n)
3224 {
3225     unsigned int avail, used;
3226 
3227     avail = vdev->vq[n].last_avail_idx;
3228     avail |= ((uint16_t)vdev->vq[n].last_avail_wrap_counter) << 15;
3229 
3230     used = vdev->vq[n].used_idx;
3231     used |= ((uint16_t)vdev->vq[n].used_wrap_counter) << 15;
3232 
3233     return avail | used << 16;
3234 }
3235 
3236 static uint16_t virtio_queue_split_get_last_avail_idx(VirtIODevice *vdev,
3237                                                       int n)
3238 {
3239     return vdev->vq[n].last_avail_idx;
3240 }
3241 
3242 unsigned int virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
3243 {
3244     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3245         return virtio_queue_packed_get_last_avail_idx(vdev, n);
3246     } else {
3247         return virtio_queue_split_get_last_avail_idx(vdev, n);
3248     }
3249 }
3250 
3251 static void virtio_queue_packed_set_last_avail_idx(VirtIODevice *vdev,
3252                                                    int n, unsigned int idx)
3253 {
3254     struct VirtQueue *vq = &vdev->vq[n];
3255 
3256     vq->last_avail_idx = vq->shadow_avail_idx = idx & 0x7fff;
3257     vq->last_avail_wrap_counter =
3258         vq->shadow_avail_wrap_counter = !!(idx & 0x8000);
3259     idx >>= 16;
3260     vq->used_idx = idx & 0x7ffff;
3261     vq->used_wrap_counter = !!(idx & 0x8000);
3262 }
3263 
3264 static void virtio_queue_split_set_last_avail_idx(VirtIODevice *vdev,
3265                                                   int n, unsigned int idx)
3266 {
3267         vdev->vq[n].last_avail_idx = idx;
3268         vdev->vq[n].shadow_avail_idx = idx;
3269 }
3270 
3271 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n,
3272                                      unsigned int idx)
3273 {
3274     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3275         virtio_queue_packed_set_last_avail_idx(vdev, n, idx);
3276     } else {
3277         virtio_queue_split_set_last_avail_idx(vdev, n, idx);
3278     }
3279 }
3280 
3281 static void virtio_queue_packed_restore_last_avail_idx(VirtIODevice *vdev,
3282                                                        int n)
3283 {
3284     /* We don't have a reference like avail idx in shared memory */
3285     return;
3286 }
3287 
3288 static void virtio_queue_split_restore_last_avail_idx(VirtIODevice *vdev,
3289                                                       int n)
3290 {
3291     RCU_READ_LOCK_GUARD();
3292     if (vdev->vq[n].vring.desc) {
3293         vdev->vq[n].last_avail_idx = vring_used_idx(&vdev->vq[n]);
3294         vdev->vq[n].shadow_avail_idx = vdev->vq[n].last_avail_idx;
3295     }
3296 }
3297 
3298 void virtio_queue_restore_last_avail_idx(VirtIODevice *vdev, int n)
3299 {
3300     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3301         virtio_queue_packed_restore_last_avail_idx(vdev, n);
3302     } else {
3303         virtio_queue_split_restore_last_avail_idx(vdev, n);
3304     }
3305 }
3306 
3307 static void virtio_queue_packed_update_used_idx(VirtIODevice *vdev, int n)
3308 {
3309     /* used idx was updated through set_last_avail_idx() */
3310     return;
3311 }
3312 
3313 static void virtio_split_packed_update_used_idx(VirtIODevice *vdev, int n)
3314 {
3315     RCU_READ_LOCK_GUARD();
3316     if (vdev->vq[n].vring.desc) {
3317         vdev->vq[n].used_idx = vring_used_idx(&vdev->vq[n]);
3318     }
3319 }
3320 
3321 void virtio_queue_update_used_idx(VirtIODevice *vdev, int n)
3322 {
3323     if (virtio_vdev_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3324         return virtio_queue_packed_update_used_idx(vdev, n);
3325     } else {
3326         return virtio_split_packed_update_used_idx(vdev, n);
3327     }
3328 }
3329 
3330 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
3331 {
3332     vdev->vq[n].signalled_used_valid = false;
3333 }
3334 
3335 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
3336 {
3337     return vdev->vq + n;
3338 }
3339 
3340 uint16_t virtio_get_queue_index(VirtQueue *vq)
3341 {
3342     return vq->queue_index;
3343 }
3344 
3345 static void virtio_queue_guest_notifier_read(EventNotifier *n)
3346 {
3347     VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
3348     if (event_notifier_test_and_clear(n)) {
3349         virtio_irq(vq);
3350     }
3351 }
3352 
3353 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
3354                                                 bool with_irqfd)
3355 {
3356     if (assign && !with_irqfd) {
3357         event_notifier_set_handler(&vq->guest_notifier,
3358                                    virtio_queue_guest_notifier_read);
3359     } else {
3360         event_notifier_set_handler(&vq->guest_notifier, NULL);
3361     }
3362     if (!assign) {
3363         /* Test and clear notifier before closing it,
3364          * in case poll callback didn't have time to run. */
3365         virtio_queue_guest_notifier_read(&vq->guest_notifier);
3366     }
3367 }
3368 
3369 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
3370 {
3371     return &vq->guest_notifier;
3372 }
3373 
3374 static void virtio_queue_host_notifier_aio_read(EventNotifier *n)
3375 {
3376     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3377     if (event_notifier_test_and_clear(n)) {
3378         virtio_queue_notify_aio_vq(vq);
3379     }
3380 }
3381 
3382 static void virtio_queue_host_notifier_aio_poll_begin(EventNotifier *n)
3383 {
3384     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3385 
3386     virtio_queue_set_notification(vq, 0);
3387 }
3388 
3389 static bool virtio_queue_host_notifier_aio_poll(void *opaque)
3390 {
3391     EventNotifier *n = opaque;
3392     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3393     bool progress;
3394 
3395     if (!vq->vring.desc || virtio_queue_empty(vq)) {
3396         return false;
3397     }
3398 
3399     progress = virtio_queue_notify_aio_vq(vq);
3400 
3401     /* In case the handler function re-enabled notifications */
3402     virtio_queue_set_notification(vq, 0);
3403     return progress;
3404 }
3405 
3406 static void virtio_queue_host_notifier_aio_poll_end(EventNotifier *n)
3407 {
3408     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3409 
3410     /* Caller polls once more after this to catch requests that race with us */
3411     virtio_queue_set_notification(vq, 1);
3412 }
3413 
3414 void virtio_queue_aio_set_host_notifier_handler(VirtQueue *vq, AioContext *ctx,
3415                                                 VirtIOHandleAIOOutput handle_output)
3416 {
3417     if (handle_output) {
3418         vq->handle_aio_output = handle_output;
3419         aio_set_event_notifier(ctx, &vq->host_notifier, true,
3420                                virtio_queue_host_notifier_aio_read,
3421                                virtio_queue_host_notifier_aio_poll);
3422         aio_set_event_notifier_poll(ctx, &vq->host_notifier,
3423                                     virtio_queue_host_notifier_aio_poll_begin,
3424                                     virtio_queue_host_notifier_aio_poll_end);
3425     } else {
3426         aio_set_event_notifier(ctx, &vq->host_notifier, true, NULL, NULL);
3427         /* Test and clear notifier before after disabling event,
3428          * in case poll callback didn't have time to run. */
3429         virtio_queue_host_notifier_aio_read(&vq->host_notifier);
3430         vq->handle_aio_output = NULL;
3431     }
3432 }
3433 
3434 void virtio_queue_host_notifier_read(EventNotifier *n)
3435 {
3436     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
3437     if (event_notifier_test_and_clear(n)) {
3438         virtio_queue_notify_vq(vq);
3439     }
3440 }
3441 
3442 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
3443 {
3444     return &vq->host_notifier;
3445 }
3446 
3447 void virtio_queue_set_host_notifier_enabled(VirtQueue *vq, bool enabled)
3448 {
3449     vq->host_notifier_enabled = enabled;
3450 }
3451 
3452 int virtio_queue_set_host_notifier_mr(VirtIODevice *vdev, int n,
3453                                       MemoryRegion *mr, bool assign)
3454 {
3455     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3456     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
3457 
3458     if (k->set_host_notifier_mr) {
3459         return k->set_host_notifier_mr(qbus->parent, n, mr, assign);
3460     }
3461 
3462     return -1;
3463 }
3464 
3465 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
3466 {
3467     g_free(vdev->bus_name);
3468     vdev->bus_name = g_strdup(bus_name);
3469 }
3470 
3471 void GCC_FMT_ATTR(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
3472 {
3473     va_list ap;
3474 
3475     va_start(ap, fmt);
3476     error_vreport(fmt, ap);
3477     va_end(ap);
3478 
3479     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
3480         vdev->status = vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET;
3481         virtio_notify_config(vdev);
3482     }
3483 
3484     vdev->broken = true;
3485 }
3486 
3487 static void virtio_memory_listener_commit(MemoryListener *listener)
3488 {
3489     VirtIODevice *vdev = container_of(listener, VirtIODevice, listener);
3490     int i;
3491 
3492     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3493         if (vdev->vq[i].vring.num == 0) {
3494             break;
3495         }
3496         virtio_init_region_cache(vdev, i);
3497     }
3498 }
3499 
3500 static void virtio_device_realize(DeviceState *dev, Error **errp)
3501 {
3502     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3503     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3504     Error *err = NULL;
3505 
3506     /* Devices should either use vmsd or the load/save methods */
3507     assert(!vdc->vmsd || !vdc->load);
3508 
3509     if (vdc->realize != NULL) {
3510         vdc->realize(dev, &err);
3511         if (err != NULL) {
3512             error_propagate(errp, err);
3513             return;
3514         }
3515     }
3516 
3517     virtio_bus_device_plugged(vdev, &err);
3518     if (err != NULL) {
3519         error_propagate(errp, err);
3520         vdc->unrealize(dev, NULL);
3521         return;
3522     }
3523 
3524     vdev->listener.commit = virtio_memory_listener_commit;
3525     memory_listener_register(&vdev->listener, vdev->dma_as);
3526 }
3527 
3528 static void virtio_device_unrealize(DeviceState *dev, Error **errp)
3529 {
3530     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3531     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3532     Error *err = NULL;
3533 
3534     virtio_bus_device_unplugged(vdev);
3535 
3536     if (vdc->unrealize != NULL) {
3537         vdc->unrealize(dev, &err);
3538         if (err != NULL) {
3539             error_propagate(errp, err);
3540             return;
3541         }
3542     }
3543 
3544     g_free(vdev->bus_name);
3545     vdev->bus_name = NULL;
3546 }
3547 
3548 static void virtio_device_free_virtqueues(VirtIODevice *vdev)
3549 {
3550     int i;
3551     if (!vdev->vq) {
3552         return;
3553     }
3554 
3555     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
3556         if (vdev->vq[i].vring.num == 0) {
3557             break;
3558         }
3559         virtio_virtqueue_reset_region_cache(&vdev->vq[i]);
3560     }
3561     g_free(vdev->vq);
3562 }
3563 
3564 static void virtio_device_instance_finalize(Object *obj)
3565 {
3566     VirtIODevice *vdev = VIRTIO_DEVICE(obj);
3567 
3568     memory_listener_unregister(&vdev->listener);
3569     virtio_device_free_virtqueues(vdev);
3570 
3571     g_free(vdev->config);
3572     g_free(vdev->vector_queues);
3573 }
3574 
3575 static Property virtio_properties[] = {
3576     DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
3577     DEFINE_PROP_BOOL("use-started", VirtIODevice, use_started, true),
3578     DEFINE_PROP_END_OF_LIST(),
3579 };
3580 
3581 static int virtio_device_start_ioeventfd_impl(VirtIODevice *vdev)
3582 {
3583     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3584     int i, n, r, err;
3585 
3586     memory_region_transaction_begin();
3587     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3588         VirtQueue *vq = &vdev->vq[n];
3589         if (!virtio_queue_get_num(vdev, n)) {
3590             continue;
3591         }
3592         r = virtio_bus_set_host_notifier(qbus, n, true);
3593         if (r < 0) {
3594             err = r;
3595             goto assign_error;
3596         }
3597         event_notifier_set_handler(&vq->host_notifier,
3598                                    virtio_queue_host_notifier_read);
3599     }
3600 
3601     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3602         /* Kick right away to begin processing requests already in vring */
3603         VirtQueue *vq = &vdev->vq[n];
3604         if (!vq->vring.num) {
3605             continue;
3606         }
3607         event_notifier_set(&vq->host_notifier);
3608     }
3609     memory_region_transaction_commit();
3610     return 0;
3611 
3612 assign_error:
3613     i = n; /* save n for a second iteration after transaction is committed. */
3614     while (--n >= 0) {
3615         VirtQueue *vq = &vdev->vq[n];
3616         if (!virtio_queue_get_num(vdev, n)) {
3617             continue;
3618         }
3619 
3620         event_notifier_set_handler(&vq->host_notifier, NULL);
3621         r = virtio_bus_set_host_notifier(qbus, n, false);
3622         assert(r >= 0);
3623     }
3624     memory_region_transaction_commit();
3625 
3626     while (--i >= 0) {
3627         if (!virtio_queue_get_num(vdev, i)) {
3628             continue;
3629         }
3630         virtio_bus_cleanup_host_notifier(qbus, i);
3631     }
3632     return err;
3633 }
3634 
3635 int virtio_device_start_ioeventfd(VirtIODevice *vdev)
3636 {
3637     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3638     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3639 
3640     return virtio_bus_start_ioeventfd(vbus);
3641 }
3642 
3643 static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
3644 {
3645     VirtioBusState *qbus = VIRTIO_BUS(qdev_get_parent_bus(DEVICE(vdev)));
3646     int n, r;
3647 
3648     memory_region_transaction_begin();
3649     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3650         VirtQueue *vq = &vdev->vq[n];
3651 
3652         if (!virtio_queue_get_num(vdev, n)) {
3653             continue;
3654         }
3655         event_notifier_set_handler(&vq->host_notifier, NULL);
3656         r = virtio_bus_set_host_notifier(qbus, n, false);
3657         assert(r >= 0);
3658     }
3659     memory_region_transaction_commit();
3660 
3661     for (n = 0; n < VIRTIO_QUEUE_MAX; n++) {
3662         if (!virtio_queue_get_num(vdev, n)) {
3663             continue;
3664         }
3665         virtio_bus_cleanup_host_notifier(qbus, n);
3666     }
3667 }
3668 
3669 int virtio_device_grab_ioeventfd(VirtIODevice *vdev)
3670 {
3671     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3672     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3673 
3674     return virtio_bus_grab_ioeventfd(vbus);
3675 }
3676 
3677 void virtio_device_release_ioeventfd(VirtIODevice *vdev)
3678 {
3679     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3680     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3681 
3682     virtio_bus_release_ioeventfd(vbus);
3683 }
3684 
3685 static void virtio_device_class_init(ObjectClass *klass, void *data)
3686 {
3687     /* Set the default value here. */
3688     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
3689     DeviceClass *dc = DEVICE_CLASS(klass);
3690 
3691     dc->realize = virtio_device_realize;
3692     dc->unrealize = virtio_device_unrealize;
3693     dc->bus_type = TYPE_VIRTIO_BUS;
3694     dc->props = virtio_properties;
3695     vdc->start_ioeventfd = virtio_device_start_ioeventfd_impl;
3696     vdc->stop_ioeventfd = virtio_device_stop_ioeventfd_impl;
3697 
3698     vdc->legacy_features |= VIRTIO_LEGACY_FEATURES;
3699 }
3700 
3701 bool virtio_device_ioeventfd_enabled(VirtIODevice *vdev)
3702 {
3703     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
3704     VirtioBusState *vbus = VIRTIO_BUS(qbus);
3705 
3706     return virtio_bus_ioeventfd_enabled(vbus);
3707 }
3708 
3709 static const TypeInfo virtio_device_info = {
3710     .name = TYPE_VIRTIO_DEVICE,
3711     .parent = TYPE_DEVICE,
3712     .instance_size = sizeof(VirtIODevice),
3713     .class_init = virtio_device_class_init,
3714     .instance_finalize = virtio_device_instance_finalize,
3715     .abstract = true,
3716     .class_size = sizeof(VirtioDeviceClass),
3717 };
3718 
3719 static void virtio_register_types(void)
3720 {
3721     type_register_static(&virtio_device_info);
3722 }
3723 
3724 type_init(virtio_register_types)
3725