xref: /openbmc/qemu/hw/virtio/virtio.c (revision 8692aa29)
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 "qemu-common.h"
17 #include "cpu.h"
18 #include "trace.h"
19 #include "exec/address-spaces.h"
20 #include "qemu/error-report.h"
21 #include "hw/virtio/virtio.h"
22 #include "qemu/atomic.h"
23 #include "hw/virtio/virtio-bus.h"
24 #include "migration/migration.h"
25 #include "hw/virtio/virtio-access.h"
26 
27 /*
28  * The alignment to use between consumer and producer parts of vring.
29  * x86 pagesize again. This is the default, used by transports like PCI
30  * which don't provide a means for the guest to tell the host the alignment.
31  */
32 #define VIRTIO_PCI_VRING_ALIGN         4096
33 
34 typedef struct VRingDesc
35 {
36     uint64_t addr;
37     uint32_t len;
38     uint16_t flags;
39     uint16_t next;
40 } VRingDesc;
41 
42 typedef struct VRingAvail
43 {
44     uint16_t flags;
45     uint16_t idx;
46     uint16_t ring[0];
47 } VRingAvail;
48 
49 typedef struct VRingUsedElem
50 {
51     uint32_t id;
52     uint32_t len;
53 } VRingUsedElem;
54 
55 typedef struct VRingUsed
56 {
57     uint16_t flags;
58     uint16_t idx;
59     VRingUsedElem ring[0];
60 } VRingUsed;
61 
62 typedef struct VRing
63 {
64     unsigned int num;
65     unsigned int num_default;
66     unsigned int align;
67     hwaddr desc;
68     hwaddr avail;
69     hwaddr used;
70 } VRing;
71 
72 struct VirtQueue
73 {
74     VRing vring;
75 
76     /* Next head to pop */
77     uint16_t last_avail_idx;
78 
79     /* Last avail_idx read from VQ. */
80     uint16_t shadow_avail_idx;
81 
82     uint16_t used_idx;
83 
84     /* Last used index value we have signalled on */
85     uint16_t signalled_used;
86 
87     /* Last used index value we have signalled on */
88     bool signalled_used_valid;
89 
90     /* Notification enabled? */
91     bool notification;
92 
93     uint16_t queue_index;
94 
95     int inuse;
96 
97     uint16_t vector;
98     void (*handle_output)(VirtIODevice *vdev, VirtQueue *vq);
99     void (*handle_aio_output)(VirtIODevice *vdev, VirtQueue *vq);
100     VirtIODevice *vdev;
101     EventNotifier guest_notifier;
102     EventNotifier host_notifier;
103     QLIST_ENTRY(VirtQueue) node;
104 };
105 
106 /* virt queue functions */
107 void virtio_queue_update_rings(VirtIODevice *vdev, int n)
108 {
109     VRing *vring = &vdev->vq[n].vring;
110 
111     if (!vring->desc) {
112         /* not yet setup -> nothing to do */
113         return;
114     }
115     vring->avail = vring->desc + vring->num * sizeof(VRingDesc);
116     vring->used = vring_align(vring->avail +
117                               offsetof(VRingAvail, ring[vring->num]),
118                               vring->align);
119 }
120 
121 static void vring_desc_read(VirtIODevice *vdev, VRingDesc *desc,
122                             hwaddr desc_pa, int i)
123 {
124     address_space_read(&address_space_memory, desc_pa + i * sizeof(VRingDesc),
125                        MEMTXATTRS_UNSPECIFIED, (void *)desc, sizeof(VRingDesc));
126     virtio_tswap64s(vdev, &desc->addr);
127     virtio_tswap32s(vdev, &desc->len);
128     virtio_tswap16s(vdev, &desc->flags);
129     virtio_tswap16s(vdev, &desc->next);
130 }
131 
132 static inline uint16_t vring_avail_flags(VirtQueue *vq)
133 {
134     hwaddr pa;
135     pa = vq->vring.avail + offsetof(VRingAvail, flags);
136     return virtio_lduw_phys(vq->vdev, pa);
137 }
138 
139 static inline uint16_t vring_avail_idx(VirtQueue *vq)
140 {
141     hwaddr pa;
142     pa = vq->vring.avail + offsetof(VRingAvail, idx);
143     vq->shadow_avail_idx = virtio_lduw_phys(vq->vdev, pa);
144     return vq->shadow_avail_idx;
145 }
146 
147 static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
148 {
149     hwaddr pa;
150     pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
151     return virtio_lduw_phys(vq->vdev, pa);
152 }
153 
154 static inline uint16_t vring_get_used_event(VirtQueue *vq)
155 {
156     return vring_avail_ring(vq, vq->vring.num);
157 }
158 
159 static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,
160                                     int i)
161 {
162     hwaddr pa;
163     virtio_tswap32s(vq->vdev, &uelem->id);
164     virtio_tswap32s(vq->vdev, &uelem->len);
165     pa = vq->vring.used + offsetof(VRingUsed, ring[i]);
166     address_space_write(&address_space_memory, pa, MEMTXATTRS_UNSPECIFIED,
167                        (void *)uelem, sizeof(VRingUsedElem));
168 }
169 
170 static uint16_t vring_used_idx(VirtQueue *vq)
171 {
172     hwaddr pa;
173     pa = vq->vring.used + offsetof(VRingUsed, idx);
174     return virtio_lduw_phys(vq->vdev, pa);
175 }
176 
177 static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
178 {
179     hwaddr pa;
180     pa = vq->vring.used + offsetof(VRingUsed, idx);
181     virtio_stw_phys(vq->vdev, pa, val);
182     vq->used_idx = val;
183 }
184 
185 static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
186 {
187     VirtIODevice *vdev = vq->vdev;
188     hwaddr pa;
189     pa = vq->vring.used + offsetof(VRingUsed, flags);
190     virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) | mask);
191 }
192 
193 static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
194 {
195     VirtIODevice *vdev = vq->vdev;
196     hwaddr pa;
197     pa = vq->vring.used + offsetof(VRingUsed, flags);
198     virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) & ~mask);
199 }
200 
201 static inline void vring_set_avail_event(VirtQueue *vq, uint16_t val)
202 {
203     hwaddr pa;
204     if (!vq->notification) {
205         return;
206     }
207     pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
208     virtio_stw_phys(vq->vdev, pa, val);
209 }
210 
211 void virtio_queue_set_notification(VirtQueue *vq, int enable)
212 {
213     vq->notification = enable;
214     if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
215         vring_set_avail_event(vq, vring_avail_idx(vq));
216     } else if (enable) {
217         vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
218     } else {
219         vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
220     }
221     if (enable) {
222         /* Expose avail event/used flags before caller checks the avail idx. */
223         smp_mb();
224     }
225 }
226 
227 int virtio_queue_ready(VirtQueue *vq)
228 {
229     return vq->vring.avail != 0;
230 }
231 
232 /* Fetch avail_idx from VQ memory only when we really need to know if
233  * guest has added some buffers. */
234 int virtio_queue_empty(VirtQueue *vq)
235 {
236     if (vq->shadow_avail_idx != vq->last_avail_idx) {
237         return 0;
238     }
239 
240     return vring_avail_idx(vq) == vq->last_avail_idx;
241 }
242 
243 static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,
244                                unsigned int len)
245 {
246     unsigned int offset;
247     int i;
248 
249     offset = 0;
250     for (i = 0; i < elem->in_num; i++) {
251         size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
252 
253         cpu_physical_memory_unmap(elem->in_sg[i].iov_base,
254                                   elem->in_sg[i].iov_len,
255                                   1, size);
256 
257         offset += size;
258     }
259 
260     for (i = 0; i < elem->out_num; i++)
261         cpu_physical_memory_unmap(elem->out_sg[i].iov_base,
262                                   elem->out_sg[i].iov_len,
263                                   0, elem->out_sg[i].iov_len);
264 }
265 
266 void virtqueue_discard(VirtQueue *vq, const VirtQueueElement *elem,
267                        unsigned int len)
268 {
269     vq->last_avail_idx--;
270     virtqueue_unmap_sg(vq, elem, len);
271 }
272 
273 void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
274                     unsigned int len, unsigned int idx)
275 {
276     VRingUsedElem uelem;
277 
278     trace_virtqueue_fill(vq, elem, len, idx);
279 
280     virtqueue_unmap_sg(vq, elem, len);
281 
282     idx = (idx + vq->used_idx) % vq->vring.num;
283 
284     uelem.id = elem->index;
285     uelem.len = len;
286     vring_used_write(vq, &uelem, idx);
287 }
288 
289 void virtqueue_flush(VirtQueue *vq, unsigned int count)
290 {
291     uint16_t old, new;
292     /* Make sure buffer is written before we update index. */
293     smp_wmb();
294     trace_virtqueue_flush(vq, count);
295     old = vq->used_idx;
296     new = old + count;
297     vring_used_idx_set(vq, new);
298     vq->inuse -= count;
299     if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
300         vq->signalled_used_valid = false;
301 }
302 
303 void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
304                     unsigned int len)
305 {
306     virtqueue_fill(vq, elem, len, 0);
307     virtqueue_flush(vq, 1);
308 }
309 
310 static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
311 {
312     uint16_t num_heads = vring_avail_idx(vq) - idx;
313 
314     /* Check it isn't doing very strange things with descriptor numbers. */
315     if (num_heads > vq->vring.num) {
316         error_report("Guest moved used index from %u to %u",
317                      idx, vq->shadow_avail_idx);
318         exit(1);
319     }
320     /* On success, callers read a descriptor at vq->last_avail_idx.
321      * Make sure descriptor read does not bypass avail index read. */
322     if (num_heads) {
323         smp_rmb();
324     }
325 
326     return num_heads;
327 }
328 
329 static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx)
330 {
331     unsigned int head;
332 
333     /* Grab the next descriptor number they're advertising, and increment
334      * the index we've seen. */
335     head = vring_avail_ring(vq, idx % vq->vring.num);
336 
337     /* If their number is silly, that's a fatal mistake. */
338     if (head >= vq->vring.num) {
339         error_report("Guest says index %u is available", head);
340         exit(1);
341     }
342 
343     return head;
344 }
345 
346 static unsigned virtqueue_read_next_desc(VirtIODevice *vdev, VRingDesc *desc,
347                                          hwaddr desc_pa, unsigned int max)
348 {
349     unsigned int next;
350 
351     /* If this descriptor says it doesn't chain, we're done. */
352     if (!(desc->flags & VRING_DESC_F_NEXT)) {
353         return max;
354     }
355 
356     /* Check they're not leading us off end of descriptors. */
357     next = desc->next;
358     /* Make sure compiler knows to grab that: we don't want it changing! */
359     smp_wmb();
360 
361     if (next >= max) {
362         error_report("Desc next is %u", next);
363         exit(1);
364     }
365 
366     vring_desc_read(vdev, desc, desc_pa, next);
367     return next;
368 }
369 
370 void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
371                                unsigned int *out_bytes,
372                                unsigned max_in_bytes, unsigned max_out_bytes)
373 {
374     unsigned int idx;
375     unsigned int total_bufs, in_total, out_total;
376 
377     idx = vq->last_avail_idx;
378 
379     total_bufs = in_total = out_total = 0;
380     while (virtqueue_num_heads(vq, idx)) {
381         VirtIODevice *vdev = vq->vdev;
382         unsigned int max, num_bufs, indirect = 0;
383         VRingDesc desc;
384         hwaddr desc_pa;
385         int i;
386 
387         max = vq->vring.num;
388         num_bufs = total_bufs;
389         i = virtqueue_get_head(vq, idx++);
390         desc_pa = vq->vring.desc;
391         vring_desc_read(vdev, &desc, desc_pa, i);
392 
393         if (desc.flags & VRING_DESC_F_INDIRECT) {
394             if (desc.len % sizeof(VRingDesc)) {
395                 error_report("Invalid size for indirect buffer table");
396                 exit(1);
397             }
398 
399             /* If we've got too many, that implies a descriptor loop. */
400             if (num_bufs >= max) {
401                 error_report("Looped descriptor");
402                 exit(1);
403             }
404 
405             /* loop over the indirect descriptor table */
406             indirect = 1;
407             max = desc.len / sizeof(VRingDesc);
408             desc_pa = desc.addr;
409             num_bufs = i = 0;
410             vring_desc_read(vdev, &desc, desc_pa, i);
411         }
412 
413         do {
414             /* If we've got too many, that implies a descriptor loop. */
415             if (++num_bufs > max) {
416                 error_report("Looped descriptor");
417                 exit(1);
418             }
419 
420             if (desc.flags & VRING_DESC_F_WRITE) {
421                 in_total += desc.len;
422             } else {
423                 out_total += desc.len;
424             }
425             if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
426                 goto done;
427             }
428         } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);
429 
430         if (!indirect)
431             total_bufs = num_bufs;
432         else
433             total_bufs++;
434     }
435 done:
436     if (in_bytes) {
437         *in_bytes = in_total;
438     }
439     if (out_bytes) {
440         *out_bytes = out_total;
441     }
442 }
443 
444 int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
445                           unsigned int out_bytes)
446 {
447     unsigned int in_total, out_total;
448 
449     virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
450     return in_bytes <= in_total && out_bytes <= out_total;
451 }
452 
453 static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
454                                unsigned int max_num_sg, bool is_write,
455                                hwaddr pa, size_t sz)
456 {
457     unsigned num_sg = *p_num_sg;
458     assert(num_sg <= max_num_sg);
459 
460     while (sz) {
461         hwaddr len = sz;
462 
463         if (num_sg == max_num_sg) {
464             error_report("virtio: too many write descriptors in indirect table");
465             exit(1);
466         }
467 
468         iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
469         iov[num_sg].iov_len = len;
470         addr[num_sg] = pa;
471 
472         sz -= len;
473         pa += len;
474         num_sg++;
475     }
476     *p_num_sg = num_sg;
477 }
478 
479 static void virtqueue_map_iovec(struct iovec *sg, hwaddr *addr,
480                                 unsigned int *num_sg, unsigned int max_size,
481                                 int is_write)
482 {
483     unsigned int i;
484     hwaddr len;
485 
486     /* Note: this function MUST validate input, some callers
487      * are passing in num_sg values received over the network.
488      */
489     /* TODO: teach all callers that this can fail, and return failure instead
490      * of asserting here.
491      * When we do, we might be able to re-enable NDEBUG below.
492      */
493 #ifdef NDEBUG
494 #error building with NDEBUG is not supported
495 #endif
496     assert(*num_sg <= max_size);
497 
498     for (i = 0; i < *num_sg; i++) {
499         len = sg[i].iov_len;
500         sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
501         if (!sg[i].iov_base) {
502             error_report("virtio: error trying to map MMIO memory");
503             exit(1);
504         }
505         if (len != sg[i].iov_len) {
506             error_report("virtio: unexpected memory split");
507             exit(1);
508         }
509     }
510 }
511 
512 void virtqueue_map(VirtQueueElement *elem)
513 {
514     virtqueue_map_iovec(elem->in_sg, elem->in_addr, &elem->in_num,
515                         VIRTQUEUE_MAX_SIZE, 1);
516     virtqueue_map_iovec(elem->out_sg, elem->out_addr, &elem->out_num,
517                         VIRTQUEUE_MAX_SIZE, 0);
518 }
519 
520 void *virtqueue_alloc_element(size_t sz, unsigned out_num, unsigned in_num)
521 {
522     VirtQueueElement *elem;
523     size_t in_addr_ofs = QEMU_ALIGN_UP(sz, __alignof__(elem->in_addr[0]));
524     size_t out_addr_ofs = in_addr_ofs + in_num * sizeof(elem->in_addr[0]);
525     size_t out_addr_end = out_addr_ofs + out_num * sizeof(elem->out_addr[0]);
526     size_t in_sg_ofs = QEMU_ALIGN_UP(out_addr_end, __alignof__(elem->in_sg[0]));
527     size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]);
528     size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]);
529 
530     assert(sz >= sizeof(VirtQueueElement));
531     elem = g_malloc(out_sg_end);
532     elem->out_num = out_num;
533     elem->in_num = in_num;
534     elem->in_addr = (void *)elem + in_addr_ofs;
535     elem->out_addr = (void *)elem + out_addr_ofs;
536     elem->in_sg = (void *)elem + in_sg_ofs;
537     elem->out_sg = (void *)elem + out_sg_ofs;
538     return elem;
539 }
540 
541 void *virtqueue_pop(VirtQueue *vq, size_t sz)
542 {
543     unsigned int i, head, max;
544     hwaddr desc_pa = vq->vring.desc;
545     VirtIODevice *vdev = vq->vdev;
546     VirtQueueElement *elem;
547     unsigned out_num, in_num;
548     hwaddr addr[VIRTQUEUE_MAX_SIZE];
549     struct iovec iov[VIRTQUEUE_MAX_SIZE];
550     VRingDesc desc;
551 
552     if (virtio_queue_empty(vq)) {
553         return NULL;
554     }
555     /* Needed after virtio_queue_empty(), see comment in
556      * virtqueue_num_heads(). */
557     smp_rmb();
558 
559     /* When we start there are none of either input nor output. */
560     out_num = in_num = 0;
561 
562     max = vq->vring.num;
563 
564     i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
565     if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
566         vring_set_avail_event(vq, vq->last_avail_idx);
567     }
568 
569     vring_desc_read(vdev, &desc, desc_pa, i);
570     if (desc.flags & VRING_DESC_F_INDIRECT) {
571         if (desc.len % sizeof(VRingDesc)) {
572             error_report("Invalid size for indirect buffer table");
573             exit(1);
574         }
575 
576         /* loop over the indirect descriptor table */
577         max = desc.len / sizeof(VRingDesc);
578         desc_pa = desc.addr;
579         i = 0;
580         vring_desc_read(vdev, &desc, desc_pa, i);
581     }
582 
583     /* Collect all the descriptors */
584     do {
585         if (desc.flags & VRING_DESC_F_WRITE) {
586             virtqueue_map_desc(&in_num, addr + out_num, iov + out_num,
587                                VIRTQUEUE_MAX_SIZE - out_num, true, desc.addr, desc.len);
588         } else {
589             if (in_num) {
590                 error_report("Incorrect order for descriptors");
591                 exit(1);
592             }
593             virtqueue_map_desc(&out_num, addr, iov,
594                                VIRTQUEUE_MAX_SIZE, false, desc.addr, desc.len);
595         }
596 
597         /* If we've got too many, that implies a descriptor loop. */
598         if ((in_num + out_num) > max) {
599             error_report("Looped descriptor");
600             exit(1);
601         }
602     } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);
603 
604     /* Now copy what we have collected and mapped */
605     elem = virtqueue_alloc_element(sz, out_num, in_num);
606     elem->index = head;
607     for (i = 0; i < out_num; i++) {
608         elem->out_addr[i] = addr[i];
609         elem->out_sg[i] = iov[i];
610     }
611     for (i = 0; i < in_num; i++) {
612         elem->in_addr[i] = addr[out_num + i];
613         elem->in_sg[i] = iov[out_num + i];
614     }
615 
616     vq->inuse++;
617 
618     trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
619     return elem;
620 }
621 
622 /* Reading and writing a structure directly to QEMUFile is *awful*, but
623  * it is what QEMU has always done by mistake.  We can change it sooner
624  * or later by bumping the version number of the affected vm states.
625  * In the meanwhile, since the in-memory layout of VirtQueueElement
626  * has changed, we need to marshal to and from the layout that was
627  * used before the change.
628  */
629 typedef struct VirtQueueElementOld {
630     unsigned int index;
631     unsigned int out_num;
632     unsigned int in_num;
633     hwaddr in_addr[VIRTQUEUE_MAX_SIZE];
634     hwaddr out_addr[VIRTQUEUE_MAX_SIZE];
635     struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
636     struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
637 } VirtQueueElementOld;
638 
639 void *qemu_get_virtqueue_element(QEMUFile *f, size_t sz)
640 {
641     VirtQueueElement *elem;
642     VirtQueueElementOld data;
643     int i;
644 
645     qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
646 
647     elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);
648     elem->index = data.index;
649 
650     for (i = 0; i < elem->in_num; i++) {
651         elem->in_addr[i] = data.in_addr[i];
652     }
653 
654     for (i = 0; i < elem->out_num; i++) {
655         elem->out_addr[i] = data.out_addr[i];
656     }
657 
658     for (i = 0; i < elem->in_num; i++) {
659         /* Base is overwritten by virtqueue_map.  */
660         elem->in_sg[i].iov_base = 0;
661         elem->in_sg[i].iov_len = data.in_sg[i].iov_len;
662     }
663 
664     for (i = 0; i < elem->out_num; i++) {
665         /* Base is overwritten by virtqueue_map.  */
666         elem->out_sg[i].iov_base = 0;
667         elem->out_sg[i].iov_len = data.out_sg[i].iov_len;
668     }
669 
670     virtqueue_map(elem);
671     return elem;
672 }
673 
674 void qemu_put_virtqueue_element(QEMUFile *f, VirtQueueElement *elem)
675 {
676     VirtQueueElementOld data;
677     int i;
678 
679     memset(&data, 0, sizeof(data));
680     data.index = elem->index;
681     data.in_num = elem->in_num;
682     data.out_num = elem->out_num;
683 
684     for (i = 0; i < elem->in_num; i++) {
685         data.in_addr[i] = elem->in_addr[i];
686     }
687 
688     for (i = 0; i < elem->out_num; i++) {
689         data.out_addr[i] = elem->out_addr[i];
690     }
691 
692     for (i = 0; i < elem->in_num; i++) {
693         /* Base is overwritten by virtqueue_map when loading.  Do not
694          * save it, as it would leak the QEMU address space layout.  */
695         data.in_sg[i].iov_len = elem->in_sg[i].iov_len;
696     }
697 
698     for (i = 0; i < elem->out_num; i++) {
699         /* Do not save iov_base as above.  */
700         data.out_sg[i].iov_len = elem->out_sg[i].iov_len;
701     }
702     qemu_put_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
703 }
704 
705 /* virtio device */
706 static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
707 {
708     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
709     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
710 
711     if (k->notify) {
712         k->notify(qbus->parent, vector);
713     }
714 }
715 
716 void virtio_update_irq(VirtIODevice *vdev)
717 {
718     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
719 }
720 
721 static int virtio_validate_features(VirtIODevice *vdev)
722 {
723     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
724 
725     if (k->validate_features) {
726         return k->validate_features(vdev);
727     } else {
728         return 0;
729     }
730 }
731 
732 int virtio_set_status(VirtIODevice *vdev, uint8_t val)
733 {
734     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
735     trace_virtio_set_status(vdev, val);
736 
737     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
738         if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
739             val & VIRTIO_CONFIG_S_FEATURES_OK) {
740             int ret = virtio_validate_features(vdev);
741 
742             if (ret) {
743                 return ret;
744             }
745         }
746     }
747     if (k->set_status) {
748         k->set_status(vdev, val);
749     }
750     vdev->status = val;
751     return 0;
752 }
753 
754 bool target_words_bigendian(void);
755 static enum virtio_device_endian virtio_default_endian(void)
756 {
757     if (target_words_bigendian()) {
758         return VIRTIO_DEVICE_ENDIAN_BIG;
759     } else {
760         return VIRTIO_DEVICE_ENDIAN_LITTLE;
761     }
762 }
763 
764 static enum virtio_device_endian virtio_current_cpu_endian(void)
765 {
766     CPUClass *cc = CPU_GET_CLASS(current_cpu);
767 
768     if (cc->virtio_is_big_endian(current_cpu)) {
769         return VIRTIO_DEVICE_ENDIAN_BIG;
770     } else {
771         return VIRTIO_DEVICE_ENDIAN_LITTLE;
772     }
773 }
774 
775 void virtio_reset(void *opaque)
776 {
777     VirtIODevice *vdev = opaque;
778     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
779     int i;
780 
781     virtio_set_status(vdev, 0);
782     if (current_cpu) {
783         /* Guest initiated reset */
784         vdev->device_endian = virtio_current_cpu_endian();
785     } else {
786         /* System reset */
787         vdev->device_endian = virtio_default_endian();
788     }
789 
790     if (k->reset) {
791         k->reset(vdev);
792     }
793 
794     vdev->guest_features = 0;
795     vdev->queue_sel = 0;
796     vdev->status = 0;
797     vdev->isr = 0;
798     vdev->config_vector = VIRTIO_NO_VECTOR;
799     virtio_notify_vector(vdev, vdev->config_vector);
800 
801     for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
802         vdev->vq[i].vring.desc = 0;
803         vdev->vq[i].vring.avail = 0;
804         vdev->vq[i].vring.used = 0;
805         vdev->vq[i].last_avail_idx = 0;
806         vdev->vq[i].shadow_avail_idx = 0;
807         vdev->vq[i].used_idx = 0;
808         virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
809         vdev->vq[i].signalled_used = 0;
810         vdev->vq[i].signalled_used_valid = false;
811         vdev->vq[i].notification = true;
812         vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
813     }
814 }
815 
816 uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
817 {
818     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
819     uint8_t val;
820 
821     if (addr + sizeof(val) > vdev->config_len) {
822         return (uint32_t)-1;
823     }
824 
825     k->get_config(vdev, vdev->config);
826 
827     val = ldub_p(vdev->config + addr);
828     return val;
829 }
830 
831 uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
832 {
833     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
834     uint16_t val;
835 
836     if (addr + sizeof(val) > vdev->config_len) {
837         return (uint32_t)-1;
838     }
839 
840     k->get_config(vdev, vdev->config);
841 
842     val = lduw_p(vdev->config + addr);
843     return val;
844 }
845 
846 uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
847 {
848     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
849     uint32_t val;
850 
851     if (addr + sizeof(val) > vdev->config_len) {
852         return (uint32_t)-1;
853     }
854 
855     k->get_config(vdev, vdev->config);
856 
857     val = ldl_p(vdev->config + addr);
858     return val;
859 }
860 
861 void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
862 {
863     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
864     uint8_t val = data;
865 
866     if (addr + sizeof(val) > vdev->config_len) {
867         return;
868     }
869 
870     stb_p(vdev->config + addr, val);
871 
872     if (k->set_config) {
873         k->set_config(vdev, vdev->config);
874     }
875 }
876 
877 void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
878 {
879     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
880     uint16_t val = data;
881 
882     if (addr + sizeof(val) > vdev->config_len) {
883         return;
884     }
885 
886     stw_p(vdev->config + addr, val);
887 
888     if (k->set_config) {
889         k->set_config(vdev, vdev->config);
890     }
891 }
892 
893 void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
894 {
895     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
896     uint32_t val = data;
897 
898     if (addr + sizeof(val) > vdev->config_len) {
899         return;
900     }
901 
902     stl_p(vdev->config + addr, val);
903 
904     if (k->set_config) {
905         k->set_config(vdev, vdev->config);
906     }
907 }
908 
909 uint32_t virtio_config_modern_readb(VirtIODevice *vdev, uint32_t addr)
910 {
911     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
912     uint8_t val;
913 
914     if (addr + sizeof(val) > vdev->config_len) {
915         return (uint32_t)-1;
916     }
917 
918     k->get_config(vdev, vdev->config);
919 
920     val = ldub_p(vdev->config + addr);
921     return val;
922 }
923 
924 uint32_t virtio_config_modern_readw(VirtIODevice *vdev, uint32_t addr)
925 {
926     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
927     uint16_t val;
928 
929     if (addr + sizeof(val) > vdev->config_len) {
930         return (uint32_t)-1;
931     }
932 
933     k->get_config(vdev, vdev->config);
934 
935     val = lduw_le_p(vdev->config + addr);
936     return val;
937 }
938 
939 uint32_t virtio_config_modern_readl(VirtIODevice *vdev, uint32_t addr)
940 {
941     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
942     uint32_t val;
943 
944     if (addr + sizeof(val) > vdev->config_len) {
945         return (uint32_t)-1;
946     }
947 
948     k->get_config(vdev, vdev->config);
949 
950     val = ldl_le_p(vdev->config + addr);
951     return val;
952 }
953 
954 void virtio_config_modern_writeb(VirtIODevice *vdev,
955                                  uint32_t addr, uint32_t data)
956 {
957     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
958     uint8_t val = data;
959 
960     if (addr + sizeof(val) > vdev->config_len) {
961         return;
962     }
963 
964     stb_p(vdev->config + addr, val);
965 
966     if (k->set_config) {
967         k->set_config(vdev, vdev->config);
968     }
969 }
970 
971 void virtio_config_modern_writew(VirtIODevice *vdev,
972                                  uint32_t addr, uint32_t data)
973 {
974     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
975     uint16_t val = data;
976 
977     if (addr + sizeof(val) > vdev->config_len) {
978         return;
979     }
980 
981     stw_le_p(vdev->config + addr, val);
982 
983     if (k->set_config) {
984         k->set_config(vdev, vdev->config);
985     }
986 }
987 
988 void virtio_config_modern_writel(VirtIODevice *vdev,
989                                  uint32_t addr, uint32_t data)
990 {
991     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
992     uint32_t val = data;
993 
994     if (addr + sizeof(val) > vdev->config_len) {
995         return;
996     }
997 
998     stl_le_p(vdev->config + addr, val);
999 
1000     if (k->set_config) {
1001         k->set_config(vdev, vdev->config);
1002     }
1003 }
1004 
1005 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
1006 {
1007     vdev->vq[n].vring.desc = addr;
1008     virtio_queue_update_rings(vdev, n);
1009 }
1010 
1011 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
1012 {
1013     return vdev->vq[n].vring.desc;
1014 }
1015 
1016 void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
1017                             hwaddr avail, hwaddr used)
1018 {
1019     vdev->vq[n].vring.desc = desc;
1020     vdev->vq[n].vring.avail = avail;
1021     vdev->vq[n].vring.used = used;
1022 }
1023 
1024 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
1025 {
1026     /* Don't allow guest to flip queue between existent and
1027      * nonexistent states, or to set it to an invalid size.
1028      */
1029     if (!!num != !!vdev->vq[n].vring.num ||
1030         num > VIRTQUEUE_MAX_SIZE ||
1031         num < 0) {
1032         return;
1033     }
1034     vdev->vq[n].vring.num = num;
1035 }
1036 
1037 VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
1038 {
1039     return QLIST_FIRST(&vdev->vector_queues[vector]);
1040 }
1041 
1042 VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
1043 {
1044     return QLIST_NEXT(vq, node);
1045 }
1046 
1047 int virtio_queue_get_num(VirtIODevice *vdev, int n)
1048 {
1049     return vdev->vq[n].vring.num;
1050 }
1051 
1052 int virtio_get_num_queues(VirtIODevice *vdev)
1053 {
1054     int i;
1055 
1056     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1057         if (!virtio_queue_get_num(vdev, i)) {
1058             break;
1059         }
1060     }
1061 
1062     return i;
1063 }
1064 
1065 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
1066 {
1067     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1068     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1069 
1070     /* virtio-1 compliant devices cannot change the alignment */
1071     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1072         error_report("tried to modify queue alignment for virtio-1 device");
1073         return;
1074     }
1075     /* Check that the transport told us it was going to do this
1076      * (so a buggy transport will immediately assert rather than
1077      * silently failing to migrate this state)
1078      */
1079     assert(k->has_variable_vring_alignment);
1080 
1081     vdev->vq[n].vring.align = align;
1082     virtio_queue_update_rings(vdev, n);
1083 }
1084 
1085 static void virtio_queue_notify_aio_vq(VirtQueue *vq)
1086 {
1087     if (vq->vring.desc && vq->handle_aio_output) {
1088         VirtIODevice *vdev = vq->vdev;
1089 
1090         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1091         vq->handle_aio_output(vdev, vq);
1092     }
1093 }
1094 
1095 static void virtio_queue_notify_vq(VirtQueue *vq)
1096 {
1097     if (vq->vring.desc && vq->handle_output) {
1098         VirtIODevice *vdev = vq->vdev;
1099 
1100         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1101         vq->handle_output(vdev, vq);
1102     }
1103 }
1104 
1105 void virtio_queue_notify(VirtIODevice *vdev, int n)
1106 {
1107     virtio_queue_notify_vq(&vdev->vq[n]);
1108 }
1109 
1110 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
1111 {
1112     return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
1113         VIRTIO_NO_VECTOR;
1114 }
1115 
1116 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
1117 {
1118     VirtQueue *vq = &vdev->vq[n];
1119 
1120     if (n < VIRTIO_QUEUE_MAX) {
1121         if (vdev->vector_queues &&
1122             vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
1123             QLIST_REMOVE(vq, node);
1124         }
1125         vdev->vq[n].vector = vector;
1126         if (vdev->vector_queues &&
1127             vector != VIRTIO_NO_VECTOR) {
1128             QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
1129         }
1130     }
1131 }
1132 
1133 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
1134                             void (*handle_output)(VirtIODevice *, VirtQueue *))
1135 {
1136     int i;
1137 
1138     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1139         if (vdev->vq[i].vring.num == 0)
1140             break;
1141     }
1142 
1143     if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
1144         abort();
1145 
1146     vdev->vq[i].vring.num = queue_size;
1147     vdev->vq[i].vring.num_default = queue_size;
1148     vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
1149     vdev->vq[i].handle_output = handle_output;
1150     vdev->vq[i].handle_aio_output = NULL;
1151 
1152     return &vdev->vq[i];
1153 }
1154 
1155 void virtio_del_queue(VirtIODevice *vdev, int n)
1156 {
1157     if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
1158         abort();
1159     }
1160 
1161     vdev->vq[n].vring.num = 0;
1162     vdev->vq[n].vring.num_default = 0;
1163 }
1164 
1165 void virtio_irq(VirtQueue *vq)
1166 {
1167     trace_virtio_irq(vq);
1168     vq->vdev->isr |= 0x01;
1169     virtio_notify_vector(vq->vdev, vq->vector);
1170 }
1171 
1172 bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
1173 {
1174     uint16_t old, new;
1175     bool v;
1176     /* We need to expose used array entries before checking used event. */
1177     smp_mb();
1178     /* Always notify when queue is empty (when feature acknowledge) */
1179     if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1180         !vq->inuse && virtio_queue_empty(vq)) {
1181         return true;
1182     }
1183 
1184     if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
1185         return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
1186     }
1187 
1188     v = vq->signalled_used_valid;
1189     vq->signalled_used_valid = true;
1190     old = vq->signalled_used;
1191     new = vq->signalled_used = vq->used_idx;
1192     return !v || vring_need_event(vring_get_used_event(vq), new, old);
1193 }
1194 
1195 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
1196 {
1197     if (!virtio_should_notify(vdev, vq)) {
1198         return;
1199     }
1200 
1201     trace_virtio_notify(vdev, vq);
1202     vdev->isr |= 0x01;
1203     virtio_notify_vector(vdev, vq->vector);
1204 }
1205 
1206 void virtio_notify_config(VirtIODevice *vdev)
1207 {
1208     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
1209         return;
1210 
1211     vdev->isr |= 0x03;
1212     vdev->generation++;
1213     virtio_notify_vector(vdev, vdev->config_vector);
1214 }
1215 
1216 static bool virtio_device_endian_needed(void *opaque)
1217 {
1218     VirtIODevice *vdev = opaque;
1219 
1220     assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
1221     if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1222         return vdev->device_endian != virtio_default_endian();
1223     }
1224     /* Devices conforming to VIRTIO 1.0 or later are always LE. */
1225     return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
1226 }
1227 
1228 static bool virtio_64bit_features_needed(void *opaque)
1229 {
1230     VirtIODevice *vdev = opaque;
1231 
1232     return (vdev->host_features >> 32) != 0;
1233 }
1234 
1235 static bool virtio_virtqueue_needed(void *opaque)
1236 {
1237     VirtIODevice *vdev = opaque;
1238 
1239     return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
1240 }
1241 
1242 static bool virtio_ringsize_needed(void *opaque)
1243 {
1244     VirtIODevice *vdev = opaque;
1245     int i;
1246 
1247     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1248         if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
1249             return true;
1250         }
1251     }
1252     return false;
1253 }
1254 
1255 static bool virtio_extra_state_needed(void *opaque)
1256 {
1257     VirtIODevice *vdev = opaque;
1258     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1259     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1260 
1261     return k->has_extra_state &&
1262         k->has_extra_state(qbus->parent);
1263 }
1264 
1265 static const VMStateDescription vmstate_virtqueue = {
1266     .name = "virtqueue_state",
1267     .version_id = 1,
1268     .minimum_version_id = 1,
1269     .fields = (VMStateField[]) {
1270         VMSTATE_UINT64(vring.avail, struct VirtQueue),
1271         VMSTATE_UINT64(vring.used, struct VirtQueue),
1272         VMSTATE_END_OF_LIST()
1273     }
1274 };
1275 
1276 static const VMStateDescription vmstate_virtio_virtqueues = {
1277     .name = "virtio/virtqueues",
1278     .version_id = 1,
1279     .minimum_version_id = 1,
1280     .needed = &virtio_virtqueue_needed,
1281     .fields = (VMStateField[]) {
1282         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1283                       VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
1284         VMSTATE_END_OF_LIST()
1285     }
1286 };
1287 
1288 static const VMStateDescription vmstate_ringsize = {
1289     .name = "ringsize_state",
1290     .version_id = 1,
1291     .minimum_version_id = 1,
1292     .fields = (VMStateField[]) {
1293         VMSTATE_UINT32(vring.num_default, struct VirtQueue),
1294         VMSTATE_END_OF_LIST()
1295     }
1296 };
1297 
1298 static const VMStateDescription vmstate_virtio_ringsize = {
1299     .name = "virtio/ringsize",
1300     .version_id = 1,
1301     .minimum_version_id = 1,
1302     .needed = &virtio_ringsize_needed,
1303     .fields = (VMStateField[]) {
1304         VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1305                       VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
1306         VMSTATE_END_OF_LIST()
1307     }
1308 };
1309 
1310 static int get_extra_state(QEMUFile *f, void *pv, size_t size)
1311 {
1312     VirtIODevice *vdev = pv;
1313     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1314     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1315 
1316     if (!k->load_extra_state) {
1317         return -1;
1318     } else {
1319         return k->load_extra_state(qbus->parent, f);
1320     }
1321 }
1322 
1323 static void put_extra_state(QEMUFile *f, void *pv, size_t size)
1324 {
1325     VirtIODevice *vdev = pv;
1326     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1327     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1328 
1329     k->save_extra_state(qbus->parent, f);
1330 }
1331 
1332 static const VMStateInfo vmstate_info_extra_state = {
1333     .name = "virtqueue_extra_state",
1334     .get = get_extra_state,
1335     .put = put_extra_state,
1336 };
1337 
1338 static const VMStateDescription vmstate_virtio_extra_state = {
1339     .name = "virtio/extra_state",
1340     .version_id = 1,
1341     .minimum_version_id = 1,
1342     .needed = &virtio_extra_state_needed,
1343     .fields = (VMStateField[]) {
1344         {
1345             .name         = "extra_state",
1346             .version_id   = 0,
1347             .field_exists = NULL,
1348             .size         = 0,
1349             .info         = &vmstate_info_extra_state,
1350             .flags        = VMS_SINGLE,
1351             .offset       = 0,
1352         },
1353         VMSTATE_END_OF_LIST()
1354     }
1355 };
1356 
1357 static const VMStateDescription vmstate_virtio_device_endian = {
1358     .name = "virtio/device_endian",
1359     .version_id = 1,
1360     .minimum_version_id = 1,
1361     .needed = &virtio_device_endian_needed,
1362     .fields = (VMStateField[]) {
1363         VMSTATE_UINT8(device_endian, VirtIODevice),
1364         VMSTATE_END_OF_LIST()
1365     }
1366 };
1367 
1368 static const VMStateDescription vmstate_virtio_64bit_features = {
1369     .name = "virtio/64bit_features",
1370     .version_id = 1,
1371     .minimum_version_id = 1,
1372     .needed = &virtio_64bit_features_needed,
1373     .fields = (VMStateField[]) {
1374         VMSTATE_UINT64(guest_features, VirtIODevice),
1375         VMSTATE_END_OF_LIST()
1376     }
1377 };
1378 
1379 static const VMStateDescription vmstate_virtio = {
1380     .name = "virtio",
1381     .version_id = 1,
1382     .minimum_version_id = 1,
1383     .minimum_version_id_old = 1,
1384     .fields = (VMStateField[]) {
1385         VMSTATE_END_OF_LIST()
1386     },
1387     .subsections = (const VMStateDescription*[]) {
1388         &vmstate_virtio_device_endian,
1389         &vmstate_virtio_64bit_features,
1390         &vmstate_virtio_virtqueues,
1391         &vmstate_virtio_ringsize,
1392         &vmstate_virtio_extra_state,
1393         NULL
1394     }
1395 };
1396 
1397 void virtio_save(VirtIODevice *vdev, QEMUFile *f)
1398 {
1399     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1400     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1401     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1402     uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
1403     int i;
1404 
1405     if (k->save_config) {
1406         k->save_config(qbus->parent, f);
1407     }
1408 
1409     qemu_put_8s(f, &vdev->status);
1410     qemu_put_8s(f, &vdev->isr);
1411     qemu_put_be16s(f, &vdev->queue_sel);
1412     qemu_put_be32s(f, &guest_features_lo);
1413     qemu_put_be32(f, vdev->config_len);
1414     qemu_put_buffer(f, vdev->config, vdev->config_len);
1415 
1416     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1417         if (vdev->vq[i].vring.num == 0)
1418             break;
1419     }
1420 
1421     qemu_put_be32(f, i);
1422 
1423     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1424         if (vdev->vq[i].vring.num == 0)
1425             break;
1426 
1427         qemu_put_be32(f, vdev->vq[i].vring.num);
1428         if (k->has_variable_vring_alignment) {
1429             qemu_put_be32(f, vdev->vq[i].vring.align);
1430         }
1431         /* XXX virtio-1 devices */
1432         qemu_put_be64(f, vdev->vq[i].vring.desc);
1433         qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
1434         if (k->save_queue) {
1435             k->save_queue(qbus->parent, i, f);
1436         }
1437     }
1438 
1439     if (vdc->save != NULL) {
1440         vdc->save(vdev, f);
1441     }
1442 
1443     /* Subsections */
1444     vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
1445 }
1446 
1447 static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
1448 {
1449     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1450     bool bad = (val & ~(vdev->host_features)) != 0;
1451 
1452     val &= vdev->host_features;
1453     if (k->set_features) {
1454         k->set_features(vdev, val);
1455     }
1456     vdev->guest_features = val;
1457     return bad ? -1 : 0;
1458 }
1459 
1460 int virtio_set_features(VirtIODevice *vdev, uint64_t val)
1461 {
1462    /*
1463      * The driver must not attempt to set features after feature negotiation
1464      * has finished.
1465      */
1466     if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
1467         return -EINVAL;
1468     }
1469     return virtio_set_features_nocheck(vdev, val);
1470 }
1471 
1472 int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
1473 {
1474     int i, ret;
1475     int32_t config_len;
1476     uint32_t num;
1477     uint32_t features;
1478     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1479     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1480     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1481 
1482     /*
1483      * We poison the endianness to ensure it does not get used before
1484      * subsections have been loaded.
1485      */
1486     vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
1487 
1488     if (k->load_config) {
1489         ret = k->load_config(qbus->parent, f);
1490         if (ret)
1491             return ret;
1492     }
1493 
1494     qemu_get_8s(f, &vdev->status);
1495     qemu_get_8s(f, &vdev->isr);
1496     qemu_get_be16s(f, &vdev->queue_sel);
1497     if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
1498         return -1;
1499     }
1500     qemu_get_be32s(f, &features);
1501 
1502     config_len = qemu_get_be32(f);
1503 
1504     /*
1505      * There are cases where the incoming config can be bigger or smaller
1506      * than what we have; so load what we have space for, and skip
1507      * any excess that's in the stream.
1508      */
1509     qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
1510 
1511     while (config_len > vdev->config_len) {
1512         qemu_get_byte(f);
1513         config_len--;
1514     }
1515 
1516     num = qemu_get_be32(f);
1517 
1518     if (num > VIRTIO_QUEUE_MAX) {
1519         error_report("Invalid number of virtqueues: 0x%x", num);
1520         return -1;
1521     }
1522 
1523     for (i = 0; i < num; i++) {
1524         vdev->vq[i].vring.num = qemu_get_be32(f);
1525         if (k->has_variable_vring_alignment) {
1526             vdev->vq[i].vring.align = qemu_get_be32(f);
1527         }
1528         vdev->vq[i].vring.desc = qemu_get_be64(f);
1529         qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
1530         vdev->vq[i].signalled_used_valid = false;
1531         vdev->vq[i].notification = true;
1532 
1533         if (vdev->vq[i].vring.desc) {
1534             /* XXX virtio-1 devices */
1535             virtio_queue_update_rings(vdev, i);
1536         } else if (vdev->vq[i].last_avail_idx) {
1537             error_report("VQ %d address 0x0 "
1538                          "inconsistent with Host index 0x%x",
1539                          i, vdev->vq[i].last_avail_idx);
1540                 return -1;
1541 	}
1542         if (k->load_queue) {
1543             ret = k->load_queue(qbus->parent, i, f);
1544             if (ret)
1545                 return ret;
1546         }
1547     }
1548 
1549     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
1550 
1551     if (vdc->load != NULL) {
1552         ret = vdc->load(vdev, f, version_id);
1553         if (ret) {
1554             return ret;
1555         }
1556     }
1557 
1558     /* Subsections */
1559     ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
1560     if (ret) {
1561         return ret;
1562     }
1563 
1564     if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
1565         vdev->device_endian = virtio_default_endian();
1566     }
1567 
1568     if (virtio_64bit_features_needed(vdev)) {
1569         /*
1570          * Subsection load filled vdev->guest_features.  Run them
1571          * through virtio_set_features to sanity-check them against
1572          * host_features.
1573          */
1574         uint64_t features64 = vdev->guest_features;
1575         if (virtio_set_features_nocheck(vdev, features64) < 0) {
1576             error_report("Features 0x%" PRIx64 " unsupported. "
1577                          "Allowed features: 0x%" PRIx64,
1578                          features64, vdev->host_features);
1579             return -1;
1580         }
1581     } else {
1582         if (virtio_set_features_nocheck(vdev, features) < 0) {
1583             error_report("Features 0x%x unsupported. "
1584                          "Allowed features: 0x%" PRIx64,
1585                          features, vdev->host_features);
1586             return -1;
1587         }
1588     }
1589 
1590     for (i = 0; i < num; i++) {
1591         if (vdev->vq[i].vring.desc) {
1592             uint16_t nheads;
1593             nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
1594             /* Check it isn't doing strange things with descriptor numbers. */
1595             if (nheads > vdev->vq[i].vring.num) {
1596                 error_report("VQ %d size 0x%x Guest index 0x%x "
1597                              "inconsistent with Host index 0x%x: delta 0x%x",
1598                              i, vdev->vq[i].vring.num,
1599                              vring_avail_idx(&vdev->vq[i]),
1600                              vdev->vq[i].last_avail_idx, nheads);
1601                 return -1;
1602             }
1603             vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
1604             vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
1605         }
1606     }
1607 
1608     return 0;
1609 }
1610 
1611 void virtio_cleanup(VirtIODevice *vdev)
1612 {
1613     qemu_del_vm_change_state_handler(vdev->vmstate);
1614     g_free(vdev->config);
1615     g_free(vdev->vq);
1616     g_free(vdev->vector_queues);
1617 }
1618 
1619 static void virtio_vmstate_change(void *opaque, int running, RunState state)
1620 {
1621     VirtIODevice *vdev = opaque;
1622     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1623     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1624     bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
1625     vdev->vm_running = running;
1626 
1627     if (backend_run) {
1628         virtio_set_status(vdev, vdev->status);
1629     }
1630 
1631     if (k->vmstate_change) {
1632         k->vmstate_change(qbus->parent, backend_run);
1633     }
1634 
1635     if (!backend_run) {
1636         virtio_set_status(vdev, vdev->status);
1637     }
1638 }
1639 
1640 void virtio_instance_init_common(Object *proxy_obj, void *data,
1641                                  size_t vdev_size, const char *vdev_name)
1642 {
1643     DeviceState *vdev = data;
1644 
1645     object_initialize(vdev, vdev_size, vdev_name);
1646     object_property_add_child(proxy_obj, "virtio-backend", OBJECT(vdev), NULL);
1647     object_unref(OBJECT(vdev));
1648     qdev_alias_all_properties(vdev, proxy_obj);
1649 }
1650 
1651 void virtio_init(VirtIODevice *vdev, const char *name,
1652                  uint16_t device_id, size_t config_size)
1653 {
1654     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1655     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1656     int i;
1657     int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
1658 
1659     if (nvectors) {
1660         vdev->vector_queues =
1661             g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
1662     }
1663 
1664     vdev->device_id = device_id;
1665     vdev->status = 0;
1666     vdev->isr = 0;
1667     vdev->queue_sel = 0;
1668     vdev->config_vector = VIRTIO_NO_VECTOR;
1669     vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);
1670     vdev->vm_running = runstate_is_running();
1671     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1672         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
1673         vdev->vq[i].vdev = vdev;
1674         vdev->vq[i].queue_index = i;
1675     }
1676 
1677     vdev->name = name;
1678     vdev->config_len = config_size;
1679     if (vdev->config_len) {
1680         vdev->config = g_malloc0(config_size);
1681     } else {
1682         vdev->config = NULL;
1683     }
1684     vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
1685                                                      vdev);
1686     vdev->device_endian = virtio_default_endian();
1687     vdev->use_guest_notifier_mask = true;
1688 }
1689 
1690 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
1691 {
1692     return vdev->vq[n].vring.desc;
1693 }
1694 
1695 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
1696 {
1697     return vdev->vq[n].vring.avail;
1698 }
1699 
1700 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
1701 {
1702     return vdev->vq[n].vring.used;
1703 }
1704 
1705 hwaddr virtio_queue_get_ring_addr(VirtIODevice *vdev, int n)
1706 {
1707     return vdev->vq[n].vring.desc;
1708 }
1709 
1710 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
1711 {
1712     return sizeof(VRingDesc) * vdev->vq[n].vring.num;
1713 }
1714 
1715 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
1716 {
1717     return offsetof(VRingAvail, ring) +
1718         sizeof(uint16_t) * vdev->vq[n].vring.num;
1719 }
1720 
1721 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
1722 {
1723     return offsetof(VRingUsed, ring) +
1724         sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
1725 }
1726 
1727 hwaddr virtio_queue_get_ring_size(VirtIODevice *vdev, int n)
1728 {
1729     return vdev->vq[n].vring.used - vdev->vq[n].vring.desc +
1730 	    virtio_queue_get_used_size(vdev, n);
1731 }
1732 
1733 uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
1734 {
1735     return vdev->vq[n].last_avail_idx;
1736 }
1737 
1738 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
1739 {
1740     vdev->vq[n].last_avail_idx = idx;
1741     vdev->vq[n].shadow_avail_idx = idx;
1742 }
1743 
1744 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
1745 {
1746     vdev->vq[n].signalled_used_valid = false;
1747 }
1748 
1749 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
1750 {
1751     return vdev->vq + n;
1752 }
1753 
1754 uint16_t virtio_get_queue_index(VirtQueue *vq)
1755 {
1756     return vq->queue_index;
1757 }
1758 
1759 static void virtio_queue_guest_notifier_read(EventNotifier *n)
1760 {
1761     VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
1762     if (event_notifier_test_and_clear(n)) {
1763         virtio_irq(vq);
1764     }
1765 }
1766 
1767 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
1768                                                 bool with_irqfd)
1769 {
1770     if (assign && !with_irqfd) {
1771         event_notifier_set_handler(&vq->guest_notifier, false,
1772                                    virtio_queue_guest_notifier_read);
1773     } else {
1774         event_notifier_set_handler(&vq->guest_notifier, false, NULL);
1775     }
1776     if (!assign) {
1777         /* Test and clear notifier before closing it,
1778          * in case poll callback didn't have time to run. */
1779         virtio_queue_guest_notifier_read(&vq->guest_notifier);
1780     }
1781 }
1782 
1783 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
1784 {
1785     return &vq->guest_notifier;
1786 }
1787 
1788 static void virtio_queue_host_notifier_aio_read(EventNotifier *n)
1789 {
1790     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
1791     if (event_notifier_test_and_clear(n)) {
1792         virtio_queue_notify_aio_vq(vq);
1793     }
1794 }
1795 
1796 void virtio_queue_aio_set_host_notifier_handler(VirtQueue *vq, AioContext *ctx,
1797                                                 void (*handle_output)(VirtIODevice *,
1798                                                                       VirtQueue *))
1799 {
1800     if (handle_output) {
1801         vq->handle_aio_output = handle_output;
1802         aio_set_event_notifier(ctx, &vq->host_notifier, true,
1803                                virtio_queue_host_notifier_aio_read);
1804     } else {
1805         aio_set_event_notifier(ctx, &vq->host_notifier, true, NULL);
1806         /* Test and clear notifier before after disabling event,
1807          * in case poll callback didn't have time to run. */
1808         virtio_queue_host_notifier_aio_read(&vq->host_notifier);
1809         vq->handle_aio_output = NULL;
1810     }
1811 }
1812 
1813 static void virtio_queue_host_notifier_read(EventNotifier *n)
1814 {
1815     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
1816     if (event_notifier_test_and_clear(n)) {
1817         virtio_queue_notify_vq(vq);
1818     }
1819 }
1820 
1821 void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
1822                                                bool set_handler)
1823 {
1824     if (assign && set_handler) {
1825         event_notifier_set_handler(&vq->host_notifier, true,
1826                                    virtio_queue_host_notifier_read);
1827     } else {
1828         event_notifier_set_handler(&vq->host_notifier, true, NULL);
1829     }
1830     if (!assign) {
1831         /* Test and clear notifier before after disabling event,
1832          * in case poll callback didn't have time to run. */
1833         virtio_queue_host_notifier_read(&vq->host_notifier);
1834     }
1835 }
1836 
1837 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
1838 {
1839     return &vq->host_notifier;
1840 }
1841 
1842 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
1843 {
1844     g_free(vdev->bus_name);
1845     vdev->bus_name = g_strdup(bus_name);
1846 }
1847 
1848 static void virtio_device_realize(DeviceState *dev, Error **errp)
1849 {
1850     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1851     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1852     Error *err = NULL;
1853 
1854     if (vdc->realize != NULL) {
1855         vdc->realize(dev, &err);
1856         if (err != NULL) {
1857             error_propagate(errp, err);
1858             return;
1859         }
1860     }
1861 
1862     virtio_bus_device_plugged(vdev, &err);
1863     if (err != NULL) {
1864         error_propagate(errp, err);
1865         return;
1866     }
1867 }
1868 
1869 static void virtio_device_unrealize(DeviceState *dev, Error **errp)
1870 {
1871     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1872     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1873     Error *err = NULL;
1874 
1875     virtio_bus_device_unplugged(vdev);
1876 
1877     if (vdc->unrealize != NULL) {
1878         vdc->unrealize(dev, &err);
1879         if (err != NULL) {
1880             error_propagate(errp, err);
1881             return;
1882         }
1883     }
1884 
1885     g_free(vdev->bus_name);
1886     vdev->bus_name = NULL;
1887 }
1888 
1889 static Property virtio_properties[] = {
1890     DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
1891     DEFINE_PROP_END_OF_LIST(),
1892 };
1893 
1894 static void virtio_device_class_init(ObjectClass *klass, void *data)
1895 {
1896     /* Set the default value here. */
1897     DeviceClass *dc = DEVICE_CLASS(klass);
1898 
1899     dc->realize = virtio_device_realize;
1900     dc->unrealize = virtio_device_unrealize;
1901     dc->bus_type = TYPE_VIRTIO_BUS;
1902     dc->props = virtio_properties;
1903 }
1904 
1905 static const TypeInfo virtio_device_info = {
1906     .name = TYPE_VIRTIO_DEVICE,
1907     .parent = TYPE_DEVICE,
1908     .instance_size = sizeof(VirtIODevice),
1909     .class_init = virtio_device_class_init,
1910     .abstract = true,
1911     .class_size = sizeof(VirtioDeviceClass),
1912 };
1913 
1914 static void virtio_register_types(void)
1915 {
1916     type_register_static(&virtio_device_info);
1917 }
1918 
1919 type_init(virtio_register_types)
1920