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