xref: /illumos-gate/usr/src/cmd/bhyve/pci_virtio_net.c (revision cab7c30c9587a8c7b5dd94af5f688dc5b8e8add7)
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  * This file and its contents are supplied under the terms of the
32  * Common Development and Distribution License ("CDDL"), version 1.0.
33  * You may only use this file in accordance with the terms of version
34  * 1.0 of the CDDL.
35  *
36  * A full copy of the text of the CDDL should have accompanied this
37  * source.  A copy of the CDDL is also available via the Internet at
38  * http://www.illumos.org/license/CDDL.
39  *
40  * Copyright 2013 Pluribus Networks Inc.
41  * Copyright 2018 Joyent, Inc.
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #ifndef WITHOUT_CAPSICUM
49 #include <sys/capsicum.h>
50 #endif
51 #include <sys/linker_set.h>
52 #include <sys/select.h>
53 #include <sys/uio.h>
54 #include <sys/ioctl.h>
55 #include <machine/atomic.h>
56 #include <net/ethernet.h>
57 #ifdef __FreeBSD__
58 #ifndef NETMAP_WITH_LIBS
59 #define NETMAP_WITH_LIBS
60 #endif
61 #include <net/netmap_user.h>
62 #endif
63 
64 #ifndef WITHOUT_CAPSICUM
65 #include <capsicum_helpers.h>
66 #endif
67 #include <err.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <stdint.h>
73 #include <string.h>
74 #include <strings.h>
75 #include <unistd.h>
76 #include <assert.h>
77 #include <md5.h>
78 #include <pthread.h>
79 #include <pthread_np.h>
80 #include <sysexits.h>
81 #ifndef __FreeBSD__
82 #include <poll.h>
83 #include <libdlpi.h>
84 #endif
85 
86 #include "bhyverun.h"
87 #include "pci_emul.h"
88 #ifdef __FreeBSD__
89 #include "mevent.h"
90 #endif
91 #include "virtio.h"
92 
93 #define VTNET_RINGSZ	1024
94 
95 #define VTNET_MAXSEGS	256
96 
97 /*
98  * Host capabilities.  Note that we only offer a few of these.
99  */
100 #define	VIRTIO_NET_F_CSUM	(1 <<  0) /* host handles partial cksum */
101 #define	VIRTIO_NET_F_GUEST_CSUM	(1 <<  1) /* guest handles partial cksum */
102 #define	VIRTIO_NET_F_MAC	(1 <<  5) /* host supplies MAC */
103 #define	VIRTIO_NET_F_GSO_DEPREC	(1 <<  6) /* deprecated: host handles GSO */
104 #define	VIRTIO_NET_F_GUEST_TSO4	(1 <<  7) /* guest can rcv TSOv4 */
105 #define	VIRTIO_NET_F_GUEST_TSO6	(1 <<  8) /* guest can rcv TSOv6 */
106 #define	VIRTIO_NET_F_GUEST_ECN	(1 <<  9) /* guest can rcv TSO with ECN */
107 #define	VIRTIO_NET_F_GUEST_UFO	(1 << 10) /* guest can rcv UFO */
108 #define	VIRTIO_NET_F_HOST_TSO4	(1 << 11) /* host can rcv TSOv4 */
109 #define	VIRTIO_NET_F_HOST_TSO6	(1 << 12) /* host can rcv TSOv6 */
110 #define	VIRTIO_NET_F_HOST_ECN	(1 << 13) /* host can rcv TSO with ECN */
111 #define	VIRTIO_NET_F_HOST_UFO	(1 << 14) /* host can rcv UFO */
112 #define	VIRTIO_NET_F_MRG_RXBUF	(1 << 15) /* host can merge RX buffers */
113 #define	VIRTIO_NET_F_STATUS	(1 << 16) /* config status field available */
114 #define	VIRTIO_NET_F_CTRL_VQ	(1 << 17) /* control channel available */
115 #define	VIRTIO_NET_F_CTRL_RX	(1 << 18) /* control channel RX mode support */
116 #define	VIRTIO_NET_F_CTRL_VLAN	(1 << 19) /* control channel VLAN filtering */
117 #define	VIRTIO_NET_F_GUEST_ANNOUNCE \
118 				(1 << 21) /* guest can send gratuitous pkts */
119 
120 #define VTNET_S_HOSTCAPS      \
121   ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_MRG_RXBUF | VIRTIO_NET_F_STATUS | \
122     VIRTIO_F_NOTIFY_ON_EMPTY | VIRTIO_RING_F_INDIRECT_DESC)
123 
124 /*
125  * PCI config-space "registers"
126  */
127 struct virtio_net_config {
128 	uint8_t  mac[6];
129 	uint16_t status;
130 } __packed;
131 
132 /*
133  * Queue definitions.
134  */
135 #define VTNET_RXQ	0
136 #define VTNET_TXQ	1
137 #define VTNET_CTLQ	2	/* NB: not yet supported */
138 
139 #define VTNET_MAXQ	3
140 
141 /*
142  * Fixed network header size
143  */
144 struct virtio_net_rxhdr {
145 	uint8_t		vrh_flags;
146 	uint8_t		vrh_gso_type;
147 	uint16_t	vrh_hdr_len;
148 	uint16_t	vrh_gso_size;
149 	uint16_t	vrh_csum_start;
150 	uint16_t	vrh_csum_offset;
151 	uint16_t	vrh_bufs;
152 } __packed;
153 
154 /*
155  * Debug printf
156  */
157 static int pci_vtnet_debug;
158 #define DPRINTF(params) if (pci_vtnet_debug) printf params
159 #define WPRINTF(params) printf params
160 
161 /*
162  * Per-device softc
163  */
164 struct pci_vtnet_softc {
165 	struct virtio_softc vsc_vs;
166 	struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
167 	pthread_mutex_t vsc_mtx;
168 	struct mevent	*vsc_mevp;
169 
170 #ifdef	__FreeBSD
171 	int		vsc_tapfd;
172 #else
173 	dlpi_handle_t	vsc_dhp;
174 	int		vsc_dlpifd;
175 #endif
176 	struct nm_desc	*vsc_nmd;
177 
178 	int		vsc_rx_ready;
179 	volatile int	resetting;	/* set and checked outside lock */
180 
181 	uint64_t	vsc_features;	/* negotiated features */
182 
183 	struct virtio_net_config vsc_config;
184 
185 	pthread_mutex_t	rx_mtx;
186 	int		rx_in_progress;
187 	int		rx_vhdrlen;
188 	int		rx_merge;	/* merged rx bufs in use */
189 
190 	pthread_t 	tx_tid;
191 	pthread_mutex_t	tx_mtx;
192 	pthread_cond_t	tx_cond;
193 	int		tx_in_progress;
194 
195 	void (*pci_vtnet_rx)(struct pci_vtnet_softc *sc);
196 	void (*pci_vtnet_tx)(struct pci_vtnet_softc *sc, struct iovec *iov,
197 			     int iovcnt, int len);
198 };
199 
200 static void pci_vtnet_reset(void *);
201 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
202 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
203 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
204 static void pci_vtnet_neg_features(void *, uint64_t);
205 
206 static struct virtio_consts vtnet_vi_consts = {
207 	"vtnet",		/* our name */
208 	VTNET_MAXQ - 1,		/* we currently support 2 virtqueues */
209 	sizeof(struct virtio_net_config), /* config reg size */
210 	pci_vtnet_reset,	/* reset */
211 	NULL,			/* device-wide qnotify -- not used */
212 	pci_vtnet_cfgread,	/* read PCI config */
213 	pci_vtnet_cfgwrite,	/* write PCI config */
214 	pci_vtnet_neg_features,	/* apply negotiated features */
215 	VTNET_S_HOSTCAPS,	/* our capabilities */
216 };
217 
218 /*
219  * If the transmit thread is active then stall until it is done.
220  */
221 static void
222 pci_vtnet_txwait(struct pci_vtnet_softc *sc)
223 {
224 
225 	pthread_mutex_lock(&sc->tx_mtx);
226 	while (sc->tx_in_progress) {
227 		pthread_mutex_unlock(&sc->tx_mtx);
228 		usleep(10000);
229 		pthread_mutex_lock(&sc->tx_mtx);
230 	}
231 	pthread_mutex_unlock(&sc->tx_mtx);
232 }
233 
234 /*
235  * If the receive thread is active then stall until it is done.
236  */
237 static void
238 pci_vtnet_rxwait(struct pci_vtnet_softc *sc)
239 {
240 
241 	pthread_mutex_lock(&sc->rx_mtx);
242 	while (sc->rx_in_progress) {
243 		pthread_mutex_unlock(&sc->rx_mtx);
244 		usleep(10000);
245 		pthread_mutex_lock(&sc->rx_mtx);
246 	}
247 	pthread_mutex_unlock(&sc->rx_mtx);
248 }
249 
250 static void
251 pci_vtnet_reset(void *vsc)
252 {
253 	struct pci_vtnet_softc *sc = vsc;
254 
255 	DPRINTF(("vtnet: device reset requested !\n"));
256 
257 	sc->resetting = 1;
258 
259 	/*
260 	 * Wait for the transmit and receive threads to finish their
261 	 * processing.
262 	 */
263 	pci_vtnet_txwait(sc);
264 	pci_vtnet_rxwait(sc);
265 
266 	sc->vsc_rx_ready = 0;
267 	sc->rx_merge = 1;
268 	sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
269 
270 	/* now reset rings, MSI-X vectors, and negotiated capabilities */
271 	vi_reset_dev(&sc->vsc_vs);
272 
273 	sc->resetting = 0;
274 }
275 
276 /*
277  * Called to send a buffer chain out to the tap device
278  */
279 #ifdef __FreeBSD__
280 static void
281 pci_vtnet_tap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
282 		 int len)
283 {
284 	static char pad[60]; /* all zero bytes */
285 
286 	if (sc->vsc_tapfd == -1)
287 		return;
288 
289 	/*
290 	 * If the length is < 60, pad out to that and add the
291 	 * extra zero'd segment to the iov. It is guaranteed that
292 	 * there is always an extra iov available by the caller.
293 	 */
294 	if (len < 60) {
295 		iov[iovcnt].iov_base = pad;
296 		iov[iovcnt].iov_len = 60 - len;
297 		iovcnt++;
298 	}
299 	(void) writev(sc->vsc_tapfd, iov, iovcnt);
300 }
301 #else
302 static void
303 pci_vtnet_tap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
304 		 int len)
305 {
306 	int i;
307 
308 	for (i = 0; i < iovcnt; i++) {
309 		(void) dlpi_send(sc->vsc_dhp, NULL, 0,
310 		    iov[i].iov_base, iov[i].iov_len, NULL);
311 	}
312 }
313 #endif /* __FreeBSD__ */
314 
315 #ifdef __FreeBSD__
316 /*
317  *  Called when there is read activity on the tap file descriptor.
318  * Each buffer posted by the guest is assumed to be able to contain
319  * an entire ethernet frame + rx header.
320  *  MP note: the dummybuf is only used for discarding frames, so there
321  * is no need for it to be per-vtnet or locked.
322  */
323 static uint8_t dummybuf[2048];
324 #endif /* __FreeBSD__ */
325 
326 static __inline struct iovec *
327 rx_iov_trim(struct iovec *iov, int *niov, int tlen)
328 {
329 	struct iovec *riov;
330 
331 	/* XXX short-cut: assume first segment is >= tlen */
332 	assert(iov[0].iov_len >= tlen);
333 
334 	iov[0].iov_len -= tlen;
335 	if (iov[0].iov_len == 0) {
336 		assert(*niov > 1);
337 		*niov -= 1;
338 		riov = &iov[1];
339 	} else {
340 		iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + tlen);
341 		riov = &iov[0];
342 	}
343 
344 	return (riov);
345 }
346 
347 static void
348 pci_vtnet_tap_rx(struct pci_vtnet_softc *sc)
349 {
350 	struct iovec iov[VTNET_MAXSEGS], *riov;
351 	struct vqueue_info *vq;
352 	void *vrx;
353 	int n;
354 #ifdef	__FreeBSD__
355 	int len;
356 #else
357 	size_t len;
358 	int ret;
359 #endif
360 	uint16_t idx;
361 
362 	/*
363 	 * Should never be called without a valid tap fd
364 	 */
365 #ifdef	__FreeBSD__
366 	assert(sc->vsc_tapfd != -1);
367 #else
368 	assert(sc->vsc_dlpifd != -1);
369 #endif
370 
371 	/*
372 	 * But, will be called when the rx ring hasn't yet
373 	 * been set up or the guest is resetting the device.
374 	 */
375 	if (!sc->vsc_rx_ready || sc->resetting) {
376 #ifdef	__FreeBSD__
377 		/*
378 		 * Drop the packet and try later.
379 		 */
380 		(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
381 #endif
382 		return;
383 	}
384 
385 	/*
386 	 * Check for available rx buffers
387 	 */
388 	vq = &sc->vsc_queues[VTNET_RXQ];
389 	if (!vq_has_descs(vq)) {
390 		/*
391 		 * Drop the packet and try later.  Interrupt on
392 		 * empty, if that's negotiated.
393 		 */
394 #ifdef	__FreeBSD__
395 		(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
396 #endif
397 		vq_endchains(vq, 1);
398 		return;
399 	}
400 
401 	do {
402 		/*
403 		 * Get descriptor chain
404 		 */
405 		n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
406 		assert(n >= 1 && n <= VTNET_MAXSEGS);
407 
408 		/*
409 		 * Get a pointer to the rx header, and use the
410 		 * data immediately following it for the packet buffer.
411 		 */
412 		vrx = iov[0].iov_base;
413 		riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
414 #ifdef	__FreeBSD__
415 		len = readv(sc->vsc_tapfd, riov, n);
416 #else
417 		len = riov[0].iov_len;
418 		ret = dlpi_recv(sc->vsc_dhp, NULL, NULL,
419 		    (uint8_t *)riov[0].iov_base, &len, 0, NULL);
420 		if (ret != DLPI_SUCCESS) {
421 			errno = EWOULDBLOCK;
422 			len = 0;
423 		}
424 #endif
425 		if (len <= 0 && errno == EWOULDBLOCK) {
426 			/*
427 			 * No more packets, but still some avail ring
428 			 * entries.  Interrupt if needed/appropriate.
429 			 */
430 			vq_retchain(vq);
431 			vq_endchains(vq, 0);
432 			return;
433 		}
434 
435 		/*
436 		 * The only valid field in the rx packet header is the
437 		 * number of buffers if merged rx bufs were negotiated.
438 		 */
439 		memset(vrx, 0, sc->rx_vhdrlen);
440 
441 		if (sc->rx_merge) {
442 			struct virtio_net_rxhdr *vrxh;
443 
444 			vrxh = vrx;
445 			vrxh->vrh_bufs = 1;
446 		}
447 
448 		/*
449 		 * Release this chain and handle more chains.
450 		 */
451 		vq_relchain(vq, idx, len + sc->rx_vhdrlen);
452 	} while (vq_has_descs(vq));
453 
454 	/* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
455 	vq_endchains(vq, 1);
456 }
457 
458 #ifdef __FreeBSD__
459 static __inline int
460 pci_vtnet_netmap_writev(struct nm_desc *nmd, struct iovec *iov, int iovcnt)
461 {
462 	int r, i;
463 	int len = 0;
464 
465 	for (r = nmd->cur_tx_ring; ; ) {
466 		struct netmap_ring *ring = NETMAP_TXRING(nmd->nifp, r);
467 		uint32_t cur, idx;
468 		char *buf;
469 
470 		if (nm_ring_empty(ring)) {
471 			r++;
472 			if (r > nmd->last_tx_ring)
473 				r = nmd->first_tx_ring;
474 			if (r == nmd->cur_tx_ring)
475 				break;
476 			continue;
477 		}
478 		cur = ring->cur;
479 		idx = ring->slot[cur].buf_idx;
480 		buf = NETMAP_BUF(ring, idx);
481 
482 		for (i = 0; i < iovcnt; i++) {
483 			if (len + iov[i].iov_len > 2048)
484 				break;
485 			memcpy(&buf[len], iov[i].iov_base, iov[i].iov_len);
486 			len += iov[i].iov_len;
487 		}
488 		ring->slot[cur].len = len;
489 		ring->head = ring->cur = nm_ring_next(ring, cur);
490 		nmd->cur_tx_ring = r;
491 		ioctl(nmd->fd, NIOCTXSYNC, NULL);
492 		break;
493 	}
494 
495 	return (len);
496 }
497 
498 static __inline int
499 pci_vtnet_netmap_readv(struct nm_desc *nmd, struct iovec *iov, int iovcnt)
500 {
501 	int len = 0;
502 	int i = 0;
503 	int r;
504 
505 	for (r = nmd->cur_rx_ring; ; ) {
506 		struct netmap_ring *ring = NETMAP_RXRING(nmd->nifp, r);
507 		uint32_t cur, idx;
508 		char *buf;
509 		size_t left;
510 
511 		if (nm_ring_empty(ring)) {
512 			r++;
513 			if (r > nmd->last_rx_ring)
514 				r = nmd->first_rx_ring;
515 			if (r == nmd->cur_rx_ring)
516 				break;
517 			continue;
518 		}
519 		cur = ring->cur;
520 		idx = ring->slot[cur].buf_idx;
521 		buf = NETMAP_BUF(ring, idx);
522 		left = ring->slot[cur].len;
523 
524 		for (i = 0; i < iovcnt && left > 0; i++) {
525 			if (iov[i].iov_len > left)
526 				iov[i].iov_len = left;
527 			memcpy(iov[i].iov_base, &buf[len], iov[i].iov_len);
528 			len += iov[i].iov_len;
529 			left -= iov[i].iov_len;
530 		}
531 		ring->head = ring->cur = nm_ring_next(ring, cur);
532 		nmd->cur_rx_ring = r;
533 		ioctl(nmd->fd, NIOCRXSYNC, NULL);
534 		break;
535 	}
536 	for (; i < iovcnt; i++)
537 		iov[i].iov_len = 0;
538 
539 	return (len);
540 }
541 
542 /*
543  * Called to send a buffer chain out to the vale port
544  */
545 static void
546 pci_vtnet_netmap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
547 		    int len)
548 {
549 	static char pad[60]; /* all zero bytes */
550 
551 	if (sc->vsc_nmd == NULL)
552 		return;
553 
554 	/*
555 	 * If the length is < 60, pad out to that and add the
556 	 * extra zero'd segment to the iov. It is guaranteed that
557 	 * there is always an extra iov available by the caller.
558 	 */
559 	if (len < 60) {
560 		iov[iovcnt].iov_base = pad;
561 		iov[iovcnt].iov_len = 60 - len;
562 		iovcnt++;
563 	}
564 	(void) pci_vtnet_netmap_writev(sc->vsc_nmd, iov, iovcnt);
565 }
566 
567 static void
568 pci_vtnet_netmap_rx(struct pci_vtnet_softc *sc)
569 {
570 	struct iovec iov[VTNET_MAXSEGS], *riov;
571 	struct vqueue_info *vq;
572 	void *vrx;
573 	int len, n;
574 	uint16_t idx;
575 
576 	/*
577 	 * Should never be called without a valid netmap descriptor
578 	 */
579 	assert(sc->vsc_nmd != NULL);
580 
581 	/*
582 	 * But, will be called when the rx ring hasn't yet
583 	 * been set up or the guest is resetting the device.
584 	 */
585 	if (!sc->vsc_rx_ready || sc->resetting) {
586 		/*
587 		 * Drop the packet and try later.
588 		 */
589 		(void) nm_nextpkt(sc->vsc_nmd, (void *)dummybuf);
590 		return;
591 	}
592 
593 	/*
594 	 * Check for available rx buffers
595 	 */
596 	vq = &sc->vsc_queues[VTNET_RXQ];
597 	if (!vq_has_descs(vq)) {
598 		/*
599 		 * Drop the packet and try later.  Interrupt on
600 		 * empty, if that's negotiated.
601 		 */
602 		(void) nm_nextpkt(sc->vsc_nmd, (void *)dummybuf);
603 		vq_endchains(vq, 1);
604 		return;
605 	}
606 
607 	do {
608 		/*
609 		 * Get descriptor chain.
610 		 */
611 		n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
612 		assert(n >= 1 && n <= VTNET_MAXSEGS);
613 
614 		/*
615 		 * Get a pointer to the rx header, and use the
616 		 * data immediately following it for the packet buffer.
617 		 */
618 		vrx = iov[0].iov_base;
619 		riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
620 
621 		len = pci_vtnet_netmap_readv(sc->vsc_nmd, riov, n);
622 
623 		if (len == 0) {
624 			/*
625 			 * No more packets, but still some avail ring
626 			 * entries.  Interrupt if needed/appropriate.
627 			 */
628 			vq_retchain(vq);
629 			vq_endchains(vq, 0);
630 			return;
631 		}
632 
633 		/*
634 		 * The only valid field in the rx packet header is the
635 		 * number of buffers if merged rx bufs were negotiated.
636 		 */
637 		memset(vrx, 0, sc->rx_vhdrlen);
638 
639 		if (sc->rx_merge) {
640 			struct virtio_net_rxhdr *vrxh;
641 
642 			vrxh = vrx;
643 			vrxh->vrh_bufs = 1;
644 		}
645 
646 		/*
647 		 * Release this chain and handle more chains.
648 		 */
649 		vq_relchain(vq, idx, len + sc->rx_vhdrlen);
650 	} while (vq_has_descs(vq));
651 
652 	/* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
653 	vq_endchains(vq, 1);
654 }
655 #endif /* __FreeBSD__ */
656 
657 #ifdef __FreeBSD__
658 static void
659 pci_vtnet_rx_callback(int fd, enum ev_type type, void *param)
660 {
661 	struct pci_vtnet_softc *sc = param;
662 
663 	pthread_mutex_lock(&sc->rx_mtx);
664 	sc->rx_in_progress = 1;
665 	sc->pci_vtnet_rx(sc);
666 	sc->rx_in_progress = 0;
667 	pthread_mutex_unlock(&sc->rx_mtx);
668 
669 }
670 #else
671 static void *
672 pci_vtnet_poll_thread(void *param)
673 {
674 	struct pci_vtnet_softc *sc = param;
675 	pollfd_t pollset;
676 
677 	pollset.fd = sc->vsc_dlpifd;
678 	pollset.events = POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND;
679 
680 	for (;;) {
681 		if (poll(&pollset, 1, -1) < 0) {
682 			if (errno == EINTR)
683 				continue;
684 			fprintf(stderr, "pci_vtnet_poll_thread poll() error %d\n", errno);
685 			continue;
686 		}
687 		pthread_mutex_lock(&sc->vsc_mtx);
688 		sc->rx_in_progress = 1;
689 		pci_vtnet_tap_rx(sc);
690 		sc->rx_in_progress = 0;
691 		pthread_mutex_unlock(&sc->vsc_mtx);
692 	}
693 
694 	return (NULL);
695 }
696 #endif /* __FreeBSD__ */
697 
698 static void
699 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
700 {
701 	struct pci_vtnet_softc *sc = vsc;
702 
703 	/*
704 	 * A qnotify means that the rx process can now begin
705 	 */
706 	if (sc->vsc_rx_ready == 0) {
707 		sc->vsc_rx_ready = 1;
708 		vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
709 	}
710 }
711 
712 static void
713 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
714 {
715 	struct iovec iov[VTNET_MAXSEGS + 1];
716 	int i, n;
717 	int plen, tlen;
718 	uint16_t idx;
719 
720 	/*
721 	 * Obtain chain of descriptors.  The first one is
722 	 * really the header descriptor, so we need to sum
723 	 * up two lengths: packet length and transfer length.
724 	 */
725 	n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
726 	assert(n >= 1 && n <= VTNET_MAXSEGS);
727 	plen = 0;
728 	tlen = iov[0].iov_len;
729 	for (i = 1; i < n; i++) {
730 		plen += iov[i].iov_len;
731 		tlen += iov[i].iov_len;
732 	}
733 
734 	DPRINTF(("virtio: packet send, %d bytes, %d segs\n\r", plen, n));
735 	sc->pci_vtnet_tx(sc, &iov[1], n - 1, plen);
736 
737 	/* chain is processed, release it and set tlen */
738 	vq_relchain(vq, idx, tlen);
739 }
740 
741 static void
742 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
743 {
744 	struct pci_vtnet_softc *sc = vsc;
745 
746 	/*
747 	 * Any ring entries to process?
748 	 */
749 	if (!vq_has_descs(vq))
750 		return;
751 
752 	/* Signal the tx thread for processing */
753 	pthread_mutex_lock(&sc->tx_mtx);
754 	vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
755 	if (sc->tx_in_progress == 0)
756 		pthread_cond_signal(&sc->tx_cond);
757 	pthread_mutex_unlock(&sc->tx_mtx);
758 }
759 
760 /*
761  * Thread which will handle processing of TX desc
762  */
763 static void *
764 pci_vtnet_tx_thread(void *param)
765 {
766 	struct pci_vtnet_softc *sc = param;
767 	struct vqueue_info *vq;
768 	int error;
769 
770 	vq = &sc->vsc_queues[VTNET_TXQ];
771 
772 	/*
773 	 * Let us wait till the tx queue pointers get initialised &
774 	 * first tx signaled
775 	 */
776 	pthread_mutex_lock(&sc->tx_mtx);
777 	error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
778 	assert(error == 0);
779 
780 	for (;;) {
781 		/* note - tx mutex is locked here */
782 		while (sc->resetting || !vq_has_descs(vq)) {
783 			vq->vq_used->vu_flags &= ~VRING_USED_F_NO_NOTIFY;
784 			mb();
785 			if (!sc->resetting && vq_has_descs(vq))
786 				break;
787 
788 			sc->tx_in_progress = 0;
789 			error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
790 			assert(error == 0);
791 		}
792 		vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
793 		sc->tx_in_progress = 1;
794 		pthread_mutex_unlock(&sc->tx_mtx);
795 
796 		do {
797 			/*
798 			 * Run through entries, placing them into
799 			 * iovecs and sending when an end-of-packet
800 			 * is found
801 			 */
802 			pci_vtnet_proctx(sc, vq);
803 		} while (vq_has_descs(vq));
804 
805 		/*
806 		 * Generate an interrupt if needed.
807 		 */
808 		vq_endchains(vq, 1);
809 
810 		pthread_mutex_lock(&sc->tx_mtx);
811 	}
812 	return (NULL);
813 }
814 
815 #ifdef __FreeBSD__
816 static void
817 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
818 {
819 
820 	DPRINTF(("vtnet: control qnotify!\n\r"));
821 }
822 #endif /* __FreeBSD__ */
823 
824 #ifdef __FreeBSD__
825 static int
826 pci_vtnet_parsemac(char *mac_str, uint8_t *mac_addr)
827 {
828 	struct ether_addr *ea;
829 	char *tmpstr;
830 	char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
831 
832 	tmpstr = strsep(&mac_str,"=");
833 
834 	if ((mac_str != NULL) && (!strcmp(tmpstr,"mac"))) {
835 		ea = ether_aton(mac_str);
836 
837 		if (ea == NULL || ETHER_IS_MULTICAST(ea->octet) ||
838 		    memcmp(ea->octet, zero_addr, ETHER_ADDR_LEN) == 0) {
839 			fprintf(stderr, "Invalid MAC %s\n", mac_str);
840 			return (EINVAL);
841 		} else
842 			memcpy(mac_addr, ea->octet, ETHER_ADDR_LEN);
843 	}
844 
845 	return (0);
846 }
847 #endif /* __FreeBSD__ */
848 
849 static void
850 pci_vtnet_tap_setup(struct pci_vtnet_softc *sc, char *devname)
851 {
852 	char tbuf[80];
853 #ifndef WITHOUT_CAPSICUM
854 	cap_rights_t rights;
855 #endif
856 #ifndef	__FreeBSD__
857 	uchar_t physaddr[DLPI_PHYSADDR_MAX];
858 	size_t physaddrlen = DLPI_PHYSADDR_MAX;
859 	int error;
860 #endif
861 
862 	strcpy(tbuf, "/dev/");
863 	strlcat(tbuf, devname, sizeof(tbuf));
864 
865 	sc->pci_vtnet_rx = pci_vtnet_tap_rx;
866 	sc->pci_vtnet_tx = pci_vtnet_tap_tx;
867 #ifdef	__FreeBSD__
868 	sc->vsc_tapfd = open(tbuf, O_RDWR);
869 	if (sc->vsc_tapfd == -1) {
870 		WPRINTF(("open of tap device %s failed\n", tbuf));
871 		return;
872 	}
873 
874 	/*
875 	 * Set non-blocking and register for read
876 	 * notifications with the event loop
877 	 */
878 	int opt = 1;
879 	if (ioctl(sc->vsc_tapfd, FIONBIO, &opt) < 0) {
880 		WPRINTF(("tap device O_NONBLOCK failed\n"));
881 		close(sc->vsc_tapfd);
882 		sc->vsc_tapfd = -1;
883 	}
884 
885 #ifndef WITHOUT_CAPSICUM
886 	cap_rights_init(&rights, CAP_EVENT, CAP_READ, CAP_WRITE);
887 	if (caph_rights_limit(sc->vsc_tapfd, &rights) == -1)
888 		errx(EX_OSERR, "Unable to apply rights for sandbox");
889 #endif
890 
891 	sc->vsc_mevp = mevent_add(sc->vsc_tapfd,
892 				  EVF_READ,
893 				  pci_vtnet_rx_callback,
894 				  sc);
895 	if (sc->vsc_mevp == NULL) {
896 		WPRINTF(("Could not register event\n"));
897 		close(sc->vsc_tapfd);
898 		sc->vsc_tapfd = -1;
899 	}
900 #else
901 	if (dlpi_open(devname, &sc->vsc_dhp, DLPI_RAW) != DLPI_SUCCESS) {
902 		WPRINTF(("open of vnic device %s failed\n", devname));
903 	}
904 
905 	if (dlpi_get_physaddr(sc->vsc_dhp, DL_CURR_PHYS_ADDR, physaddr,
906 	    &physaddrlen) != DLPI_SUCCESS) {
907 		WPRINTF(("read MAC address of vnic device %s failed\n",
908 		    devname));
909 	}
910 	if (physaddrlen != ETHERADDRL) {
911 		WPRINTF(("bad MAC address len %d on vnic device %s\n",
912 		    physaddrlen, devname));
913 	}
914 	memcpy(sc->vsc_config.mac, physaddr, ETHERADDRL);
915 
916 	if (dlpi_bind(sc->vsc_dhp, DLPI_ANY_SAP, NULL) != DLPI_SUCCESS) {
917 		WPRINTF(("bind of vnic device %s failed\n", devname));
918 	}
919 
920 	if (dlpi_promiscon(sc->vsc_dhp, DL_PROMISC_PHYS) != DLPI_SUCCESS) {
921 		WPRINTF(("enable promiscous mode(physical) of vnic device %s "
922 		    "failed\n", devname));
923 	}
924 	if (dlpi_promiscon(sc->vsc_dhp, DL_PROMISC_SAP) != DLPI_SUCCESS) {
925 		WPRINTF(("enable promiscous mode(SAP) of vnic device %s "
926 		    "failed\n", devname));
927 	}
928 
929 	sc->vsc_dlpifd = dlpi_fd(sc->vsc_dhp);
930 
931 	if (fcntl(sc->vsc_dlpifd, F_SETFL, O_NONBLOCK) < 0) {
932 		WPRINTF(("enable O_NONBLOCK of vnic device %s failed\n",
933 		    devname));
934 		dlpi_close(sc->vsc_dhp);
935 		sc->vsc_dlpifd = -1;
936 	}
937 
938 	error = pthread_create(NULL, NULL, pci_vtnet_poll_thread, sc);
939 	assert(error == 0);
940 #endif
941 }
942 
943 #ifdef __FreeBSD__
944 static void
945 pci_vtnet_netmap_setup(struct pci_vtnet_softc *sc, char *ifname)
946 {
947 	sc->pci_vtnet_rx = pci_vtnet_netmap_rx;
948 	sc->pci_vtnet_tx = pci_vtnet_netmap_tx;
949 
950 	sc->vsc_nmd = nm_open(ifname, NULL, 0, 0);
951 	if (sc->vsc_nmd == NULL) {
952 		WPRINTF(("open of netmap device %s failed\n", ifname));
953 		return;
954 	}
955 
956 	sc->vsc_mevp = mevent_add(sc->vsc_nmd->fd,
957 				  EVF_READ,
958 				  pci_vtnet_rx_callback,
959 				  sc);
960 	if (sc->vsc_mevp == NULL) {
961 		WPRINTF(("Could not register event\n"));
962 		nm_close(sc->vsc_nmd);
963 		sc->vsc_nmd = NULL;
964 	}
965 }
966 #endif /* __FreeBSD__ */
967 
968 static int
969 pci_vtnet_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
970 {
971 #ifdef	__FreeBSD__
972 	MD5_CTX mdctx;
973 	unsigned char digest[16];
974 	char nstr[80];
975 #endif
976 	char tname[MAXCOMLEN + 1];
977 	struct pci_vtnet_softc *sc;
978 	const char *env_msi;
979 	char *devname;
980 	char *vtopts;
981 #ifdef __FreeBSD__
982 	int mac_provided;
983 #endif
984 	int use_msix;
985 
986 	sc = calloc(1, sizeof(struct pci_vtnet_softc));
987 
988 	pthread_mutex_init(&sc->vsc_mtx, NULL);
989 
990 	vi_softc_linkup(&sc->vsc_vs, &vtnet_vi_consts, sc, pi, sc->vsc_queues);
991 	sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
992 
993 	sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
994 	sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
995 	sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
996 	sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
997 #ifdef __FreeBSD__
998 	sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
999         sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
1000 #endif
1001 
1002 	/*
1003 	 * Use MSI if set by user
1004 	 */
1005 	use_msix = 1;
1006 	if ((env_msi = getenv("BHYVE_USE_MSI")) != NULL) {
1007 		if (strcasecmp(env_msi, "yes") == 0)
1008 			use_msix = 0;
1009 	}
1010 
1011 	/*
1012 	 * Attempt to open the tap device and read the MAC address
1013 	 * if specified
1014 	 */
1015 #ifdef	__FreeBSD__
1016 	mac_provided = 0;
1017 	sc->vsc_tapfd = -1;
1018 #endif
1019 	sc->vsc_nmd = NULL;
1020 	if (opts != NULL) {
1021 #ifdef	__FreeBSD__
1022 		int err;
1023 #endif
1024 
1025 		devname = vtopts = strdup(opts);
1026 		(void) strsep(&vtopts, ",");
1027 
1028 #ifdef	__FreBSD__
1029 		if (vtopts != NULL) {
1030 			err = pci_vtnet_parsemac(vtopts, sc->vsc_config.mac);
1031 			if (err != 0) {
1032 				free(devname);
1033 				return (err);
1034 			}
1035 			mac_provided = 1;
1036 		}
1037 #endif
1038 
1039 #ifdef __FreeBSD__
1040 		if (strncmp(devname, "vale", 4) == 0)
1041 			pci_vtnet_netmap_setup(sc, devname);
1042 #endif
1043 		if (strncmp(devname, "tap", 3) == 0 ||
1044 		    strncmp(devname, "vmnet", 5) == 0)
1045 			pci_vtnet_tap_setup(sc, devname);
1046 
1047 		free(devname);
1048 	}
1049 
1050 #ifdef	__FreeBSD__
1051 	/*
1052 	 * The default MAC address is the standard NetApp OUI of 00-a0-98,
1053 	 * followed by an MD5 of the PCI slot/func number and dev name
1054 	 */
1055 	if (!mac_provided) {
1056 		snprintf(nstr, sizeof(nstr), "%d-%d-%s", pi->pi_slot,
1057 	            pi->pi_func, vmname);
1058 
1059 		MD5Init(&mdctx);
1060 		MD5Update(&mdctx, nstr, strlen(nstr));
1061 		MD5Final(digest, &mdctx);
1062 
1063 		sc->vsc_config.mac[0] = 0x00;
1064 		sc->vsc_config.mac[1] = 0xa0;
1065 		sc->vsc_config.mac[2] = 0x98;
1066 		sc->vsc_config.mac[3] = digest[0];
1067 		sc->vsc_config.mac[4] = digest[1];
1068 		sc->vsc_config.mac[5] = digest[2];
1069 	}
1070 #endif
1071 
1072 	/* initialize config space */
1073 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
1074 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
1075 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
1076 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
1077 	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
1078 
1079 	/* Link is up if we managed to open tap device or vale port. */
1080 #ifdef	__FreeBSD__
1081 	sc->vsc_config.status = (opts == NULL || sc->vsc_tapfd >= 0 ||
1082 #else
1083 	sc->vsc_config.status = (opts == NULL || sc->vsc_dlpifd >= 0 ||
1084 #endif
1085 	    sc->vsc_nmd != NULL);
1086 
1087 	/* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
1088 	if (vi_intr_init(&sc->vsc_vs, 1, use_msix))
1089 		return (1);
1090 
1091 	/* use BAR 0 to map config regs in IO space */
1092 	vi_set_io_bar(&sc->vsc_vs, 0);
1093 
1094 	sc->resetting = 0;
1095 
1096 	sc->rx_merge = 1;
1097 	sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
1098 	sc->rx_in_progress = 0;
1099 	pthread_mutex_init(&sc->rx_mtx, NULL);
1100 
1101 	/*
1102 	 * Initialize tx semaphore & spawn TX processing thread.
1103 	 * As of now, only one thread for TX desc processing is
1104 	 * spawned.
1105 	 */
1106 	sc->tx_in_progress = 0;
1107 	pthread_mutex_init(&sc->tx_mtx, NULL);
1108 	pthread_cond_init(&sc->tx_cond, NULL);
1109 	pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
1110 	snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
1111 	    pi->pi_func);
1112 	pthread_set_name_np(sc->tx_tid, tname);
1113 
1114 	return (0);
1115 }
1116 
1117 static int
1118 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
1119 {
1120 	struct pci_vtnet_softc *sc = vsc;
1121 	void *ptr;
1122 
1123 	if (offset < 6) {
1124 		assert(offset + size <= 6);
1125 		/*
1126 		 * The driver is allowed to change the MAC address
1127 		 */
1128 		ptr = &sc->vsc_config.mac[offset];
1129 		memcpy(ptr, &value, size);
1130 	} else {
1131 		/* silently ignore other writes */
1132 		DPRINTF(("vtnet: write to readonly reg %d\n\r", offset));
1133 	}
1134 
1135 	return (0);
1136 }
1137 
1138 static int
1139 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
1140 {
1141 	struct pci_vtnet_softc *sc = vsc;
1142 	void *ptr;
1143 
1144 	ptr = (uint8_t *)&sc->vsc_config + offset;
1145 	memcpy(retval, ptr, size);
1146 	return (0);
1147 }
1148 
1149 static void
1150 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
1151 {
1152 	struct pci_vtnet_softc *sc = vsc;
1153 
1154 	sc->vsc_features = negotiated_features;
1155 
1156 	if (!(sc->vsc_features & VIRTIO_NET_F_MRG_RXBUF)) {
1157 		sc->rx_merge = 0;
1158 		/* non-merge rx header is 2 bytes shorter */
1159 		sc->rx_vhdrlen -= 2;
1160 	}
1161 }
1162 
1163 struct pci_devemu pci_de_vnet = {
1164 	.pe_emu = 	"virtio-net",
1165 	.pe_init =	pci_vtnet_init,
1166 	.pe_barwrite =	vi_pci_write,
1167 	.pe_barread =	vi_pci_read
1168 };
1169 PCI_EMUL_SET(pci_de_vnet);
1170