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