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