2 * Copyright (c) 2013 Chris Torek <torek @ torek net>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/param.h>
42 * Functions for dealing with generalized "virtual devices" as
43 * defined by <https://www.google.com/#output=search&q=virtio+spec>
47 * In case we decide to relax the "virtio softc comes at the
48 * front of virtio-based device softc" constraint, let's use
51 #define DEV_SOFTC(vs) ((void *)(vs))
54 * Link a virtio_softc to its constants, the device softc, and
58 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
59 void *dev_softc, struct pci_devinst *pi,
60 struct vqueue_info *queues)
64 /* vs and dev_softc addresses must match */
65 assert((void *)vs == dev_softc);
70 vs->vs_queues = queues;
71 for (i = 0; i < vc->vc_nvq; i++) {
78 * Reset device (device-wide). This erases all queues, i.e.,
79 * all the queues become invalid (though we don't wipe out the
80 * internal pointers, we just clear the VQ_ALLOC flag).
82 * It resets negotiated features to "none".
84 * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
87 vi_reset_dev(struct virtio_softc *vs)
89 struct vqueue_info *vq;
92 nvq = vs->vs_vc->vc_nvq;
93 for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
95 vq->vq_last_avail = 0;
97 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
99 vs->vs_negotiated_caps = 0;
101 /* vs->vs_status = 0; -- redundant */
103 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
107 * Set I/O BAR (usually 0) to map PCI config registers.
110 vi_set_io_bar(struct virtio_softc *vs, int barnum)
115 * ??? should we use CFG0 if MSI-X is disabled?
116 * Existing code did not...
118 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
119 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
123 * Initialize MSI-X vector capabilities if we're to use MSI-X,
124 * or MSI capabilities if not.
126 * We assume we want one MSI-X vector per queue, here, plus one
127 * for the config vec.
130 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
135 vs->vs_flags |= VIRTIO_USE_MSIX;
136 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
137 nvec = vs->vs_vc->vc_nvq + 1;
138 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
141 vs->vs_flags &= ~VIRTIO_USE_MSIX;
142 pci_emul_add_msicap(vs->vs_pi, barnum);
148 * Initialize the currently-selected virtio queue (vs->vs_curq).
149 * The guest just gave us a page frame number, from which we can
150 * calculate the addresses of the queue.
153 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
155 struct vqueue_info *vq;
160 vq = &vs->vs_queues[vs->vs_curq];
162 phys = pfn << VRING_PFN;
163 size = vring_size(vq->vq_qsize);
164 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
166 /* First page(s) are descriptors... */
167 vq->vq_desc = (struct virtio_desc *)base;
168 base += vq->vq_qsize * sizeof(struct virtio_desc);
170 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
171 vq->vq_avail = (struct vring_avail *)base;
172 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
174 /* Then it's rounded up to the next page... */
175 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
177 /* ... and the last page(s) are the used ring. */
178 vq->vq_used = (struct vring_used *)base;
180 /* Mark queue as allocated, and start at 0 when we use it. */
181 vq->vq_flags = VQ_ALLOC;
182 vq->vq_last_avail = 0;
186 * Helper inline for vq_getchain(): record the i'th "real"
190 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
191 struct iovec *iov, int n_iov, uint16_t *flags) {
195 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
196 iov[i].iov_len = vd->vd_len;
198 flags[i] = vd->vd_flags;
200 #define VQ_MAX_DESCRIPTORS 512 /* see below */
203 * Examine the chain of descriptors starting at the "next one" to
204 * make sure that they describe a sensible request. If so, return
205 * the number of "real" descriptors that would be needed/used in
206 * acting on this request. This may be smaller than the number of
207 * available descriptors, e.g., if there are two available but
208 * they are two separate requests, this just returns 1. Or, it
209 * may be larger: if there are indirect descriptors involved,
210 * there may only be one descriptor available but it may be an
211 * indirect pointing to eight more. We return 8 in this case,
212 * i.e., we do not count the indirect descriptors, only the "real"
215 * Basically, this vets the vd_flags and vd_next field of each
216 * descriptor and tells you how many are involved. Since some may
217 * be indirect, this also needs the vmctx (in the pci_devinst
218 * at vs->vs_pi) so that it can find indirect descriptors.
220 * As we process each descriptor, we copy and adjust it (guest to
221 * host address wise, also using the vmtctx) into the given iov[]
222 * array (of the given size). If the array overflows, we stop
223 * placing values into the array but keep processing descriptors,
224 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
225 * So you, the caller, must not assume that iov[] is as big as the
226 * return value (you can process the same thing twice to allocate
227 * a larger iov array if needed, or supply a zero length to find
228 * out how much space is needed).
230 * If you want to verify the WRITE flag on each descriptor, pass a
231 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
232 * as n_iov and we'll copy each vd_flags field after unwinding any
235 * If some descriptor(s) are invalid, this prints a diagnostic message
236 * and returns -1. If no descriptors are ready now it simply returns 0.
238 * You are assumed to have done a vq_ring_ready() if needed (note
239 * that vq_has_descs() does one).
242 vq_getchain(struct vqueue_info *vq,
243 struct iovec *iov, int n_iov, uint16_t *flags)
246 u_int ndesc, n_indir;
247 u_int idx, head, next;
248 volatile struct virtio_desc *vdir, *vindir, *vp;
250 struct virtio_softc *vs;
254 name = vs->vs_vc->vc_name;
257 * Note: it's the responsibility of the guest not to
258 * update vq->vq_avail->va_idx until all of the descriptors
259 * the guest has written are valid (including all their
260 * vd_next fields and vd_flags).
262 * Compute (last_avail - va_idx) in integers mod 2**16. This is
263 * the number of descriptors the device has made available
264 * since the last time we updated vq->vq_last_avail.
266 * We just need to do the subtraction as an unsigned int,
267 * then trim off excess bits.
269 idx = vq->vq_last_avail;
270 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
273 if (ndesc > vq->vq_qsize) {
274 /* XXX need better way to diagnose issues */
276 "%s: ndesc (%u) out of range, driver confused?\r\n",
282 * Now count/parse "involved" descriptors starting from
283 * the head of the chain.
285 * To prevent loops, we could be more complicated and
286 * check whether we're re-visiting a previously visited
287 * index, but we just abort if the count gets excessive.
289 ctx = vs->vs_pi->pi_vmctx;
290 head = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
292 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
293 if (next >= vq->vq_qsize) {
295 "%s: descriptor index %u out of range, "
296 "driver confused?\r\n",
300 vdir = &vq->vq_desc[next];
301 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
302 _vq_record(i, vdir, ctx, iov, n_iov, flags);
304 } else if ((vs->vs_negotiated_caps &
305 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
307 "%s: descriptor has forbidden INDIRECT flag, "
308 "driver confused?\r\n",
312 n_indir = vdir->vd_len / 16;
313 if ((vdir->vd_len & 0xf) || n_indir == 0) {
315 "%s: invalid indir len 0x%x, "
316 "driver confused?\r\n",
317 name, (u_int)vdir->vd_len);
320 vindir = paddr_guest2host(ctx,
321 vdir->vd_addr, vdir->vd_len);
323 * Indirects start at the 0th, then follow
324 * their own embedded "next"s until those run
325 * out. Each one's indirect flag must be off
326 * (we don't really have to check, could just
332 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
334 "%s: indirect desc has INDIR flag,"
335 " driver confused?\r\n",
339 _vq_record(i, vp, ctx, iov, n_iov, flags);
340 if (++i > VQ_MAX_DESCRIPTORS)
342 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
345 if (next >= n_indir) {
347 "%s: invalid next %u > %u, "
348 "driver confused?\r\n",
349 name, (u_int)next, n_indir);
354 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
359 "%s: descriptor loop? count > %d - driver confused?\r\n",
365 * Return the currently-first request chain to the guest, setting
366 * its I/O length to the provided value.
368 * (This chain is the one you handled when you called vq_getchain()
369 * and used its positive return value.)
372 vq_relchain(struct vqueue_info *vq, uint32_t iolen)
374 uint16_t head, uidx, mask;
375 volatile struct vring_used *vuh;
376 volatile struct virtio_used *vue;
380 * - mask is N-1 where N is a power of 2 so computes x % N
381 * - vuh points to the "used" data shared with guest
382 * - vue points to the "used" ring entry we want to update
383 * - head is the same value we compute in vq_iovecs().
385 * (I apologize for the two fields named vu_idx; the
386 * virtio spec calls the one that vue points to, "id"...)
388 mask = vq->vq_qsize - 1;
390 head = vq->vq_avail->va_ring[vq->vq_last_avail++ & mask];
393 vue = &vuh->vu_ring[uidx++ & mask];
394 vue->vu_idx = head; /* ie, vue->id = head */
395 vue->vu_tlen = iolen;
400 * Driver has finished processing "available" chains and calling
401 * vq_relchain on each one. If driver used all the available
402 * chains, used_all should be set.
404 * If the "used" index moved we may need to inform the guest, i.e.,
405 * deliver an interrupt. Even if the used index did NOT move we
406 * may need to deliver an interrupt, if the avail ring is empty and
407 * we are supposed to interrupt on empty.
409 * Note that used_all_avail is provided by the caller because it's
410 * a snapshot of the ring state when he decided to finish interrupt
411 * processing -- it's possible that descriptors became available after
412 * that point. (It's also typically a constant 1/True as well.)
415 vq_endchains(struct vqueue_info *vq, int used_all_avail)
417 struct virtio_softc *vs;
418 uint16_t event_idx, new_idx, old_idx;
422 * Interrupt generation: if we're using EVENT_IDX,
423 * interrupt if we've crossed the event threshold.
424 * Otherwise interrupt is generated if we added "used" entries,
425 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
427 * In any case, though, if NOTIFY_ON_EMPTY is set and the
428 * entire avail was processed, we need to interrupt always.
431 new_idx = vq->vq_used->vu_idx;
432 old_idx = vq->vq_save_used;
433 if (used_all_avail &&
434 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
436 else if (vs->vs_flags & VIRTIO_EVENT_IDX) {
437 event_idx = VQ_USED_EVENT_IDX(vq);
439 * This calculation is per docs and the kernel
440 * (see src/sys/dev/virtio/virtio_ring.h).
442 intr = (uint16_t)(new_idx - event_idx - 1) <
443 (uint16_t)(new_idx - old_idx);
445 intr = new_idx != old_idx &&
446 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
449 vq_interrupt(vs, vq);
452 /* Note: these are in sorted order to make for a fast search */
453 static struct config_reg {
454 uint16_t cr_offset; /* register offset */
455 uint8_t cr_size; /* size (bytes) */
456 uint8_t cr_ro; /* true => reg is read only */
457 const char *cr_name; /* name of reg */
459 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
460 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
461 { VTCFG_R_PFN, 4, 0, "PFN" },
462 { VTCFG_R_QNUM, 2, 1, "QNUM" },
463 { VTCFG_R_QSEL, 2, 0, "QSEL" },
464 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
465 { VTCFG_R_STATUS, 1, 0, "STATUS" },
466 { VTCFG_R_ISR, 1, 0, "ISR" },
467 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
468 { VTCFG_R_QVEC, 2, 0, "QVEC" },
471 static inline struct config_reg *
472 vi_find_cr(int offset) {
474 struct config_reg *cr;
477 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
479 mid = (hi + lo) >> 1;
480 cr = &config_regs[mid];
481 if (cr->cr_offset == offset)
483 if (cr->cr_offset < offset)
492 * Handle pci config space reads.
493 * If it's to the MSI-X info, do that.
494 * If it's part of the virtio standard stuff, do that.
495 * Otherwise dispatch to the actual driver.
498 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
499 int baridx, uint64_t offset, int size)
501 struct virtio_softc *vs = pi->pi_arg;
502 struct virtio_consts *vc;
503 struct config_reg *cr;
504 uint64_t virtio_config_size, max;
510 if (vs->vs_flags & VIRTIO_USE_MSIX) {
511 if (baridx == pci_msix_table_bar(pi) ||
512 baridx == pci_msix_pba_bar(pi)) {
513 return (pci_emul_msix_tread(pi, offset, size));
517 /* XXX probably should do something better than just assert() */
521 pthread_mutex_lock(vs->vs_mtx);
525 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
527 if (size != 1 && size != 2 && size != 4)
530 if (pci_msix_enabled(pi))
531 virtio_config_size = VTCFG_R_CFG1;
533 virtio_config_size = VTCFG_R_CFG0;
535 if (offset >= virtio_config_size) {
537 * Subtract off the standard size (including MSI-X
538 * registers if enabled) and dispatch to underlying driver.
539 * If that fails, fall into general code.
541 newoff = offset - virtio_config_size;
542 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
543 if (newoff + size > max)
545 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
551 cr = vi_find_cr(offset);
552 if (cr == NULL || cr->cr_size != size) {
554 /* offset must be OK, so size must be bad */
556 "%s: read from %s: bad size %d\r\n",
557 name, cr->cr_name, size);
560 "%s: read from bad offset/size %jd/%d\r\n",
561 name, (uintmax_t)offset, size);
567 case VTCFG_R_HOSTCAP:
568 value = vc->vc_hv_caps;
570 case VTCFG_R_GUESTCAP:
571 value = vs->vs_negotiated_caps;
574 if (vs->vs_curq < vc->vc_nvq)
575 value = vs->vs_queues[vs->vs_curq].vq_pfn;
578 value = vs->vs_curq < vc->vc_nvq ?
579 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
584 case VTCFG_R_QNOTIFY:
588 value = vs->vs_status;
592 vs->vs_isr = 0; /* a read clears this flag */
595 value = vs->vs_msix_cfg_idx;
598 value = vs->vs_curq < vc->vc_nvq ?
599 vs->vs_queues[vs->vs_curq].vq_msix_idx :
600 VIRTIO_MSI_NO_VECTOR;
605 pthread_mutex_unlock(vs->vs_mtx);
610 * Handle pci config space writes.
611 * If it's to the MSI-X info, do that.
612 * If it's part of the virtio standard stuff, do that.
613 * Otherwise dispatch to the actual driver.
616 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
617 int baridx, uint64_t offset, int size, uint64_t value)
619 struct virtio_softc *vs = pi->pi_arg;
620 struct vqueue_info *vq;
621 struct virtio_consts *vc;
622 struct config_reg *cr;
623 uint64_t virtio_config_size, max;
628 if (vs->vs_flags & VIRTIO_USE_MSIX) {
629 if (baridx == pci_msix_table_bar(pi) ||
630 baridx == pci_msix_pba_bar(pi)) {
631 pci_emul_msix_twrite(pi, offset, size, value);
636 /* XXX probably should do something better than just assert() */
640 pthread_mutex_lock(vs->vs_mtx);
645 if (size != 1 && size != 2 && size != 4)
648 if (pci_msix_enabled(pi))
649 virtio_config_size = VTCFG_R_CFG1;
651 virtio_config_size = VTCFG_R_CFG0;
653 if (offset >= virtio_config_size) {
655 * Subtract off the standard size (including MSI-X
656 * registers if enabled) and dispatch to underlying driver.
658 newoff = offset - virtio_config_size;
659 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
660 if (newoff + size > max)
662 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
668 cr = vi_find_cr(offset);
669 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
671 /* offset must be OK, wrong size and/or reg is R/O */
672 if (cr->cr_size != size)
674 "%s: write to %s: bad size %d\r\n",
675 name, cr->cr_name, size);
678 "%s: write to read-only reg %s\r\n",
682 "%s: write to bad offset/size %jd/%d\r\n",
683 name, (uintmax_t)offset, size);
689 case VTCFG_R_GUESTCAP:
690 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
693 if (vs->vs_curq >= vc->vc_nvq)
695 vi_vq_init(vs, value);
699 * Note that the guest is allowed to select an
700 * invalid queue; we just need to return a QNUM
701 * of 0 while the bad queue is selected.
705 case VTCFG_R_QNOTIFY:
706 if (value >= vc->vc_nvq) {
707 fprintf(stderr, "%s: queue %d notify out of range\r\n",
711 vq = &vs->vs_queues[value];
713 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
714 else if (vc->vc_qnotify)
715 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
718 "%s: qnotify queue %d: missing vq/vc notify\r\n",
722 vs->vs_status = value;
724 (*vc->vc_reset)(DEV_SOFTC(vs));
727 vs->vs_msix_cfg_idx = value;
730 if (vs->vs_curq >= vc->vc_nvq)
732 vq = &vs->vs_queues[vs->vs_curq];
733 vq->vq_msix_idx = value;
740 "%s: write config reg %s: curq %d >= max %d\r\n",
741 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
744 pthread_mutex_unlock(vs->vs_mtx);