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