]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/pci_virtio_net.c
bhyve: vtnet: simplify thread synchronization
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / pci_virtio_net.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <sys/param.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/linker_set.h>
39 #include <sys/select.h>
40 #include <sys/uio.h>
41 #include <sys/ioctl.h>
42 #include <machine/atomic.h>
43 #include <net/ethernet.h>
44 #ifndef NETMAP_WITH_LIBS
45 #define NETMAP_WITH_LIBS
46 #endif
47 #include <net/netmap_user.h>
48
49 #ifndef WITHOUT_CAPSICUM
50 #include <capsicum_helpers.h>
51 #endif
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <stdint.h>
58 #include <string.h>
59 #include <strings.h>
60 #include <unistd.h>
61 #include <assert.h>
62 #include <md5.h>
63 #include <pthread.h>
64 #include <pthread_np.h>
65 #include <sysexits.h>
66
67 #include "bhyverun.h"
68 #include "pci_emul.h"
69 #include "mevent.h"
70 #include "virtio.h"
71
72 #define VTNET_RINGSZ    1024
73
74 #define VTNET_MAXSEGS   256
75
76 /*
77  * Host capabilities.  Note that we only offer a few of these.
78  */
79 #define VIRTIO_NET_F_CSUM       (1 <<  0) /* host handles partial cksum */
80 #define VIRTIO_NET_F_GUEST_CSUM (1 <<  1) /* guest handles partial cksum */
81 #define VIRTIO_NET_F_MAC        (1 <<  5) /* host supplies MAC */
82 #define VIRTIO_NET_F_GSO_DEPREC (1 <<  6) /* deprecated: host handles GSO */
83 #define VIRTIO_NET_F_GUEST_TSO4 (1 <<  7) /* guest can rcv TSOv4 */
84 #define VIRTIO_NET_F_GUEST_TSO6 (1 <<  8) /* guest can rcv TSOv6 */
85 #define VIRTIO_NET_F_GUEST_ECN  (1 <<  9) /* guest can rcv TSO with ECN */
86 #define VIRTIO_NET_F_GUEST_UFO  (1 << 10) /* guest can rcv UFO */
87 #define VIRTIO_NET_F_HOST_TSO4  (1 << 11) /* host can rcv TSOv4 */
88 #define VIRTIO_NET_F_HOST_TSO6  (1 << 12) /* host can rcv TSOv6 */
89 #define VIRTIO_NET_F_HOST_ECN   (1 << 13) /* host can rcv TSO with ECN */
90 #define VIRTIO_NET_F_HOST_UFO   (1 << 14) /* host can rcv UFO */
91 #define VIRTIO_NET_F_MRG_RXBUF  (1 << 15) /* host can merge RX buffers */
92 #define VIRTIO_NET_F_STATUS     (1 << 16) /* config status field available */
93 #define VIRTIO_NET_F_CTRL_VQ    (1 << 17) /* control channel available */
94 #define VIRTIO_NET_F_CTRL_RX    (1 << 18) /* control channel RX mode support */
95 #define VIRTIO_NET_F_CTRL_VLAN  (1 << 19) /* control channel VLAN filtering */
96 #define VIRTIO_NET_F_GUEST_ANNOUNCE \
97                                 (1 << 21) /* guest can send gratuitous pkts */
98
99 #define VTNET_S_HOSTCAPS      \
100   ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_MRG_RXBUF | VIRTIO_NET_F_STATUS | \
101     VIRTIO_F_NOTIFY_ON_EMPTY | VIRTIO_RING_F_INDIRECT_DESC)
102
103 /*
104  * PCI config-space "registers"
105  */
106 struct virtio_net_config {
107         uint8_t  mac[6];
108         uint16_t status;
109 } __packed;
110
111 /*
112  * Queue definitions.
113  */
114 #define VTNET_RXQ       0
115 #define VTNET_TXQ       1
116 #define VTNET_CTLQ      2       /* NB: not yet supported */
117
118 #define VTNET_MAXQ      3
119
120 /*
121  * Fixed network header size
122  */
123 struct virtio_net_rxhdr {
124         uint8_t         vrh_flags;
125         uint8_t         vrh_gso_type;
126         uint16_t        vrh_hdr_len;
127         uint16_t        vrh_gso_size;
128         uint16_t        vrh_csum_start;
129         uint16_t        vrh_csum_offset;
130         uint16_t        vrh_bufs;
131 } __packed;
132
133 /*
134  * Debug printf
135  */
136 static int pci_vtnet_debug;
137 #define DPRINTF(params) if (pci_vtnet_debug) printf params
138 #define WPRINTF(params) printf params
139
140 /*
141  * Per-device softc
142  */
143 struct pci_vtnet_softc {
144         struct virtio_softc vsc_vs;
145         struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
146         pthread_mutex_t vsc_mtx;
147         struct mevent   *vsc_mevp;
148
149         int             vsc_tapfd;
150         struct nm_desc  *vsc_nmd;
151
152         int             vsc_rx_ready;
153         int             resetting;      /* protected by tx_mtx */
154
155         uint64_t        vsc_features;   /* negotiated features */
156         
157         struct virtio_net_config vsc_config;
158
159         pthread_mutex_t rx_mtx;
160         int             rx_vhdrlen;
161         int             rx_merge;       /* merged rx bufs in use */
162
163         pthread_t       tx_tid;
164         pthread_mutex_t tx_mtx;
165         pthread_cond_t  tx_cond;
166         int             tx_in_progress;
167
168         void (*pci_vtnet_rx)(struct pci_vtnet_softc *sc);
169         void (*pci_vtnet_tx)(struct pci_vtnet_softc *sc, struct iovec *iov,
170                              int iovcnt, int len);
171 };
172
173 static void pci_vtnet_reset(void *);
174 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
175 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
176 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
177 static void pci_vtnet_neg_features(void *, uint64_t);
178
179 static struct virtio_consts vtnet_vi_consts = {
180         "vtnet",                /* our name */
181         VTNET_MAXQ - 1,         /* we currently support 2 virtqueues */
182         sizeof(struct virtio_net_config), /* config reg size */
183         pci_vtnet_reset,        /* reset */
184         NULL,                   /* device-wide qnotify -- not used */
185         pci_vtnet_cfgread,      /* read PCI config */
186         pci_vtnet_cfgwrite,     /* write PCI config */
187         pci_vtnet_neg_features, /* apply negotiated features */
188         VTNET_S_HOSTCAPS,       /* our capabilities */
189 };
190
191 static void
192 pci_vtnet_reset(void *vsc)
193 {
194         struct pci_vtnet_softc *sc = vsc;
195
196         DPRINTF(("vtnet: device reset requested !\n"));
197
198         /* Acquire the RX lock to block RX processing. */
199         pthread_mutex_lock(&sc->rx_mtx);
200
201         /* Set sc->resetting and give a chance to the TX thread to stop. */
202         pthread_mutex_lock(&sc->tx_mtx);
203         sc->resetting = 1;
204         while (sc->tx_in_progress) {
205                 pthread_mutex_unlock(&sc->tx_mtx);
206                 usleep(10000);
207                 pthread_mutex_lock(&sc->tx_mtx);
208         }
209
210         sc->vsc_rx_ready = 0;
211         sc->rx_merge = 1;
212         sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
213
214         /*
215          * Now reset rings, MSI-X vectors, and negotiated capabilities.
216          * Do that with the TX lock held, since we need to reset
217          * sc->resetting.
218          */
219         vi_reset_dev(&sc->vsc_vs);
220
221         sc->resetting = 0;
222         pthread_mutex_unlock(&sc->tx_mtx);
223         pthread_mutex_unlock(&sc->rx_mtx);
224 }
225
226 /*
227  * Called to send a buffer chain out to the tap device
228  */
229 static void
230 pci_vtnet_tap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
231                  int len)
232 {
233         static char pad[60]; /* all zero bytes */
234
235         if (sc->vsc_tapfd == -1)
236                 return;
237
238         /*
239          * If the length is < 60, pad out to that and add the
240          * extra zero'd segment to the iov. It is guaranteed that
241          * there is always an extra iov available by the caller.
242          */
243         if (len < 60) {
244                 iov[iovcnt].iov_base = pad;
245                 iov[iovcnt].iov_len = 60 - len;
246                 iovcnt++;
247         }
248         (void) writev(sc->vsc_tapfd, iov, iovcnt);
249 }
250
251 /*
252  *  Called when there is read activity on the tap file descriptor.
253  * Each buffer posted by the guest is assumed to be able to contain
254  * an entire ethernet frame + rx header.
255  *  MP note: the dummybuf is only used for discarding frames, so there
256  * is no need for it to be per-vtnet or locked.
257  */
258 static uint8_t dummybuf[2048];
259
260 static __inline struct iovec *
261 rx_iov_trim(struct iovec *iov, int *niov, int tlen)
262 {
263         struct iovec *riov;
264
265         /* XXX short-cut: assume first segment is >= tlen */
266         assert(iov[0].iov_len >= tlen);
267
268         iov[0].iov_len -= tlen;
269         if (iov[0].iov_len == 0) {
270                 assert(*niov > 1);
271                 *niov -= 1;
272                 riov = &iov[1];
273         } else {
274                 iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + tlen);
275                 riov = &iov[0];
276         }
277
278         return (riov);
279 }
280
281 static void
282 pci_vtnet_tap_rx(struct pci_vtnet_softc *sc)
283 {
284         struct iovec iov[VTNET_MAXSEGS], *riov;
285         struct vqueue_info *vq;
286         void *vrx;
287         int len, n;
288         uint16_t idx;
289
290         /*
291          * Should never be called without a valid tap fd
292          */
293         assert(sc->vsc_tapfd != -1);
294
295         /*
296          * But, will be called when the rx ring hasn't yet
297          * been set up.
298          */
299         if (!sc->vsc_rx_ready) {
300                 /*
301                  * Drop the packet and try later.
302                  */
303                 (void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
304                 return;
305         }
306
307         /*
308          * Check for available rx buffers
309          */
310         vq = &sc->vsc_queues[VTNET_RXQ];
311         if (!vq_has_descs(vq)) {
312                 /*
313                  * Drop the packet and try later.  Interrupt on
314                  * empty, if that's negotiated.
315                  */
316                 (void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
317                 vq_endchains(vq, 1);
318                 return;
319         }
320
321         do {
322                 /*
323                  * Get descriptor chain.
324                  */
325                 n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
326                 assert(n >= 1 && n <= VTNET_MAXSEGS);
327
328                 /*
329                  * Get a pointer to the rx header, and use the
330                  * data immediately following it for the packet buffer.
331                  */
332                 vrx = iov[0].iov_base;
333                 riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
334
335                 len = readv(sc->vsc_tapfd, riov, n);
336
337                 if (len < 0 && errno == EWOULDBLOCK) {
338                         /*
339                          * No more packets, but still some avail ring
340                          * entries.  Interrupt if needed/appropriate.
341                          */
342                         vq_retchain(vq);
343                         vq_endchains(vq, 0);
344                         return;
345                 }
346
347                 /*
348                  * The only valid field in the rx packet header is the
349                  * number of buffers if merged rx bufs were negotiated.
350                  */
351                 memset(vrx, 0, sc->rx_vhdrlen);
352
353                 if (sc->rx_merge) {
354                         struct virtio_net_rxhdr *vrxh;
355
356                         vrxh = vrx;
357                         vrxh->vrh_bufs = 1;
358                 }
359
360                 /*
361                  * Release this chain and handle more chains.
362                  */
363                 vq_relchain(vq, idx, len + sc->rx_vhdrlen);
364         } while (vq_has_descs(vq));
365
366         /* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
367         vq_endchains(vq, 1);
368 }
369
370 static __inline int
371 pci_vtnet_netmap_writev(struct nm_desc *nmd, struct iovec *iov, int iovcnt)
372 {
373         int r, i;
374         int len = 0;
375
376         for (r = nmd->cur_tx_ring; ; ) {
377                 struct netmap_ring *ring = NETMAP_TXRING(nmd->nifp, r);
378                 uint32_t cur, idx;
379                 char *buf;
380
381                 if (nm_ring_empty(ring)) {
382                         r++;
383                         if (r > nmd->last_tx_ring)
384                                 r = nmd->first_tx_ring;
385                         if (r == nmd->cur_tx_ring)
386                                 break;
387                         continue;
388                 }
389                 cur = ring->cur;
390                 idx = ring->slot[cur].buf_idx;
391                 buf = NETMAP_BUF(ring, idx);
392
393                 for (i = 0; i < iovcnt; i++) {
394                         if (len + iov[i].iov_len > 2048)
395                                 break;
396                         memcpy(&buf[len], iov[i].iov_base, iov[i].iov_len);
397                         len += iov[i].iov_len;
398                 }
399                 ring->slot[cur].len = len;
400                 ring->head = ring->cur = nm_ring_next(ring, cur);
401                 nmd->cur_tx_ring = r;
402                 ioctl(nmd->fd, NIOCTXSYNC, NULL);
403                 break;
404         }
405
406         return (len);
407 }
408
409 static __inline int
410 pci_vtnet_netmap_readv(struct nm_desc *nmd, struct iovec *iov, int iovcnt)
411 {
412         int len = 0;
413         int i = 0;
414         int r;
415
416         for (r = nmd->cur_rx_ring; ; ) {
417                 struct netmap_ring *ring = NETMAP_RXRING(nmd->nifp, r);
418                 uint32_t cur, idx;
419                 char *buf;
420                 size_t left;
421
422                 if (nm_ring_empty(ring)) {
423                         r++;
424                         if (r > nmd->last_rx_ring)
425                                 r = nmd->first_rx_ring;
426                         if (r == nmd->cur_rx_ring)
427                                 break;
428                         continue;
429                 }
430                 cur = ring->cur;
431                 idx = ring->slot[cur].buf_idx;
432                 buf = NETMAP_BUF(ring, idx);
433                 left = ring->slot[cur].len;
434
435                 for (i = 0; i < iovcnt && left > 0; i++) {
436                         if (iov[i].iov_len > left)
437                                 iov[i].iov_len = left;
438                         memcpy(iov[i].iov_base, &buf[len], iov[i].iov_len);
439                         len += iov[i].iov_len;
440                         left -= iov[i].iov_len;
441                 }
442                 ring->head = ring->cur = nm_ring_next(ring, cur);
443                 nmd->cur_rx_ring = r;
444                 ioctl(nmd->fd, NIOCRXSYNC, NULL);
445                 break;
446         }
447         for (; i < iovcnt; i++)
448                 iov[i].iov_len = 0;
449
450         return (len);
451 }
452
453 /*
454  * Called to send a buffer chain out to the vale port
455  */
456 static void
457 pci_vtnet_netmap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
458                     int len)
459 {
460         static char pad[60]; /* all zero bytes */
461
462         if (sc->vsc_nmd == NULL)
463                 return;
464
465         /*
466          * If the length is < 60, pad out to that and add the
467          * extra zero'd segment to the iov. It is guaranteed that
468          * there is always an extra iov available by the caller.
469          */
470         if (len < 60) {
471                 iov[iovcnt].iov_base = pad;
472                 iov[iovcnt].iov_len = 60 - len;
473                 iovcnt++;
474         }
475         (void) pci_vtnet_netmap_writev(sc->vsc_nmd, iov, iovcnt);
476 }
477
478 static void
479 pci_vtnet_netmap_rx(struct pci_vtnet_softc *sc)
480 {
481         struct iovec iov[VTNET_MAXSEGS], *riov;
482         struct vqueue_info *vq;
483         void *vrx;
484         int len, n;
485         uint16_t idx;
486
487         /*
488          * Should never be called without a valid netmap descriptor
489          */
490         assert(sc->vsc_nmd != NULL);
491
492         /*
493          * But, will be called when the rx ring hasn't yet
494          * been set up.
495          */
496         if (!sc->vsc_rx_ready) {
497                 /*
498                  * Drop the packet and try later.
499                  */
500                 (void) nm_nextpkt(sc->vsc_nmd, (void *)dummybuf);
501                 return;
502         }
503
504         /*
505          * Check for available rx buffers
506          */
507         vq = &sc->vsc_queues[VTNET_RXQ];
508         if (!vq_has_descs(vq)) {
509                 /*
510                  * Drop the packet and try later.  Interrupt on
511                  * empty, if that's negotiated.
512                  */
513                 (void) nm_nextpkt(sc->vsc_nmd, (void *)dummybuf);
514                 vq_endchains(vq, 1);
515                 return;
516         }
517
518         do {
519                 /*
520                  * Get descriptor chain.
521                  */
522                 n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
523                 assert(n >= 1 && n <= VTNET_MAXSEGS);
524
525                 /*
526                  * Get a pointer to the rx header, and use the
527                  * data immediately following it for the packet buffer.
528                  */
529                 vrx = iov[0].iov_base;
530                 riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
531
532                 len = pci_vtnet_netmap_readv(sc->vsc_nmd, riov, n);
533
534                 if (len == 0) {
535                         /*
536                          * No more packets, but still some avail ring
537                          * entries.  Interrupt if needed/appropriate.
538                          */
539                         vq_retchain(vq);
540                         vq_endchains(vq, 0);
541                         return;
542                 }
543
544                 /*
545                  * The only valid field in the rx packet header is the
546                  * number of buffers if merged rx bufs were negotiated.
547                  */
548                 memset(vrx, 0, sc->rx_vhdrlen);
549
550                 if (sc->rx_merge) {
551                         struct virtio_net_rxhdr *vrxh;
552
553                         vrxh = vrx;
554                         vrxh->vrh_bufs = 1;
555                 }
556
557                 /*
558                  * Release this chain and handle more chains.
559                  */
560                 vq_relchain(vq, idx, len + sc->rx_vhdrlen);
561         } while (vq_has_descs(vq));
562
563         /* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
564         vq_endchains(vq, 1);
565 }
566
567 static void
568 pci_vtnet_rx_callback(int fd, enum ev_type type, void *param)
569 {
570         struct pci_vtnet_softc *sc = param;
571
572         pthread_mutex_lock(&sc->rx_mtx);
573         sc->pci_vtnet_rx(sc);
574         pthread_mutex_unlock(&sc->rx_mtx);
575
576 }
577
578 static void
579 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
580 {
581         struct pci_vtnet_softc *sc = vsc;
582
583         /*
584          * A qnotify means that the rx process can now begin
585          */
586         if (sc->vsc_rx_ready == 0) {
587                 sc->vsc_rx_ready = 1;
588                 vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
589         }
590 }
591
592 static void
593 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
594 {
595         struct iovec iov[VTNET_MAXSEGS + 1];
596         int i, n;
597         int plen, tlen;
598         uint16_t idx;
599
600         /*
601          * Obtain chain of descriptors.  The first one is
602          * really the header descriptor, so we need to sum
603          * up two lengths: packet length and transfer length.
604          */
605         n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
606         assert(n >= 1 && n <= VTNET_MAXSEGS);
607         plen = 0;
608         tlen = iov[0].iov_len;
609         for (i = 1; i < n; i++) {
610                 plen += iov[i].iov_len;
611                 tlen += iov[i].iov_len;
612         }
613
614         DPRINTF(("virtio: packet send, %d bytes, %d segs\n\r", plen, n));
615         sc->pci_vtnet_tx(sc, &iov[1], n - 1, plen);
616
617         /* chain is processed, release it and set tlen */
618         vq_relchain(vq, idx, tlen);
619 }
620
621 static void
622 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
623 {
624         struct pci_vtnet_softc *sc = vsc;
625
626         /*
627          * Any ring entries to process?
628          */
629         if (!vq_has_descs(vq))
630                 return;
631
632         /* Signal the tx thread for processing */
633         pthread_mutex_lock(&sc->tx_mtx);
634         vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
635         if (sc->tx_in_progress == 0)
636                 pthread_cond_signal(&sc->tx_cond);
637         pthread_mutex_unlock(&sc->tx_mtx);
638 }
639
640 /*
641  * Thread which will handle processing of TX desc
642  */
643 static void *
644 pci_vtnet_tx_thread(void *param)
645 {
646         struct pci_vtnet_softc *sc = param;
647         struct vqueue_info *vq;
648         int error;
649
650         vq = &sc->vsc_queues[VTNET_TXQ];
651
652         /*
653          * Let us wait till the tx queue pointers get initialised &
654          * first tx signaled
655          */
656         pthread_mutex_lock(&sc->tx_mtx);
657         error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
658         assert(error == 0);
659
660         for (;;) {
661                 /* note - tx mutex is locked here */
662                 while (sc->resetting || !vq_has_descs(vq)) {
663                         vq->vq_used->vu_flags &= ~VRING_USED_F_NO_NOTIFY;
664                         mb();
665                         if (!sc->resetting && vq_has_descs(vq))
666                                 break;
667
668                         sc->tx_in_progress = 0;
669                         error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
670                         assert(error == 0);
671                 }
672                 vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
673                 sc->tx_in_progress = 1;
674                 pthread_mutex_unlock(&sc->tx_mtx);
675
676                 do {
677                         /*
678                          * Run through entries, placing them into
679                          * iovecs and sending when an end-of-packet
680                          * is found
681                          */
682                         pci_vtnet_proctx(sc, vq);
683                 } while (vq_has_descs(vq));
684
685                 /*
686                  * Generate an interrupt if needed.
687                  */
688                 vq_endchains(vq, 1);
689
690                 pthread_mutex_lock(&sc->tx_mtx);
691         }
692 }
693
694 #ifdef notyet
695 static void
696 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
697 {
698
699         DPRINTF(("vtnet: control qnotify!\n\r"));
700 }
701 #endif
702
703 static int
704 pci_vtnet_parsemac(char *mac_str, uint8_t *mac_addr)
705 {
706         struct ether_addr *ea;
707         char *tmpstr;
708         char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
709
710         tmpstr = strsep(&mac_str,"=");
711
712         if ((mac_str != NULL) && (!strcmp(tmpstr,"mac"))) {
713                 ea = ether_aton(mac_str);
714
715                 if (ea == NULL || ETHER_IS_MULTICAST(ea->octet) ||
716                     memcmp(ea->octet, zero_addr, ETHER_ADDR_LEN) == 0) {
717                         fprintf(stderr, "Invalid MAC %s\n", mac_str);
718                         return (EINVAL);
719                 } else
720                         memcpy(mac_addr, ea->octet, ETHER_ADDR_LEN);
721         }
722
723         return (0);
724 }
725
726 static void
727 pci_vtnet_tap_setup(struct pci_vtnet_softc *sc, char *devname)
728 {
729         char tbuf[80];
730 #ifndef WITHOUT_CAPSICUM
731         cap_rights_t rights;
732 #endif
733
734         strcpy(tbuf, "/dev/");
735         strlcat(tbuf, devname, sizeof(tbuf));
736
737         sc->pci_vtnet_rx = pci_vtnet_tap_rx;
738         sc->pci_vtnet_tx = pci_vtnet_tap_tx;
739
740         sc->vsc_tapfd = open(tbuf, O_RDWR);
741         if (sc->vsc_tapfd == -1) {
742                 WPRINTF(("open of tap device %s failed\n", tbuf));
743                 return;
744         }
745
746         /*
747          * Set non-blocking and register for read
748          * notifications with the event loop
749          */
750         int opt = 1;
751         if (ioctl(sc->vsc_tapfd, FIONBIO, &opt) < 0) {
752                 WPRINTF(("tap device O_NONBLOCK failed\n"));
753                 close(sc->vsc_tapfd);
754                 sc->vsc_tapfd = -1;
755         }
756
757 #ifndef WITHOUT_CAPSICUM
758         cap_rights_init(&rights, CAP_EVENT, CAP_READ, CAP_WRITE);
759         if (caph_rights_limit(sc->vsc_tapfd, &rights) == -1)
760                 errx(EX_OSERR, "Unable to apply rights for sandbox");
761 #endif
762
763         sc->vsc_mevp = mevent_add(sc->vsc_tapfd,
764                                   EVF_READ,
765                                   pci_vtnet_rx_callback,
766                                   sc);
767         if (sc->vsc_mevp == NULL) {
768                 WPRINTF(("Could not register event\n"));
769                 close(sc->vsc_tapfd);
770                 sc->vsc_tapfd = -1;
771         }
772 }
773
774 static void
775 pci_vtnet_netmap_setup(struct pci_vtnet_softc *sc, char *ifname)
776 {
777         sc->pci_vtnet_rx = pci_vtnet_netmap_rx;
778         sc->pci_vtnet_tx = pci_vtnet_netmap_tx;
779
780         sc->vsc_nmd = nm_open(ifname, NULL, 0, 0);
781         if (sc->vsc_nmd == NULL) {
782                 WPRINTF(("open of netmap device %s failed\n", ifname));
783                 return;
784         }
785
786         sc->vsc_mevp = mevent_add(sc->vsc_nmd->fd,
787                                   EVF_READ,
788                                   pci_vtnet_rx_callback,
789                                   sc);
790         if (sc->vsc_mevp == NULL) {
791                 WPRINTF(("Could not register event\n"));
792                 nm_close(sc->vsc_nmd);
793                 sc->vsc_nmd = NULL;
794         }
795 }
796
797 static int
798 pci_vtnet_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
799 {
800         MD5_CTX mdctx;
801         unsigned char digest[16];
802         char nstr[80];
803         char tname[MAXCOMLEN + 1];
804         struct pci_vtnet_softc *sc;
805         char *devname;
806         char *vtopts;
807         int mac_provided;
808
809         sc = calloc(1, sizeof(struct pci_vtnet_softc));
810
811         pthread_mutex_init(&sc->vsc_mtx, NULL);
812
813         vi_softc_linkup(&sc->vsc_vs, &vtnet_vi_consts, sc, pi, sc->vsc_queues);
814         sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
815
816         sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
817         sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
818         sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
819         sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
820 #ifdef notyet
821         sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
822         sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
823 #endif
824  
825         /*
826          * Attempt to open the tap device and read the MAC address
827          * if specified
828          */
829         mac_provided = 0;
830         sc->vsc_tapfd = -1;
831         sc->vsc_nmd = NULL;
832         if (opts != NULL) {
833                 int err;
834
835                 devname = vtopts = strdup(opts);
836                 (void) strsep(&vtopts, ",");
837
838                 if (vtopts != NULL) {
839                         err = pci_vtnet_parsemac(vtopts, sc->vsc_config.mac);
840                         if (err != 0) {
841                                 free(devname);
842                                 return (err);
843                         }
844                         mac_provided = 1;
845                 }
846
847                 if (strncmp(devname, "vale", 4) == 0)
848                         pci_vtnet_netmap_setup(sc, devname);
849                 if (strncmp(devname, "tap", 3) == 0 ||
850                     strncmp(devname, "vmnet", 5) == 0)
851                         pci_vtnet_tap_setup(sc, devname);
852
853                 free(devname);
854         }
855
856         /*
857          * The default MAC address is the standard NetApp OUI of 00-a0-98,
858          * followed by an MD5 of the PCI slot/func number and dev name
859          */
860         if (!mac_provided) {
861                 snprintf(nstr, sizeof(nstr), "%d-%d-%s", pi->pi_slot,
862                     pi->pi_func, vmname);
863
864                 MD5Init(&mdctx);
865                 MD5Update(&mdctx, nstr, strlen(nstr));
866                 MD5Final(digest, &mdctx);
867
868                 sc->vsc_config.mac[0] = 0x00;
869                 sc->vsc_config.mac[1] = 0xa0;
870                 sc->vsc_config.mac[2] = 0x98;
871                 sc->vsc_config.mac[3] = digest[0];
872                 sc->vsc_config.mac[4] = digest[1];
873                 sc->vsc_config.mac[5] = digest[2];
874         }
875
876         /* initialize config space */
877         pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
878         pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
879         pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
880         pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
881         pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
882
883         /* Link is up if we managed to open tap device or vale port. */
884         sc->vsc_config.status = (opts == NULL || sc->vsc_tapfd >= 0 ||
885             sc->vsc_nmd != NULL);
886         
887         /* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
888         if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix()))
889                 return (1);
890
891         /* use BAR 0 to map config regs in IO space */
892         vi_set_io_bar(&sc->vsc_vs, 0);
893
894         sc->resetting = 0;
895
896         sc->rx_merge = 1;
897         sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
898         pthread_mutex_init(&sc->rx_mtx, NULL); 
899
900         /* 
901          * Initialize tx semaphore & spawn TX processing thread.
902          * As of now, only one thread for TX desc processing is
903          * spawned. 
904          */
905         sc->tx_in_progress = 0;
906         pthread_mutex_init(&sc->tx_mtx, NULL);
907         pthread_cond_init(&sc->tx_cond, NULL);
908         pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
909         snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
910             pi->pi_func);
911         pthread_set_name_np(sc->tx_tid, tname);
912
913         return (0);
914 }
915
916 static int
917 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
918 {
919         struct pci_vtnet_softc *sc = vsc;
920         void *ptr;
921
922         if (offset < 6) {
923                 assert(offset + size <= 6);
924                 /*
925                  * The driver is allowed to change the MAC address
926                  */
927                 ptr = &sc->vsc_config.mac[offset];
928                 memcpy(ptr, &value, size);
929         } else {
930                 /* silently ignore other writes */
931                 DPRINTF(("vtnet: write to readonly reg %d\n\r", offset));
932         }
933
934         return (0);
935 }
936
937 static int
938 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
939 {
940         struct pci_vtnet_softc *sc = vsc;
941         void *ptr;
942
943         ptr = (uint8_t *)&sc->vsc_config + offset;
944         memcpy(retval, ptr, size);
945         return (0);
946 }
947
948 static void
949 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
950 {
951         struct pci_vtnet_softc *sc = vsc;
952
953         sc->vsc_features = negotiated_features;
954
955         if (!(sc->vsc_features & VIRTIO_NET_F_MRG_RXBUF)) {
956                 sc->rx_merge = 0;
957                 /* non-merge rx header is 2 bytes shorter */
958                 sc->rx_vhdrlen -= 2;
959         }
960 }
961
962 struct pci_devemu pci_de_vnet = {
963         .pe_emu =       "virtio-net",
964         .pe_init =      pci_vtnet_init,
965         .pe_barwrite =  vi_pci_write,
966         .pe_barread =   vi_pci_read
967 };
968 PCI_EMUL_SET(pci_de_vnet);