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