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