1253440Sgrehan/*-
2253440Sgrehan * Copyright (c) 2013  Chris Torek <torek @ torek net>
3253440Sgrehan * All rights reserved.
4253440Sgrehan *
5253440Sgrehan * Redistribution and use in source and binary forms, with or without
6253440Sgrehan * modification, are permitted provided that the following conditions
7253440Sgrehan * are met:
8253440Sgrehan * 1. Redistributions of source code must retain the above copyright
9253440Sgrehan *    notice, this list of conditions and the following disclaimer.
10253440Sgrehan * 2. Redistributions in binary form must reproduce the above copyright
11253440Sgrehan *    notice, this list of conditions and the following disclaimer in the
12253440Sgrehan *    documentation and/or other materials provided with the distribution.
13253440Sgrehan *
14253440Sgrehan * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15253440Sgrehan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16253440Sgrehan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17253440Sgrehan * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18253440Sgrehan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19253440Sgrehan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20253440Sgrehan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21253440Sgrehan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22253440Sgrehan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23253440Sgrehan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24253440Sgrehan * SUCH DAMAGE.
25253440Sgrehan */
26253440Sgrehan
27253440Sgrehan#include <sys/cdefs.h>
28253440Sgrehan__FBSDID("$FreeBSD: releng/11.0/usr.sbin/bhyve/virtio.c 282784 2015-05-11 21:24:10Z grehan $");
29253440Sgrehan
30253440Sgrehan#include <sys/param.h>
31253440Sgrehan#include <sys/uio.h>
32253440Sgrehan
33253440Sgrehan#include <stdio.h>
34253440Sgrehan#include <stdint.h>
35253440Sgrehan#include <pthread.h>
36270326Stychon#include <pthread_np.h>
37253440Sgrehan
38253440Sgrehan#include "bhyverun.h"
39253440Sgrehan#include "pci_emul.h"
40253440Sgrehan#include "virtio.h"
41253440Sgrehan
42253440Sgrehan/*
43253440Sgrehan * Functions for dealing with generalized "virtual devices" as
44253440Sgrehan * defined by <https://www.google.com/#output=search&q=virtio+spec>
45253440Sgrehan */
46253440Sgrehan
47253440Sgrehan/*
48253440Sgrehan * In case we decide to relax the "virtio softc comes at the
49253440Sgrehan * front of virtio-based device softc" constraint, let's use
50253440Sgrehan * this to convert.
51253440Sgrehan */
52253440Sgrehan#define DEV_SOFTC(vs) ((void *)(vs))
53253440Sgrehan
54253440Sgrehan/*
55253440Sgrehan * Link a virtio_softc to its constants, the device softc, and
56253440Sgrehan * the PCI emulation.
57253440Sgrehan */
58253440Sgrehanvoid
59253440Sgrehanvi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
60253440Sgrehan		void *dev_softc, struct pci_devinst *pi,
61253440Sgrehan		struct vqueue_info *queues)
62253440Sgrehan{
63253440Sgrehan	int i;
64253440Sgrehan
65253440Sgrehan	/* vs and dev_softc addresses must match */
66253440Sgrehan	assert((void *)vs == dev_softc);
67253440Sgrehan	vs->vs_vc = vc;
68253440Sgrehan	vs->vs_pi = pi;
69253440Sgrehan	pi->pi_arg = vs;
70253440Sgrehan
71253440Sgrehan	vs->vs_queues = queues;
72253440Sgrehan	for (i = 0; i < vc->vc_nvq; i++) {
73253440Sgrehan		queues[i].vq_vs = vs;
74253440Sgrehan		queues[i].vq_num = i;
75253440Sgrehan	}
76253440Sgrehan}
77253440Sgrehan
78253440Sgrehan/*
79253440Sgrehan * Reset device (device-wide).  This erases all queues, i.e.,
80253440Sgrehan * all the queues become invalid (though we don't wipe out the
81253440Sgrehan * internal pointers, we just clear the VQ_ALLOC flag).
82253440Sgrehan *
83253440Sgrehan * It resets negotiated features to "none".
84253440Sgrehan *
85253440Sgrehan * If MSI-X is enabled, this also resets all the vectors to NO_VECTOR.
86253440Sgrehan */
87253440Sgrehanvoid
88253440Sgrehanvi_reset_dev(struct virtio_softc *vs)
89253440Sgrehan{
90253440Sgrehan	struct vqueue_info *vq;
91253440Sgrehan	int i, nvq;
92253440Sgrehan
93270326Stychon	if (vs->vs_mtx)
94270326Stychon		assert(pthread_mutex_isowned_np(vs->vs_mtx));
95270326Stychon
96253440Sgrehan	nvq = vs->vs_vc->vc_nvq;
97253440Sgrehan	for (vq = vs->vs_queues, i = 0; i < nvq; vq++, i++) {
98253440Sgrehan		vq->vq_flags = 0;
99253440Sgrehan		vq->vq_last_avail = 0;
100280026Smav		vq->vq_save_used = 0;
101253440Sgrehan		vq->vq_pfn = 0;
102253440Sgrehan		vq->vq_msix_idx = VIRTIO_MSI_NO_VECTOR;
103253440Sgrehan	}
104253440Sgrehan	vs->vs_negotiated_caps = 0;
105253440Sgrehan	vs->vs_curq = 0;
106253440Sgrehan	/* vs->vs_status = 0; -- redundant */
107261268Sjhb	if (vs->vs_isr)
108261268Sjhb		pci_lintr_deassert(vs->vs_pi);
109253440Sgrehan	vs->vs_isr = 0;
110253440Sgrehan	vs->vs_msix_cfg_idx = VIRTIO_MSI_NO_VECTOR;
111253440Sgrehan}
112253440Sgrehan
113253440Sgrehan/*
114253440Sgrehan * Set I/O BAR (usually 0) to map PCI config registers.
115253440Sgrehan */
116253440Sgrehanvoid
117253440Sgrehanvi_set_io_bar(struct virtio_softc *vs, int barnum)
118253440Sgrehan{
119253440Sgrehan	size_t size;
120253440Sgrehan
121253440Sgrehan	/*
122253440Sgrehan	 * ??? should we use CFG0 if MSI-X is disabled?
123253440Sgrehan	 * Existing code did not...
124253440Sgrehan	 */
125253440Sgrehan	size = VTCFG_R_CFG1 + vs->vs_vc->vc_cfgsize;
126253440Sgrehan	pci_emul_alloc_bar(vs->vs_pi, barnum, PCIBAR_IO, size);
127253440Sgrehan}
128253440Sgrehan
129253440Sgrehan/*
130253440Sgrehan * Initialize MSI-X vector capabilities if we're to use MSI-X,
131253440Sgrehan * or MSI capabilities if not.
132253440Sgrehan *
133253440Sgrehan * We assume we want one MSI-X vector per queue, here, plus one
134253440Sgrehan * for the config vec.
135253440Sgrehan */
136253440Sgrehanint
137253440Sgrehanvi_intr_init(struct virtio_softc *vs, int barnum, int use_msix)
138253440Sgrehan{
139253440Sgrehan	int nvec;
140253440Sgrehan
141253440Sgrehan	if (use_msix) {
142253440Sgrehan		vs->vs_flags |= VIRTIO_USE_MSIX;
143270326Stychon		VS_LOCK(vs);
144253440Sgrehan		vi_reset_dev(vs); /* set all vectors to NO_VECTOR */
145270326Stychon		VS_UNLOCK(vs);
146253440Sgrehan		nvec = vs->vs_vc->vc_nvq + 1;
147253440Sgrehan		if (pci_emul_add_msixcap(vs->vs_pi, nvec, barnum))
148253440Sgrehan			return (1);
149261268Sjhb	} else
150253440Sgrehan		vs->vs_flags &= ~VIRTIO_USE_MSIX;
151280725Sgrehan
152261268Sjhb	/* Only 1 MSI vector for bhyve */
153261268Sjhb	pci_emul_add_msicap(vs->vs_pi, 1);
154280725Sgrehan
155280725Sgrehan	/* Legacy interrupts are mandatory for virtio devices */
156280725Sgrehan	pci_lintr_request(vs->vs_pi);
157280725Sgrehan
158253440Sgrehan	return (0);
159253440Sgrehan}
160253440Sgrehan
161253440Sgrehan/*
162253440Sgrehan * Initialize the currently-selected virtio queue (vs->vs_curq).
163253440Sgrehan * The guest just gave us a page frame number, from which we can
164253440Sgrehan * calculate the addresses of the queue.
165253440Sgrehan */
166253440Sgrehanvoid
167253440Sgrehanvi_vq_init(struct virtio_softc *vs, uint32_t pfn)
168253440Sgrehan{
169253440Sgrehan	struct vqueue_info *vq;
170253440Sgrehan	uint64_t phys;
171253440Sgrehan	size_t size;
172253440Sgrehan	char *base;
173253440Sgrehan
174253440Sgrehan	vq = &vs->vs_queues[vs->vs_curq];
175253440Sgrehan	vq->vq_pfn = pfn;
176260469Sgrehan	phys = (uint64_t)pfn << VRING_PFN;
177253440Sgrehan	size = vring_size(vq->vq_qsize);
178253440Sgrehan	base = paddr_guest2host(vs->vs_pi->pi_vmctx, phys, size);
179253440Sgrehan
180253440Sgrehan	/* First page(s) are descriptors... */
181253440Sgrehan	vq->vq_desc = (struct virtio_desc *)base;
182253440Sgrehan	base += vq->vq_qsize * sizeof(struct virtio_desc);
183253440Sgrehan
184253440Sgrehan	/* ... immediately followed by "avail" ring (entirely uint16_t's) */
185253440Sgrehan	vq->vq_avail = (struct vring_avail *)base;
186253440Sgrehan	base += (2 + vq->vq_qsize + 1) * sizeof(uint16_t);
187253440Sgrehan
188253440Sgrehan	/* Then it's rounded up to the next page... */
189253440Sgrehan	base = (char *)roundup2((uintptr_t)base, VRING_ALIGN);
190253440Sgrehan
191253440Sgrehan	/* ... and the last page(s) are the used ring. */
192253440Sgrehan	vq->vq_used = (struct vring_used *)base;
193253440Sgrehan
194253440Sgrehan	/* Mark queue as allocated, and start at 0 when we use it. */
195253440Sgrehan	vq->vq_flags = VQ_ALLOC;
196253440Sgrehan	vq->vq_last_avail = 0;
197280026Smav	vq->vq_save_used = 0;
198253440Sgrehan}
199253440Sgrehan
200253440Sgrehan/*
201253440Sgrehan * Helper inline for vq_getchain(): record the i'th "real"
202253440Sgrehan * descriptor.
203253440Sgrehan */
204253440Sgrehanstatic inline void
205253440Sgrehan_vq_record(int i, volatile struct virtio_desc *vd, struct vmctx *ctx,
206253440Sgrehan	   struct iovec *iov, int n_iov, uint16_t *flags) {
207253440Sgrehan
208253440Sgrehan	if (i >= n_iov)
209253440Sgrehan		return;
210253440Sgrehan	iov[i].iov_base = paddr_guest2host(ctx, vd->vd_addr, vd->vd_len);
211253440Sgrehan	iov[i].iov_len = vd->vd_len;
212253440Sgrehan	if (flags != NULL)
213253440Sgrehan		flags[i] = vd->vd_flags;
214253440Sgrehan}
215253440Sgrehan#define	VQ_MAX_DESCRIPTORS	512	/* see below */
216253440Sgrehan
217253440Sgrehan/*
218253440Sgrehan * Examine the chain of descriptors starting at the "next one" to
219253440Sgrehan * make sure that they describe a sensible request.  If so, return
220253440Sgrehan * the number of "real" descriptors that would be needed/used in
221253440Sgrehan * acting on this request.  This may be smaller than the number of
222253440Sgrehan * available descriptors, e.g., if there are two available but
223253440Sgrehan * they are two separate requests, this just returns 1.  Or, it
224253440Sgrehan * may be larger: if there are indirect descriptors involved,
225253440Sgrehan * there may only be one descriptor available but it may be an
226253440Sgrehan * indirect pointing to eight more.  We return 8 in this case,
227253440Sgrehan * i.e., we do not count the indirect descriptors, only the "real"
228253440Sgrehan * ones.
229253440Sgrehan *
230253440Sgrehan * Basically, this vets the vd_flags and vd_next field of each
231253440Sgrehan * descriptor and tells you how many are involved.  Since some may
232253440Sgrehan * be indirect, this also needs the vmctx (in the pci_devinst
233253440Sgrehan * at vs->vs_pi) so that it can find indirect descriptors.
234253440Sgrehan *
235253440Sgrehan * As we process each descriptor, we copy and adjust it (guest to
236253440Sgrehan * host address wise, also using the vmtctx) into the given iov[]
237253440Sgrehan * array (of the given size).  If the array overflows, we stop
238253440Sgrehan * placing values into the array but keep processing descriptors,
239253440Sgrehan * up to VQ_MAX_DESCRIPTORS, before giving up and returning -1.
240253440Sgrehan * So you, the caller, must not assume that iov[] is as big as the
241253440Sgrehan * return value (you can process the same thing twice to allocate
242253440Sgrehan * a larger iov array if needed, or supply a zero length to find
243253440Sgrehan * out how much space is needed).
244253440Sgrehan *
245253440Sgrehan * If you want to verify the WRITE flag on each descriptor, pass a
246253440Sgrehan * non-NULL "flags" pointer to an array of "uint16_t" of the same size
247253440Sgrehan * as n_iov and we'll copy each vd_flags field after unwinding any
248253440Sgrehan * indirects.
249253440Sgrehan *
250253440Sgrehan * If some descriptor(s) are invalid, this prints a diagnostic message
251253440Sgrehan * and returns -1.  If no descriptors are ready now it simply returns 0.
252253440Sgrehan *
253253440Sgrehan * You are assumed to have done a vq_ring_ready() if needed (note
254253440Sgrehan * that vq_has_descs() does one).
255253440Sgrehan */
256253440Sgrehanint
257280026Smavvq_getchain(struct vqueue_info *vq, uint16_t *pidx,
258253440Sgrehan	    struct iovec *iov, int n_iov, uint16_t *flags)
259253440Sgrehan{
260253440Sgrehan	int i;
261253440Sgrehan	u_int ndesc, n_indir;
262280026Smav	u_int idx, next;
263253440Sgrehan	volatile struct virtio_desc *vdir, *vindir, *vp;
264253440Sgrehan	struct vmctx *ctx;
265253440Sgrehan	struct virtio_softc *vs;
266253440Sgrehan	const char *name;
267253440Sgrehan
268253440Sgrehan	vs = vq->vq_vs;
269253440Sgrehan	name = vs->vs_vc->vc_name;
270253440Sgrehan
271253440Sgrehan	/*
272253440Sgrehan	 * Note: it's the responsibility of the guest not to
273253440Sgrehan	 * update vq->vq_avail->va_idx until all of the descriptors
274253440Sgrehan         * the guest has written are valid (including all their
275253440Sgrehan         * vd_next fields and vd_flags).
276253440Sgrehan	 *
277253440Sgrehan	 * Compute (last_avail - va_idx) in integers mod 2**16.  This is
278253440Sgrehan	 * the number of descriptors the device has made available
279253440Sgrehan	 * since the last time we updated vq->vq_last_avail.
280253440Sgrehan	 *
281253440Sgrehan	 * We just need to do the subtraction as an unsigned int,
282253440Sgrehan	 * then trim off excess bits.
283253440Sgrehan	 */
284253440Sgrehan	idx = vq->vq_last_avail;
285253440Sgrehan	ndesc = (uint16_t)((u_int)vq->vq_avail->va_idx - idx);
286253440Sgrehan	if (ndesc == 0)
287253440Sgrehan		return (0);
288253440Sgrehan	if (ndesc > vq->vq_qsize) {
289253440Sgrehan		/* XXX need better way to diagnose issues */
290253440Sgrehan		fprintf(stderr,
291253440Sgrehan		    "%s: ndesc (%u) out of range, driver confused?\r\n",
292253440Sgrehan		    name, (u_int)ndesc);
293253440Sgrehan		return (-1);
294253440Sgrehan	}
295253440Sgrehan
296253440Sgrehan	/*
297253440Sgrehan	 * Now count/parse "involved" descriptors starting from
298253440Sgrehan	 * the head of the chain.
299253440Sgrehan	 *
300253440Sgrehan	 * To prevent loops, we could be more complicated and
301253440Sgrehan	 * check whether we're re-visiting a previously visited
302253440Sgrehan	 * index, but we just abort if the count gets excessive.
303253440Sgrehan	 */
304253440Sgrehan	ctx = vs->vs_pi->pi_vmctx;
305280026Smav	*pidx = next = vq->vq_avail->va_ring[idx & (vq->vq_qsize - 1)];
306280026Smav	vq->vq_last_avail++;
307253440Sgrehan	for (i = 0; i < VQ_MAX_DESCRIPTORS; next = vdir->vd_next) {
308253440Sgrehan		if (next >= vq->vq_qsize) {
309253440Sgrehan			fprintf(stderr,
310253440Sgrehan			    "%s: descriptor index %u out of range, "
311253440Sgrehan			    "driver confused?\r\n",
312253440Sgrehan			    name, next);
313253440Sgrehan			return (-1);
314253440Sgrehan		}
315253440Sgrehan		vdir = &vq->vq_desc[next];
316253440Sgrehan		if ((vdir->vd_flags & VRING_DESC_F_INDIRECT) == 0) {
317253440Sgrehan			_vq_record(i, vdir, ctx, iov, n_iov, flags);
318253440Sgrehan			i++;
319282784Sgrehan		} else if ((vs->vs_vc->vc_hv_caps &
320253440Sgrehan		    VIRTIO_RING_F_INDIRECT_DESC) == 0) {
321253440Sgrehan			fprintf(stderr,
322253440Sgrehan			    "%s: descriptor has forbidden INDIRECT flag, "
323253440Sgrehan			    "driver confused?\r\n",
324253440Sgrehan			    name);
325253440Sgrehan			return (-1);
326253440Sgrehan		} else {
327253440Sgrehan			n_indir = vdir->vd_len / 16;
328253440Sgrehan			if ((vdir->vd_len & 0xf) || n_indir == 0) {
329253440Sgrehan				fprintf(stderr,
330253440Sgrehan				    "%s: invalid indir len 0x%x, "
331253440Sgrehan				    "driver confused?\r\n",
332253440Sgrehan				    name, (u_int)vdir->vd_len);
333253440Sgrehan				return (-1);
334253440Sgrehan			}
335253440Sgrehan			vindir = paddr_guest2host(ctx,
336253440Sgrehan			    vdir->vd_addr, vdir->vd_len);
337253440Sgrehan			/*
338253440Sgrehan			 * Indirects start at the 0th, then follow
339253440Sgrehan			 * their own embedded "next"s until those run
340253440Sgrehan			 * out.  Each one's indirect flag must be off
341253440Sgrehan			 * (we don't really have to check, could just
342253440Sgrehan			 * ignore errors...).
343253440Sgrehan			 */
344253440Sgrehan			next = 0;
345253440Sgrehan			for (;;) {
346253440Sgrehan				vp = &vindir[next];
347253440Sgrehan				if (vp->vd_flags & VRING_DESC_F_INDIRECT) {
348253440Sgrehan					fprintf(stderr,
349253440Sgrehan					    "%s: indirect desc has INDIR flag,"
350253440Sgrehan					    " driver confused?\r\n",
351253440Sgrehan					    name);
352253440Sgrehan					return (-1);
353253440Sgrehan				}
354253440Sgrehan				_vq_record(i, vp, ctx, iov, n_iov, flags);
355253440Sgrehan				if (++i > VQ_MAX_DESCRIPTORS)
356253440Sgrehan					goto loopy;
357253440Sgrehan				if ((vp->vd_flags & VRING_DESC_F_NEXT) == 0)
358253440Sgrehan					break;
359253440Sgrehan				next = vp->vd_next;
360253440Sgrehan				if (next >= n_indir) {
361253440Sgrehan					fprintf(stderr,
362253440Sgrehan					    "%s: invalid next %u > %u, "
363253440Sgrehan					    "driver confused?\r\n",
364253440Sgrehan					    name, (u_int)next, n_indir);
365253440Sgrehan					return (-1);
366253440Sgrehan				}
367253440Sgrehan			}
368253440Sgrehan		}
369253440Sgrehan		if ((vdir->vd_flags & VRING_DESC_F_NEXT) == 0)
370253440Sgrehan			return (i);
371253440Sgrehan	}
372253440Sgrehanloopy:
373253440Sgrehan	fprintf(stderr,
374253440Sgrehan	    "%s: descriptor loop? count > %d - driver confused?\r\n",
375253440Sgrehan	    name, i);
376253440Sgrehan	return (-1);
377253440Sgrehan}
378253440Sgrehan
379253440Sgrehan/*
380280041Smav * Return the currently-first request chain back to the available queue.
381253440Sgrehan *
382253440Sgrehan * (This chain is the one you handled when you called vq_getchain()
383253440Sgrehan * and used its positive return value.)
384253440Sgrehan */
385253440Sgrehanvoid
386280041Smavvq_retchain(struct vqueue_info *vq)
387280041Smav{
388280041Smav
389280041Smav	vq->vq_last_avail--;
390280041Smav}
391280041Smav
392280041Smav/*
393280041Smav * Return specified request chain to the guest, setting its I/O length
394280041Smav * to the provided value.
395280041Smav *
396280041Smav * (This chain is the one you handled when you called vq_getchain()
397280041Smav * and used its positive return value.)
398280041Smav */
399280041Smavvoid
400280026Smavvq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen)
401253440Sgrehan{
402280026Smav	uint16_t uidx, mask;
403253440Sgrehan	volatile struct vring_used *vuh;
404253440Sgrehan	volatile struct virtio_used *vue;
405253440Sgrehan
406253440Sgrehan	/*
407253440Sgrehan	 * Notes:
408253440Sgrehan	 *  - mask is N-1 where N is a power of 2 so computes x % N
409253440Sgrehan	 *  - vuh points to the "used" data shared with guest
410253440Sgrehan	 *  - vue points to the "used" ring entry we want to update
411253440Sgrehan	 *  - head is the same value we compute in vq_iovecs().
412253440Sgrehan	 *
413253440Sgrehan	 * (I apologize for the two fields named vu_idx; the
414253440Sgrehan	 * virtio spec calls the one that vue points to, "id"...)
415253440Sgrehan	 */
416253440Sgrehan	mask = vq->vq_qsize - 1;
417253440Sgrehan	vuh = vq->vq_used;
418253440Sgrehan
419253440Sgrehan	uidx = vuh->vu_idx;
420253440Sgrehan	vue = &vuh->vu_ring[uidx++ & mask];
421280026Smav	vue->vu_idx = idx;
422253440Sgrehan	vue->vu_tlen = iolen;
423253440Sgrehan	vuh->vu_idx = uidx;
424253440Sgrehan}
425253440Sgrehan
426253440Sgrehan/*
427253440Sgrehan * Driver has finished processing "available" chains and calling
428253440Sgrehan * vq_relchain on each one.  If driver used all the available
429253440Sgrehan * chains, used_all should be set.
430253440Sgrehan *
431253440Sgrehan * If the "used" index moved we may need to inform the guest, i.e.,
432253440Sgrehan * deliver an interrupt.  Even if the used index did NOT move we
433253440Sgrehan * may need to deliver an interrupt, if the avail ring is empty and
434253440Sgrehan * we are supposed to interrupt on empty.
435253440Sgrehan *
436253440Sgrehan * Note that used_all_avail is provided by the caller because it's
437253440Sgrehan * a snapshot of the ring state when he decided to finish interrupt
438253440Sgrehan * processing -- it's possible that descriptors became available after
439253440Sgrehan * that point.  (It's also typically a constant 1/True as well.)
440253440Sgrehan */
441253440Sgrehanvoid
442253440Sgrehanvq_endchains(struct vqueue_info *vq, int used_all_avail)
443253440Sgrehan{
444253440Sgrehan	struct virtio_softc *vs;
445253440Sgrehan	uint16_t event_idx, new_idx, old_idx;
446253440Sgrehan	int intr;
447253440Sgrehan
448253440Sgrehan	/*
449253440Sgrehan	 * Interrupt generation: if we're using EVENT_IDX,
450253440Sgrehan	 * interrupt if we've crossed the event threshold.
451253440Sgrehan	 * Otherwise interrupt is generated if we added "used" entries,
452253440Sgrehan	 * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.
453253440Sgrehan	 *
454253440Sgrehan	 * In any case, though, if NOTIFY_ON_EMPTY is set and the
455253440Sgrehan	 * entire avail was processed, we need to interrupt always.
456253440Sgrehan	 */
457253440Sgrehan	vs = vq->vq_vs;
458253440Sgrehan	old_idx = vq->vq_save_used;
459280026Smav	vq->vq_save_used = new_idx = vq->vq_used->vu_idx;
460253440Sgrehan	if (used_all_avail &&
461253440Sgrehan	    (vs->vs_negotiated_caps & VIRTIO_F_NOTIFY_ON_EMPTY))
462253440Sgrehan		intr = 1;
463268202Sgrehan	else if (vs->vs_negotiated_caps & VIRTIO_RING_F_EVENT_IDX) {
464253440Sgrehan		event_idx = VQ_USED_EVENT_IDX(vq);
465253440Sgrehan		/*
466253440Sgrehan		 * This calculation is per docs and the kernel
467253440Sgrehan		 * (see src/sys/dev/virtio/virtio_ring.h).
468253440Sgrehan		 */
469253440Sgrehan		intr = (uint16_t)(new_idx - event_idx - 1) <
470253440Sgrehan			(uint16_t)(new_idx - old_idx);
471253440Sgrehan	} else {
472253440Sgrehan		intr = new_idx != old_idx &&
473253440Sgrehan		    !(vq->vq_avail->va_flags & VRING_AVAIL_F_NO_INTERRUPT);
474253440Sgrehan	}
475253440Sgrehan	if (intr)
476253440Sgrehan		vq_interrupt(vs, vq);
477253440Sgrehan}
478253440Sgrehan
479253440Sgrehan/* Note: these are in sorted order to make for a fast search */
480253440Sgrehanstatic struct config_reg {
481253440Sgrehan	uint16_t	cr_offset;	/* register offset */
482253440Sgrehan	uint8_t		cr_size;	/* size (bytes) */
483253440Sgrehan	uint8_t		cr_ro;		/* true => reg is read only */
484253440Sgrehan	const char	*cr_name;	/* name of reg */
485253440Sgrehan} config_regs[] = {
486253440Sgrehan	{ VTCFG_R_HOSTCAP,	4, 1, "HOSTCAP" },
487253440Sgrehan	{ VTCFG_R_GUESTCAP,	4, 0, "GUESTCAP" },
488253440Sgrehan	{ VTCFG_R_PFN,		4, 0, "PFN" },
489253440Sgrehan	{ VTCFG_R_QNUM,		2, 1, "QNUM" },
490253440Sgrehan	{ VTCFG_R_QSEL,		2, 0, "QSEL" },
491253440Sgrehan	{ VTCFG_R_QNOTIFY,	2, 0, "QNOTIFY" },
492253440Sgrehan	{ VTCFG_R_STATUS,	1, 0, "STATUS" },
493253440Sgrehan	{ VTCFG_R_ISR,		1, 0, "ISR" },
494253440Sgrehan	{ VTCFG_R_CFGVEC,	2, 0, "CFGVEC" },
495253440Sgrehan	{ VTCFG_R_QVEC,		2, 0, "QVEC" },
496253440Sgrehan};
497253440Sgrehan
498253440Sgrehanstatic inline struct config_reg *
499253440Sgrehanvi_find_cr(int offset) {
500253440Sgrehan	u_int hi, lo, mid;
501253440Sgrehan	struct config_reg *cr;
502253440Sgrehan
503253440Sgrehan	lo = 0;
504253440Sgrehan	hi = sizeof(config_regs) / sizeof(*config_regs) - 1;
505253440Sgrehan	while (hi >= lo) {
506253440Sgrehan		mid = (hi + lo) >> 1;
507253440Sgrehan		cr = &config_regs[mid];
508253440Sgrehan		if (cr->cr_offset == offset)
509253440Sgrehan			return (cr);
510253440Sgrehan		if (cr->cr_offset < offset)
511253440Sgrehan			lo = mid + 1;
512253440Sgrehan		else
513253440Sgrehan			hi = mid - 1;
514253440Sgrehan	}
515253440Sgrehan	return (NULL);
516253440Sgrehan}
517253440Sgrehan
518253440Sgrehan/*
519253440Sgrehan * Handle pci config space reads.
520253440Sgrehan * If it's to the MSI-X info, do that.
521253440Sgrehan * If it's part of the virtio standard stuff, do that.
522253440Sgrehan * Otherwise dispatch to the actual driver.
523253440Sgrehan */
524253440Sgrehanuint64_t
525253440Sgrehanvi_pci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
526253440Sgrehan	    int baridx, uint64_t offset, int size)
527253440Sgrehan{
528253440Sgrehan	struct virtio_softc *vs = pi->pi_arg;
529253440Sgrehan	struct virtio_consts *vc;
530253440Sgrehan	struct config_reg *cr;
531253440Sgrehan	uint64_t virtio_config_size, max;
532253440Sgrehan	const char *name;
533253440Sgrehan	uint32_t newoff;
534253440Sgrehan	uint32_t value;
535253440Sgrehan	int error;
536253440Sgrehan
537253440Sgrehan	if (vs->vs_flags & VIRTIO_USE_MSIX) {
538253440Sgrehan		if (baridx == pci_msix_table_bar(pi) ||
539253440Sgrehan		    baridx == pci_msix_pba_bar(pi)) {
540253440Sgrehan			return (pci_emul_msix_tread(pi, offset, size));
541253440Sgrehan		}
542253440Sgrehan	}
543253440Sgrehan
544253440Sgrehan	/* XXX probably should do something better than just assert() */
545253440Sgrehan	assert(baridx == 0);
546253440Sgrehan
547253440Sgrehan	if (vs->vs_mtx)
548253440Sgrehan		pthread_mutex_lock(vs->vs_mtx);
549253440Sgrehan
550253440Sgrehan	vc = vs->vs_vc;
551253440Sgrehan	name = vc->vc_name;
552253440Sgrehan	value = size == 1 ? 0xff : size == 2 ? 0xffff : 0xffffffff;
553253440Sgrehan
554253440Sgrehan	if (size != 1 && size != 2 && size != 4)
555253440Sgrehan		goto bad;
556253440Sgrehan
557253440Sgrehan	if (pci_msix_enabled(pi))
558253440Sgrehan		virtio_config_size = VTCFG_R_CFG1;
559253440Sgrehan	else
560253440Sgrehan		virtio_config_size = VTCFG_R_CFG0;
561253440Sgrehan
562253440Sgrehan	if (offset >= virtio_config_size) {
563253440Sgrehan		/*
564253440Sgrehan		 * Subtract off the standard size (including MSI-X
565253440Sgrehan		 * registers if enabled) and dispatch to underlying driver.
566253440Sgrehan		 * If that fails, fall into general code.
567253440Sgrehan		 */
568253440Sgrehan		newoff = offset - virtio_config_size;
569253440Sgrehan		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
570253440Sgrehan		if (newoff + size > max)
571253440Sgrehan			goto bad;
572253440Sgrehan		error = (*vc->vc_cfgread)(DEV_SOFTC(vs), newoff, size, &value);
573253440Sgrehan		if (!error)
574253440Sgrehan			goto done;
575253440Sgrehan	}
576253440Sgrehan
577253440Sgrehanbad:
578253440Sgrehan	cr = vi_find_cr(offset);
579253440Sgrehan	if (cr == NULL || cr->cr_size != size) {
580253440Sgrehan		if (cr != NULL) {
581253440Sgrehan			/* offset must be OK, so size must be bad */
582253440Sgrehan			fprintf(stderr,
583253440Sgrehan			    "%s: read from %s: bad size %d\r\n",
584253440Sgrehan			    name, cr->cr_name, size);
585253440Sgrehan		} else {
586253440Sgrehan			fprintf(stderr,
587253440Sgrehan			    "%s: read from bad offset/size %jd/%d\r\n",
588253440Sgrehan			    name, (uintmax_t)offset, size);
589253440Sgrehan		}
590253440Sgrehan		goto done;
591253440Sgrehan	}
592253440Sgrehan
593253440Sgrehan	switch (offset) {
594253440Sgrehan	case VTCFG_R_HOSTCAP:
595253440Sgrehan		value = vc->vc_hv_caps;
596253440Sgrehan		break;
597253440Sgrehan	case VTCFG_R_GUESTCAP:
598253440Sgrehan		value = vs->vs_negotiated_caps;
599253440Sgrehan		break;
600253440Sgrehan	case VTCFG_R_PFN:
601253440Sgrehan		if (vs->vs_curq < vc->vc_nvq)
602253440Sgrehan			value = vs->vs_queues[vs->vs_curq].vq_pfn;
603253440Sgrehan		break;
604253440Sgrehan	case VTCFG_R_QNUM:
605253440Sgrehan		value = vs->vs_curq < vc->vc_nvq ?
606253440Sgrehan		    vs->vs_queues[vs->vs_curq].vq_qsize : 0;
607253440Sgrehan		break;
608253440Sgrehan	case VTCFG_R_QSEL:
609253440Sgrehan		value = vs->vs_curq;
610253440Sgrehan		break;
611253440Sgrehan	case VTCFG_R_QNOTIFY:
612253440Sgrehan		value = 0;	/* XXX */
613253440Sgrehan		break;
614253440Sgrehan	case VTCFG_R_STATUS:
615253440Sgrehan		value = vs->vs_status;
616253440Sgrehan		break;
617253440Sgrehan	case VTCFG_R_ISR:
618253440Sgrehan		value = vs->vs_isr;
619253440Sgrehan		vs->vs_isr = 0;		/* a read clears this flag */
620261268Sjhb		if (value)
621261268Sjhb			pci_lintr_deassert(pi);
622253440Sgrehan		break;
623253440Sgrehan	case VTCFG_R_CFGVEC:
624253440Sgrehan		value = vs->vs_msix_cfg_idx;
625253440Sgrehan		break;
626253440Sgrehan	case VTCFG_R_QVEC:
627253440Sgrehan		value = vs->vs_curq < vc->vc_nvq ?
628253440Sgrehan		    vs->vs_queues[vs->vs_curq].vq_msix_idx :
629253440Sgrehan		    VIRTIO_MSI_NO_VECTOR;
630253440Sgrehan		break;
631253440Sgrehan	}
632253440Sgrehandone:
633253440Sgrehan	if (vs->vs_mtx)
634253440Sgrehan		pthread_mutex_unlock(vs->vs_mtx);
635253440Sgrehan	return (value);
636253440Sgrehan}
637253440Sgrehan
638253440Sgrehan/*
639253440Sgrehan * Handle pci config space writes.
640253440Sgrehan * If it's to the MSI-X info, do that.
641253440Sgrehan * If it's part of the virtio standard stuff, do that.
642253440Sgrehan * Otherwise dispatch to the actual driver.
643253440Sgrehan */
644253440Sgrehanvoid
645253440Sgrehanvi_pci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
646253440Sgrehan	     int baridx, uint64_t offset, int size, uint64_t value)
647253440Sgrehan{
648253440Sgrehan	struct virtio_softc *vs = pi->pi_arg;
649253440Sgrehan	struct vqueue_info *vq;
650253440Sgrehan	struct virtio_consts *vc;
651253440Sgrehan	struct config_reg *cr;
652253440Sgrehan	uint64_t virtio_config_size, max;
653253440Sgrehan	const char *name;
654253440Sgrehan	uint32_t newoff;
655253440Sgrehan	int error;
656253440Sgrehan
657253440Sgrehan	if (vs->vs_flags & VIRTIO_USE_MSIX) {
658253440Sgrehan		if (baridx == pci_msix_table_bar(pi) ||
659253440Sgrehan		    baridx == pci_msix_pba_bar(pi)) {
660253440Sgrehan			pci_emul_msix_twrite(pi, offset, size, value);
661253440Sgrehan			return;
662253440Sgrehan		}
663253440Sgrehan	}
664253440Sgrehan
665253440Sgrehan	/* XXX probably should do something better than just assert() */
666253440Sgrehan	assert(baridx == 0);
667253440Sgrehan
668253440Sgrehan	if (vs->vs_mtx)
669253440Sgrehan		pthread_mutex_lock(vs->vs_mtx);
670253440Sgrehan
671253440Sgrehan	vc = vs->vs_vc;
672253440Sgrehan	name = vc->vc_name;
673253440Sgrehan
674253440Sgrehan	if (size != 1 && size != 2 && size != 4)
675253440Sgrehan		goto bad;
676253440Sgrehan
677253440Sgrehan	if (pci_msix_enabled(pi))
678253440Sgrehan		virtio_config_size = VTCFG_R_CFG1;
679253440Sgrehan	else
680253440Sgrehan		virtio_config_size = VTCFG_R_CFG0;
681253440Sgrehan
682253440Sgrehan	if (offset >= virtio_config_size) {
683253440Sgrehan		/*
684253440Sgrehan		 * Subtract off the standard size (including MSI-X
685253440Sgrehan		 * registers if enabled) and dispatch to underlying driver.
686253440Sgrehan		 */
687253440Sgrehan		newoff = offset - virtio_config_size;
688253440Sgrehan		max = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;
689253440Sgrehan		if (newoff + size > max)
690253440Sgrehan			goto bad;
691253440Sgrehan		error = (*vc->vc_cfgwrite)(DEV_SOFTC(vs), newoff, size, value);
692253440Sgrehan		if (!error)
693253440Sgrehan			goto done;
694253440Sgrehan	}
695253440Sgrehan
696253440Sgrehanbad:
697253440Sgrehan	cr = vi_find_cr(offset);
698253440Sgrehan	if (cr == NULL || cr->cr_size != size || cr->cr_ro) {
699253440Sgrehan		if (cr != NULL) {
700253440Sgrehan			/* offset must be OK, wrong size and/or reg is R/O */
701253440Sgrehan			if (cr->cr_size != size)
702253440Sgrehan				fprintf(stderr,
703253440Sgrehan				    "%s: write to %s: bad size %d\r\n",
704253440Sgrehan				    name, cr->cr_name, size);
705253440Sgrehan			if (cr->cr_ro)
706253440Sgrehan				fprintf(stderr,
707253440Sgrehan				    "%s: write to read-only reg %s\r\n",
708253440Sgrehan				    name, cr->cr_name);
709253440Sgrehan		} else {
710253440Sgrehan			fprintf(stderr,
711253440Sgrehan			    "%s: write to bad offset/size %jd/%d\r\n",
712253440Sgrehan			    name, (uintmax_t)offset, size);
713253440Sgrehan		}
714253440Sgrehan		goto done;
715253440Sgrehan	}
716253440Sgrehan
717253440Sgrehan	switch (offset) {
718253440Sgrehan	case VTCFG_R_GUESTCAP:
719253440Sgrehan		vs->vs_negotiated_caps = value & vc->vc_hv_caps;
720271299Sgrehan		if (vc->vc_apply_features)
721271299Sgrehan			(*vc->vc_apply_features)(DEV_SOFTC(vs),
722271299Sgrehan			    vs->vs_negotiated_caps);
723253440Sgrehan		break;
724253440Sgrehan	case VTCFG_R_PFN:
725253440Sgrehan		if (vs->vs_curq >= vc->vc_nvq)
726253440Sgrehan			goto bad_qindex;
727253440Sgrehan		vi_vq_init(vs, value);
728253440Sgrehan		break;
729253440Sgrehan	case VTCFG_R_QSEL:
730253440Sgrehan		/*
731253440Sgrehan		 * Note that the guest is allowed to select an
732253440Sgrehan		 * invalid queue; we just need to return a QNUM
733253440Sgrehan		 * of 0 while the bad queue is selected.
734253440Sgrehan		 */
735253440Sgrehan		vs->vs_curq = value;
736253440Sgrehan		break;
737253440Sgrehan	case VTCFG_R_QNOTIFY:
738253440Sgrehan		if (value >= vc->vc_nvq) {
739253440Sgrehan			fprintf(stderr, "%s: queue %d notify out of range\r\n",
740253440Sgrehan				name, (int)value);
741253440Sgrehan			goto done;
742253440Sgrehan		}
743253440Sgrehan		vq = &vs->vs_queues[value];
744253440Sgrehan		if (vq->vq_notify)
745253440Sgrehan			(*vq->vq_notify)(DEV_SOFTC(vs), vq);
746253440Sgrehan		else if (vc->vc_qnotify)
747253440Sgrehan			(*vc->vc_qnotify)(DEV_SOFTC(vs), vq);
748253440Sgrehan		else
749253440Sgrehan			fprintf(stderr,
750253440Sgrehan			    "%s: qnotify queue %d: missing vq/vc notify\r\n",
751253440Sgrehan				name, (int)value);
752253440Sgrehan		break;
753253440Sgrehan	case VTCFG_R_STATUS:
754253440Sgrehan		vs->vs_status = value;
755253440Sgrehan		if (value == 0)
756253440Sgrehan			(*vc->vc_reset)(DEV_SOFTC(vs));
757253440Sgrehan		break;
758253440Sgrehan	case VTCFG_R_CFGVEC:
759253440Sgrehan		vs->vs_msix_cfg_idx = value;
760253440Sgrehan		break;
761253440Sgrehan	case VTCFG_R_QVEC:
762253440Sgrehan		if (vs->vs_curq >= vc->vc_nvq)
763253440Sgrehan			goto bad_qindex;
764253440Sgrehan		vq = &vs->vs_queues[vs->vs_curq];
765253440Sgrehan		vq->vq_msix_idx = value;
766253440Sgrehan		break;
767253440Sgrehan	}
768253440Sgrehan	goto done;
769253440Sgrehan
770253440Sgrehanbad_qindex:
771253440Sgrehan	fprintf(stderr,
772253440Sgrehan	    "%s: write config reg %s: curq %d >= max %d\r\n",
773253440Sgrehan	    name, cr->cr_name, vs->vs_curq, vc->vc_nvq);
774253440Sgrehandone:
775253440Sgrehan	if (vs->vs_mtx)
776253440Sgrehan		pthread_mutex_unlock(vs->vs_mtx);
777253440Sgrehan}
778