2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2013 Chris Torek <torek @ torek net>
6 * Copyright (c) 2019 Joyent, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
36 #include <machine/atomic.h>
41 #include <pthread_np.h>
49 * Functions for dealing with generalized "virtual devices" as
50 * defined by <https://www.google.com/#output=search&q=virtio+spec>
54 * In case we decide to relax the "virtio softc comes at the
55 * front of virtio-based device softc" constraint, let's use
58 #define DEV_SOFTC(vs) ((void *)(vs))
61 * Link a virtio_softc to its constants, the device softc, and
65 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
66 void *dev_softc, struct pci_devinst *pi,
67 struct vqueue_info *queues)
71 /* vs and dev_softc addresses must match */
72 assert((void *)vs == dev_softc);
77 vs->vs_queues = queues;
78 for (i = 0; i < vc->vc_nvq; i++) {
85 * Reset device (device-wide). This erases all queues, i.e.,
86 * all the queues become invalid (though we don't wipe out the
87 * internal pointers, we just clear the VQ_ALLOC flag).
89 * It resets negotiated features to "none".
91 * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
94 vi_reset_dev(struct virtio_softc *vs)
96 struct vqueue_info *vq;
100 assert(pthread_mutex_isowned_np(vs->vs_mtx));
102 nvq = vs->vs_vc->vc_nvq;
103 for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
105 vq->vq_last_avail = 0;
106 vq->vq_next_used = 0;
107 vq->vq_save_used = 0;
109 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
111 vs->vs_negotiated_caps = 0;
113 /* vs->vs_status = 0; -- redundant */
115 pci_lintr_deassert(vs->vs_pi);
117 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
121 * Set I/O BAR (usually 0) to map PCI config registers.
124 vi_set_io_bar(struct virtio_softc *vs, int barnum)
129 * ??? should we use CFG0 if MSI-X is disabled?
130 * Existing code did not...
132 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
133 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
137 * Initialize MSI-X vector capabilities if we're to use MSI-X,
138 * or MSI capabilities if not.
140 * We assume we want one MSI-X vector per queue, here, plus one
141 * for the config vec.
144 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
149 vs->vs_flags |= VIRTIO_USE_MSIX;
151 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
153 nvec = vs->vs_vc->vc_nvq + 1;
154 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
157 vs->vs_flags &= ~VIRTIO_USE_MSIX;
159 /* Only 1 MSI vector for bhyve */
160 pci_emul_add_msicap(vs->vs_pi, 1);
162 /* Legacy interrupts are mandatory for virtio devices */
163 pci_lintr_request(vs->vs_pi);
169 * Initialize the currently-selected virtio queue (vs->vs_curq).
170 * The guest just gave us a page frame number, from which we can
171 * calculate the addresses of the queue.
174 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
176 struct vqueue_info *vq;
181 vq = &vs->vs_queues[vs->vs_curq];
183 phys = (uint64_t)pfn << VRING_PFN;
184 size = vring_size(vq->vq_qsize);
185 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
187 /* First page(s) are descriptors... */
188 vq->vq_desc = (struct virtio_desc *)base;
189 base += vq->vq_qsize * sizeof(struct virtio_desc);
191 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
192 vq->vq_avail = (struct vring_avail *)base;
193 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
195 /* Then it's rounded up to the next page... */
196 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
198 /* ... and the last page(s) are the used ring. */
199 vq->vq_used = (struct vring_used *)base;
201 /* Mark queue as allocated, and start at 0 when we use it. */
202 vq->vq_flags = VQ_ALLOC;
203 vq->vq_last_avail = 0;
204 vq->vq_next_used = 0;
205 vq->vq_save_used = 0;
209 * Helper inline for vq_getchain(): record the i'th "real"
213 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
214 struct iovec *iov, int n_iov, uint16_t *flags) {
218 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
219 iov[i].iov_len = vd->vd_len;
221 flags[i] = vd->vd_flags;
223 #define VQ_MAX_DESCRIPTORS 512 /* see below */
226 * Examine the chain of descriptors starting at the "next one" to
227 * make sure that they describe a sensible request. If so, return
228 * the number of "real" descriptors that would be needed/used in
229 * acting on this request. This may be smaller than the number of
230 * available descriptors, e.g., if there are two available but
231 * they are two separate requests, this just returns 1. Or, it
232 * may be larger: if there are indirect descriptors involved,
233 * there may only be one descriptor available but it may be an
234 * indirect pointing to eight more. We return 8 in this case,
235 * i.e., we do not count the indirect descriptors, only the "real"
238 * Basically, this vets the vd_flags and vd_next field of each
239 * descriptor and tells you how many are involved. Since some may
240 * be indirect, this also needs the vmctx (in the pci_devinst
241 * at vs->vs_pi) so that it can find indirect descriptors.
243 * As we process each descriptor, we copy and adjust it (guest to
244 * host address wise, also using the vmtctx) into the given iov[]
245 * array (of the given size). If the array overflows, we stop
246 * placing values into the array but keep processing descriptors,
247 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
248 * So you, the caller, must not assume that iov[] is as big as the
249 * return value (you can process the same thing twice to allocate
250 * a larger iov array if needed, or supply a zero length to find
251 * out how much space is needed).
253 * If you want to verify the WRITE flag on each descriptor, pass a
254 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
255 * as n_iov and we'll copy each vd_flags field after unwinding any
258 * If some descriptor(s) are invalid, this prints a diagnostic message
259 * and returns -1. If no descriptors are ready now it simply returns 0.
261 * You are assumed to have done a vq_ring_ready() if needed (note
262 * that vq_has_descs() does one).
265 vq_getchain(struct vqueue_info *vq, uint16_t *pidx,
266 struct iovec *iov, int n_iov, uint16_t *flags)
269 u_int ndesc, n_indir;
271 volatile struct virtio_desc *vdir, *vindir, *vp;
273 struct virtio_softc *vs;
277 name = vs->vs_vc->vc_name;
280 * Note: it's the responsibility of the guest not to
281 * update vq->vq_avail->va_idx until all of the descriptors
282 * the guest has written are valid (including all their
283 * vd_next fields and vd_flags).
285 * Compute (va_idx - last_avail) in integers mod 2**16. This is
286 * the number of descriptors the device has made available
287 * since the last time we updated vq->vq_last_avail.
289 * We just need to do the subtraction as an unsigned int,
290 * then trim off excess bits.
292 idx = vq->vq_last_avail;
293 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
296 if (ndesc > vq->vq_qsize) {
297 /* XXX need better way to diagnose issues */
299 "%s: ndesc (%u) out of range, driver confused?",
305 * Now count/parse "involved" descriptors starting from
306 * the head of the chain.
308 * To prevent loops, we could be more complicated and
309 * check whether we're re-visiting a previously visited
310 * index, but we just abort if the count gets excessive.
312 ctx = vs->vs_pi->pi_vmctx;
313 *pidx = next = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
315 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
316 if (next >= vq->vq_qsize) {
318 "%s: descriptor index %u out of range, "
323 vdir = &vq->vq_desc[next];
324 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
325 _vq_record(i, vdir, ctx, iov, n_iov, flags);
327 } else if ((vs->vs_vc->vc_hv_caps &
328 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
330 "%s: descriptor has forbidden INDIRECT flag, "
335 n_indir = vdir->vd_len / 16;
336 if ((vdir->vd_len & 0xf) || n_indir == 0) {
338 "%s: invalid indir len 0x%x, "
340 name, (u_int)vdir->vd_len);
343 vindir = paddr_guest2host(ctx,
344 vdir->vd_addr, vdir->vd_len);
346 * Indirects start at the 0th, then follow
347 * their own embedded "next"s until those run
348 * out. Each one's indirect flag must be off
349 * (we don't really have to check, could just
355 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
357 "%s: indirect desc has INDIR flag,"
362 _vq_record(i, vp, ctx, iov, n_iov, flags);
363 if (++i > VQ_MAX_DESCRIPTORS)
365 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
368 if (next >= n_indir) {
370 "%s: invalid next %u > %u, "
372 name, (u_int)next, n_indir);
377 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
382 "%s: descriptor loop? count > %d - driver confused?",
388 * Return the first n_chain request chains back to the available queue.
390 * (These chains are the ones you handled when you called vq_getchain()
391 * and used its positive return value.)
394 vq_retchains(struct vqueue_info *vq, uint16_t n_chains)
397 vq->vq_last_avail -= n_chains;
401 vq_relchain_prepare(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
403 volatile struct vring_used *vuh;
404 volatile struct virtio_used *vue;
409 * - mask is N-1 where N is a power of 2 so computes x % N
410 * - vuh points to the "used" data shared with guest
411 * - vue points to the "used" ring entry we want to update
413 * (I apologize for the two fields named vu_idx; the
414 * virtio spec calls the one that vue points to, "id"...)
416 mask = vq->vq_qsize - 1;
419 vue = &vuh->vu_ring[vq->vq_next_used++ & mask];
421 vue->vu_tlen = iolen;
425 vq_relchain_publish(struct vqueue_info *vq)
428 * Ensure the used descriptor is visible before updating the index.
429 * This is necessary on ISAs with memory ordering less strict than x86
430 * (and even on x86 to act as a compiler barrier).
432 atomic_thread_fence_rel();
433 vq->vq_used->vu_idx = vq->vq_next_used;
437 * Return specified request chain to the guest, setting its I/O length
438 * to the provided value.
440 * (This chain is the one you handled when you called vq_getchain()
441 * and used its positive return value.)
444 vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
446 vq_relchain_prepare(vq, idx, iolen);
447 vq_relchain_publish(vq);
451 * Driver has finished processing "available" chains and calling
452 * vq_relchain on each one. If driver used all the available
453 * chains, used_all should be set.
455 * If the "used" index moved we may need to inform the guest, i.e.,
456 * deliver an interrupt. Even if the used index did NOT move we
457 * may need to deliver an interrupt, if the avail ring is empty and
458 * we are supposed to interrupt on empty.
460 * Note that used_all_avail is provided by the caller because it's
461 * a snapshot of the ring state when he decided to finish interrupt
462 * processing -- it's possible that descriptors became available after
463 * that point. (It's also typically a constant 1/True as well.)
466 vq_endchains(struct vqueue_info *vq, int used_all_avail)
468 struct virtio_softc *vs;
469 uint16_t event_idx, new_idx, old_idx;
473 * Interrupt generation: if we're using EVENT_IDX,
474 * interrupt if we've crossed the event threshold.
475 * Otherwise interrupt is generated if we added "used" entries,
476 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
478 * In any case, though, if NOTIFY_ON_EMPTY is set and the
479 * entire avail was processed, we need to interrupt always.
482 old_idx = vq->vq_save_used;
483 vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
486 * Use full memory barrier between vu_idx store from preceding
487 * vq_relchain() call and the loads from VQ_USED_EVENT_IDX() or
490 atomic_thread_fence_seq_cst();
491 if (used_all_avail &&
492 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
494 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
495 event_idx = VQ_USED_EVENT_IDX(vq);
497 * This calculation is per docs and the kernel
498 * (see src/sys/dev/virtio/virtio_ring.h).
500 intr = (uint16_t)(new_idx - event_idx - 1) <
501 (uint16_t)(new_idx - old_idx);
503 intr = new_idx != old_idx &&
504 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
507 vq_interrupt(vs, vq);
510 /* Note: these are in sorted order to make for a fast search */
511 static struct config_reg {
512 uint16_t cr_offset; /* register offset */
513 uint8_t cr_size; /* size (bytes) */
514 uint8_t cr_ro; /* true => reg is read only */
515 const char *cr_name; /* name of reg */
517 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
518 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
519 { VTCFG_R_PFN, 4, 0, "PFN" },
520 { VTCFG_R_QNUM, 2, 1, "QNUM" },
521 { VTCFG_R_QSEL, 2, 0, "QSEL" },
522 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
523 { VTCFG_R_STATUS, 1, 0, "STATUS" },
524 { VTCFG_R_ISR, 1, 0, "ISR" },
525 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
526 { VTCFG_R_QVEC, 2, 0, "QVEC" },
529 static inline struct config_reg *
530 vi_find_cr(int offset) {
532 struct config_reg *cr;
535 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
537 mid = (hi + lo) >> 1;
538 cr = &config_regs[mid];
539 if (cr->cr_offset == offset)
541 if (cr->cr_offset < offset)
550 * Handle pci config space reads.
551 * If it's to the MSI-X info, do that.
552 * If it's part of the virtio standard stuff, do that.
553 * Otherwise dispatch to the actual driver.
556 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
557 int baridx, uint64_t offset, int size)
559 struct virtio_softc *vs = pi->pi_arg;
560 struct virtio_consts *vc;
561 struct config_reg *cr;
562 uint64_t virtio_config_size, max;
568 if (vs->vs_flags & VIRTIO_USE_MSIX) {
569 if (baridx == pci_msix_table_bar(pi) ||
570 baridx == pci_msix_pba_bar(pi)) {
571 return (pci_emul_msix_tread(pi, offset, size));
575 /* XXX probably should do something better than just assert() */
579 pthread_mutex_lock(vs->vs_mtx);
583 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
585 if (size != 1 && size != 2 && size != 4)
588 if (pci_msix_enabled(pi))
589 virtio_config_size = VTCFG_R_CFG1;
591 virtio_config_size = VTCFG_R_CFG0;
593 if (offset >= virtio_config_size) {
595 * Subtract off the standard size (including MSI-X
596 * registers if enabled) and dispatch to underlying driver.
597 * If that fails, fall into general code.
599 newoff = offset - virtio_config_size;
600 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
601 if (newoff + size > max)
603 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
609 cr = vi_find_cr(offset);
610 if (cr == NULL || cr->cr_size != size) {
612 /* offset must be OK, so size must be bad */
614 "%s: read from %s: bad size %d",
615 name, cr->cr_name, size);
618 "%s: read from bad offset/size %jd/%d",
619 name, (uintmax_t)offset, size);
625 case VTCFG_R_HOSTCAP:
626 value = vc->vc_hv_caps;
628 case VTCFG_R_GUESTCAP:
629 value = vs->vs_negotiated_caps;
632 if (vs->vs_curq < vc->vc_nvq)
633 value = vs->vs_queues[vs->vs_curq].vq_pfn;
636 value = vs->vs_curq < vc->vc_nvq ?
637 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
642 case VTCFG_R_QNOTIFY:
646 value = vs->vs_status;
650 vs->vs_isr = 0; /* a read clears this flag */
652 pci_lintr_deassert(pi);
655 value = vs->vs_msix_cfg_idx;
658 value = vs->vs_curq < vc->vc_nvq ?
659 vs->vs_queues[vs->vs_curq].vq_msix_idx :
660 VIRTIO_MSI_NO_VECTOR;
665 pthread_mutex_unlock(vs->vs_mtx);
670 * Handle pci config space writes.
671 * If it's to the MSI-X info, do that.
672 * If it's part of the virtio standard stuff, do that.
673 * Otherwise dispatch to the actual driver.
676 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
677 int baridx, uint64_t offset, int size, uint64_t value)
679 struct virtio_softc *vs = pi->pi_arg;
680 struct vqueue_info *vq;
681 struct virtio_consts *vc;
682 struct config_reg *cr;
683 uint64_t virtio_config_size, max;
688 if (vs->vs_flags & VIRTIO_USE_MSIX) {
689 if (baridx == pci_msix_table_bar(pi) ||
690 baridx == pci_msix_pba_bar(pi)) {
691 pci_emul_msix_twrite(pi, offset, size, value);
696 /* XXX probably should do something better than just assert() */
700 pthread_mutex_lock(vs->vs_mtx);
705 if (size != 1 && size != 2 && size != 4)
708 if (pci_msix_enabled(pi))
709 virtio_config_size = VTCFG_R_CFG1;
711 virtio_config_size = VTCFG_R_CFG0;
713 if (offset >= virtio_config_size) {
715 * Subtract off the standard size (including MSI-X
716 * registers if enabled) and dispatch to underlying driver.
718 newoff = offset - virtio_config_size;
719 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
720 if (newoff + size > max)
722 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
728 cr = vi_find_cr(offset);
729 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
731 /* offset must be OK, wrong size and/or reg is R/O */
732 if (cr->cr_size != size)
734 "%s: write to %s: bad size %d",
735 name, cr->cr_name, size);
738 "%s: write to read-only reg %s",
742 "%s: write to bad offset/size %jd/%d",
743 name, (uintmax_t)offset, size);
749 case VTCFG_R_GUESTCAP:
750 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
751 if (vc->vc_apply_features)
752 (*vc->vc_apply_features)(DEV_SOFTC(vs),
753 vs->vs_negotiated_caps);
756 if (vs->vs_curq >= vc->vc_nvq)
758 vi_vq_init(vs, value);
762 * Note that the guest is allowed to select an
763 * invalid queue; we just need to return a QNUM
764 * of 0 while the bad queue is selected.
768 case VTCFG_R_QNOTIFY:
769 if (value >= vc->vc_nvq) {
770 EPRINTLN("%s: queue %d notify out of range",
774 vq = &vs->vs_queues[value];
776 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
777 else if (vc->vc_qnotify)
778 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
781 "%s: qnotify queue %d: missing vq/vc notify",
785 vs->vs_status = value;
787 (*vc->vc_reset)(DEV_SOFTC(vs));
790 vs->vs_msix_cfg_idx = value;
793 if (vs->vs_curq >= vc->vc_nvq)
795 vq = &vs->vs_queues[vs->vs_curq];
796 vq->vq_msix_idx = value;
803 "%s: write config reg %s: curq %d >= max %d",
804 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
807 pthread_mutex_unlock(vs->vs_mtx);