xref: /freebsd-14-stable/usr.sbin/bhyve/virtio.c (revision ed03c309908687bdb9f71dc6d9c9c8a92c54fc20)
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) 2019 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include <sys/param.h>
32 #include <sys/uio.h>
33 
34 #include <machine/atomic.h>
35 
36 #include <dev/virtio/pci/virtio_pci_legacy_var.h>
37 
38 #include <stdio.h>
39 #include <stdint.h>
40 #include <string.h>
41 #include <pthread.h>
42 #include <pthread_np.h>
43 
44 #include "bhyverun.h"
45 #include "debug.h"
46 #include "pci_emul.h"
47 #ifdef BHYVE_SNAPSHOT
48 #include "snapshot.h"
49 #endif
50 #include "virtio.h"
51 
52 /*
53  * Functions for dealing with generalized "virtual devices" as
54  * defined by <https://www.google.com/#output=search&q=virtio+spec>
55  */
56 
57 /*
58  * In case we decide to relax the "virtio softc comes at the
59  * front of virtio-based device softc" constraint, let's use
60  * this to convert.
61  */
62 #define	DEV_SOFTC(vs) ((void *)(vs))
63 
64 /*
65  * Link a virtio_softc to its constants, the device softc, and
66  * the PCI emulation.
67  */
68 void
vi_softc_linkup(struct virtio_softc * vs,struct virtio_consts * vc,void * dev_softc,struct pci_devinst * pi,struct vqueue_info * queues)69 vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
70 		void *dev_softc, struct pci_devinst *pi,
71 		struct vqueue_info *queues)
72 {
73 	int i;
74 
75 	/* vs and dev_softc addresses must match */
76 	assert((void *)vs == dev_softc);
77 	vs->vs_vc = vc;
78 	vs->vs_pi = pi;
79 	pi->pi_arg = vs;
80 
81 	vs->vs_queues = queues;
82 	for (i = 0; i < vc->vc_nvq; i++) {
83 		queues[i].vq_vs = vs;
84 		queues[i].vq_num = i;
85 	}
86 }
87 
88 /*
89  * Reset device (device-wide).  This erases all queues, i.e.,
90  * all the queues become invalid (though we don't wipe out the
91  * internal pointers, we just clear the VQ_ALLOC flag).
92  *
93  * It resets negotiated features to "none".
94  *
95  * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
96  */
97 void
vi_reset_dev(struct virtio_softc * vs)98 vi_reset_dev(struct virtio_softc *vs)
99 {
100 	struct vqueue_info *vq;
101 	int i, nvq;
102 
103 	if (vs->vs_mtx)
104 		assert(pthread_mutex_isowned_np(vs->vs_mtx));
105 
106 	nvq = vs->vs_vc->vc_nvq;
107 	for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
108 		vq->vq_flags = 0;
109 		vq->vq_last_avail = 0;
110 		vq->vq_next_used = 0;
111 		vq->vq_save_used = 0;
112 		vq->vq_pfn = 0;
113 		vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
114 	}
115 	vs->vs_negotiated_caps = 0;
116 	vs->vs_curq = 0;
117 	/* vs->vs_status = 0; -- redundant */
118 	if (vs->vs_isr)
119 		pci_lintr_deassert(vs->vs_pi);
120 	vs->vs_isr = 0;
121 	vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
122 }
123 
124 /*
125  * Set I/O BAR (usually 0) to map PCI config registers.
126  */
127 void
vi_set_io_bar(struct virtio_softc * vs,int barnum)128 vi_set_io_bar(struct virtio_softc *vs, int barnum)
129 {
130 	size_t size;
131 
132 	/*
133 	 * ??? should we use VIRTIO_PCI_CONFIG_OFF(0) if MSI-X is disabled?
134 	 * Existing code did not...
135 	 */
136 	size = VIRTIO_PCI_CONFIG_OFF(1) + vs->vs_vc->vc_cfgsize;
137 	pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
138 }
139 
140 /*
141  * Initialize MSI-X vector capabilities if we're to use MSI-X,
142  * or MSI capabilities if not.
143  *
144  * We assume we want one MSI-X vector per queue, here, plus one
145  * for the config vec.
146  */
147 int
vi_intr_init(struct virtio_softc * vs,int barnum,int use_msix)148 vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
149 {
150 	int nvec;
151 
152 	if (use_msix) {
153 		vs->vs_flags |= VIRTIO_USE_MSIX;
154 		VS_LOCK(vs);
155 		vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
156 		VS_UNLOCK(vs);
157 		nvec = vs->vs_vc->vc_nvq + 1;
158 		if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
159 			return (1);
160 	} else
161 		vs->vs_flags &= ~VIRTIO_USE_MSIX;
162 
163 	/* Only 1 MSI vector for bhyve */
164 	pci_emul_add_msicap(vs->vs_pi, 1);
165 
166 	/* Legacy interrupts are mandatory for virtio devices */
167 	pci_lintr_request(vs->vs_pi);
168 
169 	return (0);
170 }
171 
172 /*
173  * Initialize the currently-selected virtio queue (vs->vs_curq).
174  * The guest just gave us a page frame number, from which we can
175  * calculate the addresses of the queue.
176  */
177 static void
vi_vq_init(struct virtio_softc * vs,uint32_t pfn)178 vi_vq_init(struct virtio_softc *vs, uint32_t pfn)
179 {
180 	struct vqueue_info *vq;
181 	uint64_t phys;
182 	size_t size;
183 	char *base;
184 
185 	vq = &vs->vs_queues[vs->vs_curq];
186 	vq->vq_pfn = pfn;
187 	phys = (uint64_t)pfn << VRING_PFN;
188 	size = vring_size_aligned(vq->vq_qsize);
189 	base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
190 
191 	/* First page(s) are descriptors... */
192 	vq->vq_desc = (struct vring_desc *)base;
193 	base += vq->vq_qsize * sizeof(struct vring_desc);
194 
195 	/* ... immediately followed by "avail" ring (entirely uint16_t's) */
196 	vq->vq_avail = (struct vring_avail *)base;
197 	base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
198 
199 	/* Then it's rounded up to the next page... */
200 	base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
201 
202 	/* ... and the last page(s) are the used ring. */
203 	vq->vq_used = (struct vring_used *)base;
204 
205 	/* Mark queue as allocated, and start at 0 when we use it. */
206 	vq->vq_flags = VQ_ALLOC;
207 	vq->vq_last_avail = 0;
208 	vq->vq_next_used = 0;
209 	vq->vq_save_used = 0;
210 }
211 
212 /*
213  * Helper inline for vq_getchain(): record the i'th "real"
214  * descriptor.
215  */
216 static inline void
_vq_record(int i,struct vring_desc * vd,struct vmctx * ctx,struct iovec * iov,int n_iov,struct vi_req * reqp)217 _vq_record(int i, struct vring_desc *vd, struct vmctx *ctx, struct iovec *iov,
218     int n_iov, struct vi_req *reqp)
219 {
220 	uint32_t len;
221 	uint64_t addr;
222 
223 	if (i >= n_iov)
224 		return;
225 	len = atomic_load_32(&vd->len);
226 	addr = atomic_load_64(&vd->addr);
227 	iov[i].iov_len = len;
228 	iov[i].iov_base = paddr_guest2host(ctx, addr, len);
229 	if ((vd->flags & VRING_DESC_F_WRITE) == 0)
230 		reqp->readable++;
231 	else
232 		reqp->writable++;
233 }
234 #define	VQ_MAX_DESCRIPTORS	512	/* see below */
235 
236 /*
237  * Examine the chain of descriptors starting at the "next one" to
238  * make sure that they describe a sensible request.  If so, return
239  * the number of "real" descriptors that would be needed/used in
240  * acting on this request.  This may be smaller than the number of
241  * available descriptors, e.g., if there are two available but
242  * they are two separate requests, this just returns 1.  Or, it
243  * may be larger: if there are indirect descriptors involved,
244  * there may only be one descriptor available but it may be an
245  * indirect pointing to eight more.  We return 8 in this case,
246  * i.e., we do not count the indirect descriptors, only the "real"
247  * ones.
248  *
249  * Basically, this vets the "flags" and "next" field of each
250  * descriptor and tells you how many are involved.  Since some may
251  * be indirect, this also needs the vmctx (in the pci_devinst
252  * at vs->vs_pi) so that it can find indirect descriptors.
253  *
254  * As we process each descriptor, we copy and adjust it (guest to
255  * host address wise, also using the vmtctx) into the given iov[]
256  * array (of the given size).  If the array overflows, we stop
257  * placing values into the array but keep processing descriptors,
258  * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
259  * So you, the caller, must not assume that iov[] is as big as the
260  * return value (you can process the same thing twice to allocate
261  * a larger iov array if needed, or supply a zero length to find
262  * out how much space is needed).
263  *
264  * If some descriptor(s) are invalid, this prints a diagnostic message
265  * and returns -1.  If no descriptors are ready now it simply returns 0.
266  *
267  * You are assumed to have done a vq_ring_ready() if needed (note
268  * that vq_has_descs() does one).
269  */
270 int
vq_getchain(struct vqueue_info * vq,struct iovec * iov,int niov,struct vi_req * reqp)271 vq_getchain(struct vqueue_info *vq, struct iovec *iov, int niov,
272 	    struct vi_req *reqp)
273 {
274 	int i;
275 	u_int ndesc, n_indir;
276 	u_int idx, next;
277 	struct vi_req req;
278 	struct vring_desc *vdir, *vindir, *vp;
279 	struct vmctx *ctx;
280 	struct virtio_softc *vs;
281 	const char *name;
282 
283 	vs = vq->vq_vs;
284 	name = vs->vs_vc->vc_name;
285 	memset(&req, 0, sizeof(req));
286 
287 	/*
288 	 * Note: it's the responsibility of the guest not to
289 	 * update vq->vq_avail->idx until all of the descriptors
290          * the guest has written are valid (including all their
291          * "next" fields and "flags").
292 	 *
293 	 * Compute (vq_avail->idx - last_avail) in integers mod 2**16.  This is
294 	 * the number of descriptors the device has made available
295 	 * since the last time we updated vq->vq_last_avail.
296 	 *
297 	 * We just need to do the subtraction as an unsigned int,
298 	 * then trim off excess bits.
299 	 */
300 	idx = vq->vq_last_avail;
301 	ndesc = (uint16_t)((u_int)vq->vq_avail->idx - idx);
302 	if (ndesc == 0)
303 		return (0);
304 	if (ndesc > vq->vq_qsize) {
305 		/* XXX need better way to diagnose issues */
306 		EPRINTLN(
307 		    "%s: ndesc (%u) out of range, driver confused?",
308 		    name, (u_int)ndesc);
309 		return (-1);
310 	}
311 
312 	/*
313 	 * Now count/parse "involved" descriptors starting from
314 	 * the head of the chain.
315 	 *
316 	 * To prevent loops, we could be more complicated and
317 	 * check whether we're re-visiting a previously visited
318 	 * index, but we just abort if the count gets excessive.
319 	 */
320 	ctx = vs->vs_pi->pi_vmctx;
321 	req.idx = next = vq->vq_avail->ring[idx & (vq->vq_qsize - 1)];
322 	vq->vq_last_avail++;
323 	for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->next) {
324 		if (next >= vq->vq_qsize) {
325 			EPRINTLN(
326 			    "%s: descriptor index %u out of range, "
327 			    "driver confused?",
328 			    name, next);
329 			return (-1);
330 		}
331 		vdir = &vq->vq_desc[next];
332 		if ((vdir->flags & VRING_DESC_F_INDIRECT) == 0) {
333 			_vq_record(i, vdir, ctx, iov, niov, &req);
334 			i++;
335 		} else if ((vs->vs_vc->vc_hv_caps &
336 		    VIRTIO_RING_F_INDIRECT_DESC) == 0) {
337 			EPRINTLN(
338 			    "%s: descriptor has forbidden INDIRECT flag, "
339 			    "driver confused?",
340 			    name);
341 			return (-1);
342 		} else {
343 			n_indir = vdir->len / 16;
344 			if ((vdir->len & 0xf) || n_indir == 0) {
345 				EPRINTLN(
346 				    "%s: invalid indir len 0x%x, "
347 				    "driver confused?",
348 				    name, (u_int)vdir->len);
349 				return (-1);
350 			}
351 			vindir = paddr_guest2host(ctx,
352 			    vdir->addr, vdir->len);
353 			/*
354 			 * Indirects start at the 0th, then follow
355 			 * their own embedded "next"s until those run
356 			 * out.  Each one's indirect flag must be off
357 			 * (we don't really have to check, could just
358 			 * ignore errors...).
359 			 */
360 			next = 0;
361 			for (;;) {
362 				vp = &vindir[next];
363 				if (vp->flags & VRING_DESC_F_INDIRECT) {
364 					EPRINTLN(
365 					    "%s: indirect desc has INDIR flag,"
366 					    " driver confused?",
367 					    name);
368 					return (-1);
369 				}
370 				_vq_record(i, vp, ctx, iov, niov, &req);
371 				if (++i > VQ_MAX_DESCRIPTORS)
372 					goto loopy;
373 				if ((vp->flags & VRING_DESC_F_NEXT) == 0)
374 					break;
375 				next = vp->next;
376 				if (next >= n_indir) {
377 					EPRINTLN(
378 					    "%s: invalid next %u > %u, "
379 					    "driver confused?",
380 					    name, (u_int)next, n_indir);
381 					return (-1);
382 				}
383 			}
384 		}
385 		if ((vdir->flags & VRING_DESC_F_NEXT) == 0)
386 			goto done;
387 	}
388 
389 loopy:
390 	EPRINTLN(
391 	    "%s: descriptor loop? count > %d - driver confused?",
392 	    name, i);
393 	return (-1);
394 
395 done:
396 	*reqp = req;
397 	return (i);
398 }
399 
400 /*
401  * Return the first n_chain request chains back to the available queue.
402  *
403  * (These chains are the ones you handled when you called vq_getchain()
404  * and used its positive return value.)
405  */
406 void
vq_retchains(struct vqueue_info * vq,uint16_t n_chains)407 vq_retchains(struct vqueue_info *vq, uint16_t n_chains)
408 {
409 
410 	vq->vq_last_avail -= n_chains;
411 }
412 
413 void
vq_relchain_prepare(struct vqueue_info * vq,uint16_t idx,uint32_t iolen)414 vq_relchain_prepare(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
415 {
416 	struct vring_used *vuh;
417 	struct vring_used_elem *vue;
418 	uint16_t mask;
419 
420 	/*
421 	 * Notes:
422 	 *  - mask is N-1 where N is a power of 2 so computes x % N
423 	 *  - vuh points to the "used" data shared with guest
424 	 *  - vue points to the "used" ring entry we want to update
425 	 */
426 	mask = vq->vq_qsize - 1;
427 	vuh = vq->vq_used;
428 
429 	vue = &vuh->ring[vq->vq_next_used++ & mask];
430 	vue->id = idx;
431 	vue->len = iolen;
432 }
433 
434 void
vq_relchain_publish(struct vqueue_info * vq)435 vq_relchain_publish(struct vqueue_info *vq)
436 {
437 	/*
438 	 * Ensure the used descriptor is visible before updating the index.
439 	 * This is necessary on ISAs with memory ordering less strict than x86
440 	 * (and even on x86 to act as a compiler barrier).
441 	 */
442 	atomic_thread_fence_rel();
443 	vq->vq_used->idx = vq->vq_next_used;
444 }
445 
446 /*
447  * Return specified request chain to the guest, setting its I/O length
448  * to the provided value.
449  *
450  * (This chain is the one you handled when you called vq_getchain()
451  * and used its positive return value.)
452  */
453 void
vq_relchain(struct vqueue_info * vq,uint16_t idx,uint32_t iolen)454 vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
455 {
456 	vq_relchain_prepare(vq, idx, iolen);
457 	vq_relchain_publish(vq);
458 }
459 
460 /*
461  * Driver has finished processing "available" chains and calling
462  * vq_relchain on each one.  If driver used all the available
463  * chains, used_all should be set.
464  *
465  * If the "used" index moved we may need to inform the guest, i.e.,
466  * deliver an interrupt.  Even if the used index did NOT move we
467  * may need to deliver an interrupt, if the avail ring is empty and
468  * we are supposed to interrupt on empty.
469  *
470  * Note that used_all_avail is provided by the caller because it's
471  * a snapshot of the ring state when he decided to finish interrupt
472  * processing -- it's possible that descriptors became available after
473  * that point.  (It's also typically a constant 1/True as well.)
474  */
475 void
vq_endchains(struct vqueue_info * vq,int used_all_avail)476 vq_endchains(struct vqueue_info *vq, int used_all_avail)
477 {
478 	struct virtio_softc *vs;
479 	uint16_t event_idx, new_idx, old_idx;
480 	int intr;
481 
482 	/*
483 	 * Interrupt generation: if we're using EVENT_IDX,
484 	 * interrupt if we've crossed the event threshold.
485 	 * Otherwise interrupt is generated if we added "used" entries,
486 	 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
487 	 *
488 	 * In any case, though, if NOTIFY_ON_EMPTY is set and the
489 	 * entire avail was processed, we need to interrupt always.
490 	 */
491 	vs = vq->vq_vs;
492 	old_idx = vq->vq_save_used;
493 	vq->vq_save_used = new_idx = vq->vq_used->idx;
494 
495 	/*
496 	 * Use full memory barrier between "idx" store from preceding
497 	 * vq_relchain() call and the loads from VQ_USED_EVENT_IDX() or
498 	 * "flags" field below.
499 	 */
500 	atomic_thread_fence_seq_cst();
501 	if (used_all_avail &&
502 	    (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
503 		intr = 1;
504 	else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
505 		event_idx = VQ_USED_EVENT_IDX(vq);
506 		/*
507 		 * This calculation is per docs and the kernel
508 		 * (see src/sys/dev/virtio/virtio_ring.h).
509 		 */
510 		intr = (uint16_t)(new_idx - event_idx - 1) <
511 			(uint16_t)(new_idx - old_idx);
512 	} else {
513 		intr = new_idx != old_idx &&
514 		    !(vq->vq_avail->flags & VRING_AVAIL_F_NO_INTERRUPT);
515 	}
516 	if (intr)
517 		vq_interrupt(vs, vq);
518 }
519 
520 /* Note: these are in sorted order to make for a fast search */
521 static struct config_reg {
522 	uint16_t	cr_offset;	/* register offset */
523 	uint8_t		cr_size;	/* size (bytes) */
524 	uint8_t		cr_ro;		/* true => reg is read only */
525 	const char	*cr_name;	/* name of reg */
526 } config_regs[] = {
527 	{ VIRTIO_PCI_HOST_FEATURES,	4, 1, "HOST_FEATURES" },
528 	{ VIRTIO_PCI_GUEST_FEATURES,	4, 0, "GUEST_FEATURES" },
529 	{ VIRTIO_PCI_QUEUE_PFN,		4, 0, "QUEUE_PFN" },
530 	{ VIRTIO_PCI_QUEUE_NUM,		2, 1, "QUEUE_NUM" },
531 	{ VIRTIO_PCI_QUEUE_SEL,		2, 0, "QUEUE_SEL" },
532 	{ VIRTIO_PCI_QUEUE_NOTIFY,	2, 0, "QUEUE_NOTIFY" },
533 	{ VIRTIO_PCI_STATUS,		1, 0, "STATUS" },
534 	{ VIRTIO_PCI_ISR,		1, 0, "ISR" },
535 	{ VIRTIO_MSI_CONFIG_VECTOR,	2, 0, "CONFIG_VECTOR" },
536 	{ VIRTIO_MSI_QUEUE_VECTOR,	2, 0, "QUEUE_VECTOR" },
537 };
538 
539 static inline struct config_reg *
vi_find_cr(int offset)540 vi_find_cr(int offset) {
541 	u_int hi, lo, mid;
542 	struct config_reg *cr;
543 
544 	lo = 0;
545 	hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
546 	while (hi >= lo) {
547 		mid = (hi + lo) >> 1;
548 		cr = &config_regs[mid];
549 		if (cr->cr_offset == offset)
550 			return (cr);
551 		if (cr->cr_offset < offset)
552 			lo = mid + 1;
553 		else
554 			hi = mid - 1;
555 	}
556 	return (NULL);
557 }
558 
559 /*
560  * Handle pci config space reads.
561  * If it's to the MSI-X info, do that.
562  * If it's part of the virtio standard stuff, do that.
563  * Otherwise dispatch to the actual driver.
564  */
565 uint64_t
vi_pci_read(struct pci_devinst * pi,int baridx,uint64_t offset,int size)566 vi_pci_read(struct pci_devinst *pi, int baridx, uint64_t offset, int size)
567 {
568 	struct virtio_softc *vs = pi->pi_arg;
569 	struct virtio_consts *vc;
570 	struct config_reg *cr;
571 	uint64_t virtio_config_size, max;
572 	const char *name;
573 	uint32_t newoff;
574 	uint32_t value;
575 	int error;
576 
577 	if (vs->vs_flags & VIRTIO_USE_MSIX) {
578 		if (baridx == pci_msix_table_bar(pi) ||
579 		    baridx == pci_msix_pba_bar(pi)) {
580 			return (pci_emul_msix_tread(pi, offset, size));
581 		}
582 	}
583 
584 	/* XXX probably should do something better than just assert() */
585 	assert(baridx == 0);
586 
587 	if (vs->vs_mtx)
588 		pthread_mutex_lock(vs->vs_mtx);
589 
590 	vc = vs->vs_vc;
591 	name = vc->vc_name;
592 	value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
593 
594 	if (size != 1 && size != 2 && size != 4)
595 		goto bad;
596 
597 	virtio_config_size = VIRTIO_PCI_CONFIG_OFF(pci_msix_enabled(pi));
598 
599 	if (offset >= virtio_config_size) {
600 		/*
601 		 * Subtract off the standard size (including MSI-X
602 		 * registers if enabled) and dispatch to underlying driver.
603 		 * If that fails, fall into general code.
604 		 */
605 		newoff = offset - virtio_config_size;
606 		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
607 		if (newoff + size > max)
608 			goto bad;
609 		if (vc->vc_cfgread != NULL)
610 			error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
611 		else
612 			error = 0;
613 		if (!error)
614 			goto done;
615 	}
616 
617 bad:
618 	cr = vi_find_cr(offset);
619 	if (cr == NULL || cr->cr_size != size) {
620 		if (cr != NULL) {
621 			/* offset must be OK, so size must be bad */
622 			EPRINTLN(
623 			    "%s: read from %s: bad size %d",
624 			    name, cr->cr_name, size);
625 		} else {
626 			EPRINTLN(
627 			    "%s: read from bad offset/size %jd/%d",
628 			    name, (uintmax_t)offset, size);
629 		}
630 		goto done;
631 	}
632 
633 	switch (offset) {
634 	case VIRTIO_PCI_HOST_FEATURES:
635 		value = vc->vc_hv_caps;
636 		break;
637 	case VIRTIO_PCI_GUEST_FEATURES:
638 		value = vs->vs_negotiated_caps;
639 		break;
640 	case VIRTIO_PCI_QUEUE_PFN:
641 		if (vs->vs_curq < vc->vc_nvq)
642 			value = vs->vs_queues[vs->vs_curq].vq_pfn;
643 		break;
644 	case VIRTIO_PCI_QUEUE_NUM:
645 		value = vs->vs_curq < vc->vc_nvq ?
646 		    vs->vs_queues[vs->vs_curq].vq_qsize : 0;
647 		break;
648 	case VIRTIO_PCI_QUEUE_SEL:
649 		value = vs->vs_curq;
650 		break;
651 	case VIRTIO_PCI_QUEUE_NOTIFY:
652 		value = 0;	/* XXX */
653 		break;
654 	case VIRTIO_PCI_STATUS:
655 		value = vs->vs_status;
656 		break;
657 	case VIRTIO_PCI_ISR:
658 		value = vs->vs_isr;
659 		vs->vs_isr = 0;		/* a read clears this flag */
660 		if (value)
661 			pci_lintr_deassert(pi);
662 		break;
663 	case VIRTIO_MSI_CONFIG_VECTOR:
664 		value = vs->vs_msix_cfg_idx;
665 		break;
666 	case VIRTIO_MSI_QUEUE_VECTOR:
667 		value = vs->vs_curq < vc->vc_nvq ?
668 		    vs->vs_queues[vs->vs_curq].vq_msix_idx :
669 		    VIRTIO_MSI_NO_VECTOR;
670 		break;
671 	}
672 done:
673 	if (vs->vs_mtx)
674 		pthread_mutex_unlock(vs->vs_mtx);
675 	return (value);
676 }
677 
678 /*
679  * Handle pci config space writes.
680  * If it's to the MSI-X info, do that.
681  * If it's part of the virtio standard stuff, do that.
682  * Otherwise dispatch to the actual driver.
683  */
684 void
vi_pci_write(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)685 vi_pci_write(struct pci_devinst *pi, int baridx, uint64_t offset, int size,
686     uint64_t value)
687 {
688 	struct virtio_softc *vs = pi->pi_arg;
689 	struct vqueue_info *vq;
690 	struct virtio_consts *vc;
691 	struct config_reg *cr;
692 	uint64_t virtio_config_size, max;
693 	const char *name;
694 	uint32_t newoff;
695 	int error;
696 
697 	if (vs->vs_flags & VIRTIO_USE_MSIX) {
698 		if (baridx == pci_msix_table_bar(pi) ||
699 		    baridx == pci_msix_pba_bar(pi)) {
700 			pci_emul_msix_twrite(pi, offset, size, value);
701 			return;
702 		}
703 	}
704 
705 	/* XXX probably should do something better than just assert() */
706 	assert(baridx == 0);
707 
708 	if (vs->vs_mtx)
709 		pthread_mutex_lock(vs->vs_mtx);
710 
711 	vc = vs->vs_vc;
712 	name = vc->vc_name;
713 
714 	if (size != 1 && size != 2 && size != 4)
715 		goto bad;
716 
717 	virtio_config_size = VIRTIO_PCI_CONFIG_OFF(pci_msix_enabled(pi));
718 
719 	if (offset >= virtio_config_size) {
720 		/*
721 		 * Subtract off the standard size (including MSI-X
722 		 * registers if enabled) and dispatch to underlying driver.
723 		 */
724 		newoff = offset - virtio_config_size;
725 		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
726 		if (newoff + size > max)
727 			goto bad;
728 		if (vc->vc_cfgwrite != NULL)
729 			error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
730 		else
731 			error = 0;
732 		if (!error)
733 			goto done;
734 	}
735 
736 bad:
737 	cr = vi_find_cr(offset);
738 	if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
739 		if (cr != NULL) {
740 			/* offset must be OK, wrong size and/or reg is R/O */
741 			if (cr->cr_size != size)
742 				EPRINTLN(
743 				    "%s: write to %s: bad size %d",
744 				    name, cr->cr_name, size);
745 			if (cr->cr_ro)
746 				EPRINTLN(
747 				    "%s: write to read-only reg %s",
748 				    name, cr->cr_name);
749 		} else {
750 			EPRINTLN(
751 			    "%s: write to bad offset/size %jd/%d",
752 			    name, (uintmax_t)offset, size);
753 		}
754 		goto done;
755 	}
756 
757 	switch (offset) {
758 	case VIRTIO_PCI_GUEST_FEATURES:
759 		vs->vs_negotiated_caps = value & vc->vc_hv_caps;
760 		if (vc->vc_apply_features)
761 			(*vc->vc_apply_features)(DEV_SOFTC(vs),
762 			    vs->vs_negotiated_caps);
763 		break;
764 	case VIRTIO_PCI_QUEUE_PFN:
765 		if (vs->vs_curq >= vc->vc_nvq)
766 			goto bad_qindex;
767 		vi_vq_init(vs, value);
768 		break;
769 	case VIRTIO_PCI_QUEUE_SEL:
770 		/*
771 		 * Note that the guest is allowed to select an
772 		 * invalid queue; we just need to return a QNUM
773 		 * of 0 while the bad queue is selected.
774 		 */
775 		vs->vs_curq = value;
776 		break;
777 	case VIRTIO_PCI_QUEUE_NOTIFY:
778 		if (value >= (unsigned int)vc->vc_nvq) {
779 			EPRINTLN("%s: queue %d notify out of range",
780 				name, (int)value);
781 			goto done;
782 		}
783 		vq = &vs->vs_queues[value];
784 		if (vq->vq_notify)
785 			(*vq->vq_notify)(DEV_SOFTC(vs), vq);
786 		else if (vc->vc_qnotify)
787 			(*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
788 		else
789 			EPRINTLN(
790 			    "%s: qnotify queue %d: missing vq/vc notify",
791 				name, (int)value);
792 		break;
793 	case VIRTIO_PCI_STATUS:
794 		vs->vs_status = value;
795 		if (value == 0)
796 			(*vc->vc_reset)(DEV_SOFTC(vs));
797 		break;
798 	case VIRTIO_MSI_CONFIG_VECTOR:
799 		vs->vs_msix_cfg_idx = value;
800 		break;
801 	case VIRTIO_MSI_QUEUE_VECTOR:
802 		if (vs->vs_curq >= vc->vc_nvq)
803 			goto bad_qindex;
804 		vq = &vs->vs_queues[vs->vs_curq];
805 		vq->vq_msix_idx = value;
806 		break;
807 	}
808 	goto done;
809 
810 bad_qindex:
811 	EPRINTLN(
812 	    "%s: write config reg %s: curq %d >= max %d",
813 	    name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
814 done:
815 	if (vs->vs_mtx)
816 		pthread_mutex_unlock(vs->vs_mtx);
817 }
818 
819 #ifdef BHYVE_SNAPSHOT
820 int
vi_pci_pause(struct pci_devinst * pi)821 vi_pci_pause(struct pci_devinst *pi)
822 {
823 	struct virtio_softc *vs;
824 	struct virtio_consts *vc;
825 
826 	vs = pi->pi_arg;
827 	vc = vs->vs_vc;
828 
829 	vc = vs->vs_vc;
830 	assert(vc->vc_pause != NULL);
831 	(*vc->vc_pause)(DEV_SOFTC(vs));
832 
833 	return (0);
834 }
835 
836 int
vi_pci_resume(struct pci_devinst * pi)837 vi_pci_resume(struct pci_devinst *pi)
838 {
839 	struct virtio_softc *vs;
840 	struct virtio_consts *vc;
841 
842 	vs = pi->pi_arg;
843 	vc = vs->vs_vc;
844 
845 	vc = vs->vs_vc;
846 	assert(vc->vc_resume != NULL);
847 	(*vc->vc_resume)(DEV_SOFTC(vs));
848 
849 	return (0);
850 }
851 
852 static int
vi_pci_snapshot_softc(struct virtio_softc * vs,struct vm_snapshot_meta * meta)853 vi_pci_snapshot_softc(struct virtio_softc *vs, struct vm_snapshot_meta *meta)
854 {
855 	int ret;
856 
857 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_flags, meta, ret, done);
858 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_negotiated_caps, meta, ret, done);
859 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_curq, meta, ret, done);
860 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_status, meta, ret, done);
861 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_isr, meta, ret, done);
862 	SNAPSHOT_VAR_OR_LEAVE(vs->vs_msix_cfg_idx, meta, ret, done);
863 
864 done:
865 	return (ret);
866 }
867 
868 static int
vi_pci_snapshot_consts(struct virtio_consts * vc,struct vm_snapshot_meta * meta)869 vi_pci_snapshot_consts(struct virtio_consts *vc, struct vm_snapshot_meta *meta)
870 {
871 	int ret;
872 
873 	SNAPSHOT_VAR_CMP_OR_LEAVE(vc->vc_nvq, meta, ret, done);
874 	SNAPSHOT_VAR_CMP_OR_LEAVE(vc->vc_cfgsize, meta, ret, done);
875 	SNAPSHOT_VAR_CMP_OR_LEAVE(vc->vc_hv_caps, meta, ret, done);
876 
877 done:
878 	return (ret);
879 }
880 
881 static int
vi_pci_snapshot_queues(struct virtio_softc * vs,struct vm_snapshot_meta * meta)882 vi_pci_snapshot_queues(struct virtio_softc *vs, struct vm_snapshot_meta *meta)
883 {
884 	int i;
885 	int ret;
886 	struct virtio_consts *vc;
887 	struct vqueue_info *vq;
888 	struct vmctx *ctx;
889 	uint64_t addr_size;
890 
891 	ctx = vs->vs_pi->pi_vmctx;
892 	vc = vs->vs_vc;
893 
894 	/* Save virtio queue info */
895 	for (i = 0; i < vc->vc_nvq; i++) {
896 		vq = &vs->vs_queues[i];
897 
898 		SNAPSHOT_VAR_CMP_OR_LEAVE(vq->vq_qsize, meta, ret, done);
899 		SNAPSHOT_VAR_CMP_OR_LEAVE(vq->vq_num, meta, ret, done);
900 
901 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_flags, meta, ret, done);
902 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_last_avail, meta, ret, done);
903 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_next_used, meta, ret, done);
904 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_save_used, meta, ret, done);
905 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_msix_idx, meta, ret, done);
906 
907 		SNAPSHOT_VAR_OR_LEAVE(vq->vq_pfn, meta, ret, done);
908 
909 		if (!vq_ring_ready(vq))
910 			continue;
911 
912 		addr_size = vq->vq_qsize * sizeof(struct vring_desc);
913 		SNAPSHOT_GUEST2HOST_ADDR_OR_LEAVE(ctx, vq->vq_desc, addr_size,
914 			false, meta, ret, done);
915 
916 		addr_size = (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
917 		SNAPSHOT_GUEST2HOST_ADDR_OR_LEAVE(ctx, vq->vq_avail, addr_size,
918 			false, meta, ret, done);
919 
920 		addr_size  = (2 + 2 * vq->vq_qsize + 1) * sizeof(uint16_t);
921 		SNAPSHOT_GUEST2HOST_ADDR_OR_LEAVE(ctx, vq->vq_used, addr_size,
922 			false, meta, ret, done);
923 
924 		SNAPSHOT_BUF_OR_LEAVE(vq->vq_desc,
925 			vring_size_aligned(vq->vq_qsize), meta, ret, done);
926 	}
927 
928 done:
929 	return (ret);
930 }
931 
932 int
vi_pci_snapshot(struct vm_snapshot_meta * meta)933 vi_pci_snapshot(struct vm_snapshot_meta *meta)
934 {
935 	int ret;
936 	struct pci_devinst *pi;
937 	struct virtio_softc *vs;
938 	struct virtio_consts *vc;
939 
940 	pi = meta->dev_data;
941 	vs = pi->pi_arg;
942 	vc = vs->vs_vc;
943 
944 	/* Save virtio softc */
945 	ret = vi_pci_snapshot_softc(vs, meta);
946 	if (ret != 0)
947 		goto done;
948 
949 	/* Save virtio consts */
950 	ret = vi_pci_snapshot_consts(vc, meta);
951 	if (ret != 0)
952 		goto done;
953 
954 	/* Save virtio queue info */
955 	ret = vi_pci_snapshot_queues(vs, meta);
956 	if (ret != 0)
957 		goto done;
958 
959 	/* Save device softc, if needed */
960 	if (vc->vc_snapshot != NULL) {
961 		ret = (*vc->vc_snapshot)(DEV_SOFTC(vs), meta);
962 		if (ret != 0)
963 			goto done;
964 	}
965 
966 done:
967 	return (ret);
968 }
969 #endif
970