2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2013 Chris Torek <torek @ torek net>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
38 #include <pthread_np.h>
45 * Functions for dealing with generalized "virtual devices" as
46 * defined by <https://www.google.com/#output=search&q=virtio+spec>
50 * In case we decide to relax the "virtio softc comes at the
51 * front of virtio-based device softc" constraint, let's use
54 #define DEV_SOFTC(vs) ((void *)(vs))
57 * Link a virtio_softc to its constants, the device softc, and
61 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
62 void *dev_softc, struct pci_devinst *pi,
63 struct vqueue_info *queues)
67 /* vs and dev_softc addresses must match */
68 assert((void *)vs == dev_softc);
73 vs->vs_queues = queues;
74 for (i = 0; i < vc->vc_nvq; i++) {
81 * Reset device (device-wide). This erases all queues, i.e.,
82 * all the queues become invalid (though we don't wipe out the
83 * internal pointers, we just clear the VQ_ALLOC flag).
85 * It resets negotiated features to "none".
87 * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
90 vi_reset_dev(struct virtio_softc *vs)
92 struct vqueue_info *vq;
96 assert(pthread_mutex_isowned_np(vs->vs_mtx));
98 nvq = vs->vs_vc->vc_nvq;
99 for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
101 vq->vq_last_avail = 0;
102 vq->vq_save_used = 0;
104 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
106 vs->vs_negotiated_caps = 0;
108 /* vs->vs_status = 0; -- redundant */
110 pci_lintr_deassert(vs->vs_pi);
112 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
116 * Set I/O BAR (usually 0) to map PCI config registers.
119 vi_set_io_bar(struct virtio_softc *vs, int barnum)
124 * ??? should we use CFG0 if MSI-X is disabled?
125 * Existing code did not...
127 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
128 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
132 * Initialize MSI-X vector capabilities if we're to use MSI-X,
133 * or MSI capabilities if not.
135 * We assume we want one MSI-X vector per queue, here, plus one
136 * for the config vec.
139 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
144 vs->vs_flags |= VIRTIO_USE_MSIX;
146 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
148 nvec = vs->vs_vc->vc_nvq + 1;
149 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
152 vs->vs_flags &= ~VIRTIO_USE_MSIX;
154 /* Only 1 MSI vector for bhyve */
155 pci_emul_add_msicap(vs->vs_pi, 1);
157 /* Legacy interrupts are mandatory for virtio devices */
158 pci_lintr_request(vs->vs_pi);
164 * Initialize the currently-selected virtio queue (vs->vs_curq).
165 * The guest just gave us a page frame number, from which we can
166 * calculate the addresses of the queue.
169 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
171 struct vqueue_info *vq;
176 vq = &vs->vs_queues[vs->vs_curq];
178 phys = (uint64_t)pfn << VRING_PFN;
179 size = vring_size(vq->vq_qsize);
180 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
182 /* First page(s) are descriptors... */
183 vq->vq_desc = (struct virtio_desc *)base;
184 base += vq->vq_qsize * sizeof(struct virtio_desc);
186 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
187 vq->vq_avail = (struct vring_avail *)base;
188 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
190 /* Then it's rounded up to the next page... */
191 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
193 /* ... and the last page(s) are the used ring. */
194 vq->vq_used = (struct vring_used *)base;
196 /* Mark queue as allocated, and start at 0 when we use it. */
197 vq->vq_flags = VQ_ALLOC;
198 vq->vq_last_avail = 0;
199 vq->vq_save_used = 0;
203 * Helper inline for vq_getchain(): record the i'th "real"
207 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
208 struct iovec *iov, int n_iov, uint16_t *flags) {
212 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
213 iov[i].iov_len = vd->vd_len;
215 flags[i] = vd->vd_flags;
217 #define VQ_MAX_DESCRIPTORS 512 /* see below */
220 * Examine the chain of descriptors starting at the "next one" to
221 * make sure that they describe a sensible request. If so, return
222 * the number of "real" descriptors that would be needed/used in
223 * acting on this request. This may be smaller than the number of
224 * available descriptors, e.g., if there are two available but
225 * they are two separate requests, this just returns 1. Or, it
226 * may be larger: if there are indirect descriptors involved,
227 * there may only be one descriptor available but it may be an
228 * indirect pointing to eight more. We return 8 in this case,
229 * i.e., we do not count the indirect descriptors, only the "real"
232 * Basically, this vets the vd_flags and vd_next field of each
233 * descriptor and tells you how many are involved. Since some may
234 * be indirect, this also needs the vmctx (in the pci_devinst
235 * at vs->vs_pi) so that it can find indirect descriptors.
237 * As we process each descriptor, we copy and adjust it (guest to
238 * host address wise, also using the vmtctx) into the given iov[]
239 * array (of the given size). If the array overflows, we stop
240 * placing values into the array but keep processing descriptors,
241 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
242 * So you, the caller, must not assume that iov[] is as big as the
243 * return value (you can process the same thing twice to allocate
244 * a larger iov array if needed, or supply a zero length to find
245 * out how much space is needed).
247 * If you want to verify the WRITE flag on each descriptor, pass a
248 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
249 * as n_iov and we'll copy each vd_flags field after unwinding any
252 * If some descriptor(s) are invalid, this prints a diagnostic message
253 * and returns -1. If no descriptors are ready now it simply returns 0.
255 * You are assumed to have done a vq_ring_ready() if needed (note
256 * that vq_has_descs() does one).
259 vq_getchain(struct vqueue_info *vq, uint16_t *pidx,
260 struct iovec *iov, int n_iov, uint16_t *flags)
263 u_int ndesc, n_indir;
265 volatile struct virtio_desc *vdir, *vindir, *vp;
267 struct virtio_softc *vs;
271 name = vs->vs_vc->vc_name;
274 * Note: it's the responsibility of the guest not to
275 * update vq->vq_avail->va_idx until all of the descriptors
276 * the guest has written are valid (including all their
277 * vd_next fields and vd_flags).
279 * Compute (last_avail - va_idx) in integers mod 2**16. This is
280 * the number of descriptors the device has made available
281 * since the last time we updated vq->vq_last_avail.
283 * We just need to do the subtraction as an unsigned int,
284 * then trim off excess bits.
286 idx = vq->vq_last_avail;
287 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
290 if (ndesc > vq->vq_qsize) {
291 /* XXX need better way to diagnose issues */
293 "%s: ndesc (%u) out of range, driver confused?\r\n",
299 * Now count/parse "involved" descriptors starting from
300 * the head of the chain.
302 * To prevent loops, we could be more complicated and
303 * check whether we're re-visiting a previously visited
304 * index, but we just abort if the count gets excessive.
306 ctx = vs->vs_pi->pi_vmctx;
307 *pidx = next = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
309 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
310 if (next >= vq->vq_qsize) {
312 "%s: descriptor index %u out of range, "
313 "driver confused?\r\n",
317 vdir = &vq->vq_desc[next];
318 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
319 _vq_record(i, vdir, ctx, iov, n_iov, flags);
321 } else if ((vs->vs_vc->vc_hv_caps &
322 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
324 "%s: descriptor has forbidden INDIRECT flag, "
325 "driver confused?\r\n",
329 n_indir = vdir->vd_len / 16;
330 if ((vdir->vd_len & 0xf) || n_indir == 0) {
332 "%s: invalid indir len 0x%x, "
333 "driver confused?\r\n",
334 name, (u_int)vdir->vd_len);
337 vindir = paddr_guest2host(ctx,
338 vdir->vd_addr, vdir->vd_len);
340 * Indirects start at the 0th, then follow
341 * their own embedded "next"s until those run
342 * out. Each one's indirect flag must be off
343 * (we don't really have to check, could just
349 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
351 "%s: indirect desc has INDIR flag,"
352 " driver confused?\r\n",
356 _vq_record(i, vp, ctx, iov, n_iov, flags);
357 if (++i > VQ_MAX_DESCRIPTORS)
359 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
362 if (next >= n_indir) {
364 "%s: invalid next %u > %u, "
365 "driver confused?\r\n",
366 name, (u_int)next, n_indir);
371 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
376 "%s: descriptor loop? count > %d - driver confused?\r\n",
382 * Return the currently-first request chain back to the available queue.
384 * (This chain is the one you handled when you called vq_getchain()
385 * and used its positive return value.)
388 vq_retchain(struct vqueue_info *vq)
395 * Return specified request chain to the guest, setting its I/O length
396 * to the provided value.
398 * (This chain is the one you handled when you called vq_getchain()
399 * and used its positive return value.)
402 vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
405 volatile struct vring_used *vuh;
406 volatile struct virtio_used *vue;
410 * - mask is N-1 where N is a power of 2 so computes x % N
411 * - vuh points to the "used" data shared with guest
412 * - vue points to the "used" ring entry we want to update
413 * - head is the same value we compute in vq_iovecs().
415 * (I apologize for the two fields named vu_idx; the
416 * virtio spec calls the one that vue points to, "id"...)
418 mask = vq->vq_qsize - 1;
422 vue = &vuh->vu_ring[uidx++ & mask];
424 vue->vu_tlen = iolen;
429 * Driver has finished processing "available" chains and calling
430 * vq_relchain on each one. If driver used all the available
431 * chains, used_all should be set.
433 * If the "used" index moved we may need to inform the guest, i.e.,
434 * deliver an interrupt. Even if the used index did NOT move we
435 * may need to deliver an interrupt, if the avail ring is empty and
436 * we are supposed to interrupt on empty.
438 * Note that used_all_avail is provided by the caller because it's
439 * a snapshot of the ring state when he decided to finish interrupt
440 * processing -- it's possible that descriptors became available after
441 * that point. (It's also typically a constant 1/True as well.)
444 vq_endchains(struct vqueue_info *vq, int used_all_avail)
446 struct virtio_softc *vs;
447 uint16_t event_idx, new_idx, old_idx;
451 * Interrupt generation: if we're using EVENT_IDX,
452 * interrupt if we've crossed the event threshold.
453 * Otherwise interrupt is generated if we added "used" entries,
454 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
456 * In any case, though, if NOTIFY_ON_EMPTY is set and the
457 * entire avail was processed, we need to interrupt always.
460 old_idx = vq->vq_save_used;
461 vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
462 if (used_all_avail &&
463 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
465 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
466 event_idx = VQ_USED_EVENT_IDX(vq);
468 * This calculation is per docs and the kernel
469 * (see src/sys/dev/virtio/virtio_ring.h).
471 intr = (uint16_t)(new_idx - event_idx - 1) <
472 (uint16_t)(new_idx - old_idx);
474 intr = new_idx != old_idx &&
475 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
478 vq_interrupt(vs, vq);
481 /* Note: these are in sorted order to make for a fast search */
482 static struct config_reg {
483 uint16_t cr_offset; /* register offset */
484 uint8_t cr_size; /* size (bytes) */
485 uint8_t cr_ro; /* true => reg is read only */
486 const char *cr_name; /* name of reg */
488 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
489 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
490 { VTCFG_R_PFN, 4, 0, "PFN" },
491 { VTCFG_R_QNUM, 2, 1, "QNUM" },
492 { VTCFG_R_QSEL, 2, 0, "QSEL" },
493 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
494 { VTCFG_R_STATUS, 1, 0, "STATUS" },
495 { VTCFG_R_ISR, 1, 0, "ISR" },
496 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
497 { VTCFG_R_QVEC, 2, 0, "QVEC" },
500 static inline struct config_reg *
501 vi_find_cr(int offset) {
503 struct config_reg *cr;
506 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
508 mid = (hi + lo) >> 1;
509 cr = &config_regs[mid];
510 if (cr->cr_offset == offset)
512 if (cr->cr_offset < offset)
521 * Handle pci config space reads.
522 * If it's to the MSI-X info, do that.
523 * If it's part of the virtio standard stuff, do that.
524 * Otherwise dispatch to the actual driver.
527 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
528 int baridx, uint64_t offset, int size)
530 struct virtio_softc *vs = pi->pi_arg;
531 struct virtio_consts *vc;
532 struct config_reg *cr;
533 uint64_t virtio_config_size, max;
539 if (vs->vs_flags & VIRTIO_USE_MSIX) {
540 if (baridx == pci_msix_table_bar(pi) ||
541 baridx == pci_msix_pba_bar(pi)) {
542 return (pci_emul_msix_tread(pi, offset, size));
546 /* XXX probably should do something better than just assert() */
550 pthread_mutex_lock(vs->vs_mtx);
554 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
556 if (size != 1 && size != 2 && size != 4)
559 if (pci_msix_enabled(pi))
560 virtio_config_size = VTCFG_R_CFG1;
562 virtio_config_size = VTCFG_R_CFG0;
564 if (offset >= virtio_config_size) {
566 * Subtract off the standard size (including MSI-X
567 * registers if enabled) and dispatch to underlying driver.
568 * If that fails, fall into general code.
570 newoff = offset - virtio_config_size;
571 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
572 if (newoff + size > max)
574 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
580 cr = vi_find_cr(offset);
581 if (cr == NULL || cr->cr_size != size) {
583 /* offset must be OK, so size must be bad */
585 "%s: read from %s: bad size %d\r\n",
586 name, cr->cr_name, size);
589 "%s: read from bad offset/size %jd/%d\r\n",
590 name, (uintmax_t)offset, size);
596 case VTCFG_R_HOSTCAP:
597 value = vc->vc_hv_caps;
599 case VTCFG_R_GUESTCAP:
600 value = vs->vs_negotiated_caps;
603 if (vs->vs_curq < vc->vc_nvq)
604 value = vs->vs_queues[vs->vs_curq].vq_pfn;
607 value = vs->vs_curq < vc->vc_nvq ?
608 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
613 case VTCFG_R_QNOTIFY:
617 value = vs->vs_status;
621 vs->vs_isr = 0; /* a read clears this flag */
623 pci_lintr_deassert(pi);
626 value = vs->vs_msix_cfg_idx;
629 value = vs->vs_curq < vc->vc_nvq ?
630 vs->vs_queues[vs->vs_curq].vq_msix_idx :
631 VIRTIO_MSI_NO_VECTOR;
636 pthread_mutex_unlock(vs->vs_mtx);
641 * Handle pci config space writes.
642 * If it's to the MSI-X info, do that.
643 * If it's part of the virtio standard stuff, do that.
644 * Otherwise dispatch to the actual driver.
647 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
648 int baridx, uint64_t offset, int size, uint64_t value)
650 struct virtio_softc *vs = pi->pi_arg;
651 struct vqueue_info *vq;
652 struct virtio_consts *vc;
653 struct config_reg *cr;
654 uint64_t virtio_config_size, max;
659 if (vs->vs_flags & VIRTIO_USE_MSIX) {
660 if (baridx == pci_msix_table_bar(pi) ||
661 baridx == pci_msix_pba_bar(pi)) {
662 pci_emul_msix_twrite(pi, offset, size, value);
667 /* XXX probably should do something better than just assert() */
671 pthread_mutex_lock(vs->vs_mtx);
676 if (size != 1 && size != 2 && size != 4)
679 if (pci_msix_enabled(pi))
680 virtio_config_size = VTCFG_R_CFG1;
682 virtio_config_size = VTCFG_R_CFG0;
684 if (offset >= virtio_config_size) {
686 * Subtract off the standard size (including MSI-X
687 * registers if enabled) and dispatch to underlying driver.
689 newoff = offset - virtio_config_size;
690 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
691 if (newoff + size > max)
693 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
699 cr = vi_find_cr(offset);
700 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
702 /* offset must be OK, wrong size and/or reg is R/O */
703 if (cr->cr_size != size)
705 "%s: write to %s: bad size %d\r\n",
706 name, cr->cr_name, size);
709 "%s: write to read-only reg %s\r\n",
713 "%s: write to bad offset/size %jd/%d\r\n",
714 name, (uintmax_t)offset, size);
720 case VTCFG_R_GUESTCAP:
721 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
722 if (vc->vc_apply_features)
723 (*vc->vc_apply_features)(DEV_SOFTC(vs),
724 vs->vs_negotiated_caps);
727 if (vs->vs_curq >= vc->vc_nvq)
729 vi_vq_init(vs, value);
733 * Note that the guest is allowed to select an
734 * invalid queue; we just need to return a QNUM
735 * of 0 while the bad queue is selected.
739 case VTCFG_R_QNOTIFY:
740 if (value >= vc->vc_nvq) {
741 fprintf(stderr, "%s: queue %d notify out of range\r\n",
745 vq = &vs->vs_queues[value];
747 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
748 else if (vc->vc_qnotify)
749 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
752 "%s: qnotify queue %d: missing vq/vc notify\r\n",
756 vs->vs_status = value;
758 (*vc->vc_reset)(DEV_SOFTC(vs));
761 vs->vs_msix_cfg_idx = value;
764 if (vs->vs_curq >= vc->vc_nvq)
766 vq = &vs->vs_queues[vs->vs_curq];
767 vq->vq_msix_idx = value;
774 "%s: write config reg %s: curq %d >= max %d\r\n",
775 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
778 pthread_mutex_unlock(vs->vs_mtx);