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