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;
101 vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
103 vs->vs_negotiated_caps = 0;
105 /* vs->vs_status = 0; -- redundant */
107 pci_lintr_deassert(vs->vs_pi);
109 vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
113 * Set I/O BAR (usually 0) to map PCI config registers.
116 vi_set_io_bar(struct virtio_softc *vs, int barnum)
121 * ??? should we use CFG0 if MSI-X is disabled?
122 * Existing code did not...
124 size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
125 pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
129 * Initialize MSI-X vector capabilities if we're to use MSI-X,
130 * or MSI capabilities if not.
132 * We assume we want one MSI-X vector per queue, here, plus one
133 * for the config vec.
136 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
141 vs->vs_flags |= VIRTIO_USE_MSIX;
143 vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
145 nvec = vs->vs_vc->vc_nvq + 1;
146 if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
149 vs->vs_flags &= ~VIRTIO_USE_MSIX;
150 /* Only 1 MSI vector for bhyve */
151 pci_emul_add_msicap(vs->vs_pi, 1);
156 * Initialize the currently-selected virtio queue (vs->vs_curq).
157 * The guest just gave us a page frame number, from which we can
158 * calculate the addresses of the queue.
161 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
163 struct vqueue_info *vq;
168 vq = &vs->vs_queues[vs->vs_curq];
170 phys = (uint64_t)pfn << VRING_PFN;
171 size = vring_size(vq->vq_qsize);
172 base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
174 /* First page(s) are descriptors... */
175 vq->vq_desc = (struct virtio_desc *)base;
176 base += vq->vq_qsize * sizeof(struct virtio_desc);
178 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
179 vq->vq_avail = (struct vring_avail *)base;
180 base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
182 /* Then it's rounded up to the next page... */
183 base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
185 /* ... and the last page(s) are the used ring. */
186 vq->vq_used = (struct vring_used *)base;
188 /* Mark queue as allocated, and start at 0 when we use it. */
189 vq->vq_flags = VQ_ALLOC;
190 vq->vq_last_avail = 0;
194 * Helper inline for vq_getchain(): record the i'th "real"
198 _vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
199 struct iovec *iov, int n_iov, uint16_t *flags) {
203 iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
204 iov[i].iov_len = vd->vd_len;
206 flags[i] = vd->vd_flags;
208 #define VQ_MAX_DESCRIPTORS 512 /* see below */
211 * Examine the chain of descriptors starting at the "next one" to
212 * make sure that they describe a sensible request. If so, return
213 * the number of "real" descriptors that would be needed/used in
214 * acting on this request. This may be smaller than the number of
215 * available descriptors, e.g., if there are two available but
216 * they are two separate requests, this just returns 1. Or, it
217 * may be larger: if there are indirect descriptors involved,
218 * there may only be one descriptor available but it may be an
219 * indirect pointing to eight more. We return 8 in this case,
220 * i.e., we do not count the indirect descriptors, only the "real"
223 * Basically, this vets the vd_flags and vd_next field of each
224 * descriptor and tells you how many are involved. Since some may
225 * be indirect, this also needs the vmctx (in the pci_devinst
226 * at vs->vs_pi) so that it can find indirect descriptors.
228 * As we process each descriptor, we copy and adjust it (guest to
229 * host address wise, also using the vmtctx) into the given iov[]
230 * array (of the given size). If the array overflows, we stop
231 * placing values into the array but keep processing descriptors,
232 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
233 * So you, the caller, must not assume that iov[] is as big as the
234 * return value (you can process the same thing twice to allocate
235 * a larger iov array if needed, or supply a zero length to find
236 * out how much space is needed).
238 * If you want to verify the WRITE flag on each descriptor, pass a
239 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
240 * as n_iov and we'll copy each vd_flags field after unwinding any
243 * If some descriptor(s) are invalid, this prints a diagnostic message
244 * and returns -1. If no descriptors are ready now it simply returns 0.
246 * You are assumed to have done a vq_ring_ready() if needed (note
247 * that vq_has_descs() does one).
250 vq_getchain(struct vqueue_info *vq,
251 struct iovec *iov, int n_iov, uint16_t *flags)
254 u_int ndesc, n_indir;
255 u_int idx, head, next;
256 volatile struct virtio_desc *vdir, *vindir, *vp;
258 struct virtio_softc *vs;
262 name = vs->vs_vc->vc_name;
265 * Note: it's the responsibility of the guest not to
266 * update vq->vq_avail->va_idx until all of the descriptors
267 * the guest has written are valid (including all their
268 * vd_next fields and vd_flags).
270 * Compute (last_avail - va_idx) in integers mod 2**16. This is
271 * the number of descriptors the device has made available
272 * since the last time we updated vq->vq_last_avail.
274 * We just need to do the subtraction as an unsigned int,
275 * then trim off excess bits.
277 idx = vq->vq_last_avail;
278 ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
281 if (ndesc > vq->vq_qsize) {
282 /* XXX need better way to diagnose issues */
284 "%s: ndesc (%u) out of range, driver confused?\r\n",
290 * Now count/parse "involved" descriptors starting from
291 * the head of the chain.
293 * To prevent loops, we could be more complicated and
294 * check whether we're re-visiting a previously visited
295 * index, but we just abort if the count gets excessive.
297 ctx = vs->vs_pi->pi_vmctx;
298 head = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
300 for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
301 if (next >= vq->vq_qsize) {
303 "%s: descriptor index %u out of range, "
304 "driver confused?\r\n",
308 vdir = &vq->vq_desc[next];
309 if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
310 _vq_record(i, vdir, ctx, iov, n_iov, flags);
312 } else if ((vs->vs_negotiated_caps &
313 VIRTIO_RING_F_INDIRECT_DESC) == 0) {
315 "%s: descriptor has forbidden INDIRECT flag, "
316 "driver confused?\r\n",
320 n_indir = vdir->vd_len / 16;
321 if ((vdir->vd_len & 0xf) || n_indir == 0) {
323 "%s: invalid indir len 0x%x, "
324 "driver confused?\r\n",
325 name, (u_int)vdir->vd_len);
328 vindir = paddr_guest2host(ctx,
329 vdir->vd_addr, vdir->vd_len);
331 * Indirects start at the 0th, then follow
332 * their own embedded "next"s until those run
333 * out. Each one's indirect flag must be off
334 * (we don't really have to check, could just
340 if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
342 "%s: indirect desc has INDIR flag,"
343 " driver confused?\r\n",
347 _vq_record(i, vp, ctx, iov, n_iov, flags);
348 if (++i > VQ_MAX_DESCRIPTORS)
350 if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
353 if (next >= n_indir) {
355 "%s: invalid next %u > %u, "
356 "driver confused?\r\n",
357 name, (u_int)next, n_indir);
362 if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
367 "%s: descriptor loop? count > %d - driver confused?\r\n",
373 * Return the currently-first request chain to the guest, setting
374 * its I/O length to the provided value.
376 * (This chain is the one you handled when you called vq_getchain()
377 * and used its positive return value.)
380 vq_relchain(struct vqueue_info *vq, uint32_t iolen)
382 uint16_t head, uidx, mask;
383 volatile struct vring_used *vuh;
384 volatile struct virtio_used *vue;
388 * - mask is N-1 where N is a power of 2 so computes x % N
389 * - vuh points to the "used" data shared with guest
390 * - vue points to the "used" ring entry we want to update
391 * - head is the same value we compute in vq_iovecs().
393 * (I apologize for the two fields named vu_idx; the
394 * virtio spec calls the one that vue points to, "id"...)
396 mask = vq->vq_qsize - 1;
398 head = vq->vq_avail->va_ring[vq->vq_last_avail++ & mask];
401 vue = &vuh->vu_ring[uidx++ & mask];
402 vue->vu_idx = head; /* ie, vue->id = head */
403 vue->vu_tlen = iolen;
408 * Driver has finished processing "available" chains and calling
409 * vq_relchain on each one. If driver used all the available
410 * chains, used_all should be set.
412 * If the "used" index moved we may need to inform the guest, i.e.,
413 * deliver an interrupt. Even if the used index did NOT move we
414 * may need to deliver an interrupt, if the avail ring is empty and
415 * we are supposed to interrupt on empty.
417 * Note that used_all_avail is provided by the caller because it's
418 * a snapshot of the ring state when he decided to finish interrupt
419 * processing -- it's possible that descriptors became available after
420 * that point. (It's also typically a constant 1/True as well.)
423 vq_endchains(struct vqueue_info *vq, int used_all_avail)
425 struct virtio_softc *vs;
426 uint16_t event_idx, new_idx, old_idx;
430 * Interrupt generation: if we're using EVENT_IDX,
431 * interrupt if we've crossed the event threshold.
432 * Otherwise interrupt is generated if we added "used" entries,
433 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
435 * In any case, though, if NOTIFY_ON_EMPTY is set and the
436 * entire avail was processed, we need to interrupt always.
439 new_idx = vq->vq_used->vu_idx;
440 old_idx = vq->vq_save_used;
441 if (used_all_avail &&
442 (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
444 else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
445 event_idx = VQ_USED_EVENT_IDX(vq);
447 * This calculation is per docs and the kernel
448 * (see src/sys/dev/virtio/virtio_ring.h).
450 intr = (uint16_t)(new_idx - event_idx - 1) <
451 (uint16_t)(new_idx - old_idx);
453 intr = new_idx != old_idx &&
454 !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
457 vq_interrupt(vs, vq);
460 /* Note: these are in sorted order to make for a fast search */
461 static struct config_reg {
462 uint16_t cr_offset; /* register offset */
463 uint8_t cr_size; /* size (bytes) */
464 uint8_t cr_ro; /* true => reg is read only */
465 const char *cr_name; /* name of reg */
467 { VTCFG_R_HOSTCAP, 4, 1, "HOSTCAP" },
468 { VTCFG_R_GUESTCAP, 4, 0, "GUESTCAP" },
469 { VTCFG_R_PFN, 4, 0, "PFN" },
470 { VTCFG_R_QNUM, 2, 1, "QNUM" },
471 { VTCFG_R_QSEL, 2, 0, "QSEL" },
472 { VTCFG_R_QNOTIFY, 2, 0, "QNOTIFY" },
473 { VTCFG_R_STATUS, 1, 0, "STATUS" },
474 { VTCFG_R_ISR, 1, 0, "ISR" },
475 { VTCFG_R_CFGVEC, 2, 0, "CFGVEC" },
476 { VTCFG_R_QVEC, 2, 0, "QVEC" },
479 static inline struct config_reg *
480 vi_find_cr(int offset) {
482 struct config_reg *cr;
485 hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
487 mid = (hi + lo) >> 1;
488 cr = &config_regs[mid];
489 if (cr->cr_offset == offset)
491 if (cr->cr_offset < offset)
500 * Handle pci config space reads.
501 * If it's to the MSI-X info, do that.
502 * If it's part of the virtio standard stuff, do that.
503 * Otherwise dispatch to the actual driver.
506 vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
507 int baridx, uint64_t offset, int size)
509 struct virtio_softc *vs = pi->pi_arg;
510 struct virtio_consts *vc;
511 struct config_reg *cr;
512 uint64_t virtio_config_size, max;
518 if (vs->vs_flags & VIRTIO_USE_MSIX) {
519 if (baridx == pci_msix_table_bar(pi) ||
520 baridx == pci_msix_pba_bar(pi)) {
521 return (pci_emul_msix_tread(pi, offset, size));
525 /* XXX probably should do something better than just assert() */
529 pthread_mutex_lock(vs->vs_mtx);
533 value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
535 if (size != 1 && size != 2 && size != 4)
538 if (pci_msix_enabled(pi))
539 virtio_config_size = VTCFG_R_CFG1;
541 virtio_config_size = VTCFG_R_CFG0;
543 if (offset >= virtio_config_size) {
545 * Subtract off the standard size (including MSI-X
546 * registers if enabled) and dispatch to underlying driver.
547 * If that fails, fall into general code.
549 newoff = offset - virtio_config_size;
550 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
551 if (newoff + size > max)
553 error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
559 cr = vi_find_cr(offset);
560 if (cr == NULL || cr->cr_size != size) {
562 /* offset must be OK, so size must be bad */
564 "%s: read from %s: bad size %d\r\n",
565 name, cr->cr_name, size);
568 "%s: read from bad offset/size %jd/%d\r\n",
569 name, (uintmax_t)offset, size);
575 case VTCFG_R_HOSTCAP:
576 value = vc->vc_hv_caps;
578 case VTCFG_R_GUESTCAP:
579 value = vs->vs_negotiated_caps;
582 if (vs->vs_curq < vc->vc_nvq)
583 value = vs->vs_queues[vs->vs_curq].vq_pfn;
586 value = vs->vs_curq < vc->vc_nvq ?
587 vs->vs_queues[vs->vs_curq].vq_qsize : 0;
592 case VTCFG_R_QNOTIFY:
596 value = vs->vs_status;
600 vs->vs_isr = 0; /* a read clears this flag */
602 pci_lintr_deassert(pi);
605 value = vs->vs_msix_cfg_idx;
608 value = vs->vs_curq < vc->vc_nvq ?
609 vs->vs_queues[vs->vs_curq].vq_msix_idx :
610 VIRTIO_MSI_NO_VECTOR;
615 pthread_mutex_unlock(vs->vs_mtx);
620 * Handle pci config space writes.
621 * If it's to the MSI-X info, do that.
622 * If it's part of the virtio standard stuff, do that.
623 * Otherwise dispatch to the actual driver.
626 vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
627 int baridx, uint64_t offset, int size, uint64_t value)
629 struct virtio_softc *vs = pi->pi_arg;
630 struct vqueue_info *vq;
631 struct virtio_consts *vc;
632 struct config_reg *cr;
633 uint64_t virtio_config_size, max;
638 if (vs->vs_flags & VIRTIO_USE_MSIX) {
639 if (baridx == pci_msix_table_bar(pi) ||
640 baridx == pci_msix_pba_bar(pi)) {
641 pci_emul_msix_twrite(pi, offset, size, value);
646 /* XXX probably should do something better than just assert() */
650 pthread_mutex_lock(vs->vs_mtx);
655 if (size != 1 && size != 2 && size != 4)
658 if (pci_msix_enabled(pi))
659 virtio_config_size = VTCFG_R_CFG1;
661 virtio_config_size = VTCFG_R_CFG0;
663 if (offset >= virtio_config_size) {
665 * Subtract off the standard size (including MSI-X
666 * registers if enabled) and dispatch to underlying driver.
668 newoff = offset - virtio_config_size;
669 max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
670 if (newoff + size > max)
672 error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
678 cr = vi_find_cr(offset);
679 if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
681 /* offset must be OK, wrong size and/or reg is R/O */
682 if (cr->cr_size != size)
684 "%s: write to %s: bad size %d\r\n",
685 name, cr->cr_name, size);
688 "%s: write to read-only reg %s\r\n",
692 "%s: write to bad offset/size %jd/%d\r\n",
693 name, (uintmax_t)offset, size);
699 case VTCFG_R_GUESTCAP:
700 vs->vs_negotiated_caps = value & vc->vc_hv_caps;
701 if (vc->vc_apply_features)
702 (*vc->vc_apply_features)(DEV_SOFTC(vs),
703 vs->vs_negotiated_caps);
706 if (vs->vs_curq >= vc->vc_nvq)
708 vi_vq_init(vs, value);
712 * Note that the guest is allowed to select an
713 * invalid queue; we just need to return a QNUM
714 * of 0 while the bad queue is selected.
718 case VTCFG_R_QNOTIFY:
719 if (value >= vc->vc_nvq) {
720 fprintf(stderr, "%s: queue %d notify out of range\r\n",
724 vq = &vs->vs_queues[value];
726 (*vq->vq_notify)(DEV_SOFTC(vs), vq);
727 else if (vc->vc_qnotify)
728 (*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
731 "%s: qnotify queue %d: missing vq/vc notify\r\n",
735 vs->vs_status = value;
737 (*vc->vc_reset)(DEV_SOFTC(vs));
740 vs->vs_msix_cfg_idx = value;
743 if (vs->vs_curq >= vc->vc_nvq)
745 vq = &vs->vs_queues[vs->vs_curq];
746 vq->vq_msix_idx = value;
753 "%s: write config reg %s: curq %d >= max %d\r\n",
754 name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
757 pthread_mutex_unlock(vs->vs_mtx);