1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2013 Chris Torek <torek @ torek net>
5 * All rights reserved.
6 * Copyright (c) 2021 The FreeBSD Foundation
7 *
8 * Portions of this software were developed by Ka Ho Ng
9 * under sponsorship of the FreeBSD Foundation.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32 /*
33 * This file and its contents are supplied under the terms of the
34 * Common Development and Distribution License ("CDDL"), version 1.0.
35 * You may only use this file in accordance with the terms of version
36 * 1.0 of the CDDL.
37 *
38 * A full copy of the text of the CDDL should have accompanied this
39 * source. A copy of the CDDL is also available via the Internet at
40 * http://www.illumos.org/license/CDDL.
41 */
42 /* This file is dual-licensed; see usr/src/contrib/bhyve/LICENSE */
43
44 /*
45 * Copyright 2026 Oxide Computer Company
46 */
47
48 #ifndef _BHYVE_VIRTIO_H_
49 #define _BHYVE_VIRTIO_H_
50
51 #include <pthread_np.h>
52 #include <machine/atomic.h>
53 #include <sys/ccompile.h>
54
55 #include <dev/virtio/virtio.h>
56
57 /*
58 * Virtio legacy support is derived from several specifications below:
59 * https://github.com/rustyrussell/virtio-spec
60 * http://people.redhat.com/pbonzini/virtio-spec.pdf
61 *
62 * Virtio modern support is authored with the reference below:
63 * https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.pdf
64 */
65
66 /*
67 * A virtual device has zero or more "virtual queues" (virtqueue).
68 * For a legacy device, each virtqueue uses at least two 4096-byte pages, laid
69 * out thus:
70 *
71 * +-----------------------------------------------+
72 * | "desc": <N> descriptors, 16 bytes each |
73 * | ----------------------------------------- |
74 * | "avail": 2 uint16; <N> uint16; 1 uint16 |
75 * | ----------------------------------------- |
76 * | pad to 4k boundary |
77 * +-----------------------------------------------+
78 * | "used": 2 x uint16; <N> elems; 1 uint16 |
79 * | ----------------------------------------- |
80 * | pad to 4k boundary |
81 * +-----------------------------------------------+
82 *
83 * The number <N> that appears here is always a power of two and is
84 * limited to no more than 32768 (as it must fit in a 16-bit field).
85 * If <N> is sufficiently large, the above will occupy more than
86 * two pages. In any case, all pages must be physically contiguous
87 * within the guest's physical address space.
88 *
89 * The <N> 16-byte "desc" descriptors consist of a 64-bit guest
90 * physical address <addr>, a 32-bit length <len>, a 16-bit
91 * <flags>, and a 16-bit <next> field (all in guest byte order).
92 *
93 * There are three flags that may be set :
94 * NEXT descriptor is chained, so use its "next" field
95 * WRITE descriptor is for host to write into guest RAM
96 * (else host is to read from guest RAM)
97 * INDIRECT descriptor address field is (guest physical)
98 * address of a linear array of descriptors
99 *
100 * Unless INDIRECT is set, <len> is the number of bytes that may
101 * be read/written from guest physical address <addr>. If
102 * INDIRECT is set, WRITE is ignored and <len> provides the length
103 * of the indirect descriptors (and <len> must be a multiple of
104 * 16). Note that NEXT may still be set in the main descriptor
105 * pointing to the indirect, and should be set in each indirect
106 * descriptor that uses the next descriptor (these should generally
107 * be numbered sequentially). However, INDIRECT must not be set
108 * in the indirect descriptors. Upon reaching an indirect descriptor
109 * without a NEXT bit, control returns to the direct descriptors.
110 *
111 * Except inside an indirect, each <next> value must be in the
112 * range [0 .. N) (i.e., the half-open interval). (Inside an
113 * indirect, each <next> must be in the range [0 .. <len>/16).)
114 *
115 * The "avail" data structures reside in the same pages as the
116 * "desc" structures since both together are used by the device to
117 * pass information to the hypervisor's virtual driver. These
118 * begin with a 16-bit <flags> field and 16-bit index <idx>, then
119 * have <N> 16-bit <ring> values, followed by one final 16-bit
120 * field <used_event>. The <N> <ring> entries are simply indices
121 * into the descriptor ring (and thus must meet the same
122 * constraints as each <next> value). However, <idx> is counted
123 * up from 0 (initially) and simply wraps around after 65535; it
124 * is taken mod <N> to find the next available entry.
125 *
126 * The "used" ring occupies a separate page or pages, and contains
127 * values written from the virtual driver back to the guest OS.
128 * This begins with a 16-bit <flags> and 16-bit <idx>, then there
129 * are <N> "vring_used" elements, followed by a 16-bit <avail_event>.
130 * The <N> "vring_used" elements consist of a 32-bit <id> and a
131 * 32-bit <len> (vu_tlen below). The <id> is simply the index of
132 * the head of a descriptor chain the guest made available
133 * earlier, and the <len> is the number of bytes actually written,
134 * e.g., in the case of a network driver that provided a large
135 * receive buffer but received only a small amount of data.
136 *
137 * The two event fields, <used_event> and <avail_event>, in the
138 * avail and used rings (respectively -- note the reversal!), are
139 * always provided, but are used only if the virtual device
140 * negotiates the VIRTIO_RING_F_EVENT_IDX feature during feature
141 * negotiation. Similarly, both rings provide a flag --
142 * VRING_AVAIL_F_NO_INTERRUPT and VRING_USED_F_NO_NOTIFY -- in
143 * their <flags> field, indicating that the guest does not need an
144 * interrupt, or that the hypervisor driver does not need a
145 * notify, when descriptors are added to the corresponding ring.
146 * (These are provided only for interrupt optimization and need
147 * not be implemented.)
148 */
149 #define LEGACY_VRING_ALIGN 4096
150
151 /*
152 * Virtio legacy:
153 *
154 * The address of any given virtual queue is determined by a single
155 * Page Frame Number register. The guest writes the PFN into the
156 * PCI config space. However, a device that has two or more
157 * virtqueues can have a different PFN, and size, for each queue.
158 * The number of queues is determinable via the PCI config space
159 * VTCFG_R_QSEL register. Writes to QSEL select the queue: 0 means
160 * queue #0, 1 means queue#1, etc. Once a queue is selected, the
161 * remaining PFN and QNUM registers refer to that queue.
162 *
163 * QNUM is a read-only register containing a nonzero power of two
164 * that indicates the (hypervisor's) queue size. Or, if reading it
165 * produces zero, the hypervisor does not have a corresponding
166 * queue. (The number of possible queues depends on the virtual
167 * device. The block device has just one; the network device
168 * provides either two -- 0 = receive, 1 = transmit -- or three,
169 * with 2 = control.)
170 *
171 * PFN is a read/write register giving the physical page address of
172 * the virtqueue in guest memory (the guest must allocate enough space
173 * based on the hypervisor's provided QNUM).
174 *
175 * QNOTIFY is effectively write-only: when the guest writes a queue
176 * number to the register, the hypervisor should scan the specified
177 * virtqueue. (Reading QNOTIFY currently always gets 0).
178 */
179
180 /*
181 * PFN register shift amount
182 */
183 #define LEGACY_VRING_PFN 12
184
185 /*
186 * PCI vendor/device IDs
187 */
188 #define VIRTIO_VENDOR 0x1AF4
189 #define VIRTIO_DEV_NET 0x1000
190 #define VIRTIO_DEV_BLOCK 0x1001
191 #define VIRTIO_DEV_CONSOLE 0x1003
192 #define VIRTIO_DEV_SCSI 0x1004
193 #define VIRTIO_DEV_RANDOM 0x1005
194 #define VIRTIO_DEV_9P 0x1009
195 #define VIRTIO_DEV_INPUT 0x1052
196
197 /*
198 * PCI revision IDs
199 */
200 #define VIRTIO_REV_INPUT 1
201
202 /*
203 * PCI subvendor IDs
204 */
205 #define VIRTIO_SUBVEN_INPUT 0x108E
206
207 /*
208 * PCI subdevice IDs
209 */
210 #define VIRTIO_SUBDEV_INPUT 0x1100
211
212 struct pci_devinst;
213 struct vqueue_info;
214
215 /*
216 * A virtual device, with some number (possibly 0) of virtual
217 * queues and some size (possibly 0) of configuration-space
218 * registers private to the device. The virtio_softc should come
219 * at the front of each "derived class", so that a pointer to the
220 * virtio_softc is also a pointer to the more specific, derived-
221 * from-virtio driver's softc.
222 *
223 * Note: inside each hypervisor virtio driver, changes to these
224 * data structures must be locked against other threads, if any.
225 * Except for PCI config space register read/write, we assume each
226 * driver does the required locking, but we need a pointer to the
227 * lock (if there is one) for PCI config space read/write ops.
228 *
229 * When the guest reads or writes the device's config space, the
230 * generic layer checks for operations on the special registers
231 * described above. If the offset of the register(s) being read
232 * or written is past the CFG area (CFG0 or CFG1), the request is
233 * passed on to the virtual device, after subtracting off the
234 * generic-layer size. (So, drivers can just use the offset as
235 * an offset into "struct config", for instance.)
236 *
237 * (The virtio layer also makes sure that the read or write is to/
238 * from a "good" config offset, hence vc_cfgsize, and on BAR #0.
239 * However, the driver must verify the read or write size and offset
240 * and that no one is writing a readonly register.)
241 */
242 typedef enum virtio_flags {
243 VIRTIO_DEBUG = 1 << 0,
244 VIRTIO_USE_MSIX = 1 << 1,
245 VIRTIO_EVENT_IDX = 1 << 2, /* use the event-index values */
246 VIRTIO_DEVCFG_CHG = 1 << 3, /* Device configuration changed */
247 VIRTIO_BROKEN = 1 << 4,
248 } virtio_flags_t;
249
250 typedef enum virtio_mode {
251 VIRTIO_MODE_UNSET = 0,
252 VIRTIO_MODE_LEGACY,
253 VIRTIO_MODE_TRANSITIONAL,
254 VIRTIO_MODE_MODERN
255 } virtio_mode_t;
256
257 /*
258 * This describes a Virtio PCI capability in config space.
259 */
260 typedef struct virtio_pci_capcfg {
261 uint8_t c_captype;
262 /*
263 * The offset and length of the capability in config space.
264 */
265 uint32_t c_capoff;
266 uint32_t c_caplen;
267 /*
268 * The containing BAR, offset and length of the data to which the
269 * capability points.
270 */
271 uint32_t c_barlen;
272 uint32_t c_baroff;
273 uint8_t c_baridx;
274 } virtio_pci_capcfg_t;
275
276 struct virtio_softc {
277 struct virtio_consts *vs_vc; /* constants (see below) */
278 virtio_flags_t vs_flags; /* VIRTIO_* flags from above */
279 virtio_mode_t vs_mode; /* VIRTIO_MODE_* values from above */
280 pthread_mutex_t *vs_mtx; /* POSIX mutex, if any */
281 struct pci_devinst *vs_pi; /* PCI device instance */
282 uint64_t vs_negotiated_caps; /* negotiated capabilities */
283 struct vqueue_info *vs_queues; /* one per vc_nvq */
284 int vs_curq; /* current queue */
285 uint8_t vs_status; /* value from last status write */
286 uint8_t vs_isr; /* ISR flags, if not MSI-X */
287 uint16_t vs_msix_cfg_idx; /* MSI-X vector for config event */
288 uint32_t vs_dfselect; /* Current DFSELECT value */
289 uint32_t vs_gfselect; /* Current GFSELECT value */
290 uint8_t vs_devcfg_gen; /* Generation of device config space */
291 virtio_pci_capcfg_t vs_caps[VIRTIO_PCI_CAP_MAX]; /* PCI capabilities */
292 virtio_pci_capcfg_t *vs_pcicap; /* PCI configuration access cap */
293 uint_t vs_ncaps; /* Number of PCI capabilities */
294 };
295
296 #define VS_LOCK(vs) \
297 do { \
298 if (vs->vs_mtx) \
299 pthread_mutex_lock(vs->vs_mtx); \
300 } while (0)
301
302 #define VS_UNLOCK(vs) \
303 do { \
304 if (vs->vs_mtx) \
305 pthread_mutex_unlock(vs->vs_mtx); \
306 } while (0)
307
308 /*
309 * To aid debugging we allow drivers to provide a table to map feature bits to
310 * text.
311 */
312 typedef struct virtio_capstr {
313 uint64_t vp_flag;
314 const char *vp_name;
315 } virtio_capstr_t;
316
317 struct virtio_consts {
318 const char *vc_name; /* name of driver (for diagnostics) */
319 int vc_nvq; /* current number of virtual queues */
320 int vc_max_nvq; /* max no. queues, for multi-queue */
321 size_t vc_cfgsize; /* size of dev-specific config regs */
322 void (*vc_reset)(void *); /* called on virtual device reset */
323 void (*vc_qinit)(void *, uint64_t, bool);
324 void (*vc_qnotify)(void *, struct vqueue_info *);
325 /* called on QNOTIFY if no VQ notify */
326 int (*vc_cfgread)(void *, int, int, uint32_t *);
327 /* called to read config regs */
328 int (*vc_cfgwrite)(void *, int, int, uint32_t);
329 /* called to write config regs */
330 void (*vc_apply_features)(void *, uint64_t *);
331 /* called to apply negotiated features */
332 uint64_t (*vc_hv_features)(void *, bool);
333 /* called to read device features */
334 void (*vc_set_msix)(void *, int);
335 void (*vc_update_msix)(void *, uint64_t);
336 uint64_t vc_hv_caps_legacy;
337 /* hypervisor-provided capabilities (legacy) */
338 uint64_t vc_hv_caps_modern;
339 /* hypervisor-provided capabilities (modern) */
340 /*
341 * Optional feature bit map.
342 */
343 size_t vc_ncapstr;
344 virtio_capstr_t *vc_capstr;
345 };
346
347 /*
348 * Data structure allocated (statically) per virtual queue.
349 *
350 * Drivers may change vq_qsize after a reset. When the guest OS
351 * requests a device reset, the hypervisor first calls
352 * vs->vs_vc->vc_reset(); then the data structure below is
353 * reinitialized (for each virtqueue: vs->vs_vc->vc_nvq).
354 *
355 * The remaining fields should only be fussed-with by the generic
356 * code.
357 *
358 * Note: the addresses of vq_desc, vq_avail, and vq_used are all
359 * computable from each other in the legacy interface, but even
360 * there it's a lot simpler if we just keep a pointer to
361 * each one. The event indices are similarly (but more
362 * easily) computable, and this time we'll compute them:
363 * they're just XX_ring[N].
364 */
365 #define VQ_ALLOC 0x01 /* set once we have a pfn */
366 #define VQ_ENABLED 0x02 /* set if the queue was enabled */
367 struct vqueue_info {
368 uint16_t vq_qsize; /* size of this queue (a power of 2) */
369 void (*vq_notify)(void *, struct vqueue_info *);
370 /* called instead of vc_notify, if not NULL */
371
372 struct virtio_softc *vq_vs; /* backpointer to softc */
373 uint16_t vq_num; /* we're the num'th queue in the softc */
374
375 uint16_t vq_flags; /* flags (see above) */
376 uint16_t vq_last_avail; /* a recent value of vq_avail->idx */
377 uint16_t vq_next_used; /* index of the next used slot to be filled */
378 uint16_t vq_save_used; /* saved vq_used->idx; see vq_endchains */
379 uint16_t vq_msix_idx; /* MSI-X index, or VIRTIO_MSI_NO_VECTOR */
380
381 uint32_t vq_pfn; /* PFN of virt queue (not shifted!) */
382 uint64_t vq_desc_gpa; /* PA of virtqueue descriptors ring */
383 uint64_t vq_avail_gpa; /* PA of virtqueue avail ring */
384 uint64_t vq_used_gpa; /* PA of virtqueue used ring */
385
386 struct vring_desc *vq_desc; /* descriptor array */
387 struct vring_avail *vq_avail; /* the "avail" ring */
388 struct vring_used *vq_used; /* the "used" ring */
389
390 };
391 /*
392 * As noted above, these are sort of backwards, name-wise.
393 *
394 * Endian helpers must be used when using the following macros.
395 */
396 #define VQ_AVAIL_EVENT_IDX(vq) \
397 (*(uint16_t *)&(vq)->vq_used->ring[(vq)->vq_qsize])
398 #define VQ_USED_EVENT_IDX(vq) \
399 ((vq)->vq_avail->ring[(vq)->vq_qsize])
400
401 /*
402 * Is this ring ready for I/O?
403 */
404 static inline int
vq_ring_ready(struct vqueue_info * vq)405 vq_ring_ready(struct vqueue_info *vq)
406 {
407 return (vq->vq_flags & VQ_ALLOC);
408 }
409
410 /*
411 * Are there "available" descriptors? (This does not count
412 * how many, just returns True if there are some.)
413 */
414 static inline int
vq_has_descs(struct vqueue_info * vq)415 vq_has_descs(struct vqueue_info *vq)
416 {
417 return (vq_ring_ready(vq) && vq->vq_last_avail != vq->vq_avail->idx);
418 }
419
420 /*
421 * Deliver an interrupt to the guest for a specific MSI-X queue or
422 * event.
423 */
424 static inline void
vi_interrupt(struct virtio_softc * vs,uint8_t isr,uint16_t msix_idx)425 vi_interrupt(struct virtio_softc *vs, uint8_t isr, uint16_t msix_idx)
426 {
427 if (!(vs->vs_status & VIRTIO_CONFIG_STATUS_DRIVER_OK))
428 return;
429
430 if (pci_msix_enabled(vs->vs_pi)) {
431 pci_generate_msix(vs->vs_pi, msix_idx);
432 } else {
433 vs->vs_isr |= isr;
434 pci_generate_msi(vs->vs_pi, 0);
435 pci_lintr_assert(vs->vs_pi);
436 }
437 }
438
439 /*
440 * Deliver an interrupt to the guest on the given virtual queue (if
441 * possible, or a generic MSI interrupt if not using MSI-X).
442 */
443 static inline void
vq_interrupt(struct virtio_softc * vs,struct vqueue_info * vq)444 vq_interrupt(struct virtio_softc *vs, struct vqueue_info *vq)
445 {
446 vi_interrupt(vs, VIRTIO_PCI_ISR_INTR, vq->vq_msix_idx);
447 }
448
449 /*
450 * Deliver an interrupt to guest on device-specific configuration changes
451 * (if possible, or a generic MSI interrupt if not using MSI-X).
452 */
453 static inline void
vq_devcfg_changed(struct virtio_softc * vs)454 vq_devcfg_changed(struct virtio_softc *vs)
455 {
456 vs->vs_flags |= VIRTIO_DEVCFG_CHG;
457 vi_interrupt(vs, VIRTIO_PCI_ISR_CONFIG, vs->vs_msix_cfg_idx);
458 }
459
460 static inline void
vq_kick_enable(struct vqueue_info * vq)461 vq_kick_enable(struct vqueue_info *vq)
462 {
463 vq->vq_used->flags &= ~VRING_USED_F_NO_NOTIFY;
464 /*
465 * Full memory barrier to make sure the store to vq_used->flags
466 * happens before the load from vq_avail->idx, which results from a
467 * subsequent call to vq_has_descs().
468 */
469 atomic_thread_fence_seq_cst();
470 }
471
472 static inline void
vq_kick_disable(struct vqueue_info * vq)473 vq_kick_disable(struct vqueue_info *vq)
474 {
475 vq->vq_used->flags |= VRING_USED_F_NO_NOTIFY;
476 }
477
478 #define VIRTIO_LEGACY_BAR 0 /* BAR for virtio legacy cfg regs */
479 #define VIRTIO_MSIX_BAR 1 /* BAR for host MSI-X tables */
480 #define VIRTIO_MODERN_BAR 2 /* BAR for virtio modern cfg regs */
481
482 struct iovec;
483
484 /*
485 * Request description returned by vq_getchain.
486 *
487 * Writable iovecs start at iov[req.readable].
488 */
489 struct vi_req {
490 int readable; /* num of readable iovecs */
491 int writable; /* num of writable iovecs */
492 unsigned int idx; /* ring index */
493 };
494
495 void vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
496 void *dev_softc, struct pci_devinst *pi,
497 struct vqueue_info *queues);
498 void vi_queue_linkup(struct virtio_softc *vc, struct vqueue_info *queues);
499 bool vi_intr_init(struct virtio_softc *vs, bool use_msix);
500 void vi_pci_init(struct pci_devinst *, virtio_mode_t, uint16_t,
501 uint16_t, uint8_t);
502 bool vi_pcibar_setup(struct virtio_softc *);
503 virtio_pci_capcfg_t *vi_pci_cfg_bytype(struct virtio_softc *, uint8_t);
504 virtio_pci_capcfg_t *vi_pci_cfg_bycapaddr(struct virtio_softc *,
505 uint32_t, uint32_t);
506 virtio_pci_capcfg_t *vi_pci_cfg_bybaraddr(struct virtio_softc *,
507 uint8_t, uint64_t, uint32_t);
508 void vi_reset_dev(struct virtio_softc *);
509 void vi_set_debug(struct virtio_softc *, bool);
510 bool vi_is_modern(struct virtio_softc *);
511 void vi_error(struct virtio_softc *, const char *, ...) __PRINTFLIKE(2);
512
513 int vq_getchain(struct vqueue_info *vq, struct iovec *iov, int niov,
514 struct vi_req *reqp);
515 void vq_retchains(struct vqueue_info *vq, uint16_t n_chains);
516 void vq_relchain_prepare(struct vqueue_info *vq, uint16_t idx,
517 uint32_t iolen);
518 void vq_relchain_publish(struct vqueue_info *vq);
519 void vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen);
520 void vq_endchains(struct vqueue_info *vq, int used_all_avail);
521
522 int vi_pci_cfgread(struct pci_devinst *pi, int offset, int bytes,
523 uint32_t *retval);
524 int vi_pci_cfgwrite(struct pci_devinst *pi, int offset, int bytes,
525 uint32_t val);
526 uint64_t vi_pci_read(struct pci_devinst *pi, int baridx, uint64_t offset,
527 int size);
528 void vi_pci_write(struct pci_devinst *pi, int baridx, uint64_t offset,
529 int size, uint64_t value);
530
531 void vi_vq_init(struct virtio_softc *);
532 void vi_legacy_vq_init(struct virtio_softc *, uint32_t);
533
534 #endif /* _BHYVE_VIRTIO_H_ */
535