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