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>
48 * Functions for dealing with generalized "virtual devices" as
49 * defined by <https://www.google.com/#output=search&q=virtio+spec>
53 * In case we decide to relax the "virtio softc comes at the
54 * front of virtio-based device softc" constraint, let's use
57 #define DEV_SOFTC(vs) ((void *)(vs))
60 * Link a virtio_softc to its constants, the device softc, and
64 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
65 void *dev_softc, struct pci_devinst *pi,
66 struct vqueue_info *queues)
70 /* vs and dev_softc addresses must match */
71 assert((void *)vs == dev_softc);
76 vs->vs_queues = queues;
77 for (i = 0; i < vc->vc_nvq; i++) {
84 * Reset device (device-wide). This erases all queues, i.e.,
85 * all the queues become invalid (though we don't wipe out the
86 * internal pointers, we just clear the VQ_ALLOC flag).
88 * It resets negotiated features to "none".
90 * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
93 vi_reset_dev(struct virtio_softc *vs)
95 struct vqueue_info *vq;
99 assert(pthread_mutex_isowned_np(vs->vs_mtx));
101 nvq = vs->vs_vc->vc_nvq;
102 for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
104 vq->vq_last_avail = 0;
105 vq->vq_save_used = 0;
107 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
109 vs->vs_negotiated_caps = 0;
111 /* vs->vs_status = 0; -- redundant */
113 pci_lintr_deassert(vs->vs_pi);
115 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
119 * Set I/O BAR (usually 0) to map PCI config registers.
122 vi_set_io_bar(struct virtio_softc *vs, int barnum)
127 * ??? should we use CFG0 if MSI-X is disabled?
128 * Existing code did not...
130 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
131 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
135 * Initialize MSI-X vector capabilities if we're to use MSI-X,
136 * or MSI capabilities if not.
138 * We assume we want one MSI-X vector per queue, here, plus one
139 * for the config vec.
142 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
147 vs->vs_flags |= VIRTIO_USE_MSIX;
149 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
151 nvec = vs->vs_vc->vc_nvq + 1;
152 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
155 vs->vs_flags &= ~VIRTIO_USE_MSIX;
157 /* Only 1 MSI vector for bhyve */
158 pci_emul_add_msicap(vs->vs_pi, 1);
160 /* Legacy interrupts are mandatory for virtio devices */
161 pci_lintr_request(vs->vs_pi);
167 * Initialize the currently-selected virtio queue (vs->vs_curq).
168 * The guest just gave us a page frame number, from which we can
169 * calculate the addresses of the queue.
172 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
174 struct vqueue_info *vq;
179 vq = &vs->vs_queues[vs->vs_curq];
181 phys = (uint64_t)pfn << VRING_PFN;
182 size = vring_size(vq->vq_qsize);
183 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
185 /* First page(s) are descriptors... */
186 vq->vq_desc = (struct virtio_desc *)base;
187 base += vq->vq_qsize * sizeof(struct virtio_desc);
189 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
190 vq->vq_avail = (struct vring_avail *)base;
191 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
193 /* Then it's rounded up to the next page... */
194 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
196 /* ... and the last page(s) are the used ring. */
197 vq->vq_used = (struct vring_used *)base;
199 /* Mark queue as allocated, and start at 0 when we use it. */
200 vq->vq_flags = VQ_ALLOC;
201 vq->vq_last_avail = 0;
202 vq->vq_save_used = 0;
206 * Helper inline for vq_getchain(): record the i'th "real"
210 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
211 struct iovec *iov, int n_iov, uint16_t *flags) {
215 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
216 iov[i].iov_len = vd->vd_len;
218 flags[i] = vd->vd_flags;
220 #define VQ_MAX_DESCRIPTORS 512 /* see below */
223 * Examine the chain of descriptors starting at the "next one" to
224 * make sure that they describe a sensible request. If so, return
225 * the number of "real" descriptors that would be needed/used in
226 * acting on this request. This may be smaller than the number of
227 * available descriptors, e.g., if there are two available but
228 * they are two separate requests, this just returns 1. Or, it
229 * may be larger: if there are indirect descriptors involved,
230 * there may only be one descriptor available but it may be an
231 * indirect pointing to eight more. We return 8 in this case,
232 * i.e., we do not count the indirect descriptors, only the "real"
235 * Basically, this vets the vd_flags and vd_next field of each
236 * descriptor and tells you how many are involved. Since some may
237 * be indirect, this also needs the vmctx (in the pci_devinst
238 * at vs->vs_pi) so that it can find indirect descriptors.
240 * As we process each descriptor, we copy and adjust it (guest to
241 * host address wise, also using the vmtctx) into the given iov[]
242 * array (of the given size). If the array overflows, we stop
243 * placing values into the array but keep processing descriptors,
244 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
245 * So you, the caller, must not assume that iov[] is as big as the
246 * return value (you can process the same thing twice to allocate
247 * a larger iov array if needed, or supply a zero length to find
248 * out how much space is needed).
250 * If you want to verify the WRITE flag on each descriptor, pass a
251 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
252 * as n_iov and we'll copy each vd_flags field after unwinding any
255 * If some descriptor(s) are invalid, this prints a diagnostic message
256 * and returns -1. If no descriptors are ready now it simply returns 0.
258 * You are assumed to have done a vq_ring_ready() if needed (note
259 * that vq_has_descs() does one).
262 vq_getchain(struct vqueue_info *vq, uint16_t *pidx,
263 struct iovec *iov, int n_iov, uint16_t *flags)
266 u_int ndesc, n_indir;
268 volatile struct virtio_desc *vdir, *vindir, *vp;
270 struct virtio_softc *vs;
274 name = vs->vs_vc->vc_name;
277 * Note: it's the responsibility of the guest not to
278 * update vq->vq_avail->va_idx until all of the descriptors
279 * the guest has written are valid (including all their
280 * vd_next fields and vd_flags).
282 * Compute (last_avail - va_idx) in integers mod 2**16. This is
283 * the number of descriptors the device has made available
284 * since the last time we updated vq->vq_last_avail.
286 * We just need to do the subtraction as an unsigned int,
287 * then trim off excess bits.
289 idx = vq->vq_last_avail;
290 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
293 if (ndesc > vq->vq_qsize) {
294 /* XXX need better way to diagnose issues */
296 "%s: ndesc (%u) out of range, driver confused?\r\n",
302 * Now count/parse "involved" descriptors starting from
303 * the head of the chain.
305 * To prevent loops, we could be more complicated and
306 * check whether we're re-visiting a previously visited
307 * index, but we just abort if the count gets excessive.
309 ctx = vs->vs_pi->pi_vmctx;
310 *pidx = next = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
312 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
313 if (next >= vq->vq_qsize) {
315 "%s: descriptor index %u out of range, "
316 "driver confused?\r\n",
320 vdir = &vq->vq_desc[next];
321 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
322 _vq_record(i, vdir, ctx, iov, n_iov, flags);
324 } else if ((vs->vs_vc->vc_hv_caps &
325 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
327 "%s: descriptor has forbidden INDIRECT flag, "
328 "driver confused?\r\n",
332 n_indir = vdir->vd_len / 16;
333 if ((vdir->vd_len & 0xf) || n_indir == 0) {
335 "%s: invalid indir len 0x%x, "
336 "driver confused?\r\n",
337 name, (u_int)vdir->vd_len);
340 vindir = paddr_guest2host(ctx,
341 vdir->vd_addr, vdir->vd_len);
343 * Indirects start at the 0th, then follow
344 * their own embedded "next"s until those run
345 * out. Each one's indirect flag must be off
346 * (we don't really have to check, could just
352 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
354 "%s: indirect desc has INDIR flag,"
355 " driver confused?\r\n",
359 _vq_record(i, vp, ctx, iov, n_iov, flags);
360 if (++i > VQ_MAX_DESCRIPTORS)
362 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
365 if (next >= n_indir) {
367 "%s: invalid next %u > %u, "
368 "driver confused?\r\n",
369 name, (u_int)next, n_indir);
374 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
379 "%s: descriptor loop? count > %d - driver confused?\r\n",
385 * Return the currently-first request chain back to the available queue.
387 * (This chain is the one you handled when you called vq_getchain()
388 * and used its positive return value.)
391 vq_retchain(struct vqueue_info *vq)
398 * Return specified request chain to the guest, setting its I/O length
399 * to the provided value.
401 * (This chain is the one you handled when you called vq_getchain()
402 * and used its positive return value.)
405 vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
408 volatile struct vring_used *vuh;
409 volatile struct virtio_used *vue;
413 * - mask is N-1 where N is a power of 2 so computes x % N
414 * - vuh points to the "used" data shared with guest
415 * - vue points to the "used" ring entry we want to update
416 * - head is the same value we compute in vq_iovecs().
418 * (I apologize for the two fields named vu_idx; the
419 * virtio spec calls the one that vue points to, "id"...)
421 mask = vq->vq_qsize - 1;
425 vue = &vuh->vu_ring[uidx++ & mask];
427 vue->vu_tlen = iolen;
430 * Ensure the used descriptor is visible before updating the index.
431 * This is necessary on ISAs with memory ordering less strict than x86
432 * (and even on x86 to act as a compiler barrier).
434 atomic_thread_fence_rel();
439 * Driver has finished processing "available" chains and calling
440 * vq_relchain on each one. If driver used all the available
441 * chains, used_all should be set.
443 * If the "used" index moved we may need to inform the guest, i.e.,
444 * deliver an interrupt. Even if the used index did NOT move we
445 * may need to deliver an interrupt, if the avail ring is empty and
446 * we are supposed to interrupt on empty.
448 * Note that used_all_avail is provided by the caller because it's
449 * a snapshot of the ring state when he decided to finish interrupt
450 * processing -- it's possible that descriptors became available after
451 * that point. (It's also typically a constant 1/True as well.)
454 vq_endchains(struct vqueue_info *vq, int used_all_avail)
456 struct virtio_softc *vs;
457 uint16_t event_idx, new_idx, old_idx;
461 * Interrupt generation: if we're using EVENT_IDX,
462 * interrupt if we've crossed the event threshold.
463 * Otherwise interrupt is generated if we added "used" entries,
464 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
466 * In any case, though, if NOTIFY_ON_EMPTY is set and the
467 * entire avail was processed, we need to interrupt always.
470 old_idx = vq->vq_save_used;
471 vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
474 * Use full memory barrier between vu_idx store from preceding
475 * vq_relchain() call and the loads from VQ_USED_EVENT_IDX() or
478 atomic_thread_fence_seq_cst();
479 if (used_all_avail &&
480 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
482 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
483 event_idx = VQ_USED_EVENT_IDX(vq);
485 * This calculation is per docs and the kernel
486 * (see src/sys/dev/virtio/virtio_ring.h).
488 intr = (uint16_t)(new_idx - event_idx - 1) <
489 (uint16_t)(new_idx - old_idx);
491 intr = new_idx != old_idx &&
492 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
495 vq_interrupt(vs, vq);
498 /* Note: these are in sorted order to make for a fast search */
499 static struct config_reg {
500 uint16_t cr_offset; /* register offset */
501 uint8_t cr_size; /* size (bytes) */
502 uint8_t cr_ro; /* true => reg is read only */
503 const char *cr_name; /* name of reg */
505 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
506 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
507 { VTCFG_R_PFN, 4, 0, "PFN" },
508 { VTCFG_R_QNUM, 2, 1, "QNUM" },
509 { VTCFG_R_QSEL, 2, 0, "QSEL" },
510 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
511 { VTCFG_R_STATUS, 1, 0, "STATUS" },
512 { VTCFG_R_ISR, 1, 0, "ISR" },
513 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
514 { VTCFG_R_QVEC, 2, 0, "QVEC" },
517 static inline struct config_reg *
518 vi_find_cr(int offset) {
520 struct config_reg *cr;
523 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
525 mid = (hi + lo) >> 1;
526 cr = &config_regs[mid];
527 if (cr->cr_offset == offset)
529 if (cr->cr_offset < offset)
538 * Handle pci config space reads.
539 * If it's to the MSI-X info, do that.
540 * If it's part of the virtio standard stuff, do that.
541 * Otherwise dispatch to the actual driver.
544 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
545 int baridx, uint64_t offset, int size)
547 struct virtio_softc *vs = pi->pi_arg;
548 struct virtio_consts *vc;
549 struct config_reg *cr;
550 uint64_t virtio_config_size, max;
556 if (vs->vs_flags & VIRTIO_USE_MSIX) {
557 if (baridx == pci_msix_table_bar(pi) ||
558 baridx == pci_msix_pba_bar(pi)) {
559 return (pci_emul_msix_tread(pi, offset, size));
563 /* XXX probably should do something better than just assert() */
567 pthread_mutex_lock(vs->vs_mtx);
571 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
573 if (size != 1 && size != 2 && size != 4)
576 if (pci_msix_enabled(pi))
577 virtio_config_size = VTCFG_R_CFG1;
579 virtio_config_size = VTCFG_R_CFG0;
581 if (offset >= virtio_config_size) {
583 * Subtract off the standard size (including MSI-X
584 * registers if enabled) and dispatch to underlying driver.
585 * If that fails, fall into general code.
587 newoff = offset - virtio_config_size;
588 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
589 if (newoff + size > max)
591 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
597 cr = vi_find_cr(offset);
598 if (cr == NULL || cr->cr_size != size) {
600 /* offset must be OK, so size must be bad */
602 "%s: read from %s: bad size %d\r\n",
603 name, cr->cr_name, size);
606 "%s: read from bad offset/size %jd/%d\r\n",
607 name, (uintmax_t)offset, size);
613 case VTCFG_R_HOSTCAP:
614 value = vc->vc_hv_caps;
616 case VTCFG_R_GUESTCAP:
617 value = vs->vs_negotiated_caps;
620 if (vs->vs_curq < vc->vc_nvq)
621 value = vs->vs_queues[vs->vs_curq].vq_pfn;
624 value = vs->vs_curq < vc->vc_nvq ?
625 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
630 case VTCFG_R_QNOTIFY:
634 value = vs->vs_status;
638 vs->vs_isr = 0; /* a read clears this flag */
640 pci_lintr_deassert(pi);
643 value = vs->vs_msix_cfg_idx;
646 value = vs->vs_curq < vc->vc_nvq ?
647 vs->vs_queues[vs->vs_curq].vq_msix_idx :
648 VIRTIO_MSI_NO_VECTOR;
653 pthread_mutex_unlock(vs->vs_mtx);
658 * Handle pci config space writes.
659 * If it's to the MSI-X info, do that.
660 * If it's part of the virtio standard stuff, do that.
661 * Otherwise dispatch to the actual driver.
664 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
665 int baridx, uint64_t offset, int size, uint64_t value)
667 struct virtio_softc *vs = pi->pi_arg;
668 struct vqueue_info *vq;
669 struct virtio_consts *vc;
670 struct config_reg *cr;
671 uint64_t virtio_config_size, max;
676 if (vs->vs_flags & VIRTIO_USE_MSIX) {
677 if (baridx == pci_msix_table_bar(pi) ||
678 baridx == pci_msix_pba_bar(pi)) {
679 pci_emul_msix_twrite(pi, offset, size, value);
684 /* XXX probably should do something better than just assert() */
688 pthread_mutex_lock(vs->vs_mtx);
693 if (size != 1 && size != 2 && size != 4)
696 if (pci_msix_enabled(pi))
697 virtio_config_size = VTCFG_R_CFG1;
699 virtio_config_size = VTCFG_R_CFG0;
701 if (offset >= virtio_config_size) {
703 * Subtract off the standard size (including MSI-X
704 * registers if enabled) and dispatch to underlying driver.
706 newoff = offset - virtio_config_size;
707 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
708 if (newoff + size > max)
710 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
716 cr = vi_find_cr(offset);
717 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
719 /* offset must be OK, wrong size and/or reg is R/O */
720 if (cr->cr_size != size)
722 "%s: write to %s: bad size %d\r\n",
723 name, cr->cr_name, size);
726 "%s: write to read-only reg %s\r\n",
730 "%s: write to bad offset/size %jd/%d\r\n",
731 name, (uintmax_t)offset, size);
737 case VTCFG_R_GUESTCAP:
738 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
739 if (vc->vc_apply_features)
740 (*vc->vc_apply_features)(DEV_SOFTC(vs),
741 vs->vs_negotiated_caps);
744 if (vs->vs_curq >= vc->vc_nvq)
746 vi_vq_init(vs, value);
750 * Note that the guest is allowed to select an
751 * invalid queue; we just need to return a QNUM
752 * of 0 while the bad queue is selected.
756 case VTCFG_R_QNOTIFY:
757 if (value >= vc->vc_nvq) {
758 fprintf(stderr, "%s: queue %d notify out of range\r\n",
762 vq = &vs->vs_queues[value];
764 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
765 else if (vc->vc_qnotify)
766 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
769 "%s: qnotify queue %d: missing vq/vc notify\r\n",
773 vs->vs_status = value;
775 (*vc->vc_reset)(DEV_SOFTC(vs));
778 vs->vs_msix_cfg_idx = value;
781 if (vs->vs_curq >= vc->vc_nvq)
783 vq = &vs->vs_queues[vs->vs_curq];
784 vq->vq_msix_idx = value;
791 "%s: write config reg %s: curq %d >= max %d\r\n",
792 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
795 pthread_mutex_unlock(vs->vs_mtx);