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