xref: /freebsd/usr.sbin/bhyve/virtio.h (revision 0410385580055abe1a007ab26bf8d9199f16ef7c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2013  Chris Torek <torek @ torek net>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #ifndef	_VIRTIO_H_
32 #define	_VIRTIO_H_
33 
34 #include <machine/atomic.h>
35 
36 /*
37  * These are derived from several virtio specifications.
38  *
39  * Some useful links:
40  *    https://github.com/rustyrussell/virtio-spec
41  *    http://people.redhat.com/pbonzini/virtio-spec.pdf
42  */
43 
44 /*
45  * A virtual device has zero or more "virtual queues" (virtqueue).
46  * Each virtqueue uses at least two 4096-byte pages, laid out thus:
47  *
48  *      +-----------------------------------------------+
49  *      |    "desc":  <N> descriptors, 16 bytes each    |
50  *      |   -----------------------------------------   |
51  *      |   "avail":   2 uint16; <N> uint16; 1 uint16   |
52  *      |   -----------------------------------------   |
53  *      |              pad to 4k boundary               |
54  *      +-----------------------------------------------+
55  *      |   "used": 2 x uint16; <N> elems; 1 uint16     |
56  *      |   -----------------------------------------   |
57  *      |              pad to 4k boundary               |
58  *      +-----------------------------------------------+
59  *
60  * The number <N> that appears here is always a power of two and is
61  * limited to no more than 32768 (as it must fit in a 16-bit field).
62  * If <N> is sufficiently large, the above will occupy more than
63  * two pages.  In any case, all pages must be physically contiguous
64  * within the guest's physical address space.
65  *
66  * The <N> 16-byte "desc" descriptors consist of a 64-bit guest
67  * physical address <addr>, a 32-bit length <len>, a 16-bit
68  * <flags>, and a 16-bit <next> field (all in guest byte order).
69  *
70  * There are three flags that may be set :
71  *	NEXT    descriptor is chained, so use its "next" field
72  *	WRITE   descriptor is for host to write into guest RAM
73  *		(else host is to read from guest RAM)
74  *	INDIRECT   descriptor address field is (guest physical)
75  *		address of a linear array of descriptors
76  *
77  * Unless INDIRECT is set, <len> is the number of bytes that may
78  * be read/written from guest physical address <addr>.  If
79  * INDIRECT is set, WRITE is ignored and <len> provides the length
80  * of the indirect descriptors (and <len> must be a multiple of
81  * 16).  Note that NEXT may still be set in the main descriptor
82  * pointing to the indirect, and should be set in each indirect
83  * descriptor that uses the next descriptor (these should generally
84  * be numbered sequentially).  However, INDIRECT must not be set
85  * in the indirect descriptors.  Upon reaching an indirect descriptor
86  * without a NEXT bit, control returns to the direct descriptors.
87  *
88  * Except inside an indirect, each <next> value must be in the
89  * range [0 .. N) (i.e., the half-open interval).  (Inside an
90  * indirect, each <next> must be in the range [0 .. <len>/16).)
91  *
92  * The "avail" data structures reside in the same pages as the
93  * "desc" structures since both together are used by the device to
94  * pass information to the hypervisor's virtual driver.  These
95  * begin with a 16-bit <flags> field and 16-bit index <idx>, then
96  * have <N> 16-bit <ring> values, followed by one final 16-bit
97  * field <used_event>.  The <N> <ring> entries are simply indices
98  * indices into the descriptor ring (and thus must meet the same
99  * constraints as each <next> value).  However, <idx> is counted
100  * up from 0 (initially) and simply wraps around after 65535; it
101  * is taken mod <N> to find the next available entry.
102  *
103  * The "used" ring occupies a separate page or pages, and contains
104  * values written from the virtual driver back to the guest OS.
105  * This begins with a 16-bit <flags> and 16-bit <idx>, then there
106  * are <N> "vring_used" elements, followed by a 16-bit <avail_event>.
107  * The <N> "vring_used" elements consist of a 32-bit <id> and a
108  * 32-bit <len> (vu_tlen below).  The <id> is simply the index of
109  * the head of a descriptor chain the guest made available
110  * earlier, and the <len> is the number of bytes actually written,
111  * e.g., in the case of a network driver that provided a large
112  * receive buffer but received only a small amount of data.
113  *
114  * The two event fields, <used_event> and <avail_event>, in the
115  * avail and used rings (respectively -- note the reversal!), are
116  * always provided, but are used only if the virtual device
117  * negotiates the VIRTIO_RING_F_EVENT_IDX feature during feature
118  * negotiation.  Similarly, both rings provide a flag --
119  * VRING_AVAIL_F_NO_INTERRUPT and VRING_USED_F_NO_NOTIFY -- in
120  * their <flags> field, indicating that the guest does not need an
121  * interrupt, or that the hypervisor driver does not need a
122  * notify, when descriptors are added to the corresponding ring.
123  * (These are provided only for interrupt optimization and need
124  * not be implemented.)
125  */
126 #define VRING_ALIGN	4096
127 
128 #define VRING_DESC_F_NEXT	(1 << 0)
129 #define VRING_DESC_F_WRITE	(1 << 1)
130 #define VRING_DESC_F_INDIRECT	(1 << 2)
131 
132 struct virtio_desc {			/* AKA vring_desc */
133 	uint64_t	vd_addr;	/* guest physical address */
134 	uint32_t	vd_len;		/* length of scatter/gather seg */
135 	uint16_t	vd_flags;	/* VRING_F_DESC_* */
136 	uint16_t	vd_next;	/* next desc if F_NEXT */
137 } __packed;
138 
139 struct virtio_used {			/* AKA vring_used_elem */
140 	uint32_t	vu_idx;		/* head of used descriptor chain */
141 	uint32_t	vu_tlen;	/* length written-to */
142 } __packed;
143 
144 #define VRING_AVAIL_F_NO_INTERRUPT   1
145 
146 struct vring_avail {
147 	uint16_t	va_flags;	/* VRING_AVAIL_F_* */
148 	uint16_t	va_idx;		/* counts to 65535, then cycles */
149 	uint16_t	va_ring[];	/* size N, reported in QNUM value */
150 /*	uint16_t	va_used_event;	-- after N ring entries */
151 } __packed;
152 
153 #define	VRING_USED_F_NO_NOTIFY		1
154 struct vring_used {
155 	uint16_t	vu_flags;	/* VRING_USED_F_* */
156 	uint16_t	vu_idx;		/* counts to 65535, then cycles */
157 	struct virtio_used vu_ring[];	/* size N */
158 /*	uint16_t	vu_avail_event;	-- after N ring entries */
159 } __packed;
160 
161 /*
162  * The address of any given virtual queue is determined by a single
163  * Page Frame Number register.  The guest writes the PFN into the
164  * PCI config space.  However, a device that has two or more
165  * virtqueues can have a different PFN, and size, for each queue.
166  * The number of queues is determinable via the PCI config space
167  * VTCFG_R_QSEL register.  Writes to QSEL select the queue: 0 means
168  * queue #0, 1 means queue#1, etc.  Once a queue is selected, the
169  * remaining PFN and QNUM registers refer to that queue.
170  *
171  * QNUM is a read-only register containing a nonzero power of two
172  * that indicates the (hypervisor's) queue size.  Or, if reading it
173  * produces zero, the hypervisor does not have a corresponding
174  * queue.  (The number of possible queues depends on the virtual
175  * device.  The block device has just one; the network device
176  * provides either two -- 0 = receive, 1 = transmit -- or three,
177  * with 2 = control.)
178  *
179  * PFN is a read/write register giving the physical page address of
180  * the virtqueue in guest memory (the guest must allocate enough space
181  * based on the hypervisor's provided QNUM).
182  *
183  * QNOTIFY is effectively write-only: when the guest writes a queue
184  * number to the register, the hypervisor should scan the specified
185  * virtqueue. (Reading QNOTIFY currently always gets 0).
186  */
187 
188 /*
189  * PFN register shift amount
190  */
191 #define	VRING_PFN		12
192 
193 /*
194  * Virtio device types
195  *
196  * XXX Should really be merged with <dev/virtio/virtio.h> defines
197  */
198 #define	VIRTIO_TYPE_NET		1
199 #define	VIRTIO_TYPE_BLOCK	2
200 #define	VIRTIO_TYPE_CONSOLE	3
201 #define	VIRTIO_TYPE_ENTROPY	4
202 #define	VIRTIO_TYPE_BALLOON	5
203 #define	VIRTIO_TYPE_IOMEMORY	6
204 #define	VIRTIO_TYPE_RPMSG	7
205 #define	VIRTIO_TYPE_SCSI	8
206 #define	VIRTIO_TYPE_9P		9
207 
208 /* experimental IDs start at 65535 and work down */
209 
210 /*
211  * PCI vendor/device IDs
212  */
213 #define	VIRTIO_VENDOR		0x1AF4
214 #define	VIRTIO_DEV_NET		0x1000
215 #define	VIRTIO_DEV_BLOCK	0x1001
216 #define	VIRTIO_DEV_CONSOLE	0x1003
217 #define	VIRTIO_DEV_RANDOM	0x1005
218 #define	VIRTIO_DEV_SCSI		0x1008
219 #define	VIRTIO_DEV_9P		0x1009
220 
221 /*
222  * PCI config space constants.
223  *
224  * If MSI-X is enabled, the ISR register is generally not used,
225  * and the configuration vector and queue vector appear at offsets
226  * 20 and 22 with the remaining configuration registers at 24.
227  * If MSI-X is not enabled, those two registers disappear and
228  * the remaining configuration registers start at offset 20.
229  */
230 #define	VTCFG_R_HOSTCAP		0
231 #define	VTCFG_R_GUESTCAP	4
232 #define	VTCFG_R_PFN		8
233 #define	VTCFG_R_QNUM		12
234 #define	VTCFG_R_QSEL		14
235 #define	VTCFG_R_QNOTIFY		16
236 #define	VTCFG_R_STATUS		18
237 #define	VTCFG_R_ISR		19
238 #define	VTCFG_R_CFGVEC		20
239 #define	VTCFG_R_QVEC		22
240 #define	VTCFG_R_CFG0		20	/* No MSI-X */
241 #define	VTCFG_R_CFG1		24	/* With MSI-X */
242 #define	VTCFG_R_MSIX		20
243 
244 /*
245  * Bits in VTCFG_R_STATUS.  Guests need not actually set any of these,
246  * but a guest writing 0 to this register means "please reset".
247  */
248 #define	VTCFG_STATUS_ACK	0x01	/* guest OS has acknowledged dev */
249 #define	VTCFG_STATUS_DRIVER	0x02	/* guest OS driver is loaded */
250 #define	VTCFG_STATUS_DRIVER_OK	0x04	/* guest OS driver ready */
251 #define	VTCFG_STATUS_FAILED	0x80	/* guest has given up on this dev */
252 
253 /*
254  * Bits in VTCFG_R_ISR.  These apply only if not using MSI-X.
255  *
256  * (We don't [yet?] ever use CONF_CHANGED.)
257  */
258 #define	VTCFG_ISR_QUEUES	0x01	/* re-scan queues */
259 #define	VTCFG_ISR_CONF_CHANGED	0x80	/* configuration changed */
260 
261 #define	VIRTIO_MSI_NO_VECTOR	0xFFFF
262 
263 /*
264  * Feature flags.
265  * Note: bits 0 through 23 are reserved to each device type.
266  */
267 #define	VIRTIO_F_NOTIFY_ON_EMPTY	(1 << 24)
268 #define	VIRTIO_RING_F_INDIRECT_DESC	(1 << 28)
269 #define	VIRTIO_RING_F_EVENT_IDX		(1 << 29)
270 
271 /* From section 2.3, "Virtqueue Configuration", of the virtio specification */
272 static inline size_t
273 vring_size(u_int qsz)
274 {
275 	size_t size;
276 
277 	/* constant 3 below = va_flags, va_idx, va_used_event */
278 	size = sizeof(struct virtio_desc) * qsz + sizeof(uint16_t) * (3 + qsz);
279 	size = roundup2(size, VRING_ALIGN);
280 
281 	/* constant 3 below = vu_flags, vu_idx, vu_avail_event */
282 	size += sizeof(uint16_t) * 3 + sizeof(struct virtio_used) * qsz;
283 	size = roundup2(size, VRING_ALIGN);
284 
285 	return (size);
286 }
287 
288 struct vmctx;
289 struct pci_devinst;
290 struct vqueue_info;
291 struct vm_snapshot_meta;
292 
293 /*
294  * A virtual device, with some number (possibly 0) of virtual
295  * queues and some size (possibly 0) of configuration-space
296  * registers private to the device.  The virtio_softc should come
297  * at the front of each "derived class", so that a pointer to the
298  * virtio_softc is also a pointer to the more specific, derived-
299  * from-virtio driver's softc.
300  *
301  * Note: inside each hypervisor virtio driver, changes to these
302  * data structures must be locked against other threads, if any.
303  * Except for PCI config space register read/write, we assume each
304  * driver does the required locking, but we need a pointer to the
305  * lock (if there is one) for PCI config space read/write ops.
306  *
307  * When the guest reads or writes the device's config space, the
308  * generic layer checks for operations on the special registers
309  * described above.  If the offset of the register(s) being read
310  * or written is past the CFG area (CFG0 or CFG1), the request is
311  * passed on to the virtual device, after subtracting off the
312  * generic-layer size.  (So, drivers can just use the offset as
313  * an offset into "struct config", for instance.)
314  *
315  * (The virtio layer also makes sure that the read or write is to/
316  * from a "good" config offset, hence vc_cfgsize, and on BAR #0.
317  * However, the driver must verify the read or write size and offset
318  * and that no one is writing a readonly register.)
319  *
320  * The BROKED flag ("this thing done gone and broked") is for future
321  * use.
322  */
323 #define	VIRTIO_USE_MSIX		0x01
324 #define	VIRTIO_EVENT_IDX	0x02	/* use the event-index values */
325 #define	VIRTIO_BROKED		0x08	/* ??? */
326 
327 struct virtio_softc {
328 	struct virtio_consts *vs_vc;	/* constants (see below) */
329 	int	vs_flags;		/* VIRTIO_* flags from above */
330 	pthread_mutex_t *vs_mtx;	/* POSIX mutex, if any */
331 	struct pci_devinst *vs_pi;	/* PCI device instance */
332 	uint32_t vs_negotiated_caps;	/* negotiated capabilities */
333 	struct vqueue_info *vs_queues;	/* one per vc_nvq */
334 	int	vs_curq;		/* current queue */
335 	uint8_t	vs_status;		/* value from last status write */
336 	uint8_t	vs_isr;			/* ISR flags, if not MSI-X */
337 	uint16_t vs_msix_cfg_idx;	/* MSI-X vector for config event */
338 };
339 
340 #define	VS_LOCK(vs)							\
341 do {									\
342 	if (vs->vs_mtx)							\
343 		pthread_mutex_lock(vs->vs_mtx);				\
344 } while (0)
345 
346 #define	VS_UNLOCK(vs)							\
347 do {									\
348 	if (vs->vs_mtx)							\
349 		pthread_mutex_unlock(vs->vs_mtx);			\
350 } while (0)
351 
352 struct virtio_consts {
353 	const char *vc_name;		/* name of driver (for diagnostics) */
354 	int	vc_nvq;			/* number of virtual queues */
355 	size_t	vc_cfgsize;		/* size of dev-specific config regs */
356 	void	(*vc_reset)(void *);	/* called on virtual device reset */
357 	void	(*vc_qnotify)(void *, struct vqueue_info *);
358 					/* called on QNOTIFY if no VQ notify */
359 	int	(*vc_cfgread)(void *, int, int, uint32_t *);
360 					/* called to read config regs */
361 	int	(*vc_cfgwrite)(void *, int, int, uint32_t);
362 					/* called to write config regs */
363 	void    (*vc_apply_features)(void *, uint64_t);
364 				/* called to apply negotiated features */
365 	uint64_t vc_hv_caps;		/* hypervisor-provided capabilities */
366 	void	(*vc_pause)(void *);	/* called to pause device activity */
367 	void	(*vc_resume)(void *);	/* called to resume device activity */
368 	int	(*vc_snapshot)(void *, struct vm_snapshot_meta *);
369 				/* called to save / restore device state */
370 };
371 
372 /*
373  * Data structure allocated (statically) per virtual queue.
374  *
375  * Drivers may change vq_qsize after a reset.  When the guest OS
376  * requests a device reset, the hypervisor first calls
377  * vs->vs_vc->vc_reset(); then the data structure below is
378  * reinitialized (for each virtqueue: vs->vs_vc->vc_nvq).
379  *
380  * The remaining fields should only be fussed-with by the generic
381  * code.
382  *
383  * Note: the addresses of vq_desc, vq_avail, and vq_used are all
384  * computable from each other, but it's a lot simpler if we just
385  * keep a pointer to each one.  The event indices are similarly
386  * (but more easily) computable, and this time we'll compute them:
387  * they're just XX_ring[N].
388  */
389 #define	VQ_ALLOC	0x01	/* set once we have a pfn */
390 #define	VQ_BROKED	0x02	/* ??? */
391 struct vqueue_info {
392 	uint16_t vq_qsize;	/* size of this queue (a power of 2) */
393 	void	(*vq_notify)(void *, struct vqueue_info *);
394 				/* called instead of vc_notify, if not NULL */
395 
396 	struct virtio_softc *vq_vs;	/* backpointer to softc */
397 	uint16_t vq_num;	/* we're the num'th queue in the softc */
398 
399 	uint16_t vq_flags;	/* flags (see above) */
400 	uint16_t vq_last_avail;	/* a recent value of vq_avail->va_idx */
401 	uint16_t vq_next_used;	/* index of the next used slot to be filled */
402 	uint16_t vq_save_used;	/* saved vq_used->vu_idx; see vq_endchains */
403 	uint16_t vq_msix_idx;	/* MSI-X index, or VIRTIO_MSI_NO_VECTOR */
404 
405 	uint32_t vq_pfn;	/* PFN of virt queue (not shifted!) */
406 
407 	volatile struct virtio_desc *vq_desc;	/* descriptor array */
408 	volatile struct vring_avail *vq_avail;	/* the "avail" ring */
409 	volatile struct vring_used *vq_used;	/* the "used" ring */
410 
411 };
412 /* as noted above, these are sort of backwards, name-wise */
413 #define VQ_AVAIL_EVENT_IDX(vq) \
414 	(*(volatile uint16_t *)&(vq)->vq_used->vu_ring[(vq)->vq_qsize])
415 #define VQ_USED_EVENT_IDX(vq) \
416 	((vq)->vq_avail->va_ring[(vq)->vq_qsize])
417 
418 /*
419  * Is this ring ready for I/O?
420  */
421 static inline int
422 vq_ring_ready(struct vqueue_info *vq)
423 {
424 
425 	return (vq->vq_flags & VQ_ALLOC);
426 }
427 
428 /*
429  * Are there "available" descriptors?  (This does not count
430  * how many, just returns True if there are some.)
431  */
432 static inline int
433 vq_has_descs(struct vqueue_info *vq)
434 {
435 
436 	return (vq_ring_ready(vq) && vq->vq_last_avail !=
437 	    vq->vq_avail->va_idx);
438 }
439 
440 /*
441  * Deliver an interrupt to guest on the given virtual queue
442  * (if possible, or a generic MSI interrupt if not using MSI-X).
443  */
444 static inline void
445 vq_interrupt(struct virtio_softc *vs, struct vqueue_info *vq)
446 {
447 
448 	if (pci_msix_enabled(vs->vs_pi))
449 		pci_generate_msix(vs->vs_pi, vq->vq_msix_idx);
450 	else {
451 		VS_LOCK(vs);
452 		vs->vs_isr |= VTCFG_ISR_QUEUES;
453 		pci_generate_msi(vs->vs_pi, 0);
454 		pci_lintr_assert(vs->vs_pi);
455 		VS_UNLOCK(vs);
456 	}
457 }
458 
459 static inline void
460 vq_kick_enable(struct vqueue_info *vq)
461 {
462 
463 	vq->vq_used->vu_flags &= ~VRING_USED_F_NO_NOTIFY;
464 	/*
465 	 * Full memory barrier to make sure the store to vu_flags
466 	 * happens before the load from va_idx, which results from
467 	 * a subsequent call to vq_has_descs().
468 	 */
469 	atomic_thread_fence_seq_cst();
470 }
471 
472 static inline void
473 vq_kick_disable(struct vqueue_info *vq)
474 {
475 
476 	vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
477 }
478 
479 struct iovec;
480 void	vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
481 			void *dev_softc, struct pci_devinst *pi,
482 			struct vqueue_info *queues);
483 int	vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix);
484 void	vi_reset_dev(struct virtio_softc *);
485 void	vi_set_io_bar(struct virtio_softc *, int);
486 
487 int	vq_getchain(struct vqueue_info *vq, uint16_t *pidx,
488 		    struct iovec *iov, int n_iov, uint16_t *flags);
489 void	vq_retchains(struct vqueue_info *vq, uint16_t n_chains);
490 void	vq_relchain_prepare(struct vqueue_info *vq, uint16_t idx,
491 			    uint32_t iolen);
492 void	vq_relchain_publish(struct vqueue_info *vq);
493 void	vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen);
494 void	vq_endchains(struct vqueue_info *vq, int used_all_avail);
495 
496 uint64_t vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
497 		     int baridx, uint64_t offset, int size);
498 void	vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
499 		     int baridx, uint64_t offset, int size, uint64_t value);
500 #ifdef BHYVE_SNAPSHOT
501 int	vi_pci_snapshot(struct vm_snapshot_meta *meta);
502 int	vi_pci_pause(struct vmctx *ctx, struct pci_devinst *pi);
503 int	vi_pci_resume(struct vmctx *ctx, struct pci_devinst *pi);
504 #endif
505 #endif	/* _VIRTIO_H_ */
506