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 */
104 pci_lintr_deassert(vs->vs_pi);
107 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
111 * Set I/O BAR (usually 0) to map PCI config registers.
114 vi_set_io_bar(struct virtio_softc *vs, int barnum)
119 * ??? should we use CFG0 if MSI-X is disabled?
120 * Existing code did not...
122 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
123 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
127 * Initialize MSI-X vector capabilities if we're to use MSI-X,
128 * or MSI capabilities if not.
130 * We assume we want one MSI-X vector per queue, here, plus one
131 * for the config vec.
134 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
139 vs->vs_flags |= VIRTIO_USE_MSIX;
140 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
141 nvec = vs->vs_vc->vc_nvq + 1;
142 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
145 vs->vs_flags &= ~VIRTIO_USE_MSIX;
146 /* Only 1 MSI vector for bhyve */
147 pci_emul_add_msicap(vs->vs_pi, 1);
152 * Initialize the currently-selected virtio queue (vs->vs_curq).
153 * The guest just gave us a page frame number, from which we can
154 * calculate the addresses of the queue.
157 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
159 struct vqueue_info *vq;
164 vq = &vs->vs_queues[vs->vs_curq];
166 phys = (uint64_t)pfn << VRING_PFN;
167 size = vring_size(vq->vq_qsize);
168 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
170 /* First page(s) are descriptors... */
171 vq->vq_desc = (struct virtio_desc *)base;
172 base += vq->vq_qsize * sizeof(struct virtio_desc);
174 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
175 vq->vq_avail = (struct vring_avail *)base;
176 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
178 /* Then it's rounded up to the next page... */
179 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
181 /* ... and the last page(s) are the used ring. */
182 vq->vq_used = (struct vring_used *)base;
184 /* Mark queue as allocated, and start at 0 when we use it. */
185 vq->vq_flags = VQ_ALLOC;
186 vq->vq_last_avail = 0;
190 * Helper inline for vq_getchain(): record the i'th "real"
194 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
195 struct iovec *iov, int n_iov, uint16_t *flags) {
199 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
200 iov[i].iov_len = vd->vd_len;
202 flags[i] = vd->vd_flags;
204 #define VQ_MAX_DESCRIPTORS 512 /* see below */
207 * Examine the chain of descriptors starting at the "next one" to
208 * make sure that they describe a sensible request. If so, return
209 * the number of "real" descriptors that would be needed/used in
210 * acting on this request. This may be smaller than the number of
211 * available descriptors, e.g., if there are two available but
212 * they are two separate requests, this just returns 1. Or, it
213 * may be larger: if there are indirect descriptors involved,
214 * there may only be one descriptor available but it may be an
215 * indirect pointing to eight more. We return 8 in this case,
216 * i.e., we do not count the indirect descriptors, only the "real"
219 * Basically, this vets the vd_flags and vd_next field of each
220 * descriptor and tells you how many are involved. Since some may
221 * be indirect, this also needs the vmctx (in the pci_devinst
222 * at vs->vs_pi) so that it can find indirect descriptors.
224 * As we process each descriptor, we copy and adjust it (guest to
225 * host address wise, also using the vmtctx) into the given iov[]
226 * array (of the given size). If the array overflows, we stop
227 * placing values into the array but keep processing descriptors,
228 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
229 * So you, the caller, must not assume that iov[] is as big as the
230 * return value (you can process the same thing twice to allocate
231 * a larger iov array if needed, or supply a zero length to find
232 * out how much space is needed).
234 * If you want to verify the WRITE flag on each descriptor, pass a
235 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
236 * as n_iov and we'll copy each vd_flags field after unwinding any
239 * If some descriptor(s) are invalid, this prints a diagnostic message
240 * and returns -1. If no descriptors are ready now it simply returns 0.
242 * You are assumed to have done a vq_ring_ready() if needed (note
243 * that vq_has_descs() does one).
246 vq_getchain(struct vqueue_info *vq,
247 struct iovec *iov, int n_iov, uint16_t *flags)
250 u_int ndesc, n_indir;
251 u_int idx, head, next;
252 volatile struct virtio_desc *vdir, *vindir, *vp;
254 struct virtio_softc *vs;
258 name = vs->vs_vc->vc_name;
261 * Note: it's the responsibility of the guest not to
262 * update vq->vq_avail->va_idx until all of the descriptors
263 * the guest has written are valid (including all their
264 * vd_next fields and vd_flags).
266 * Compute (last_avail - va_idx) in integers mod 2**16. This is
267 * the number of descriptors the device has made available
268 * since the last time we updated vq->vq_last_avail.
270 * We just need to do the subtraction as an unsigned int,
271 * then trim off excess bits.
273 idx = vq->vq_last_avail;
274 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
277 if (ndesc > vq->vq_qsize) {
278 /* XXX need better way to diagnose issues */
280 "%s: ndesc (%u) out of range, driver confused?\r\n",
286 * Now count/parse "involved" descriptors starting from
287 * the head of the chain.
289 * To prevent loops, we could be more complicated and
290 * check whether we're re-visiting a previously visited
291 * index, but we just abort if the count gets excessive.
293 ctx = vs->vs_pi->pi_vmctx;
294 head = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
296 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
297 if (next >= vq->vq_qsize) {
299 "%s: descriptor index %u out of range, "
300 "driver confused?\r\n",
304 vdir = &vq->vq_desc[next];
305 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
306 _vq_record(i, vdir, ctx, iov, n_iov, flags);
308 } else if ((vs->vs_negotiated_caps &
309 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
311 "%s: descriptor has forbidden INDIRECT flag, "
312 "driver confused?\r\n",
316 n_indir = vdir->vd_len / 16;
317 if ((vdir->vd_len & 0xf) || n_indir == 0) {
319 "%s: invalid indir len 0x%x, "
320 "driver confused?\r\n",
321 name, (u_int)vdir->vd_len);
324 vindir = paddr_guest2host(ctx,
325 vdir->vd_addr, vdir->vd_len);
327 * Indirects start at the 0th, then follow
328 * their own embedded "next"s until those run
329 * out. Each one's indirect flag must be off
330 * (we don't really have to check, could just
336 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
338 "%s: indirect desc has INDIR flag,"
339 " driver confused?\r\n",
343 _vq_record(i, vp, ctx, iov, n_iov, flags);
344 if (++i > VQ_MAX_DESCRIPTORS)
346 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
349 if (next >= n_indir) {
351 "%s: invalid next %u > %u, "
352 "driver confused?\r\n",
353 name, (u_int)next, n_indir);
358 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
363 "%s: descriptor loop? count > %d - driver confused?\r\n",
369 * Return the currently-first request chain to the guest, setting
370 * its I/O length to the provided value.
372 * (This chain is the one you handled when you called vq_getchain()
373 * and used its positive return value.)
376 vq_relchain(struct vqueue_info *vq, uint32_t iolen)
378 uint16_t head, uidx, mask;
379 volatile struct vring_used *vuh;
380 volatile struct virtio_used *vue;
384 * - mask is N-1 where N is a power of 2 so computes x % N
385 * - vuh points to the "used" data shared with guest
386 * - vue points to the "used" ring entry we want to update
387 * - head is the same value we compute in vq_iovecs().
389 * (I apologize for the two fields named vu_idx; the
390 * virtio spec calls the one that vue points to, "id"...)
392 mask = vq->vq_qsize - 1;
394 head = vq->vq_avail->va_ring[vq->vq_last_avail++ & mask];
397 vue = &vuh->vu_ring[uidx++ & mask];
398 vue->vu_idx = head; /* ie, vue->id = head */
399 vue->vu_tlen = iolen;
404 * Driver has finished processing "available" chains and calling
405 * vq_relchain on each one. If driver used all the available
406 * chains, used_all should be set.
408 * If the "used" index moved we may need to inform the guest, i.e.,
409 * deliver an interrupt. Even if the used index did NOT move we
410 * may need to deliver an interrupt, if the avail ring is empty and
411 * we are supposed to interrupt on empty.
413 * Note that used_all_avail is provided by the caller because it's
414 * a snapshot of the ring state when he decided to finish interrupt
415 * processing -- it's possible that descriptors became available after
416 * that point. (It's also typically a constant 1/True as well.)
419 vq_endchains(struct vqueue_info *vq, int used_all_avail)
421 struct virtio_softc *vs;
422 uint16_t event_idx, new_idx, old_idx;
426 * Interrupt generation: if we're using EVENT_IDX,
427 * interrupt if we've crossed the event threshold.
428 * Otherwise interrupt is generated if we added "used" entries,
429 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
431 * In any case, though, if NOTIFY_ON_EMPTY is set and the
432 * entire avail was processed, we need to interrupt always.
435 new_idx = vq->vq_used->vu_idx;
436 old_idx = vq->vq_save_used;
437 if (used_all_avail &&
438 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
440 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
441 event_idx = VQ_USED_EVENT_IDX(vq);
443 * This calculation is per docs and the kernel
444 * (see src/sys/dev/virtio/virtio_ring.h).
446 intr = (uint16_t)(new_idx - event_idx - 1) <
447 (uint16_t)(new_idx - old_idx);
449 intr = new_idx != old_idx &&
450 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
453 vq_interrupt(vs, vq);
456 /* Note: these are in sorted order to make for a fast search */
457 static struct config_reg {
458 uint16_t cr_offset; /* register offset */
459 uint8_t cr_size; /* size (bytes) */
460 uint8_t cr_ro; /* true => reg is read only */
461 const char *cr_name; /* name of reg */
463 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
464 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
465 { VTCFG_R_PFN, 4, 0, "PFN" },
466 { VTCFG_R_QNUM, 2, 1, "QNUM" },
467 { VTCFG_R_QSEL, 2, 0, "QSEL" },
468 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
469 { VTCFG_R_STATUS, 1, 0, "STATUS" },
470 { VTCFG_R_ISR, 1, 0, "ISR" },
471 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
472 { VTCFG_R_QVEC, 2, 0, "QVEC" },
475 static inline struct config_reg *
476 vi_find_cr(int offset) {
478 struct config_reg *cr;
481 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
483 mid = (hi + lo) >> 1;
484 cr = &config_regs[mid];
485 if (cr->cr_offset == offset)
487 if (cr->cr_offset < offset)
496 * Handle pci config space reads.
497 * If it's to the MSI-X info, do that.
498 * If it's part of the virtio standard stuff, do that.
499 * Otherwise dispatch to the actual driver.
502 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
503 int baridx, uint64_t offset, int size)
505 struct virtio_softc *vs = pi->pi_arg;
506 struct virtio_consts *vc;
507 struct config_reg *cr;
508 uint64_t virtio_config_size, max;
514 if (vs->vs_flags & VIRTIO_USE_MSIX) {
515 if (baridx == pci_msix_table_bar(pi) ||
516 baridx == pci_msix_pba_bar(pi)) {
517 return (pci_emul_msix_tread(pi, offset, size));
521 /* XXX probably should do something better than just assert() */
525 pthread_mutex_lock(vs->vs_mtx);
529 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
531 if (size != 1 && size != 2 && size != 4)
534 if (pci_msix_enabled(pi))
535 virtio_config_size = VTCFG_R_CFG1;
537 virtio_config_size = VTCFG_R_CFG0;
539 if (offset >= virtio_config_size) {
541 * Subtract off the standard size (including MSI-X
542 * registers if enabled) and dispatch to underlying driver.
543 * If that fails, fall into general code.
545 newoff = offset - virtio_config_size;
546 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
547 if (newoff + size > max)
549 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
555 cr = vi_find_cr(offset);
556 if (cr == NULL || cr->cr_size != size) {
558 /* offset must be OK, so size must be bad */
560 "%s: read from %s: bad size %d\r\n",
561 name, cr->cr_name, size);
564 "%s: read from bad offset/size %jd/%d\r\n",
565 name, (uintmax_t)offset, size);
571 case VTCFG_R_HOSTCAP:
572 value = vc->vc_hv_caps;
574 case VTCFG_R_GUESTCAP:
575 value = vs->vs_negotiated_caps;
578 if (vs->vs_curq < vc->vc_nvq)
579 value = vs->vs_queues[vs->vs_curq].vq_pfn;
582 value = vs->vs_curq < vc->vc_nvq ?
583 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
588 case VTCFG_R_QNOTIFY:
592 value = vs->vs_status;
596 vs->vs_isr = 0; /* a read clears this flag */
598 pci_lintr_deassert(pi);
601 value = vs->vs_msix_cfg_idx;
604 value = vs->vs_curq < vc->vc_nvq ?
605 vs->vs_queues[vs->vs_curq].vq_msix_idx :
606 VIRTIO_MSI_NO_VECTOR;
611 pthread_mutex_unlock(vs->vs_mtx);
616 * Handle pci config space writes.
617 * If it's to the MSI-X info, do that.
618 * If it's part of the virtio standard stuff, do that.
619 * Otherwise dispatch to the actual driver.
622 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
623 int baridx, uint64_t offset, int size, uint64_t value)
625 struct virtio_softc *vs = pi->pi_arg;
626 struct vqueue_info *vq;
627 struct virtio_consts *vc;
628 struct config_reg *cr;
629 uint64_t virtio_config_size, max;
634 if (vs->vs_flags & VIRTIO_USE_MSIX) {
635 if (baridx == pci_msix_table_bar(pi) ||
636 baridx == pci_msix_pba_bar(pi)) {
637 pci_emul_msix_twrite(pi, offset, size, value);
642 /* XXX probably should do something better than just assert() */
646 pthread_mutex_lock(vs->vs_mtx);
651 if (size != 1 && size != 2 && size != 4)
654 if (pci_msix_enabled(pi))
655 virtio_config_size = VTCFG_R_CFG1;
657 virtio_config_size = VTCFG_R_CFG0;
659 if (offset >= virtio_config_size) {
661 * Subtract off the standard size (including MSI-X
662 * registers if enabled) and dispatch to underlying driver.
664 newoff = offset - virtio_config_size;
665 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
666 if (newoff + size > max)
668 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
674 cr = vi_find_cr(offset);
675 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
677 /* offset must be OK, wrong size and/or reg is R/O */
678 if (cr->cr_size != size)
680 "%s: write to %s: bad size %d\r\n",
681 name, cr->cr_name, size);
684 "%s: write to read-only reg %s\r\n",
688 "%s: write to bad offset/size %jd/%d\r\n",
689 name, (uintmax_t)offset, size);
695 case VTCFG_R_GUESTCAP:
696 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
697 if (vc->vc_apply_features)
698 (*vc->vc_apply_features)(DEV_SOFTC(vs),
699 vs->vs_negotiated_caps);
702 if (vs->vs_curq >= vc->vc_nvq)
704 vi_vq_init(vs, value);
708 * Note that the guest is allowed to select an
709 * invalid queue; we just need to return a QNUM
710 * of 0 while the bad queue is selected.
714 case VTCFG_R_QNOTIFY:
715 if (value >= vc->vc_nvq) {
716 fprintf(stderr, "%s: queue %d notify out of range\r\n",
720 vq = &vs->vs_queues[value];
722 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
723 else if (vc->vc_qnotify)
724 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
727 "%s: qnotify queue %d: missing vq/vc notify\r\n",
731 vs->vs_status = value;
733 (*vc->vc_reset)(DEV_SOFTC(vs));
736 vs->vs_msix_cfg_idx = value;
739 if (vs->vs_curq >= vc->vc_nvq)
741 vq = &vs->vs_queues[vs->vs_curq];
742 vq->vq_msix_idx = value;
749 "%s: write config reg %s: curq %d >= max %d\r\n",
750 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
753 pthread_mutex_unlock(vs->vs_mtx);