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>
36 #include <pthread_np.h>
43 * Functions for dealing with generalized "virtual devices" as
44 * defined by <https://www.google.com/#output=search&q=virtio+spec>
48 * In case we decide to relax the "virtio softc comes at the
49 * front of virtio-based device softc" constraint, let's use
52 #define DEV_SOFTC(vs) ((void *)(vs))
55 * Link a virtio_softc to its constants, the device softc, and
59 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
60 void *dev_softc, struct pci_devinst *pi,
61 struct vqueue_info *queues)
65 /* vs and dev_softc addresses must match */
66 assert((void *)vs == dev_softc);
71 vs->vs_queues = queues;
72 for (i = 0; i < vc->vc_nvq; i++) {
79 * Reset device (device-wide). This erases all queues, i.e.,
80 * all the queues become invalid (though we don't wipe out the
81 * internal pointers, we just clear the VQ_ALLOC flag).
83 * It resets negotiated features to "none".
85 * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
88 vi_reset_dev(struct virtio_softc *vs)
90 struct vqueue_info *vq;
94 assert(pthread_mutex_isowned_np(vs->vs_mtx));
96 nvq = vs->vs_vc->vc_nvq;
97 for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
99 vq->vq_last_avail = 0;
100 vq->vq_save_used = 0;
102 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
104 vs->vs_negotiated_caps = 0;
106 /* vs->vs_status = 0; -- redundant */
108 pci_lintr_deassert(vs->vs_pi);
110 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
114 * Set I/O BAR (usually 0) to map PCI config registers.
117 vi_set_io_bar(struct virtio_softc *vs, int barnum)
122 * ??? should we use CFG0 if MSI-X is disabled?
123 * Existing code did not...
125 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
126 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
130 * Initialize MSI-X vector capabilities if we're to use MSI-X,
131 * or MSI capabilities if not.
133 * We assume we want one MSI-X vector per queue, here, plus one
134 * for the config vec.
137 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
142 vs->vs_flags |= VIRTIO_USE_MSIX;
144 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
146 nvec = vs->vs_vc->vc_nvq + 1;
147 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
150 vs->vs_flags &= ~VIRTIO_USE_MSIX;
151 /* Only 1 MSI vector for bhyve */
152 pci_emul_add_msicap(vs->vs_pi, 1);
157 * Initialize the currently-selected virtio queue (vs->vs_curq).
158 * The guest just gave us a page frame number, from which we can
159 * calculate the addresses of the queue.
162 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
164 struct vqueue_info *vq;
169 vq = &vs->vs_queues[vs->vs_curq];
171 phys = (uint64_t)pfn << VRING_PFN;
172 size = vring_size(vq->vq_qsize);
173 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
175 /* First page(s) are descriptors... */
176 vq->vq_desc = (struct virtio_desc *)base;
177 base += vq->vq_qsize * sizeof(struct virtio_desc);
179 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
180 vq->vq_avail = (struct vring_avail *)base;
181 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
183 /* Then it's rounded up to the next page... */
184 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
186 /* ... and the last page(s) are the used ring. */
187 vq->vq_used = (struct vring_used *)base;
189 /* Mark queue as allocated, and start at 0 when we use it. */
190 vq->vq_flags = VQ_ALLOC;
191 vq->vq_last_avail = 0;
192 vq->vq_save_used = 0;
196 * Helper inline for vq_getchain(): record the i'th "real"
200 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
201 struct iovec *iov, int n_iov, uint16_t *flags) {
205 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
206 iov[i].iov_len = vd->vd_len;
208 flags[i] = vd->vd_flags;
210 #define VQ_MAX_DESCRIPTORS 512 /* see below */
213 * Examine the chain of descriptors starting at the "next one" to
214 * make sure that they describe a sensible request. If so, return
215 * the number of "real" descriptors that would be needed/used in
216 * acting on this request. This may be smaller than the number of
217 * available descriptors, e.g., if there are two available but
218 * they are two separate requests, this just returns 1. Or, it
219 * may be larger: if there are indirect descriptors involved,
220 * there may only be one descriptor available but it may be an
221 * indirect pointing to eight more. We return 8 in this case,
222 * i.e., we do not count the indirect descriptors, only the "real"
225 * Basically, this vets the vd_flags and vd_next field of each
226 * descriptor and tells you how many are involved. Since some may
227 * be indirect, this also needs the vmctx (in the pci_devinst
228 * at vs->vs_pi) so that it can find indirect descriptors.
230 * As we process each descriptor, we copy and adjust it (guest to
231 * host address wise, also using the vmtctx) into the given iov[]
232 * array (of the given size). If the array overflows, we stop
233 * placing values into the array but keep processing descriptors,
234 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
235 * So you, the caller, must not assume that iov[] is as big as the
236 * return value (you can process the same thing twice to allocate
237 * a larger iov array if needed, or supply a zero length to find
238 * out how much space is needed).
240 * If you want to verify the WRITE flag on each descriptor, pass a
241 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
242 * as n_iov and we'll copy each vd_flags field after unwinding any
245 * If some descriptor(s) are invalid, this prints a diagnostic message
246 * and returns -1. If no descriptors are ready now it simply returns 0.
248 * You are assumed to have done a vq_ring_ready() if needed (note
249 * that vq_has_descs() does one).
252 vq_getchain(struct vqueue_info *vq, uint16_t *pidx,
253 struct iovec *iov, int n_iov, uint16_t *flags)
256 u_int ndesc, n_indir;
258 volatile struct virtio_desc *vdir, *vindir, *vp;
260 struct virtio_softc *vs;
264 name = vs->vs_vc->vc_name;
267 * Note: it's the responsibility of the guest not to
268 * update vq->vq_avail->va_idx until all of the descriptors
269 * the guest has written are valid (including all their
270 * vd_next fields and vd_flags).
272 * Compute (last_avail - va_idx) in integers mod 2**16. This is
273 * the number of descriptors the device has made available
274 * since the last time we updated vq->vq_last_avail.
276 * We just need to do the subtraction as an unsigned int,
277 * then trim off excess bits.
279 idx = vq->vq_last_avail;
280 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
283 if (ndesc > vq->vq_qsize) {
284 /* XXX need better way to diagnose issues */
286 "%s: ndesc (%u) out of range, driver confused?\r\n",
292 * Now count/parse "involved" descriptors starting from
293 * the head of the chain.
295 * To prevent loops, we could be more complicated and
296 * check whether we're re-visiting a previously visited
297 * index, but we just abort if the count gets excessive.
299 ctx = vs->vs_pi->pi_vmctx;
300 *pidx = next = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
302 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
303 if (next >= vq->vq_qsize) {
305 "%s: descriptor index %u out of range, "
306 "driver confused?\r\n",
310 vdir = &vq->vq_desc[next];
311 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
312 _vq_record(i, vdir, ctx, iov, n_iov, flags);
314 } else if ((vs->vs_negotiated_caps &
315 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
317 "%s: descriptor has forbidden INDIRECT flag, "
318 "driver confused?\r\n",
322 n_indir = vdir->vd_len / 16;
323 if ((vdir->vd_len & 0xf) || n_indir == 0) {
325 "%s: invalid indir len 0x%x, "
326 "driver confused?\r\n",
327 name, (u_int)vdir->vd_len);
330 vindir = paddr_guest2host(ctx,
331 vdir->vd_addr, vdir->vd_len);
333 * Indirects start at the 0th, then follow
334 * their own embedded "next"s until those run
335 * out. Each one's indirect flag must be off
336 * (we don't really have to check, could just
342 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
344 "%s: indirect desc has INDIR flag,"
345 " driver confused?\r\n",
349 _vq_record(i, vp, ctx, iov, n_iov, flags);
350 if (++i > VQ_MAX_DESCRIPTORS)
352 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
355 if (next >= n_indir) {
357 "%s: invalid next %u > %u, "
358 "driver confused?\r\n",
359 name, (u_int)next, n_indir);
364 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
369 "%s: descriptor loop? count > %d - driver confused?\r\n",
375 * Return the currently-first request chain back to the available queue.
377 * (This chain is the one you handled when you called vq_getchain()
378 * and used its positive return value.)
381 vq_retchain(struct vqueue_info *vq)
388 * Return specified request chain to the guest, setting its I/O length
389 * to the provided value.
391 * (This chain is the one you handled when you called vq_getchain()
392 * and used its positive return value.)
395 vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
398 volatile struct vring_used *vuh;
399 volatile struct virtio_used *vue;
403 * - mask is N-1 where N is a power of 2 so computes x % N
404 * - vuh points to the "used" data shared with guest
405 * - vue points to the "used" ring entry we want to update
406 * - head is the same value we compute in vq_iovecs().
408 * (I apologize for the two fields named vu_idx; the
409 * virtio spec calls the one that vue points to, "id"...)
411 mask = vq->vq_qsize - 1;
415 vue = &vuh->vu_ring[uidx++ & mask];
417 vue->vu_tlen = iolen;
422 * Driver has finished processing "available" chains and calling
423 * vq_relchain on each one. If driver used all the available
424 * chains, used_all should be set.
426 * If the "used" index moved we may need to inform the guest, i.e.,
427 * deliver an interrupt. Even if the used index did NOT move we
428 * may need to deliver an interrupt, if the avail ring is empty and
429 * we are supposed to interrupt on empty.
431 * Note that used_all_avail is provided by the caller because it's
432 * a snapshot of the ring state when he decided to finish interrupt
433 * processing -- it's possible that descriptors became available after
434 * that point. (It's also typically a constant 1/True as well.)
437 vq_endchains(struct vqueue_info *vq, int used_all_avail)
439 struct virtio_softc *vs;
440 uint16_t event_idx, new_idx, old_idx;
444 * Interrupt generation: if we're using EVENT_IDX,
445 * interrupt if we've crossed the event threshold.
446 * Otherwise interrupt is generated if we added "used" entries,
447 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
449 * In any case, though, if NOTIFY_ON_EMPTY is set and the
450 * entire avail was processed, we need to interrupt always.
453 old_idx = vq->vq_save_used;
454 vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
455 if (used_all_avail &&
456 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
458 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
459 event_idx = VQ_USED_EVENT_IDX(vq);
461 * This calculation is per docs and the kernel
462 * (see src/sys/dev/virtio/virtio_ring.h).
464 intr = (uint16_t)(new_idx - event_idx - 1) <
465 (uint16_t)(new_idx - old_idx);
467 intr = new_idx != old_idx &&
468 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
471 vq_interrupt(vs, vq);
474 /* Note: these are in sorted order to make for a fast search */
475 static struct config_reg {
476 uint16_t cr_offset; /* register offset */
477 uint8_t cr_size; /* size (bytes) */
478 uint8_t cr_ro; /* true => reg is read only */
479 const char *cr_name; /* name of reg */
481 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
482 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
483 { VTCFG_R_PFN, 4, 0, "PFN" },
484 { VTCFG_R_QNUM, 2, 1, "QNUM" },
485 { VTCFG_R_QSEL, 2, 0, "QSEL" },
486 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
487 { VTCFG_R_STATUS, 1, 0, "STATUS" },
488 { VTCFG_R_ISR, 1, 0, "ISR" },
489 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
490 { VTCFG_R_QVEC, 2, 0, "QVEC" },
493 static inline struct config_reg *
494 vi_find_cr(int offset) {
496 struct config_reg *cr;
499 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
501 mid = (hi + lo) >> 1;
502 cr = &config_regs[mid];
503 if (cr->cr_offset == offset)
505 if (cr->cr_offset < offset)
514 * Handle pci config space reads.
515 * If it's to the MSI-X info, do that.
516 * If it's part of the virtio standard stuff, do that.
517 * Otherwise dispatch to the actual driver.
520 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
521 int baridx, uint64_t offset, int size)
523 struct virtio_softc *vs = pi->pi_arg;
524 struct virtio_consts *vc;
525 struct config_reg *cr;
526 uint64_t virtio_config_size, max;
532 if (vs->vs_flags & VIRTIO_USE_MSIX) {
533 if (baridx == pci_msix_table_bar(pi) ||
534 baridx == pci_msix_pba_bar(pi)) {
535 return (pci_emul_msix_tread(pi, offset, size));
539 /* XXX probably should do something better than just assert() */
543 pthread_mutex_lock(vs->vs_mtx);
547 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
549 if (size != 1 && size != 2 && size != 4)
552 if (pci_msix_enabled(pi))
553 virtio_config_size = VTCFG_R_CFG1;
555 virtio_config_size = VTCFG_R_CFG0;
557 if (offset >= virtio_config_size) {
559 * Subtract off the standard size (including MSI-X
560 * registers if enabled) and dispatch to underlying driver.
561 * If that fails, fall into general code.
563 newoff = offset - virtio_config_size;
564 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
565 if (newoff + size > max)
567 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
573 cr = vi_find_cr(offset);
574 if (cr == NULL || cr->cr_size != size) {
576 /* offset must be OK, so size must be bad */
578 "%s: read from %s: bad size %d\r\n",
579 name, cr->cr_name, size);
582 "%s: read from bad offset/size %jd/%d\r\n",
583 name, (uintmax_t)offset, size);
589 case VTCFG_R_HOSTCAP:
590 value = vc->vc_hv_caps;
592 case VTCFG_R_GUESTCAP:
593 value = vs->vs_negotiated_caps;
596 if (vs->vs_curq < vc->vc_nvq)
597 value = vs->vs_queues[vs->vs_curq].vq_pfn;
600 value = vs->vs_curq < vc->vc_nvq ?
601 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
606 case VTCFG_R_QNOTIFY:
610 value = vs->vs_status;
614 vs->vs_isr = 0; /* a read clears this flag */
616 pci_lintr_deassert(pi);
619 value = vs->vs_msix_cfg_idx;
622 value = vs->vs_curq < vc->vc_nvq ?
623 vs->vs_queues[vs->vs_curq].vq_msix_idx :
624 VIRTIO_MSI_NO_VECTOR;
629 pthread_mutex_unlock(vs->vs_mtx);
634 * Handle pci config space writes.
635 * If it's to the MSI-X info, do that.
636 * If it's part of the virtio standard stuff, do that.
637 * Otherwise dispatch to the actual driver.
640 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
641 int baridx, uint64_t offset, int size, uint64_t value)
643 struct virtio_softc *vs = pi->pi_arg;
644 struct vqueue_info *vq;
645 struct virtio_consts *vc;
646 struct config_reg *cr;
647 uint64_t virtio_config_size, max;
652 if (vs->vs_flags & VIRTIO_USE_MSIX) {
653 if (baridx == pci_msix_table_bar(pi) ||
654 baridx == pci_msix_pba_bar(pi)) {
655 pci_emul_msix_twrite(pi, offset, size, value);
660 /* XXX probably should do something better than just assert() */
664 pthread_mutex_lock(vs->vs_mtx);
669 if (size != 1 && size != 2 && size != 4)
672 if (pci_msix_enabled(pi))
673 virtio_config_size = VTCFG_R_CFG1;
675 virtio_config_size = VTCFG_R_CFG0;
677 if (offset >= virtio_config_size) {
679 * Subtract off the standard size (including MSI-X
680 * registers if enabled) and dispatch to underlying driver.
682 newoff = offset - virtio_config_size;
683 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
684 if (newoff + size > max)
686 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
692 cr = vi_find_cr(offset);
693 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
695 /* offset must be OK, wrong size and/or reg is R/O */
696 if (cr->cr_size != size)
698 "%s: write to %s: bad size %d\r\n",
699 name, cr->cr_name, size);
702 "%s: write to read-only reg %s\r\n",
706 "%s: write to bad offset/size %jd/%d\r\n",
707 name, (uintmax_t)offset, size);
713 case VTCFG_R_GUESTCAP:
714 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
715 if (vc->vc_apply_features)
716 (*vc->vc_apply_features)(DEV_SOFTC(vs),
717 vs->vs_negotiated_caps);
720 if (vs->vs_curq >= vc->vc_nvq)
722 vi_vq_init(vs, value);
726 * Note that the guest is allowed to select an
727 * invalid queue; we just need to return a QNUM
728 * of 0 while the bad queue is selected.
732 case VTCFG_R_QNOTIFY:
733 if (value >= vc->vc_nvq) {
734 fprintf(stderr, "%s: queue %d notify out of range\r\n",
738 vq = &vs->vs_queues[value];
740 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
741 else if (vc->vc_qnotify)
742 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
745 "%s: qnotify queue %d: missing vq/vc notify\r\n",
749 vs->vs_status = value;
751 (*vc->vc_reset)(DEV_SOFTC(vs));
754 vs->vs_msix_cfg_idx = value;
757 if (vs->vs_curq >= vc->vc_nvq)
759 vq = &vs->vs_queues[vs->vs_curq];
760 vq->vq_msix_idx = value;
767 "%s: write config reg %s: curq %d >= max %d\r\n",
768 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
771 pthread_mutex_unlock(vs->vs_mtx);