xref: /openbmc/qemu/hw/virtio/virtio.c (revision 52f91c37)
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 <inttypes.h>
15 
16 #include "trace.h"
17 #include "exec/address-spaces.h"
18 #include "qemu/error-report.h"
19 #include "hw/virtio/virtio.h"
20 #include "qemu/atomic.h"
21 #include "hw/virtio/virtio-bus.h"
22 
23 /*
24  * The alignment to use between consumer and producer parts of vring.
25  * x86 pagesize again. This is the default, used by transports like PCI
26  * which don't provide a means for the guest to tell the host the alignment.
27  */
28 #define VIRTIO_PCI_VRING_ALIGN         4096
29 
30 typedef struct VRingDesc
31 {
32     uint64_t addr;
33     uint32_t len;
34     uint16_t flags;
35     uint16_t next;
36 } VRingDesc;
37 
38 typedef struct VRingAvail
39 {
40     uint16_t flags;
41     uint16_t idx;
42     uint16_t ring[0];
43 } VRingAvail;
44 
45 typedef struct VRingUsedElem
46 {
47     uint32_t id;
48     uint32_t len;
49 } VRingUsedElem;
50 
51 typedef struct VRingUsed
52 {
53     uint16_t flags;
54     uint16_t idx;
55     VRingUsedElem ring[0];
56 } VRingUsed;
57 
58 typedef struct VRing
59 {
60     unsigned int num;
61     unsigned int align;
62     hwaddr desc;
63     hwaddr avail;
64     hwaddr used;
65 } VRing;
66 
67 struct VirtQueue
68 {
69     VRing vring;
70     hwaddr pa;
71     uint16_t last_avail_idx;
72     /* Last used index value we have signalled on */
73     uint16_t signalled_used;
74 
75     /* Last used index value we have signalled on */
76     bool signalled_used_valid;
77 
78     /* Notification enabled? */
79     bool notification;
80 
81     uint16_t queue_index;
82 
83     int inuse;
84 
85     uint16_t vector;
86     void (*handle_output)(VirtIODevice *vdev, VirtQueue *vq);
87     VirtIODevice *vdev;
88     EventNotifier guest_notifier;
89     EventNotifier host_notifier;
90 };
91 
92 /* virt queue functions */
93 static void virtqueue_init(VirtQueue *vq)
94 {
95     hwaddr pa = vq->pa;
96 
97     vq->vring.desc = pa;
98     vq->vring.avail = pa + vq->vring.num * sizeof(VRingDesc);
99     vq->vring.used = vring_align(vq->vring.avail +
100                                  offsetof(VRingAvail, ring[vq->vring.num]),
101                                  vq->vring.align);
102 }
103 
104 static inline uint64_t vring_desc_addr(hwaddr desc_pa, int i)
105 {
106     hwaddr pa;
107     pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, addr);
108     return ldq_phys(&address_space_memory, pa);
109 }
110 
111 static inline uint32_t vring_desc_len(hwaddr desc_pa, int i)
112 {
113     hwaddr pa;
114     pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, len);
115     return ldl_phys(&address_space_memory, pa);
116 }
117 
118 static inline uint16_t vring_desc_flags(hwaddr desc_pa, int i)
119 {
120     hwaddr pa;
121     pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, flags);
122     return lduw_phys(&address_space_memory, pa);
123 }
124 
125 static inline uint16_t vring_desc_next(hwaddr desc_pa, int i)
126 {
127     hwaddr pa;
128     pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, next);
129     return lduw_phys(&address_space_memory, pa);
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 lduw_phys(&address_space_memory, 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     return lduw_phys(&address_space_memory, pa);
144 }
145 
146 static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
147 {
148     hwaddr pa;
149     pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
150     return lduw_phys(&address_space_memory, pa);
151 }
152 
153 static inline uint16_t vring_used_event(VirtQueue *vq)
154 {
155     return vring_avail_ring(vq, vq->vring.num);
156 }
157 
158 static inline void vring_used_ring_id(VirtQueue *vq, int i, uint32_t val)
159 {
160     hwaddr pa;
161     pa = vq->vring.used + offsetof(VRingUsed, ring[i].id);
162     stl_phys(&address_space_memory, pa, val);
163 }
164 
165 static inline void vring_used_ring_len(VirtQueue *vq, int i, uint32_t val)
166 {
167     hwaddr pa;
168     pa = vq->vring.used + offsetof(VRingUsed, ring[i].len);
169     stl_phys(&address_space_memory, pa, val);
170 }
171 
172 static uint16_t vring_used_idx(VirtQueue *vq)
173 {
174     hwaddr pa;
175     pa = vq->vring.used + offsetof(VRingUsed, idx);
176     return lduw_phys(&address_space_memory, pa);
177 }
178 
179 static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
180 {
181     hwaddr pa;
182     pa = vq->vring.used + offsetof(VRingUsed, idx);
183     stw_phys(&address_space_memory, pa, val);
184 }
185 
186 static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
187 {
188     hwaddr pa;
189     pa = vq->vring.used + offsetof(VRingUsed, flags);
190     stw_phys(&address_space_memory,
191              pa, lduw_phys(&address_space_memory, pa) | mask);
192 }
193 
194 static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
195 {
196     hwaddr pa;
197     pa = vq->vring.used + offsetof(VRingUsed, flags);
198     stw_phys(&address_space_memory,
199              pa, lduw_phys(&address_space_memory, pa) & ~mask);
200 }
201 
202 static inline void vring_avail_event(VirtQueue *vq, uint16_t val)
203 {
204     hwaddr pa;
205     if (!vq->notification) {
206         return;
207     }
208     pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
209     stw_phys(&address_space_memory, pa, val);
210 }
211 
212 void virtio_queue_set_notification(VirtQueue *vq, int enable)
213 {
214     vq->notification = enable;
215     if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
216         vring_avail_event(vq, vring_avail_idx(vq));
217     } else if (enable) {
218         vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
219     } else {
220         vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
221     }
222     if (enable) {
223         /* Expose avail event/used flags before caller checks the avail idx. */
224         smp_mb();
225     }
226 }
227 
228 int virtio_queue_ready(VirtQueue *vq)
229 {
230     return vq->vring.avail != 0;
231 }
232 
233 int virtio_queue_empty(VirtQueue *vq)
234 {
235     return vring_avail_idx(vq) == vq->last_avail_idx;
236 }
237 
238 void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
239                     unsigned int len, unsigned int idx)
240 {
241     unsigned int offset;
242     int i;
243 
244     trace_virtqueue_fill(vq, elem, len, idx);
245 
246     offset = 0;
247     for (i = 0; i < elem->in_num; i++) {
248         size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
249 
250         cpu_physical_memory_unmap(elem->in_sg[i].iov_base,
251                                   elem->in_sg[i].iov_len,
252                                   1, size);
253 
254         offset += size;
255     }
256 
257     for (i = 0; i < elem->out_num; i++)
258         cpu_physical_memory_unmap(elem->out_sg[i].iov_base,
259                                   elem->out_sg[i].iov_len,
260                                   0, elem->out_sg[i].iov_len);
261 
262     idx = (idx + vring_used_idx(vq)) % vq->vring.num;
263 
264     /* Get a pointer to the next entry in the used ring. */
265     vring_used_ring_id(vq, idx, elem->index);
266     vring_used_ring_len(vq, idx, len);
267 }
268 
269 void virtqueue_flush(VirtQueue *vq, unsigned int count)
270 {
271     uint16_t old, new;
272     /* Make sure buffer is written before we update index. */
273     smp_wmb();
274     trace_virtqueue_flush(vq, count);
275     old = vring_used_idx(vq);
276     new = old + count;
277     vring_used_idx_set(vq, new);
278     vq->inuse -= count;
279     if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
280         vq->signalled_used_valid = false;
281 }
282 
283 void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
284                     unsigned int len)
285 {
286     virtqueue_fill(vq, elem, len, 0);
287     virtqueue_flush(vq, 1);
288 }
289 
290 static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
291 {
292     uint16_t num_heads = vring_avail_idx(vq) - idx;
293 
294     /* Check it isn't doing very strange things with descriptor numbers. */
295     if (num_heads > vq->vring.num) {
296         error_report("Guest moved used index from %u to %u",
297                      idx, vring_avail_idx(vq));
298         exit(1);
299     }
300     /* On success, callers read a descriptor at vq->last_avail_idx.
301      * Make sure descriptor read does not bypass avail index read. */
302     if (num_heads) {
303         smp_rmb();
304     }
305 
306     return num_heads;
307 }
308 
309 static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx)
310 {
311     unsigned int head;
312 
313     /* Grab the next descriptor number they're advertising, and increment
314      * the index we've seen. */
315     head = vring_avail_ring(vq, idx % vq->vring.num);
316 
317     /* If their number is silly, that's a fatal mistake. */
318     if (head >= vq->vring.num) {
319         error_report("Guest says index %u is available", head);
320         exit(1);
321     }
322 
323     return head;
324 }
325 
326 static unsigned virtqueue_next_desc(hwaddr desc_pa,
327                                     unsigned int i, unsigned int max)
328 {
329     unsigned int next;
330 
331     /* If this descriptor says it doesn't chain, we're done. */
332     if (!(vring_desc_flags(desc_pa, i) & VRING_DESC_F_NEXT))
333         return max;
334 
335     /* Check they're not leading us off end of descriptors. */
336     next = vring_desc_next(desc_pa, i);
337     /* Make sure compiler knows to grab that: we don't want it changing! */
338     smp_wmb();
339 
340     if (next >= max) {
341         error_report("Desc next is %u", next);
342         exit(1);
343     }
344 
345     return next;
346 }
347 
348 void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
349                                unsigned int *out_bytes,
350                                unsigned max_in_bytes, unsigned max_out_bytes)
351 {
352     unsigned int idx;
353     unsigned int total_bufs, in_total, out_total;
354 
355     idx = vq->last_avail_idx;
356 
357     total_bufs = in_total = out_total = 0;
358     while (virtqueue_num_heads(vq, idx)) {
359         unsigned int max, num_bufs, indirect = 0;
360         hwaddr desc_pa;
361         int i;
362 
363         max = vq->vring.num;
364         num_bufs = total_bufs;
365         i = virtqueue_get_head(vq, idx++);
366         desc_pa = vq->vring.desc;
367 
368         if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
369             if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
370                 error_report("Invalid size for indirect buffer table");
371                 exit(1);
372             }
373 
374             /* If we've got too many, that implies a descriptor loop. */
375             if (num_bufs >= max) {
376                 error_report("Looped descriptor");
377                 exit(1);
378             }
379 
380             /* loop over the indirect descriptor table */
381             indirect = 1;
382             max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
383             desc_pa = vring_desc_addr(desc_pa, i);
384             num_bufs = i = 0;
385         }
386 
387         do {
388             /* If we've got too many, that implies a descriptor loop. */
389             if (++num_bufs > max) {
390                 error_report("Looped descriptor");
391                 exit(1);
392             }
393 
394             if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
395                 in_total += vring_desc_len(desc_pa, i);
396             } else {
397                 out_total += vring_desc_len(desc_pa, i);
398             }
399             if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
400                 goto done;
401             }
402         } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
403 
404         if (!indirect)
405             total_bufs = num_bufs;
406         else
407             total_bufs++;
408     }
409 done:
410     if (in_bytes) {
411         *in_bytes = in_total;
412     }
413     if (out_bytes) {
414         *out_bytes = out_total;
415     }
416 }
417 
418 int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
419                           unsigned int out_bytes)
420 {
421     unsigned int in_total, out_total;
422 
423     virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
424     return in_bytes <= in_total && out_bytes <= out_total;
425 }
426 
427 void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
428     size_t num_sg, int is_write)
429 {
430     unsigned int i;
431     hwaddr len;
432 
433     if (num_sg >= VIRTQUEUE_MAX_SIZE) {
434         error_report("virtio: map attempt out of bounds: %zd > %d",
435                      num_sg, VIRTQUEUE_MAX_SIZE);
436         exit(1);
437     }
438 
439     for (i = 0; i < num_sg; i++) {
440         len = sg[i].iov_len;
441         sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
442         if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
443             error_report("virtio: trying to map MMIO memory");
444             exit(1);
445         }
446     }
447 }
448 
449 int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem)
450 {
451     unsigned int i, head, max;
452     hwaddr desc_pa = vq->vring.desc;
453 
454     if (!virtqueue_num_heads(vq, vq->last_avail_idx))
455         return 0;
456 
457     /* When we start there are none of either input nor output. */
458     elem->out_num = elem->in_num = 0;
459 
460     max = vq->vring.num;
461 
462     i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
463     if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
464         vring_avail_event(vq, vring_avail_idx(vq));
465     }
466 
467     if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
468         if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
469             error_report("Invalid size for indirect buffer table");
470             exit(1);
471         }
472 
473         /* loop over the indirect descriptor table */
474         max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
475         desc_pa = vring_desc_addr(desc_pa, i);
476         i = 0;
477     }
478 
479     /* Collect all the descriptors */
480     do {
481         struct iovec *sg;
482 
483         if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
484             if (elem->in_num >= ARRAY_SIZE(elem->in_sg)) {
485                 error_report("Too many write descriptors in indirect table");
486                 exit(1);
487             }
488             elem->in_addr[elem->in_num] = vring_desc_addr(desc_pa, i);
489             sg = &elem->in_sg[elem->in_num++];
490         } else {
491             if (elem->out_num >= ARRAY_SIZE(elem->out_sg)) {
492                 error_report("Too many read descriptors in indirect table");
493                 exit(1);
494             }
495             elem->out_addr[elem->out_num] = vring_desc_addr(desc_pa, i);
496             sg = &elem->out_sg[elem->out_num++];
497         }
498 
499         sg->iov_len = vring_desc_len(desc_pa, i);
500 
501         /* If we've got too many, that implies a descriptor loop. */
502         if ((elem->in_num + elem->out_num) > max) {
503             error_report("Looped descriptor");
504             exit(1);
505         }
506     } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
507 
508     /* Now map what we have collected */
509     virtqueue_map_sg(elem->in_sg, elem->in_addr, elem->in_num, 1);
510     virtqueue_map_sg(elem->out_sg, elem->out_addr, elem->out_num, 0);
511 
512     elem->index = head;
513 
514     vq->inuse++;
515 
516     trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
517     return elem->in_num + elem->out_num;
518 }
519 
520 /* virtio device */
521 static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
522 {
523     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
524     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
525 
526     if (k->notify) {
527         k->notify(qbus->parent, vector);
528     }
529 }
530 
531 void virtio_update_irq(VirtIODevice *vdev)
532 {
533     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
534 }
535 
536 void virtio_set_status(VirtIODevice *vdev, uint8_t val)
537 {
538     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
539     trace_virtio_set_status(vdev, val);
540 
541     if (k->set_status) {
542         k->set_status(vdev, val);
543     }
544     vdev->status = val;
545 }
546 
547 void virtio_reset(void *opaque)
548 {
549     VirtIODevice *vdev = opaque;
550     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
551     int i;
552 
553     virtio_set_status(vdev, 0);
554 
555     if (k->reset) {
556         k->reset(vdev);
557     }
558 
559     vdev->guest_features = 0;
560     vdev->queue_sel = 0;
561     vdev->status = 0;
562     vdev->isr = 0;
563     vdev->config_vector = VIRTIO_NO_VECTOR;
564     virtio_notify_vector(vdev, vdev->config_vector);
565 
566     for(i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
567         vdev->vq[i].vring.desc = 0;
568         vdev->vq[i].vring.avail = 0;
569         vdev->vq[i].vring.used = 0;
570         vdev->vq[i].last_avail_idx = 0;
571         vdev->vq[i].pa = 0;
572         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
573         vdev->vq[i].signalled_used = 0;
574         vdev->vq[i].signalled_used_valid = false;
575         vdev->vq[i].notification = true;
576     }
577 }
578 
579 uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
580 {
581     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
582     uint8_t val;
583 
584     if (addr + sizeof(val) > vdev->config_len) {
585         return (uint32_t)-1;
586     }
587 
588     k->get_config(vdev, vdev->config);
589 
590     val = ldub_p(vdev->config + addr);
591     return val;
592 }
593 
594 uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
595 {
596     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
597     uint16_t val;
598 
599     if (addr + sizeof(val) > vdev->config_len) {
600         return (uint32_t)-1;
601     }
602 
603     k->get_config(vdev, vdev->config);
604 
605     val = lduw_p(vdev->config + addr);
606     return val;
607 }
608 
609 uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
610 {
611     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
612     uint32_t val;
613 
614     if (addr + sizeof(val) > vdev->config_len) {
615         return (uint32_t)-1;
616     }
617 
618     k->get_config(vdev, vdev->config);
619 
620     val = ldl_p(vdev->config + addr);
621     return val;
622 }
623 
624 void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
625 {
626     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
627     uint8_t val = data;
628 
629     if (addr + sizeof(val) > vdev->config_len) {
630         return;
631     }
632 
633     stb_p(vdev->config + addr, val);
634 
635     if (k->set_config) {
636         k->set_config(vdev, vdev->config);
637     }
638 }
639 
640 void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
641 {
642     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
643     uint16_t val = data;
644 
645     if (addr + sizeof(val) > vdev->config_len) {
646         return;
647     }
648 
649     stw_p(vdev->config + addr, val);
650 
651     if (k->set_config) {
652         k->set_config(vdev, vdev->config);
653     }
654 }
655 
656 void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
657 {
658     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
659     uint32_t val = data;
660 
661     if (addr + sizeof(val) > vdev->config_len) {
662         return;
663     }
664 
665     stl_p(vdev->config + addr, val);
666 
667     if (k->set_config) {
668         k->set_config(vdev, vdev->config);
669     }
670 }
671 
672 void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
673 {
674     vdev->vq[n].pa = addr;
675     virtqueue_init(&vdev->vq[n]);
676 }
677 
678 hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
679 {
680     return vdev->vq[n].pa;
681 }
682 
683 void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
684 {
685     /* Don't allow guest to flip queue between existent and
686      * nonexistent states, or to set it to an invalid size.
687      */
688     if (!!num != !!vdev->vq[n].vring.num ||
689         num > VIRTQUEUE_MAX_SIZE ||
690         num < 0) {
691         return;
692     }
693     vdev->vq[n].vring.num = num;
694     virtqueue_init(&vdev->vq[n]);
695 }
696 
697 int virtio_queue_get_num(VirtIODevice *vdev, int n)
698 {
699     return vdev->vq[n].vring.num;
700 }
701 
702 int virtio_queue_get_id(VirtQueue *vq)
703 {
704     VirtIODevice *vdev = vq->vdev;
705     assert(vq >= &vdev->vq[0] && vq < &vdev->vq[VIRTIO_PCI_QUEUE_MAX]);
706     return vq - &vdev->vq[0];
707 }
708 
709 void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
710 {
711     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
712     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
713 
714     /* Check that the transport told us it was going to do this
715      * (so a buggy transport will immediately assert rather than
716      * silently failing to migrate this state)
717      */
718     assert(k->has_variable_vring_alignment);
719 
720     vdev->vq[n].vring.align = align;
721     virtqueue_init(&vdev->vq[n]);
722 }
723 
724 void virtio_queue_notify_vq(VirtQueue *vq)
725 {
726     if (vq->vring.desc) {
727         VirtIODevice *vdev = vq->vdev;
728         trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
729         vq->handle_output(vdev, vq);
730     }
731 }
732 
733 void virtio_queue_notify(VirtIODevice *vdev, int n)
734 {
735     virtio_queue_notify_vq(&vdev->vq[n]);
736 }
737 
738 uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
739 {
740     return n < VIRTIO_PCI_QUEUE_MAX ? vdev->vq[n].vector :
741         VIRTIO_NO_VECTOR;
742 }
743 
744 void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
745 {
746     if (n < VIRTIO_PCI_QUEUE_MAX)
747         vdev->vq[n].vector = vector;
748 }
749 
750 VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
751                             void (*handle_output)(VirtIODevice *, VirtQueue *))
752 {
753     int i;
754 
755     for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
756         if (vdev->vq[i].vring.num == 0)
757             break;
758     }
759 
760     if (i == VIRTIO_PCI_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
761         abort();
762 
763     vdev->vq[i].vring.num = queue_size;
764     vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
765     vdev->vq[i].handle_output = handle_output;
766 
767     return &vdev->vq[i];
768 }
769 
770 void virtio_del_queue(VirtIODevice *vdev, int n)
771 {
772     if (n < 0 || n >= VIRTIO_PCI_QUEUE_MAX) {
773         abort();
774     }
775 
776     vdev->vq[n].vring.num = 0;
777 }
778 
779 void virtio_irq(VirtQueue *vq)
780 {
781     trace_virtio_irq(vq);
782     vq->vdev->isr |= 0x01;
783     virtio_notify_vector(vq->vdev, vq->vector);
784 }
785 
786 /* Assuming a given event_idx value from the other size, if
787  * we have just incremented index from old to new_idx,
788  * should we trigger an event? */
789 static inline int vring_need_event(uint16_t event, uint16_t new, uint16_t old)
790 {
791 	/* Note: Xen has similar logic for notification hold-off
792 	 * in include/xen/interface/io/ring.h with req_event and req_prod
793 	 * corresponding to event_idx + 1 and new respectively.
794 	 * Note also that req_event and req_prod in Xen start at 1,
795 	 * event indexes in virtio start at 0. */
796 	return (uint16_t)(new - event - 1) < (uint16_t)(new - old);
797 }
798 
799 static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq)
800 {
801     uint16_t old, new;
802     bool v;
803     /* We need to expose used array entries before checking used event. */
804     smp_mb();
805     /* Always notify when queue is empty (when feature acknowledge) */
806     if (((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) &&
807          !vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx)) {
808         return true;
809     }
810 
811     if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) {
812         return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
813     }
814 
815     v = vq->signalled_used_valid;
816     vq->signalled_used_valid = true;
817     old = vq->signalled_used;
818     new = vq->signalled_used = vring_used_idx(vq);
819     return !v || vring_need_event(vring_used_event(vq), new, old);
820 }
821 
822 void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
823 {
824     if (!vring_notify(vdev, vq)) {
825         return;
826     }
827 
828     trace_virtio_notify(vdev, vq);
829     vdev->isr |= 0x01;
830     virtio_notify_vector(vdev, vq->vector);
831 }
832 
833 void virtio_notify_config(VirtIODevice *vdev)
834 {
835     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
836         return;
837 
838     vdev->isr |= 0x03;
839     virtio_notify_vector(vdev, vdev->config_vector);
840 }
841 
842 void virtio_save(VirtIODevice *vdev, QEMUFile *f)
843 {
844     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
845     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
846     int i;
847 
848     if (k->save_config) {
849         k->save_config(qbus->parent, f);
850     }
851 
852     qemu_put_8s(f, &vdev->status);
853     qemu_put_8s(f, &vdev->isr);
854     qemu_put_be16s(f, &vdev->queue_sel);
855     qemu_put_be32s(f, &vdev->guest_features);
856     qemu_put_be32(f, vdev->config_len);
857     qemu_put_buffer(f, vdev->config, vdev->config_len);
858 
859     for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
860         if (vdev->vq[i].vring.num == 0)
861             break;
862     }
863 
864     qemu_put_be32(f, i);
865 
866     for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
867         if (vdev->vq[i].vring.num == 0)
868             break;
869 
870         qemu_put_be32(f, vdev->vq[i].vring.num);
871         if (k->has_variable_vring_alignment) {
872             qemu_put_be32(f, vdev->vq[i].vring.align);
873         }
874         qemu_put_be64(f, vdev->vq[i].pa);
875         qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
876         if (k->save_queue) {
877             k->save_queue(qbus->parent, i, f);
878         }
879     }
880 }
881 
882 int virtio_set_features(VirtIODevice *vdev, uint32_t val)
883 {
884     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
885     VirtioBusClass *vbusk = VIRTIO_BUS_GET_CLASS(qbus);
886     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
887     uint32_t supported_features = vbusk->get_features(qbus->parent);
888     bool bad = (val & ~supported_features) != 0;
889 
890     val &= supported_features;
891     if (k->set_features) {
892         k->set_features(vdev, val);
893     }
894     vdev->guest_features = val;
895     return bad ? -1 : 0;
896 }
897 
898 int virtio_load(VirtIODevice *vdev, QEMUFile *f)
899 {
900     int i, ret;
901     uint32_t num;
902     uint32_t features;
903     uint32_t supported_features;
904     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
905     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
906 
907     if (k->load_config) {
908         ret = k->load_config(qbus->parent, f);
909         if (ret)
910             return ret;
911     }
912 
913     qemu_get_8s(f, &vdev->status);
914     qemu_get_8s(f, &vdev->isr);
915     qemu_get_be16s(f, &vdev->queue_sel);
916     if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
917         return -1;
918     }
919     qemu_get_be32s(f, &features);
920 
921     if (virtio_set_features(vdev, features) < 0) {
922         supported_features = k->get_features(qbus->parent);
923         error_report("Features 0x%x unsupported. Allowed features: 0x%x",
924                      features, supported_features);
925         return -1;
926     }
927     vdev->config_len = qemu_get_be32(f);
928     qemu_get_buffer(f, vdev->config, vdev->config_len);
929 
930     num = qemu_get_be32(f);
931 
932     if (num > VIRTIO_PCI_QUEUE_MAX) {
933         error_report("Invalid number of PCI queues: 0x%x", num);
934         return -1;
935     }
936 
937     for (i = 0; i < num; i++) {
938         vdev->vq[i].vring.num = qemu_get_be32(f);
939         if (k->has_variable_vring_alignment) {
940             vdev->vq[i].vring.align = qemu_get_be32(f);
941         }
942         vdev->vq[i].pa = qemu_get_be64(f);
943         qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
944         vdev->vq[i].signalled_used_valid = false;
945         vdev->vq[i].notification = true;
946 
947         if (vdev->vq[i].pa) {
948             uint16_t nheads;
949             virtqueue_init(&vdev->vq[i]);
950             nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
951             /* Check it isn't doing very strange things with descriptor numbers. */
952             if (nheads > vdev->vq[i].vring.num) {
953                 error_report("VQ %d size 0x%x Guest index 0x%x "
954                              "inconsistent with Host index 0x%x: delta 0x%x",
955                              i, vdev->vq[i].vring.num,
956                              vring_avail_idx(&vdev->vq[i]),
957                              vdev->vq[i].last_avail_idx, nheads);
958                 return -1;
959             }
960         } else if (vdev->vq[i].last_avail_idx) {
961             error_report("VQ %d address 0x0 "
962                          "inconsistent with Host index 0x%x",
963                          i, vdev->vq[i].last_avail_idx);
964                 return -1;
965 	}
966         if (k->load_queue) {
967             ret = k->load_queue(qbus->parent, i, f);
968             if (ret)
969                 return ret;
970         }
971     }
972 
973     virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
974     return 0;
975 }
976 
977 void virtio_cleanup(VirtIODevice *vdev)
978 {
979     qemu_del_vm_change_state_handler(vdev->vmstate);
980     g_free(vdev->config);
981     g_free(vdev->vq);
982 }
983 
984 static void virtio_vmstate_change(void *opaque, int running, RunState state)
985 {
986     VirtIODevice *vdev = opaque;
987     BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
988     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
989     bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
990     vdev->vm_running = running;
991 
992     if (backend_run) {
993         virtio_set_status(vdev, vdev->status);
994     }
995 
996     if (k->vmstate_change) {
997         k->vmstate_change(qbus->parent, backend_run);
998     }
999 
1000     if (!backend_run) {
1001         virtio_set_status(vdev, vdev->status);
1002     }
1003 }
1004 
1005 void virtio_init(VirtIODevice *vdev, const char *name,
1006                  uint16_t device_id, size_t config_size)
1007 {
1008     int i;
1009     vdev->device_id = device_id;
1010     vdev->status = 0;
1011     vdev->isr = 0;
1012     vdev->queue_sel = 0;
1013     vdev->config_vector = VIRTIO_NO_VECTOR;
1014     vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_PCI_QUEUE_MAX);
1015     vdev->vm_running = runstate_is_running();
1016     for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
1017         vdev->vq[i].vector = VIRTIO_NO_VECTOR;
1018         vdev->vq[i].vdev = vdev;
1019         vdev->vq[i].queue_index = i;
1020     }
1021 
1022     vdev->name = name;
1023     vdev->config_len = config_size;
1024     if (vdev->config_len) {
1025         vdev->config = g_malloc0(config_size);
1026     } else {
1027         vdev->config = NULL;
1028     }
1029     vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
1030                                                      vdev);
1031 }
1032 
1033 hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
1034 {
1035     return vdev->vq[n].vring.desc;
1036 }
1037 
1038 hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
1039 {
1040     return vdev->vq[n].vring.avail;
1041 }
1042 
1043 hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
1044 {
1045     return vdev->vq[n].vring.used;
1046 }
1047 
1048 hwaddr virtio_queue_get_ring_addr(VirtIODevice *vdev, int n)
1049 {
1050     return vdev->vq[n].vring.desc;
1051 }
1052 
1053 hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
1054 {
1055     return sizeof(VRingDesc) * vdev->vq[n].vring.num;
1056 }
1057 
1058 hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
1059 {
1060     return offsetof(VRingAvail, ring) +
1061         sizeof(uint64_t) * vdev->vq[n].vring.num;
1062 }
1063 
1064 hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
1065 {
1066     return offsetof(VRingUsed, ring) +
1067         sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
1068 }
1069 
1070 hwaddr virtio_queue_get_ring_size(VirtIODevice *vdev, int n)
1071 {
1072     return vdev->vq[n].vring.used - vdev->vq[n].vring.desc +
1073 	    virtio_queue_get_used_size(vdev, n);
1074 }
1075 
1076 uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
1077 {
1078     return vdev->vq[n].last_avail_idx;
1079 }
1080 
1081 void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
1082 {
1083     vdev->vq[n].last_avail_idx = idx;
1084 }
1085 
1086 void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
1087 {
1088     vdev->vq[n].signalled_used_valid = false;
1089 }
1090 
1091 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
1092 {
1093     return vdev->vq + n;
1094 }
1095 
1096 uint16_t virtio_get_queue_index(VirtQueue *vq)
1097 {
1098     return vq->queue_index;
1099 }
1100 
1101 static void virtio_queue_guest_notifier_read(EventNotifier *n)
1102 {
1103     VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
1104     if (event_notifier_test_and_clear(n)) {
1105         virtio_irq(vq);
1106     }
1107 }
1108 
1109 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
1110                                                 bool with_irqfd)
1111 {
1112     if (assign && !with_irqfd) {
1113         event_notifier_set_handler(&vq->guest_notifier,
1114                                    virtio_queue_guest_notifier_read);
1115     } else {
1116         event_notifier_set_handler(&vq->guest_notifier, NULL);
1117     }
1118     if (!assign) {
1119         /* Test and clear notifier before closing it,
1120          * in case poll callback didn't have time to run. */
1121         virtio_queue_guest_notifier_read(&vq->guest_notifier);
1122     }
1123 }
1124 
1125 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
1126 {
1127     return &vq->guest_notifier;
1128 }
1129 
1130 static void virtio_queue_host_notifier_read(EventNotifier *n)
1131 {
1132     VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
1133     if (event_notifier_test_and_clear(n)) {
1134         virtio_queue_notify_vq(vq);
1135     }
1136 }
1137 
1138 void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
1139                                                bool set_handler)
1140 {
1141     if (assign && set_handler) {
1142         event_notifier_set_handler(&vq->host_notifier,
1143                                    virtio_queue_host_notifier_read);
1144     } else {
1145         event_notifier_set_handler(&vq->host_notifier, NULL);
1146     }
1147     if (!assign) {
1148         /* Test and clear notifier before after disabling event,
1149          * in case poll callback didn't have time to run. */
1150         virtio_queue_host_notifier_read(&vq->host_notifier);
1151     }
1152 }
1153 
1154 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
1155 {
1156     return &vq->host_notifier;
1157 }
1158 
1159 void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
1160 {
1161     if (vdev->bus_name) {
1162         g_free(vdev->bus_name);
1163         vdev->bus_name = NULL;
1164     }
1165 
1166     if (bus_name) {
1167         vdev->bus_name = g_strdup(bus_name);
1168     }
1169 }
1170 
1171 static void virtio_device_realize(DeviceState *dev, Error **errp)
1172 {
1173     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1174     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1175     Error *err = NULL;
1176 
1177     if (vdc->realize != NULL) {
1178         vdc->realize(dev, &err);
1179         if (err != NULL) {
1180             error_propagate(errp, err);
1181             return;
1182         }
1183     }
1184     virtio_bus_device_plugged(vdev);
1185 }
1186 
1187 static void virtio_device_unrealize(DeviceState *dev, Error **errp)
1188 {
1189     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1190     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1191     Error *err = NULL;
1192 
1193     virtio_bus_device_unplugged(vdev);
1194 
1195     if (vdc->unrealize != NULL) {
1196         vdc->unrealize(dev, &err);
1197         if (err != NULL) {
1198             error_propagate(errp, err);
1199             return;
1200         }
1201     }
1202 
1203     if (vdev->bus_name) {
1204         g_free(vdev->bus_name);
1205         vdev->bus_name = NULL;
1206     }
1207 }
1208 
1209 static void virtio_device_class_init(ObjectClass *klass, void *data)
1210 {
1211     /* Set the default value here. */
1212     DeviceClass *dc = DEVICE_CLASS(klass);
1213 
1214     dc->realize = virtio_device_realize;
1215     dc->unrealize = virtio_device_unrealize;
1216     dc->bus_type = TYPE_VIRTIO_BUS;
1217 }
1218 
1219 static const TypeInfo virtio_device_info = {
1220     .name = TYPE_VIRTIO_DEVICE,
1221     .parent = TYPE_DEVICE,
1222     .instance_size = sizeof(VirtIODevice),
1223     .class_init = virtio_device_class_init,
1224     .abstract = true,
1225     .class_size = sizeof(VirtioDeviceClass),
1226 };
1227 
1228 static void virtio_register_types(void)
1229 {
1230     type_register_static(&virtio_device_info);
1231 }
1232 
1233 type_init(virtio_register_types)
1234