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