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