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