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;
100 vq
->vq_save_used
= 0;
102 vq
->vq_msix_idx
= VIRTIO_MSI_NO_VECTOR
;
104 vs
->vs_negotiated_caps
= 0;
106 /* vs->vs_status = 0; -- redundant */
108 pci_lintr_deassert(vs
->vs_pi
);
110 vs
->vs_msix_cfg_idx
= VIRTIO_MSI_NO_VECTOR
;
114 * Set I/O BAR (usually 0) to map PCI config registers.
117 vi_set_io_bar(struct virtio_softc
*vs
, int barnum
)
122 * ??? should we use CFG0 if MSI-X is disabled?
123 * Existing code did not...
125 size
= VTCFG_R_CFG1
+ vs
->vs_vc
->vc_cfgsize
;
126 pci_emul_alloc_bar(vs
->vs_pi
, barnum
, PCIBAR_IO
, size
);
130 * Initialize MSI-X vector capabilities if we're to use MSI-X,
131 * or MSI capabilities if not.
133 * We assume we want one MSI-X vector per queue, here, plus one
134 * for the config vec.
137 vi_intr_init(struct virtio_softc
*vs
, int barnum
, int use_msix
)
142 vs
->vs_flags
|= VIRTIO_USE_MSIX
;
144 vi_reset_dev(vs
); /* set all vectors to NO_VECTOR */
146 nvec
= vs
->vs_vc
->vc_nvq
+ 1;
147 if (pci_emul_add_msixcap(vs
->vs_pi
, nvec
, barnum
))
150 vs
->vs_flags
&= ~VIRTIO_USE_MSIX
;
152 /* Only 1 MSI vector for bhyve */
153 pci_emul_add_msicap(vs
->vs_pi
, 1);
155 /* Legacy interrupts are mandatory for virtio devices */
156 pci_lintr_request(vs
->vs_pi
);
162 * Initialize the currently-selected virtio queue (vs->vs_curq).
163 * The guest just gave us a page frame number, from which we can
164 * calculate the addresses of the queue.
167 vi_vq_init(struct virtio_softc
*vs
, uint32_t pfn
)
169 struct vqueue_info
*vq
;
174 vq
= &vs
->vs_queues
[vs
->vs_curq
];
176 phys
= (uint64_t)pfn
<< VRING_PFN
;
177 size
= vring_size(vq
->vq_qsize
);
178 base
= paddr_guest2host(vs
->vs_pi
->pi_vmctx
, phys
, size
);
180 /* First page(s) are descriptors... */
181 vq
->vq_desc
= (struct virtio_desc
*)base
;
182 base
+= vq
->vq_qsize
* sizeof(struct virtio_desc
);
184 /* ... immediately followed by "avail" ring (entirely uint16_t's) */
185 vq
->vq_avail
= (struct vring_avail
*)base
;
186 base
+= (2 + vq
->vq_qsize
+ 1) * sizeof(uint16_t);
188 /* Then it's rounded up to the next page... */
189 base
= (char *)roundup2((uintptr_t)base
, VRING_ALIGN
);
191 /* ... and the last page(s) are the used ring. */
192 vq
->vq_used
= (struct vring_used
*)base
;
194 /* Mark queue as allocated, and start at 0 when we use it. */
195 vq
->vq_flags
= VQ_ALLOC
;
196 vq
->vq_last_avail
= 0;
197 vq
->vq_save_used
= 0;
201 * Helper inline for vq_getchain(): record the i'th "real"
205 _vq_record(int i
, volatile struct virtio_desc
*vd
, struct vmctx
*ctx
,
206 struct iovec
*iov
, int n_iov
, uint16_t *flags
) {
210 iov
[i
].iov_base
= paddr_guest2host(ctx
, vd
->vd_addr
, vd
->vd_len
);
211 iov
[i
].iov_len
= vd
->vd_len
;
213 flags
[i
] = vd
->vd_flags
;
215 #define VQ_MAX_DESCRIPTORS 512 /* see below */
218 * Examine the chain of descriptors starting at the "next one" to
219 * make sure that they describe a sensible request. If so, return
220 * the number of "real" descriptors that would be needed/used in
221 * acting on this request. This may be smaller than the number of
222 * available descriptors, e.g., if there are two available but
223 * they are two separate requests, this just returns 1. Or, it
224 * may be larger: if there are indirect descriptors involved,
225 * there may only be one descriptor available but it may be an
226 * indirect pointing to eight more. We return 8 in this case,
227 * i.e., we do not count the indirect descriptors, only the "real"
230 * Basically, this vets the vd_flags and vd_next field of each
231 * descriptor and tells you how many are involved. Since some may
232 * be indirect, this also needs the vmctx (in the pci_devinst
233 * at vs->vs_pi) so that it can find indirect descriptors.
235 * As we process each descriptor, we copy and adjust it (guest to
236 * host address wise, also using the vmtctx) into the given iov[]
237 * array (of the given size). If the array overflows, we stop
238 * placing values into the array but keep processing descriptors,
239 * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
240 * So you, the caller, must not assume that iov[] is as big as the
241 * return value (you can process the same thing twice to allocate
242 * a larger iov array if needed, or supply a zero length to find
243 * out how much space is needed).
245 * If you want to verify the WRITE flag on each descriptor, pass a
246 * non-NULL "flags" pointer to an array of "uint16_t" of the same size
247 * as n_iov and we'll copy each vd_flags field after unwinding any
250 * If some descriptor(s) are invalid, this prints a diagnostic message
251 * and returns -1. If no descriptors are ready now it simply returns 0.
253 * You are assumed to have done a vq_ring_ready() if needed (note
254 * that vq_has_descs() does one).
257 vq_getchain(struct vqueue_info
*vq
, uint16_t *pidx
,
258 struct iovec
*iov
, int n_iov
, uint16_t *flags
)
261 u_int ndesc
, n_indir
;
263 volatile struct virtio_desc
*vdir
, *vindir
, *vp
;
265 struct virtio_softc
*vs
;
269 name
= vs
->vs_vc
->vc_name
;
272 * Note: it's the responsibility of the guest not to
273 * update vq->vq_avail->va_idx until all of the descriptors
274 * the guest has written are valid (including all their
275 * vd_next fields and vd_flags).
277 * Compute (last_avail - va_idx) in integers mod 2**16. This is
278 * the number of descriptors the device has made available
279 * since the last time we updated vq->vq_last_avail.
281 * We just need to do the subtraction as an unsigned int,
282 * then trim off excess bits.
284 idx
= vq
->vq_last_avail
;
285 ndesc
= (uint16_t)((u_int
)vq
->vq_avail
->va_idx
- idx
);
288 if (ndesc
> vq
->vq_qsize
) {
289 /* XXX need better way to diagnose issues */
291 "%s: ndesc (%u) out of range, driver confused?\r\n",
297 * Now count/parse "involved" descriptors starting from
298 * the head of the chain.
300 * To prevent loops, we could be more complicated and
301 * check whether we're re-visiting a previously visited
302 * index, but we just abort if the count gets excessive.
304 ctx
= vs
->vs_pi
->pi_vmctx
;
305 *pidx
= next
= vq
->vq_avail
->va_ring
[idx
& (vq
->vq_qsize
- 1)];
307 for (i
= 0; i
< VQ_MAX_DESCRIPTORS
; next
= vdir
->vd_next
) {
308 if (next
>= vq
->vq_qsize
) {
310 "%s: descriptor index %u out of range, "
311 "driver confused?\r\n",
315 vdir
= &vq
->vq_desc
[next
];
316 if ((vdir
->vd_flags
& VRING_DESC_F_INDIRECT
) == 0) {
317 _vq_record(i
, vdir
, ctx
, iov
, n_iov
, flags
);
319 } else if ((vs
->vs_vc
->vc_hv_caps
&
320 VIRTIO_RING_F_INDIRECT_DESC
) == 0) {
322 "%s: descriptor has forbidden INDIRECT flag, "
323 "driver confused?\r\n",
327 n_indir
= vdir
->vd_len
/ 16;
328 if ((vdir
->vd_len
& 0xf) || n_indir
== 0) {
330 "%s: invalid indir len 0x%x, "
331 "driver confused?\r\n",
332 name
, (u_int
)vdir
->vd_len
);
335 vindir
= paddr_guest2host(ctx
,
336 vdir
->vd_addr
, vdir
->vd_len
);
338 * Indirects start at the 0th, then follow
339 * their own embedded "next"s until those run
340 * out. Each one's indirect flag must be off
341 * (we don't really have to check, could just
347 if (vp
->vd_flags
& VRING_DESC_F_INDIRECT
) {
349 "%s: indirect desc has INDIR flag,"
350 " driver confused?\r\n",
354 _vq_record(i
, vp
, ctx
, iov
, n_iov
, flags
);
355 if (++i
> VQ_MAX_DESCRIPTORS
)
357 if ((vp
->vd_flags
& VRING_DESC_F_NEXT
) == 0)
360 if (next
>= n_indir
) {
362 "%s: invalid next %u > %u, "
363 "driver confused?\r\n",
364 name
, (u_int
)next
, n_indir
);
369 if ((vdir
->vd_flags
& VRING_DESC_F_NEXT
) == 0)
374 "%s: descriptor loop? count > %d - driver confused?\r\n",
380 * Return the currently-first request chain back to the available queue.
382 * (This chain is the one you handled when you called vq_getchain()
383 * and used its positive return value.)
386 vq_retchain(struct vqueue_info
*vq
)
393 * Return specified request chain to the guest, setting its I/O length
394 * to the provided value.
396 * (This chain is the one you handled when you called vq_getchain()
397 * and used its positive return value.)
400 vq_relchain(struct vqueue_info
*vq
, uint16_t idx
, uint32_t iolen
)
403 volatile struct vring_used
*vuh
;
404 volatile struct virtio_used
*vue
;
408 * - mask is N-1 where N is a power of 2 so computes x % N
409 * - vuh points to the "used" data shared with guest
410 * - vue points to the "used" ring entry we want to update
411 * - head is the same value we compute in vq_iovecs().
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;
420 vue
= &vuh
->vu_ring
[uidx
++ & mask
];
422 vue
->vu_tlen
= iolen
;
427 * Driver has finished processing "available" chains and calling
428 * vq_relchain on each one. If driver used all the available
429 * chains, used_all should be set.
431 * If the "used" index moved we may need to inform the guest, i.e.,
432 * deliver an interrupt. Even if the used index did NOT move we
433 * may need to deliver an interrupt, if the avail ring is empty and
434 * we are supposed to interrupt on empty.
436 * Note that used_all_avail is provided by the caller because it's
437 * a snapshot of the ring state when he decided to finish interrupt
438 * processing -- it's possible that descriptors became available after
439 * that point. (It's also typically a constant 1/True as well.)
442 vq_endchains(struct vqueue_info
*vq
, int used_all_avail
)
444 struct virtio_softc
*vs
;
445 uint16_t event_idx
, new_idx
, old_idx
;
449 * Interrupt generation: if we're using EVENT_IDX,
450 * interrupt if we've crossed the event threshold.
451 * Otherwise interrupt is generated if we added "used" entries,
452 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
454 * In any case, though, if NOTIFY_ON_EMPTY is set and the
455 * entire avail was processed, we need to interrupt always.
458 old_idx
= vq
->vq_save_used
;
459 vq
->vq_save_used
= new_idx
= vq
->vq_used
->vu_idx
;
460 if (used_all_avail
&&
461 (vs
->vs_negotiated_caps
& VIRTIO_F_NOTIFY_ON_EMPTY
))
463 else if (vs
->vs_negotiated_caps
& VIRTIO_RING_F_EVENT_IDX
) {
464 event_idx
= VQ_USED_EVENT_IDX(vq
);
466 * This calculation is per docs and the kernel
467 * (see src/sys/dev/virtio/virtio_ring.h).
469 intr
= (uint16_t)(new_idx
- event_idx
- 1) <
470 (uint16_t)(new_idx
- old_idx
);
472 intr
= new_idx
!= old_idx
&&
473 !(vq
->vq_avail
->va_flags
& VRING_AVAIL_F_NO_INTERRUPT
);
476 vq_interrupt(vs
, vq
);
479 /* Note: these are in sorted order to make for a fast search */
480 static struct config_reg
{
481 uint16_t cr_offset
; /* register offset */
482 uint8_t cr_size
; /* size (bytes) */
483 uint8_t cr_ro
; /* true => reg is read only */
484 const char *cr_name
; /* name of reg */
486 { VTCFG_R_HOSTCAP
, 4, 1, "HOSTCAP" },
487 { VTCFG_R_GUESTCAP
, 4, 0, "GUESTCAP" },
488 { VTCFG_R_PFN
, 4, 0, "PFN" },
489 { VTCFG_R_QNUM
, 2, 1, "QNUM" },
490 { VTCFG_R_QSEL
, 2, 0, "QSEL" },
491 { VTCFG_R_QNOTIFY
, 2, 0, "QNOTIFY" },
492 { VTCFG_R_STATUS
, 1, 0, "STATUS" },
493 { VTCFG_R_ISR
, 1, 0, "ISR" },
494 { VTCFG_R_CFGVEC
, 2, 0, "CFGVEC" },
495 { VTCFG_R_QVEC
, 2, 0, "QVEC" },
498 static inline struct config_reg
*
499 vi_find_cr(int offset
) {
501 struct config_reg
*cr
;
504 hi
= sizeof(config_regs
) / sizeof(*config_regs
) - 1;
506 mid
= (hi
+ lo
) >> 1;
507 cr
= &config_regs
[mid
];
508 if (cr
->cr_offset
== offset
)
510 if (cr
->cr_offset
< offset
)
519 * Handle pci config space reads.
520 * If it's to the MSI-X info, do that.
521 * If it's part of the virtio standard stuff, do that.
522 * Otherwise dispatch to the actual driver.
525 vi_pci_read(struct vmctx
*ctx
, int vcpu
, struct pci_devinst
*pi
,
526 int baridx
, uint64_t offset
, int size
)
528 struct virtio_softc
*vs
= pi
->pi_arg
;
529 struct virtio_consts
*vc
;
530 struct config_reg
*cr
;
531 uint64_t virtio_config_size
, max
;
537 if (vs
->vs_flags
& VIRTIO_USE_MSIX
) {
538 if (baridx
== pci_msix_table_bar(pi
) ||
539 baridx
== pci_msix_pba_bar(pi
)) {
540 return (pci_emul_msix_tread(pi
, offset
, size
));
544 /* XXX probably should do something better than just assert() */
548 pthread_mutex_lock(vs
->vs_mtx
);
552 value
= size
== 1 ? 0xff : size
== 2 ? 0xffff : 0xffffffff;
554 if (size
!= 1 && size
!= 2 && size
!= 4)
557 if (pci_msix_enabled(pi
))
558 virtio_config_size
= VTCFG_R_CFG1
;
560 virtio_config_size
= VTCFG_R_CFG0
;
562 if (offset
>= virtio_config_size
) {
564 * Subtract off the standard size (including MSI-X
565 * registers if enabled) and dispatch to underlying driver.
566 * If that fails, fall into general code.
568 newoff
= offset
- virtio_config_size
;
569 max
= vc
->vc_cfgsize
? vc
->vc_cfgsize
: 0x100000000;
570 if (newoff
+ size
> max
)
572 error
= (*vc
->vc_cfgread
)(DEV_SOFTC(vs
), newoff
, size
, &value
);
578 cr
= vi_find_cr(offset
);
579 if (cr
== NULL
|| cr
->cr_size
!= size
) {
581 /* offset must be OK, so size must be bad */
583 "%s: read from %s: bad size %d\r\n",
584 name
, cr
->cr_name
, size
);
587 "%s: read from bad offset/size %jd/%d\r\n",
588 name
, (uintmax_t)offset
, size
);
594 case VTCFG_R_HOSTCAP
:
595 value
= vc
->vc_hv_caps
;
597 case VTCFG_R_GUESTCAP
:
598 value
= vs
->vs_negotiated_caps
;
601 if (vs
->vs_curq
< vc
->vc_nvq
)
602 value
= vs
->vs_queues
[vs
->vs_curq
].vq_pfn
;
605 value
= vs
->vs_curq
< vc
->vc_nvq
?
606 vs
->vs_queues
[vs
->vs_curq
].vq_qsize
: 0;
611 case VTCFG_R_QNOTIFY
:
615 value
= vs
->vs_status
;
619 vs
->vs_isr
= 0; /* a read clears this flag */
621 pci_lintr_deassert(pi
);
624 value
= vs
->vs_msix_cfg_idx
;
627 value
= vs
->vs_curq
< vc
->vc_nvq
?
628 vs
->vs_queues
[vs
->vs_curq
].vq_msix_idx
:
629 VIRTIO_MSI_NO_VECTOR
;
634 pthread_mutex_unlock(vs
->vs_mtx
);
639 * Handle pci config space writes.
640 * If it's to the MSI-X info, do that.
641 * If it's part of the virtio standard stuff, do that.
642 * Otherwise dispatch to the actual driver.
645 vi_pci_write(struct vmctx
*ctx
, int vcpu
, struct pci_devinst
*pi
,
646 int baridx
, uint64_t offset
, int size
, uint64_t value
)
648 struct virtio_softc
*vs
= pi
->pi_arg
;
649 struct vqueue_info
*vq
;
650 struct virtio_consts
*vc
;
651 struct config_reg
*cr
;
652 uint64_t virtio_config_size
, max
;
657 if (vs
->vs_flags
& VIRTIO_USE_MSIX
) {
658 if (baridx
== pci_msix_table_bar(pi
) ||
659 baridx
== pci_msix_pba_bar(pi
)) {
660 pci_emul_msix_twrite(pi
, offset
, size
, value
);
665 /* XXX probably should do something better than just assert() */
669 pthread_mutex_lock(vs
->vs_mtx
);
674 if (size
!= 1 && size
!= 2 && size
!= 4)
677 if (pci_msix_enabled(pi
))
678 virtio_config_size
= VTCFG_R_CFG1
;
680 virtio_config_size
= VTCFG_R_CFG0
;
682 if (offset
>= virtio_config_size
) {
684 * Subtract off the standard size (including MSI-X
685 * registers if enabled) and dispatch to underlying driver.
687 newoff
= offset
- virtio_config_size
;
688 max
= vc
->vc_cfgsize
? vc
->vc_cfgsize
: 0x100000000;
689 if (newoff
+ size
> max
)
691 error
= (*vc
->vc_cfgwrite
)(DEV_SOFTC(vs
), newoff
, size
, value
);
697 cr
= vi_find_cr(offset
);
698 if (cr
== NULL
|| cr
->cr_size
!= size
|| cr
->cr_ro
) {
700 /* offset must be OK, wrong size and/or reg is R/O */
701 if (cr
->cr_size
!= size
)
703 "%s: write to %s: bad size %d\r\n",
704 name
, cr
->cr_name
, size
);
707 "%s: write to read-only reg %s\r\n",
711 "%s: write to bad offset/size %jd/%d\r\n",
712 name
, (uintmax_t)offset
, size
);
718 case VTCFG_R_GUESTCAP
:
719 vs
->vs_negotiated_caps
= value
& vc
->vc_hv_caps
;
720 if (vc
->vc_apply_features
)
721 (*vc
->vc_apply_features
)(DEV_SOFTC(vs
),
722 vs
->vs_negotiated_caps
);
725 if (vs
->vs_curq
>= vc
->vc_nvq
)
727 vi_vq_init(vs
, value
);
731 * Note that the guest is allowed to select an
732 * invalid queue; we just need to return a QNUM
733 * of 0 while the bad queue is selected.
737 case VTCFG_R_QNOTIFY
:
738 if (value
>= vc
->vc_nvq
) {
739 fprintf(stderr
, "%s: queue %d notify out of range\r\n",
743 vq
= &vs
->vs_queues
[value
];
745 (*vq
->vq_notify
)(DEV_SOFTC(vs
), vq
);
746 else if (vc
->vc_qnotify
)
747 (*vc
->vc_qnotify
)(DEV_SOFTC(vs
), vq
);
750 "%s: qnotify queue %d: missing vq/vc notify\r\n",
754 vs
->vs_status
= value
;
756 (*vc
->vc_reset
)(DEV_SOFTC(vs
));
759 vs
->vs_msix_cfg_idx
= value
;
762 if (vs
->vs_curq
>= vc
->vc_nvq
)
764 vq
= &vs
->vs_queues
[vs
->vs_curq
];
765 vq
->vq_msix_idx
= value
;
772 "%s: write config reg %s: curq %d >= max %d\r\n",
773 name
, cr
->cr_name
, vs
->vs_curq
, vc
->vc_nvq
);
776 pthread_mutex_unlock(vs
->vs_mtx
);