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: stable/11/usr.sbin/bhyve/virtio.c 349704 2019-07-03 20:22:36Z vmaffione $");
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 */
63void
64vi_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 */
92void
93vi_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 */
121void
122vi_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 */
141int
142vi_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 */
171void
172vi_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 */
209static 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 */
261int
262vq_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	}
377loopy:
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 */
390void
391vq_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 */
404void
405vq_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	 * (and even on x86 to act as a compiler barrier).
433	 */
434	atomic_thread_fence_rel();
435	vuh->vu_idx = uidx;
436}
437
438/*
439 * Driver has finished processing "available" chains and calling
440 * vq_relchain on each one.  If driver used all the available
441 * chains, used_all should be set.
442 *
443 * If the "used" index moved we may need to inform the guest, i.e.,
444 * deliver an interrupt.  Even if the used index did NOT move we
445 * may need to deliver an interrupt, if the avail ring is empty and
446 * we are supposed to interrupt on empty.
447 *
448 * Note that used_all_avail is provided by the caller because it's
449 * a snapshot of the ring state when he decided to finish interrupt
450 * processing -- it's possible that descriptors became available after
451 * that point.  (It's also typically a constant 1/True as well.)
452 */
453void
454vq_endchains(struct vqueue_info *vq, int used_all_avail)
455{
456	struct virtio_softc *vs;
457	uint16_t event_idx, new_idx, old_idx;
458	int intr;
459
460	/*
461	 * Interrupt generation: if we're using EVENT_IDX,
462	 * interrupt if we've crossed the event threshold.
463	 * Otherwise interrupt is generated if we added "used" entries,
464	 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
465	 *
466	 * In any case, though, if NOTIFY_ON_EMPTY is set and the
467	 * entire avail was processed, we need to interrupt always.
468	 */
469	vs = vq->vq_vs;
470	old_idx = vq->vq_save_used;
471	vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
472
473	/*
474	 * Use full memory barrier between vu_idx store from preceding
475	 * vq_relchain() call and the loads from VQ_USED_EVENT_IDX() or
476	 * va_flags below.
477	 */
478	atomic_thread_fence_seq_cst();
479	if (used_all_avail &&
480	    (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
481		intr = 1;
482	else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
483		event_idx = VQ_USED_EVENT_IDX(vq);
484		/*
485		 * This calculation is per docs and the kernel
486		 * (see src/sys/dev/virtio/virtio_ring.h).
487		 */
488		intr = (uint16_t)(new_idx - event_idx - 1) <
489			(uint16_t)(new_idx - old_idx);
490	} else {
491		intr = new_idx != old_idx &&
492		    !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
493	}
494	if (intr)
495		vq_interrupt(vs, vq);
496}
497
498/* Note: these are in sorted order to make for a fast search */
499static struct config_reg {
500	uint16_t	cr_offset;	/* register offset */
501	uint8_t		cr_size;	/* size (bytes) */
502	uint8_t		cr_ro;		/* true => reg is read only */
503	const char	*cr_name;	/* name of reg */
504} config_regs[] = {
505	{ VTCFG_R_HOSTCAP,	4, 1, "HOSTCAP" },
506	{ VTCFG_R_GUESTCAP,	4, 0, "GUESTCAP" },
507	{ VTCFG_R_PFN,		4, 0, "PFN" },
508	{ VTCFG_R_QNUM,		2, 1, "QNUM" },
509	{ VTCFG_R_QSEL,		2, 0, "QSEL" },
510	{ VTCFG_R_QNOTIFY,	2, 0, "QNOTIFY" },
511	{ VTCFG_R_STATUS,	1, 0, "STATUS" },
512	{ VTCFG_R_ISR,		1, 0, "ISR" },
513	{ VTCFG_R_CFGVEC,	2, 0, "CFGVEC" },
514	{ VTCFG_R_QVEC,		2, 0, "QVEC" },
515};
516
517static inline struct config_reg *
518vi_find_cr(int offset) {
519	u_int hi, lo, mid;
520	struct config_reg *cr;
521
522	lo = 0;
523	hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
524	while (hi >= lo) {
525		mid = (hi + lo) >> 1;
526		cr = &config_regs[mid];
527		if (cr->cr_offset == offset)
528			return (cr);
529		if (cr->cr_offset < offset)
530			lo = mid + 1;
531		else
532			hi = mid - 1;
533	}
534	return (NULL);
535}
536
537/*
538 * Handle pci config space reads.
539 * If it's to the MSI-X info, do that.
540 * If it's part of the virtio standard stuff, do that.
541 * Otherwise dispatch to the actual driver.
542 */
543uint64_t
544vi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
545	    int baridx, uint64_t offset, int size)
546{
547	struct virtio_softc *vs = pi->pi_arg;
548	struct virtio_consts *vc;
549	struct config_reg *cr;
550	uint64_t virtio_config_size, max;
551	const char *name;
552	uint32_t newoff;
553	uint32_t value;
554	int error;
555
556	if (vs->vs_flags & VIRTIO_USE_MSIX) {
557		if (baridx == pci_msix_table_bar(pi) ||
558		    baridx == pci_msix_pba_bar(pi)) {
559			return (pci_emul_msix_tread(pi, offset, size));
560		}
561	}
562
563	/* XXX probably should do something better than just assert() */
564	assert(baridx == 0);
565
566	if (vs->vs_mtx)
567		pthread_mutex_lock(vs->vs_mtx);
568
569	vc = vs->vs_vc;
570	name = vc->vc_name;
571	value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
572
573	if (size != 1 && size != 2 && size != 4)
574		goto bad;
575
576	if (pci_msix_enabled(pi))
577		virtio_config_size = VTCFG_R_CFG1;
578	else
579		virtio_config_size = VTCFG_R_CFG0;
580
581	if (offset >= virtio_config_size) {
582		/*
583		 * Subtract off the standard size (including MSI-X
584		 * registers if enabled) and dispatch to underlying driver.
585		 * If that fails, fall into general code.
586		 */
587		newoff = offset - virtio_config_size;
588		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
589		if (newoff + size > max)
590			goto bad;
591		error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
592		if (!error)
593			goto done;
594	}
595
596bad:
597	cr = vi_find_cr(offset);
598	if (cr == NULL || cr->cr_size != size) {
599		if (cr != NULL) {
600			/* offset must be OK, so size must be bad */
601			fprintf(stderr,
602			    "%s: read from %s: bad size %d\r\n",
603			    name, cr->cr_name, size);
604		} else {
605			fprintf(stderr,
606			    "%s: read from bad offset/size %jd/%d\r\n",
607			    name, (uintmax_t)offset, size);
608		}
609		goto done;
610	}
611
612	switch (offset) {
613	case VTCFG_R_HOSTCAP:
614		value = vc->vc_hv_caps;
615		break;
616	case VTCFG_R_GUESTCAP:
617		value = vs->vs_negotiated_caps;
618		break;
619	case VTCFG_R_PFN:
620		if (vs->vs_curq < vc->vc_nvq)
621			value = vs->vs_queues[vs->vs_curq].vq_pfn;
622		break;
623	case VTCFG_R_QNUM:
624		value = vs->vs_curq < vc->vc_nvq ?
625		    vs->vs_queues[vs->vs_curq].vq_qsize : 0;
626		break;
627	case VTCFG_R_QSEL:
628		value = vs->vs_curq;
629		break;
630	case VTCFG_R_QNOTIFY:
631		value = 0;	/* XXX */
632		break;
633	case VTCFG_R_STATUS:
634		value = vs->vs_status;
635		break;
636	case VTCFG_R_ISR:
637		value = vs->vs_isr;
638		vs->vs_isr = 0;		/* a read clears this flag */
639		if (value)
640			pci_lintr_deassert(pi);
641		break;
642	case VTCFG_R_CFGVEC:
643		value = vs->vs_msix_cfg_idx;
644		break;
645	case VTCFG_R_QVEC:
646		value = vs->vs_curq < vc->vc_nvq ?
647		    vs->vs_queues[vs->vs_curq].vq_msix_idx :
648		    VIRTIO_MSI_NO_VECTOR;
649		break;
650	}
651done:
652	if (vs->vs_mtx)
653		pthread_mutex_unlock(vs->vs_mtx);
654	return (value);
655}
656
657/*
658 * Handle pci config space writes.
659 * If it's to the MSI-X info, do that.
660 * If it's part of the virtio standard stuff, do that.
661 * Otherwise dispatch to the actual driver.
662 */
663void
664vi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
665	     int baridx, uint64_t offset, int size, uint64_t value)
666{
667	struct virtio_softc *vs = pi->pi_arg;
668	struct vqueue_info *vq;
669	struct virtio_consts *vc;
670	struct config_reg *cr;
671	uint64_t virtio_config_size, max;
672	const char *name;
673	uint32_t newoff;
674	int error;
675
676	if (vs->vs_flags & VIRTIO_USE_MSIX) {
677		if (baridx == pci_msix_table_bar(pi) ||
678		    baridx == pci_msix_pba_bar(pi)) {
679			pci_emul_msix_twrite(pi, offset, size, value);
680			return;
681		}
682	}
683
684	/* XXX probably should do something better than just assert() */
685	assert(baridx == 0);
686
687	if (vs->vs_mtx)
688		pthread_mutex_lock(vs->vs_mtx);
689
690	vc = vs->vs_vc;
691	name = vc->vc_name;
692
693	if (size != 1 && size != 2 && size != 4)
694		goto bad;
695
696	if (pci_msix_enabled(pi))
697		virtio_config_size = VTCFG_R_CFG1;
698	else
699		virtio_config_size = VTCFG_R_CFG0;
700
701	if (offset >= virtio_config_size) {
702		/*
703		 * Subtract off the standard size (including MSI-X
704		 * registers if enabled) and dispatch to underlying driver.
705		 */
706		newoff = offset - virtio_config_size;
707		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
708		if (newoff + size > max)
709			goto bad;
710		error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
711		if (!error)
712			goto done;
713	}
714
715bad:
716	cr = vi_find_cr(offset);
717	if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
718		if (cr != NULL) {
719			/* offset must be OK, wrong size and/or reg is R/O */
720			if (cr->cr_size != size)
721				fprintf(stderr,
722				    "%s: write to %s: bad size %d\r\n",
723				    name, cr->cr_name, size);
724			if (cr->cr_ro)
725				fprintf(stderr,
726				    "%s: write to read-only reg %s\r\n",
727				    name, cr->cr_name);
728		} else {
729			fprintf(stderr,
730			    "%s: write to bad offset/size %jd/%d\r\n",
731			    name, (uintmax_t)offset, size);
732		}
733		goto done;
734	}
735
736	switch (offset) {
737	case VTCFG_R_GUESTCAP:
738		vs->vs_negotiated_caps = value & vc->vc_hv_caps;
739		if (vc->vc_apply_features)
740			(*vc->vc_apply_features)(DEV_SOFTC(vs),
741			    vs->vs_negotiated_caps);
742		break;
743	case VTCFG_R_PFN:
744		if (vs->vs_curq >= vc->vc_nvq)
745			goto bad_qindex;
746		vi_vq_init(vs, value);
747		break;
748	case VTCFG_R_QSEL:
749		/*
750		 * Note that the guest is allowed to select an
751		 * invalid queue; we just need to return a QNUM
752		 * of 0 while the bad queue is selected.
753		 */
754		vs->vs_curq = value;
755		break;
756	case VTCFG_R_QNOTIFY:
757		if (value >= vc->vc_nvq) {
758			fprintf(stderr, "%s: queue %d notify out of range\r\n",
759				name, (int)value);
760			goto done;
761		}
762		vq = &vs->vs_queues[value];
763		if (vq->vq_notify)
764			(*vq->vq_notify)(DEV_SOFTC(vs), vq);
765		else if (vc->vc_qnotify)
766			(*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
767		else
768			fprintf(stderr,
769			    "%s: qnotify queue %d: missing vq/vc notify\r\n",
770				name, (int)value);
771		break;
772	case VTCFG_R_STATUS:
773		vs->vs_status = value;
774		if (value == 0)
775			(*vc->vc_reset)(DEV_SOFTC(vs));
776		break;
777	case VTCFG_R_CFGVEC:
778		vs->vs_msix_cfg_idx = value;
779		break;
780	case VTCFG_R_QVEC:
781		if (vs->vs_curq >= vc->vc_nvq)
782			goto bad_qindex;
783		vq = &vs->vs_queues[vs->vs_curq];
784		vq->vq_msix_idx = value;
785		break;
786	}
787	goto done;
788
789bad_qindex:
790	fprintf(stderr,
791	    "%s: write config reg %s: curq %d >= max %d\r\n",
792	    name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
793done:
794	if (vs->vs_mtx)
795		pthread_mutex_unlock(vs->vs_mtx);
796}
797