xref: /illumos-gate/usr/src/cmd/bhyve/pci_virtio_net.c (revision f37b3cbb6f67aaea5eec1c335bdc7bf432867d64)
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 #include <sys/linker_set.h>
36 #include <sys/select.h>
37 #include <sys/uio.h>
38 #include <sys/ioctl.h>
39 #include <net/ethernet.h>
40 #include <net/if.h> /* IFNAMSIZ */
41 
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <stdint.h>
48 #include <string.h>
49 #include <strings.h>
50 #include <unistd.h>
51 #include <assert.h>
52 #include <pthread.h>
53 #include <pthread_np.h>
54 
55 #include "bhyverun.h"
56 #include "config.h"
57 #include "debug.h"
58 #include "pci_emul.h"
59 #include "mevent.h"
60 #include "virtio.h"
61 #include "net_utils.h"
62 #include "net_backends.h"
63 #include "iov.h"
64 
65 #define VTNET_RINGSZ	1024
66 
67 #define VTNET_MAXSEGS	256
68 
69 #define VTNET_MAX_PKT_LEN	(65536 + 64)
70 
71 #define VTNET_MIN_MTU	ETHERMIN
72 #define VTNET_MAX_MTU	65535
73 
74 #define VTNET_S_HOSTCAPS      \
75   ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_STATUS | \
76     VIRTIO_F_NOTIFY_ON_EMPTY | VIRTIO_RING_F_INDIRECT_DESC)
77 
78 /*
79  * PCI config-space "registers"
80  */
81 struct virtio_net_config {
82 	uint8_t  mac[6];
83 	uint16_t status;
84 	uint16_t max_virtqueue_pairs;
85 	uint16_t mtu;
86 } __packed;
87 
88 /*
89  * Queue definitions.
90  */
91 #define VTNET_RXQ	0
92 #define VTNET_TXQ	1
93 #define VTNET_CTLQ	2	/* NB: not yet supported */
94 
95 #define VTNET_MAXQ	3
96 
97 /*
98  * Debug printf
99  */
100 static int pci_vtnet_debug;
101 #define DPRINTF(params) if (pci_vtnet_debug) PRINTLN params
102 #define WPRINTF(params) PRINTLN params
103 
104 /*
105  * Per-device softc
106  */
107 struct pci_vtnet_softc {
108 	struct virtio_softc vsc_vs;
109 	struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
110 	pthread_mutex_t vsc_mtx;
111 
112 	net_backend_t	*vsc_be;
113 
114 	bool    features_negotiated;	/* protected by rx_mtx */
115 
116 	int		resetting;	/* protected by tx_mtx */
117 
118 	uint64_t	vsc_features;	/* negotiated features */
119 
120 	pthread_mutex_t	rx_mtx;
121 	int		rx_merge;	/* merged rx bufs in use */
122 
123 	pthread_t 	tx_tid;
124 	pthread_mutex_t	tx_mtx;
125 	pthread_cond_t	tx_cond;
126 	int		tx_in_progress;
127 
128 	size_t		vhdrlen;
129 	size_t		be_vhdrlen;
130 
131 	struct virtio_net_config vsc_config;
132 	struct virtio_consts vsc_consts;
133 };
134 
135 static void pci_vtnet_reset(void *);
136 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
137 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
138 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
139 static void pci_vtnet_neg_features(void *, uint64_t);
140 
141 static struct virtio_consts vtnet_vi_consts = {
142 	.vc_name =	"vtnet",
143 	.vc_nvq =	VTNET_MAXQ - 1,
144 	.vc_cfgsize =	sizeof(struct virtio_net_config),
145 	.vc_reset =	pci_vtnet_reset,
146 	.vc_cfgread =	pci_vtnet_cfgread,
147 	.vc_cfgwrite =	pci_vtnet_cfgwrite,
148 	.vc_apply_features = pci_vtnet_neg_features,
149 	.vc_hv_caps =	VTNET_S_HOSTCAPS,
150 };
151 
152 static void
153 pci_vtnet_reset(void *vsc)
154 {
155 	struct pci_vtnet_softc *sc = vsc;
156 
157 	DPRINTF(("vtnet: device reset requested !"));
158 
159 	/* Acquire the RX lock to block RX processing. */
160 	pthread_mutex_lock(&sc->rx_mtx);
161 
162 	/*
163 	 * Make sure receive operation is disabled at least until we
164 	 * re-negotiate the features, since receive operation depends
165 	 * on the value of sc->rx_merge and the header length, which
166 	 * are both set in pci_vtnet_neg_features().
167 	 * Receive operation will be enabled again once the guest adds
168 	 * the first receive buffers and kicks us.
169 	 */
170 	sc->features_negotiated = false;
171 	netbe_rx_disable(sc->vsc_be);
172 
173 	/* Set sc->resetting and give a chance to the TX thread to stop. */
174 	pthread_mutex_lock(&sc->tx_mtx);
175 	sc->resetting = 1;
176 	while (sc->tx_in_progress) {
177 		pthread_mutex_unlock(&sc->tx_mtx);
178 		usleep(10000);
179 		pthread_mutex_lock(&sc->tx_mtx);
180 	}
181 
182 	/*
183 	 * Now reset rings, MSI-X vectors, and negotiated capabilities.
184 	 * Do that with the TX lock held, since we need to reset
185 	 * sc->resetting.
186 	 */
187 	vi_reset_dev(&sc->vsc_vs);
188 
189 	sc->resetting = 0;
190 	pthread_mutex_unlock(&sc->tx_mtx);
191 	pthread_mutex_unlock(&sc->rx_mtx);
192 }
193 
194 static __inline struct iovec *
195 iov_trim_hdr(struct iovec *iov, int *iovcnt, unsigned int hlen)
196 {
197 	struct iovec *riov;
198 
199 	if (iov[0].iov_len < hlen) {
200 		/*
201 		 * Not enough header space in the first fragment.
202 		 * That's not ok for us.
203 		 */
204 		return NULL;
205 	}
206 
207 	iov[0].iov_len -= hlen;
208 	if (iov[0].iov_len == 0) {
209 		*iovcnt -= 1;
210 		if (*iovcnt == 0) {
211 			/*
212 			 * Only space for the header. That's not
213 			 * enough for us.
214 			 */
215 			return NULL;
216 		}
217 		riov = &iov[1];
218 	} else {
219 		iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + hlen);
220 		riov = &iov[0];
221 	}
222 
223 	return (riov);
224 }
225 
226 struct virtio_mrg_rxbuf_info {
227 	uint16_t idx;
228 	uint16_t pad;
229 	uint32_t len;
230 };
231 
232 static void
233 pci_vtnet_rx(struct pci_vtnet_softc *sc)
234 {
235 	int prepend_hdr_len = sc->vhdrlen - sc->be_vhdrlen;
236 	struct virtio_mrg_rxbuf_info info[VTNET_MAXSEGS];
237 	struct iovec iov[VTNET_MAXSEGS + 1];
238 	struct vqueue_info *vq;
239 	struct vi_req req;
240 
241 	vq = &sc->vsc_queues[VTNET_RXQ];
242 
243 	/* Features must be negotiated */
244 	if (!sc->features_negotiated) {
245 		return;
246 	}
247 
248 	for (;;) {
249 		struct virtio_net_rxhdr *hdr;
250 		uint32_t riov_bytes;
251 		struct iovec *riov;
252 		uint32_t ulen;
253 		int riov_len;
254 		int n_chains;
255 		ssize_t rlen;
256 		ssize_t plen;
257 
258 		plen = netbe_peek_recvlen(sc->vsc_be);
259 		if (plen <= 0) {
260 			/*
261 			 * No more packets (plen == 0), or backend errored
262 			 * (plen < 0). Interrupt if needed and stop.
263 			 */
264 			vq_endchains(vq, /*used_all_avail=*/0);
265 			return;
266 		}
267 		plen += prepend_hdr_len;
268 
269 		/*
270 		 * Get a descriptor chain to store the next ingress
271 		 * packet. In case of mergeable rx buffers, get as
272 		 * many chains as necessary in order to make room
273 		 * for plen bytes.
274 		 */
275 		riov_bytes = 0;
276 		riov_len = 0;
277 		riov = iov;
278 		n_chains = 0;
279 		do {
280 			int n = vq_getchain(vq, riov, VTNET_MAXSEGS - riov_len,
281 			    &req);
282 			info[n_chains].idx = req.idx;
283 
284 			if (n == 0) {
285 				/*
286 				 * No rx buffers. Enable RX kicks and double
287 				 * check.
288 				 */
289 				vq_kick_enable(vq);
290 				if (!vq_has_descs(vq)) {
291 					/*
292 					 * Still no buffers. Return the unused
293 					 * chains (if any), interrupt if needed
294 					 * (including for NOTIFY_ON_EMPTY), and
295 					 * disable the backend until the next
296 					 * kick.
297 					 */
298 					vq_retchains(vq, n_chains);
299 					vq_endchains(vq, /*used_all_avail=*/1);
300 					netbe_rx_disable(sc->vsc_be);
301 					return;
302 				}
303 
304 				/* More rx buffers found, so keep going. */
305 				vq_kick_disable(vq);
306 				continue;
307 			}
308 #ifndef __FreeBSD__
309 			if (n == -1) {
310 				/*
311 				 * An error from vq_getchain() means that
312 				 * an invalid descriptor was found.
313 				 */
314 				vq_retchains(vq, n_chains);
315 				vq_endchains(vq, /*used_all_avail=*/0);
316 				return;
317 			}
318 #endif
319 			assert(n >= 1 && riov_len + n <= VTNET_MAXSEGS);
320 			riov_len += n;
321 			if (!sc->rx_merge) {
322 				n_chains = 1;
323 				break;
324 			}
325 #ifndef __FreeBSD__
326 			size_t c = count_iov(riov, n);
327 			if (c > UINT32_MAX) {
328 				vq_retchains(vq, n_chains);
329 				vq_endchains(vq, /*used_all_avail=*/0);
330 				return;
331 			}
332 			info[n_chains].len = (uint32_t)c;
333 #else
334 			info[n_chains].len = (uint32_t)count_iov(riov, n);
335 #endif
336 			riov_bytes += info[n_chains].len;
337 			riov += n;
338 			n_chains++;
339 		} while (riov_bytes < plen && riov_len < VTNET_MAXSEGS);
340 
341 		riov = iov;
342 #ifdef __FreeBSD__
343 		hdr = riov[0].iov_base;
344 #else
345 		hdr = (struct virtio_net_rxhdr *)riov[0].iov_base;
346 #endif
347 		if (prepend_hdr_len > 0) {
348 			/*
349 			 * The frontend uses a virtio-net header, but the
350 			 * backend does not. We need to prepend a zeroed
351 			 * header.
352 			 */
353 			riov = iov_trim_hdr(riov, &riov_len, prepend_hdr_len);
354 			if (riov == NULL) {
355 				/*
356 				 * The first collected chain is nonsensical,
357 				 * as it is not even enough to store the
358 				 * virtio-net header. Just drop it.
359 				 */
360 				vq_relchain(vq, info[0].idx, 0);
361 				vq_retchains(vq, n_chains - 1);
362 				continue;
363 			}
364 			memset(hdr, 0, prepend_hdr_len);
365 		}
366 
367 		rlen = netbe_recv(sc->vsc_be, riov, riov_len);
368 		if (rlen != plen - prepend_hdr_len) {
369 			/*
370 			 * If this happens it means there is something
371 			 * wrong with the backend (e.g., some other
372 			 * process is stealing our packets).
373 			 */
374 			WPRINTF(("netbe_recv: expected %zd bytes, "
375 				"got %zd", plen - prepend_hdr_len, rlen));
376 			vq_retchains(vq, n_chains);
377 			continue;
378 		}
379 
380 		ulen = (uint32_t)plen;
381 
382 		/*
383 		 * Publish the used buffers to the guest, reporting the
384 		 * number of bytes that we wrote.
385 		 */
386 		if (!sc->rx_merge) {
387 			vq_relchain(vq, info[0].idx, ulen);
388 		} else {
389 			uint32_t iolen;
390 			int i = 0;
391 
392 			do {
393 				iolen = info[i].len;
394 				if (iolen > ulen) {
395 					iolen = ulen;
396 				}
397 				vq_relchain_prepare(vq, info[i].idx, iolen);
398 				ulen -= iolen;
399 				i++;
400 			} while (ulen > 0);
401 
402 			hdr->vrh_bufs = i;
403 			vq_relchain_publish(vq);
404 			assert(i == n_chains);
405 		}
406 	}
407 
408 }
409 
410 /*
411  * Called when there is read activity on the backend file descriptor.
412  * Each buffer posted by the guest is assumed to be able to contain
413  * an entire ethernet frame + rx header.
414  */
415 static void
416 pci_vtnet_rx_callback(int fd __unused, enum ev_type type __unused, void *param)
417 {
418 	struct pci_vtnet_softc *sc = param;
419 
420 	pthread_mutex_lock(&sc->rx_mtx);
421 	pci_vtnet_rx(sc);
422 	pthread_mutex_unlock(&sc->rx_mtx);
423 
424 }
425 
426 /* Called on RX kick. */
427 static void
428 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
429 {
430 	struct pci_vtnet_softc *sc = vsc;
431 
432 	/*
433 	 * A qnotify means that the rx process can now begin.
434 	 * Enable RX only if features are negotiated.
435 	 */
436 	pthread_mutex_lock(&sc->rx_mtx);
437 	if (!sc->features_negotiated) {
438 		pthread_mutex_unlock(&sc->rx_mtx);
439 		return;
440 	}
441 
442 	vq_kick_disable(vq);
443 	netbe_rx_enable(sc->vsc_be);
444 	pthread_mutex_unlock(&sc->rx_mtx);
445 }
446 
447 /* TX virtqueue processing, called by the TX thread. */
448 static void
449 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
450 {
451 	struct iovec iov[VTNET_MAXSEGS + 1];
452 	struct iovec *siov = iov;
453 	struct vi_req req;
454 	ssize_t len;
455 	int n;
456 
457 	/*
458 	 * Obtain chain of descriptors. The first descriptor also
459 	 * contains the virtio-net header.
460 	 */
461 	n = vq_getchain(vq, iov, VTNET_MAXSEGS, &req);
462 	assert(n >= 1 && n <= VTNET_MAXSEGS);
463 
464 	if (sc->vhdrlen != sc->be_vhdrlen) {
465 		/*
466 		 * The frontend uses a virtio-net header, but the backend
467 		 * does not. We simply strip the header and ignore it, as
468 		 * it should be zero-filled.
469 		 */
470 		siov = iov_trim_hdr(siov, &n, sc->vhdrlen);
471 	}
472 
473 	if (siov == NULL) {
474 		/* The chain is nonsensical. Just drop it. */
475 		len = 0;
476 	} else {
477 		len = netbe_send(sc->vsc_be, siov, n);
478 		if (len < 0) {
479 			/*
480 			 * If send failed, report that 0 bytes
481 			 * were read.
482 			 */
483 			len = 0;
484 		}
485 	}
486 
487 	/*
488 	 * Return the processed chain to the guest, reporting
489 	 * the number of bytes that we read.
490 	 */
491 	vq_relchain(vq, req.idx, len);
492 }
493 
494 /* Called on TX kick. */
495 static void
496 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
497 {
498 	struct pci_vtnet_softc *sc = vsc;
499 
500 	/*
501 	 * Any ring entries to process?
502 	 */
503 	if (!vq_has_descs(vq))
504 		return;
505 
506 	/* Signal the tx thread for processing */
507 	pthread_mutex_lock(&sc->tx_mtx);
508 	vq_kick_disable(vq);
509 	if (sc->tx_in_progress == 0)
510 		pthread_cond_signal(&sc->tx_cond);
511 	pthread_mutex_unlock(&sc->tx_mtx);
512 }
513 
514 /*
515  * Thread which will handle processing of TX desc
516  */
517 static void *
518 pci_vtnet_tx_thread(void *param)
519 {
520 	struct pci_vtnet_softc *sc = param;
521 	struct vqueue_info *vq;
522 	int error;
523 
524 	vq = &sc->vsc_queues[VTNET_TXQ];
525 
526 	/*
527 	 * Let us wait till the tx queue pointers get initialised &
528 	 * first tx signaled
529 	 */
530 	pthread_mutex_lock(&sc->tx_mtx);
531 	error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
532 	assert(error == 0);
533 
534 	for (;;) {
535 		/* note - tx mutex is locked here */
536 		while (sc->resetting || !vq_has_descs(vq)) {
537 			vq_kick_enable(vq);
538 			if (!sc->resetting && vq_has_descs(vq))
539 				break;
540 
541 			sc->tx_in_progress = 0;
542 			error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
543 			assert(error == 0);
544 		}
545 		vq_kick_disable(vq);
546 		sc->tx_in_progress = 1;
547 		pthread_mutex_unlock(&sc->tx_mtx);
548 
549 		do {
550 			/*
551 			 * Run through entries, placing them into
552 			 * iovecs and sending when an end-of-packet
553 			 * is found
554 			 */
555 			pci_vtnet_proctx(sc, vq);
556 		} while (vq_has_descs(vq));
557 
558 		/*
559 		 * Generate an interrupt if needed.
560 		 */
561 		vq_endchains(vq, /*used_all_avail=*/1);
562 
563 		pthread_mutex_lock(&sc->tx_mtx);
564 	}
565 #ifndef __FreeBSD__
566 	return (NULL);
567 #endif
568 }
569 
570 #ifdef notyet
571 static void
572 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
573 {
574 
575 	DPRINTF(("vtnet: control qnotify!"));
576 }
577 #endif
578 
579 static int
580 pci_vtnet_init(struct vmctx *ctx __unused, struct pci_devinst *pi,
581     nvlist_t *nvl)
582 {
583 	struct pci_vtnet_softc *sc;
584 	const char *value;
585 	char tname[MAXCOMLEN + 1];
586 	unsigned long mtu = ETHERMTU;
587 	int err;
588 
589 	/*
590 	 * Allocate data structures for further virtio initializations.
591 	 * sc also contains a copy of vtnet_vi_consts, since capabilities
592 	 * change depending on the backend.
593 	 */
594 	sc = calloc(1, sizeof(struct pci_vtnet_softc));
595 
596 	sc->vsc_consts = vtnet_vi_consts;
597 	pthread_mutex_init(&sc->vsc_mtx, NULL);
598 
599 	sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
600 	sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
601 	sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
602 	sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
603 #ifdef notyet
604 	sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
605         sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
606 #endif
607 
608 	value = get_config_value_node(nvl, "mac");
609 	if (value != NULL) {
610 		err = net_parsemac(value, sc->vsc_config.mac);
611 		if (err) {
612 			free(sc);
613 			return (err);
614 		}
615 	} else
616 		net_genmac(pi, sc->vsc_config.mac);
617 
618 	value = get_config_value_node(nvl, "mtu");
619 	if (value != NULL) {
620 		err = net_parsemtu(value, &mtu);
621 		if (err) {
622 			free(sc);
623 			return (err);
624 		}
625 
626 		if (mtu < VTNET_MIN_MTU || mtu > VTNET_MAX_MTU) {
627 			err = EINVAL;
628 			errno = EINVAL;
629 			free(sc);
630 			return (err);
631 		}
632 		sc->vsc_consts.vc_hv_caps |= VIRTIO_NET_F_MTU;
633 	}
634 	sc->vsc_config.mtu = mtu;
635 
636 	/* Permit interfaces without a configured backend. */
637 	if (get_config_value_node(nvl, "backend") != NULL) {
638 		err = netbe_init(&sc->vsc_be, nvl, pci_vtnet_rx_callback, sc);
639 		if (err) {
640 			free(sc);
641 			return (err);
642 		}
643 #ifndef __FreeBSD__
644 		size_t buflen = sizeof (sc->vsc_config.mac);
645 
646 		err = netbe_get_mac(sc->vsc_be, sc->vsc_config.mac, &buflen);
647 		if (err != 0) {
648 		       free(sc);
649 		       return (err);
650 		}
651 #endif
652 	}
653 
654 	sc->vsc_consts.vc_hv_caps |= VIRTIO_NET_F_MRG_RXBUF |
655 	    netbe_get_cap(sc->vsc_be);
656 
657 	/*
658 	 * Since we do not actually support multiqueue,
659 	 * set the maximum virtqueue pairs to 1.
660 	 */
661 	sc->vsc_config.max_virtqueue_pairs = 1;
662 
663 	/* initialize config space */
664 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
665 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
666 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
667 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_ID_NETWORK);
668 	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
669 
670 	/* Link is always up. */
671 	sc->vsc_config.status = 1;
672 
673 	vi_softc_linkup(&sc->vsc_vs, &sc->vsc_consts, sc, pi, sc->vsc_queues);
674 	sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
675 
676 	/* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
677 	if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix())) {
678 		free(sc);
679 		return (1);
680 	}
681 
682 	/* use BAR 0 to map config regs in IO space */
683 	vi_set_io_bar(&sc->vsc_vs, 0);
684 
685 	sc->resetting = 0;
686 
687 	sc->rx_merge = 0;
688 	sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
689 	pthread_mutex_init(&sc->rx_mtx, NULL);
690 
691 	/*
692 	 * Initialize tx semaphore & spawn TX processing thread.
693 	 * As of now, only one thread for TX desc processing is
694 	 * spawned.
695 	 */
696 	sc->tx_in_progress = 0;
697 	pthread_mutex_init(&sc->tx_mtx, NULL);
698 	pthread_cond_init(&sc->tx_cond, NULL);
699 	pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
700 	snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
701 	    pi->pi_func);
702 	pthread_set_name_np(sc->tx_tid, tname);
703 
704 	return (0);
705 }
706 
707 static int
708 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
709 {
710 	struct pci_vtnet_softc *sc = vsc;
711 	void *ptr;
712 
713 	if (offset < (int)sizeof(sc->vsc_config.mac)) {
714 		assert(offset + size <= (int)sizeof(sc->vsc_config.mac));
715 		/*
716 		 * The driver is allowed to change the MAC address
717 		 */
718 		ptr = &sc->vsc_config.mac[offset];
719 		memcpy(ptr, &value, size);
720 	} else {
721 		/* silently ignore other writes */
722 		DPRINTF(("vtnet: write to readonly reg %d", offset));
723 	}
724 
725 	return (0);
726 }
727 
728 static int
729 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
730 {
731 	struct pci_vtnet_softc *sc = vsc;
732 	void *ptr;
733 
734 	ptr = (uint8_t *)&sc->vsc_config + offset;
735 	memcpy(retval, ptr, size);
736 	return (0);
737 }
738 
739 static void
740 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
741 {
742 	struct pci_vtnet_softc *sc = vsc;
743 
744 	sc->vsc_features = negotiated_features;
745 
746 	if (negotiated_features & VIRTIO_NET_F_MRG_RXBUF) {
747 		sc->vhdrlen = sizeof(struct virtio_net_rxhdr);
748 		sc->rx_merge = 1;
749 	} else {
750 		/*
751 		 * Without mergeable rx buffers, virtio-net header is 2
752 		 * bytes shorter than sizeof(struct virtio_net_rxhdr).
753 		 */
754 		sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
755 		sc->rx_merge = 0;
756 	}
757 
758 	/* Tell the backend to enable some capabilities it has advertised. */
759 	netbe_set_cap(sc->vsc_be, negotiated_features, sc->vhdrlen);
760 	sc->be_vhdrlen = netbe_get_vnet_hdr_len(sc->vsc_be);
761 	assert(sc->be_vhdrlen == 0 || sc->be_vhdrlen == sc->vhdrlen);
762 
763 	pthread_mutex_lock(&sc->rx_mtx);
764 	sc->features_negotiated = true;
765 	pthread_mutex_unlock(&sc->rx_mtx);
766 }
767 
768 static const struct pci_devemu pci_de_vnet = {
769 	.pe_emu = 	"virtio-net",
770 	.pe_init =	pci_vtnet_init,
771 	.pe_legacy_config = netbe_legacy_config,
772 	.pe_barwrite =	vi_pci_write,
773 	.pe_barread =	vi_pci_read,
774 };
775 PCI_EMUL_SET(pci_de_vnet);
776