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