xref: /freebsd/usr.sbin/bhyve/pci_virtio_net.c (revision ec0e626bafb335b30c499d06066997f54b10c092)
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 #include <sys/linker_set.h>
34 #include <sys/select.h>
35 #include <sys/uio.h>
36 #include <sys/ioctl.h>
37 #include <net/ethernet.h>
38 
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <stdint.h>
44 #include <string.h>
45 #include <strings.h>
46 #include <unistd.h>
47 #include <assert.h>
48 #include <md5.h>
49 #include <pthread.h>
50 #include <pthread_np.h>
51 
52 #include "bhyverun.h"
53 #include "pci_emul.h"
54 #include "mevent.h"
55 #include "virtio.h"
56 
57 #define VTNET_RINGSZ	1024
58 
59 #define VTNET_MAXSEGS	32
60 
61 /*
62  * Host capabilities.  Note that we only offer a few of these.
63  */
64 #define	VIRTIO_NET_F_CSUM	(1 <<  0) /* host handles partial cksum */
65 #define	VIRTIO_NET_F_GUEST_CSUM	(1 <<  1) /* guest handles partial cksum */
66 #define	VIRTIO_NET_F_MAC	(1 <<  5) /* host supplies MAC */
67 #define	VIRTIO_NET_F_GSO_DEPREC	(1 <<  6) /* deprecated: host handles GSO */
68 #define	VIRTIO_NET_F_GUEST_TSO4	(1 <<  7) /* guest can rcv TSOv4 */
69 #define	VIRTIO_NET_F_GUEST_TSO6	(1 <<  8) /* guest can rcv TSOv6 */
70 #define	VIRTIO_NET_F_GUEST_ECN	(1 <<  9) /* guest can rcv TSO with ECN */
71 #define	VIRTIO_NET_F_GUEST_UFO	(1 << 10) /* guest can rcv UFO */
72 #define	VIRTIO_NET_F_HOST_TSO4	(1 << 11) /* host can rcv TSOv4 */
73 #define	VIRTIO_NET_F_HOST_TSO6	(1 << 12) /* host can rcv TSOv6 */
74 #define	VIRTIO_NET_F_HOST_ECN	(1 << 13) /* host can rcv TSO with ECN */
75 #define	VIRTIO_NET_F_HOST_UFO	(1 << 14) /* host can rcv UFO */
76 #define	VIRTIO_NET_F_MRG_RXBUF	(1 << 15) /* host can merge RX buffers */
77 #define	VIRTIO_NET_F_STATUS	(1 << 16) /* config status field available */
78 #define	VIRTIO_NET_F_CTRL_VQ	(1 << 17) /* control channel available */
79 #define	VIRTIO_NET_F_CTRL_RX	(1 << 18) /* control channel RX mode support */
80 #define	VIRTIO_NET_F_CTRL_VLAN	(1 << 19) /* control channel VLAN filtering */
81 #define	VIRTIO_NET_F_GUEST_ANNOUNCE \
82 				(1 << 21) /* guest can send gratuitous pkts */
83 
84 #define VTNET_S_HOSTCAPS      \
85   ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_MRG_RXBUF | VIRTIO_NET_F_STATUS | \
86     VIRTIO_F_NOTIFY_ON_EMPTY)
87 
88 /*
89  * PCI config-space "registers"
90  */
91 struct virtio_net_config {
92 	uint8_t  mac[6];
93 	uint16_t status;
94 } __packed;
95 
96 /*
97  * Queue definitions.
98  */
99 #define VTNET_RXQ	0
100 #define VTNET_TXQ	1
101 #define VTNET_CTLQ	2	/* NB: not yet supported */
102 
103 #define VTNET_MAXQ	3
104 
105 /*
106  * Fixed network header size
107  */
108 struct virtio_net_rxhdr {
109 	uint8_t		vrh_flags;
110 	uint8_t		vrh_gso_type;
111 	uint16_t	vrh_hdr_len;
112 	uint16_t	vrh_gso_size;
113 	uint16_t	vrh_csum_start;
114 	uint16_t	vrh_csum_offset;
115 	uint16_t	vrh_bufs;
116 } __packed;
117 
118 /*
119  * Debug printf
120  */
121 static int pci_vtnet_debug;
122 #define DPRINTF(params) if (pci_vtnet_debug) printf params
123 #define WPRINTF(params) printf params
124 
125 /*
126  * Per-device softc
127  */
128 struct pci_vtnet_softc {
129 	struct virtio_softc vsc_vs;
130 	struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
131 	pthread_mutex_t vsc_mtx;
132 	struct mevent	*vsc_mevp;
133 
134 	int		vsc_tapfd;
135 	int		vsc_rx_ready;
136 	volatile int	resetting;	/* set and checked outside lock */
137 
138 	uint64_t	vsc_features;	/* negotiated features */
139 
140 	struct virtio_net_config vsc_config;
141 
142 	pthread_mutex_t	rx_mtx;
143 	int		rx_in_progress;
144 	int		rx_vhdrlen;
145 	int		rx_merge;	/* merged rx bufs in use */
146 
147 	pthread_t 	tx_tid;
148 	pthread_mutex_t	tx_mtx;
149 	pthread_cond_t	tx_cond;
150 	int		tx_in_progress;
151 };
152 
153 static void pci_vtnet_reset(void *);
154 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
155 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
156 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
157 static void pci_vtnet_neg_features(void *, uint64_t);
158 
159 static struct virtio_consts vtnet_vi_consts = {
160 	"vtnet",		/* our name */
161 	VTNET_MAXQ - 1,		/* we currently support 2 virtqueues */
162 	sizeof(struct virtio_net_config), /* config reg size */
163 	pci_vtnet_reset,	/* reset */
164 	NULL,			/* device-wide qnotify -- not used */
165 	pci_vtnet_cfgread,	/* read PCI config */
166 	pci_vtnet_cfgwrite,	/* write PCI config */
167 	pci_vtnet_neg_features,	/* apply negotiated features */
168 	VTNET_S_HOSTCAPS,	/* our capabilities */
169 };
170 
171 /*
172  * If the transmit thread is active then stall until it is done.
173  */
174 static void
175 pci_vtnet_txwait(struct pci_vtnet_softc *sc)
176 {
177 
178 	pthread_mutex_lock(&sc->tx_mtx);
179 	while (sc->tx_in_progress) {
180 		pthread_mutex_unlock(&sc->tx_mtx);
181 		usleep(10000);
182 		pthread_mutex_lock(&sc->tx_mtx);
183 	}
184 	pthread_mutex_unlock(&sc->tx_mtx);
185 }
186 
187 /*
188  * If the receive thread is active then stall until it is done.
189  */
190 static void
191 pci_vtnet_rxwait(struct pci_vtnet_softc *sc)
192 {
193 
194 	pthread_mutex_lock(&sc->rx_mtx);
195 	while (sc->rx_in_progress) {
196 		pthread_mutex_unlock(&sc->rx_mtx);
197 		usleep(10000);
198 		pthread_mutex_lock(&sc->rx_mtx);
199 	}
200 	pthread_mutex_unlock(&sc->rx_mtx);
201 }
202 
203 static void
204 pci_vtnet_reset(void *vsc)
205 {
206 	struct pci_vtnet_softc *sc = vsc;
207 
208 	DPRINTF(("vtnet: device reset requested !\n"));
209 
210 	sc->resetting = 1;
211 
212 	/*
213 	 * Wait for the transmit and receive threads to finish their
214 	 * processing.
215 	 */
216 	pci_vtnet_txwait(sc);
217 	pci_vtnet_rxwait(sc);
218 
219 	sc->vsc_rx_ready = 0;
220 	sc->rx_merge = 1;
221 	sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
222 
223 	/* now reset rings, MSI-X vectors, and negotiated capabilities */
224 	vi_reset_dev(&sc->vsc_vs);
225 
226 	sc->resetting = 0;
227 }
228 
229 /*
230  * Called to send a buffer chain out to the tap device
231  */
232 static void
233 pci_vtnet_tap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
234 		 int len)
235 {
236 	static char pad[60]; /* all zero bytes */
237 
238 	if (sc->vsc_tapfd == -1)
239 		return;
240 
241 	/*
242 	 * If the length is < 60, pad out to that and add the
243 	 * extra zero'd segment to the iov. It is guaranteed that
244 	 * there is always an extra iov available by the caller.
245 	 */
246 	if (len < 60) {
247 		iov[iovcnt].iov_base = pad;
248 		iov[iovcnt].iov_len = 60 - len;
249 		iovcnt++;
250 	}
251 	(void) writev(sc->vsc_tapfd, iov, iovcnt);
252 }
253 
254 /*
255  *  Called when there is read activity on the tap file descriptor.
256  * Each buffer posted by the guest is assumed to be able to contain
257  * an entire ethernet frame + rx header.
258  *  MP note: the dummybuf is only used for discarding frames, so there
259  * is no need for it to be per-vtnet or locked.
260  */
261 static uint8_t dummybuf[2048];
262 
263 static __inline struct iovec *
264 rx_iov_trim(struct iovec *iov, int *niov, int tlen)
265 {
266 	struct iovec *riov;
267 
268 	/* XXX short-cut: assume first segment is >= tlen */
269 	assert(iov[0].iov_len >= tlen);
270 
271 	iov[0].iov_len -= tlen;
272 	if (iov[0].iov_len == 0) {
273 		assert(*niov > 1);
274 		*niov -= 1;
275 		riov = &iov[1];
276 	} else {
277 		iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + tlen);
278 		riov = &iov[0];
279 	}
280 
281 	return (riov);
282 }
283 
284 static void
285 pci_vtnet_tap_rx(struct pci_vtnet_softc *sc)
286 {
287 	struct iovec iov[VTNET_MAXSEGS], *riov;
288 	struct vqueue_info *vq;
289 	void *vrx;
290 	int len, n;
291 	uint16_t idx;
292 
293 	/*
294 	 * Should never be called without a valid tap fd
295 	 */
296 	assert(sc->vsc_tapfd != -1);
297 
298 	/*
299 	 * But, will be called when the rx ring hasn't yet
300 	 * been set up or the guest is resetting the device.
301 	 */
302 	if (!sc->vsc_rx_ready || sc->resetting) {
303 		/*
304 		 * Drop the packet and try later.
305 		 */
306 		(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
307 		return;
308 	}
309 
310 	/*
311 	 * Check for available rx buffers
312 	 */
313 	vq = &sc->vsc_queues[VTNET_RXQ];
314 	if (!vq_has_descs(vq)) {
315 		/*
316 		 * Drop the packet and try later.  Interrupt on
317 		 * empty, if that's negotiated.
318 		 */
319 		(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
320 		vq_endchains(vq, 1);
321 		return;
322 	}
323 
324 	do {
325 		/*
326 		 * Get descriptor chain.
327 		 */
328 		n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
329 		assert(n >= 1 && n <= VTNET_MAXSEGS);
330 
331 		/*
332 		 * Get a pointer to the rx header, and use the
333 		 * data immediately following it for the packet buffer.
334 		 */
335 		vrx = iov[0].iov_base;
336 		riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
337 
338 		len = readv(sc->vsc_tapfd, riov, n);
339 
340 		if (len < 0 && errno == EWOULDBLOCK) {
341 			/*
342 			 * No more packets, but still some avail ring
343 			 * entries.  Interrupt if needed/appropriate.
344 			 */
345 			vq_retchain(vq);
346 			vq_endchains(vq, 0);
347 			return;
348 		}
349 
350 		/*
351 		 * The only valid field in the rx packet header is the
352 		 * number of buffers if merged rx bufs were negotiated.
353 		 */
354 		memset(vrx, 0, sc->rx_vhdrlen);
355 
356 		if (sc->rx_merge) {
357 			struct virtio_net_rxhdr *vrxh;
358 
359 			vrxh = vrx;
360 			vrxh->vrh_bufs = 1;
361 		}
362 
363 		/*
364 		 * Release this chain and handle more chains.
365 		 */
366 		vq_relchain(vq, idx, len + sc->rx_vhdrlen);
367 	} while (vq_has_descs(vq));
368 
369 	/* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
370 	vq_endchains(vq, 1);
371 }
372 
373 static void
374 pci_vtnet_tap_callback(int fd, enum ev_type type, void *param)
375 {
376 	struct pci_vtnet_softc *sc = param;
377 
378 	pthread_mutex_lock(&sc->rx_mtx);
379 	sc->rx_in_progress = 1;
380 	pci_vtnet_tap_rx(sc);
381 	sc->rx_in_progress = 0;
382 	pthread_mutex_unlock(&sc->rx_mtx);
383 
384 }
385 
386 static void
387 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
388 {
389 	struct pci_vtnet_softc *sc = vsc;
390 
391 	/*
392 	 * A qnotify means that the rx process can now begin
393 	 */
394 	if (sc->vsc_rx_ready == 0) {
395 		sc->vsc_rx_ready = 1;
396 	}
397 }
398 
399 static void
400 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
401 {
402 	struct iovec iov[VTNET_MAXSEGS + 1];
403 	int i, n;
404 	int plen, tlen;
405 	uint16_t idx;
406 
407 	/*
408 	 * Obtain chain of descriptors.  The first one is
409 	 * really the header descriptor, so we need to sum
410 	 * up two lengths: packet length and transfer length.
411 	 */
412 	n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
413 	assert(n >= 1 && n <= VTNET_MAXSEGS);
414 	plen = 0;
415 	tlen = iov[0].iov_len;
416 	for (i = 1; i < n; i++) {
417 		plen += iov[i].iov_len;
418 		tlen += iov[i].iov_len;
419 	}
420 
421 	DPRINTF(("virtio: packet send, %d bytes, %d segs\n\r", plen, n));
422 	pci_vtnet_tap_tx(sc, &iov[1], n - 1, plen);
423 
424 	/* chain is processed, release it and set tlen */
425 	vq_relchain(vq, idx, tlen);
426 }
427 
428 static void
429 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
430 {
431 	struct pci_vtnet_softc *sc = vsc;
432 
433 	/*
434 	 * Any ring entries to process?
435 	 */
436 	if (!vq_has_descs(vq))
437 		return;
438 
439 	/* Signal the tx thread for processing */
440 	pthread_mutex_lock(&sc->tx_mtx);
441 	if (sc->tx_in_progress == 0)
442 		pthread_cond_signal(&sc->tx_cond);
443 	pthread_mutex_unlock(&sc->tx_mtx);
444 }
445 
446 /*
447  * Thread which will handle processing of TX desc
448  */
449 static void *
450 pci_vtnet_tx_thread(void *param)
451 {
452 	struct pci_vtnet_softc *sc = param;
453 	struct vqueue_info *vq;
454 	int have_work, error;
455 
456 	vq = &sc->vsc_queues[VTNET_TXQ];
457 
458 	/*
459 	 * Let us wait till the tx queue pointers get initialised &
460 	 * first tx signaled
461 	 */
462 	pthread_mutex_lock(&sc->tx_mtx);
463 	error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
464 	assert(error == 0);
465 
466 	for (;;) {
467 		/* note - tx mutex is locked here */
468 		do {
469 			if (sc->resetting)
470 				have_work = 0;
471 			else
472 				have_work = vq_has_descs(vq);
473 
474 			if (!have_work) {
475 				sc->tx_in_progress = 0;
476 				error = pthread_cond_wait(&sc->tx_cond,
477 							  &sc->tx_mtx);
478 				assert(error == 0);
479 			}
480 		} while (!have_work);
481 		sc->tx_in_progress = 1;
482 		pthread_mutex_unlock(&sc->tx_mtx);
483 
484 		do {
485 			/*
486 			 * Run through entries, placing them into
487 			 * iovecs and sending when an end-of-packet
488 			 * is found
489 			 */
490 			pci_vtnet_proctx(sc, vq);
491 		} while (vq_has_descs(vq));
492 
493 		/*
494 		 * Generate an interrupt if needed.
495 		 */
496 		vq_endchains(vq, 1);
497 
498 		pthread_mutex_lock(&sc->tx_mtx);
499 	}
500 }
501 
502 #ifdef notyet
503 static void
504 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
505 {
506 
507 	DPRINTF(("vtnet: control qnotify!\n\r"));
508 }
509 #endif
510 
511 static int
512 pci_vtnet_parsemac(char *mac_str, uint8_t *mac_addr)
513 {
514         struct ether_addr *ea;
515         char *tmpstr;
516         char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
517 
518         tmpstr = strsep(&mac_str,"=");
519 
520         if ((mac_str != NULL) && (!strcmp(tmpstr,"mac"))) {
521                 ea = ether_aton(mac_str);
522 
523                 if (ea == NULL || ETHER_IS_MULTICAST(ea->octet) ||
524                     memcmp(ea->octet, zero_addr, ETHER_ADDR_LEN) == 0) {
525 			fprintf(stderr, "Invalid MAC %s\n", mac_str);
526                         return (EINVAL);
527                 } else
528                         memcpy(mac_addr, ea->octet, ETHER_ADDR_LEN);
529         }
530 
531         return (0);
532 }
533 
534 
535 static int
536 pci_vtnet_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
537 {
538 	MD5_CTX mdctx;
539 	unsigned char digest[16];
540 	char nstr[80];
541 	char tname[MAXCOMLEN + 1];
542 	struct pci_vtnet_softc *sc;
543 	char *devname;
544 	char *vtopts;
545 	int mac_provided;
546 
547 	sc = calloc(1, sizeof(struct pci_vtnet_softc));
548 
549 	pthread_mutex_init(&sc->vsc_mtx, NULL);
550 
551 	vi_softc_linkup(&sc->vsc_vs, &vtnet_vi_consts, sc, pi, sc->vsc_queues);
552 	sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
553 
554 	sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
555 	sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
556 	sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
557 	sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
558 #ifdef notyet
559 	sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
560         sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
561 #endif
562 
563 	/*
564 	 * Attempt to open the tap device and read the MAC address
565 	 * if specified
566 	 */
567 	mac_provided = 0;
568 	sc->vsc_tapfd = -1;
569 	if (opts != NULL) {
570 		char tbuf[80];
571 		int err;
572 
573 		devname = vtopts = strdup(opts);
574 		(void) strsep(&vtopts, ",");
575 
576 		if (vtopts != NULL) {
577 			err = pci_vtnet_parsemac(vtopts, sc->vsc_config.mac);
578 			if (err != 0) {
579 				free(devname);
580 				return (err);
581 			}
582 			mac_provided = 1;
583 		}
584 
585 		strcpy(tbuf, "/dev/");
586 		strlcat(tbuf, devname, sizeof(tbuf));
587 
588 		free(devname);
589 
590 		sc->vsc_tapfd = open(tbuf, O_RDWR);
591 		if (sc->vsc_tapfd == -1) {
592 			WPRINTF(("open of tap device %s failed\n", tbuf));
593 		} else {
594 			/*
595 			 * Set non-blocking and register for read
596 			 * notifications with the event loop
597 			 */
598 			int opt = 1;
599 			if (ioctl(sc->vsc_tapfd, FIONBIO, &opt) < 0) {
600 				WPRINTF(("tap device O_NONBLOCK failed\n"));
601 				close(sc->vsc_tapfd);
602 				sc->vsc_tapfd = -1;
603 			}
604 
605 			sc->vsc_mevp = mevent_add(sc->vsc_tapfd,
606 						  EVF_READ,
607 						  pci_vtnet_tap_callback,
608 						  sc);
609 			if (sc->vsc_mevp == NULL) {
610 				WPRINTF(("Could not register event\n"));
611 				close(sc->vsc_tapfd);
612 				sc->vsc_tapfd = -1;
613 			}
614 		}
615 	}
616 
617 	/*
618 	 * The default MAC address is the standard NetApp OUI of 00-a0-98,
619 	 * followed by an MD5 of the PCI slot/func number and dev name
620 	 */
621 	if (!mac_provided) {
622 		snprintf(nstr, sizeof(nstr), "%d-%d-%s", pi->pi_slot,
623 		    pi->pi_func, vmname);
624 
625 		MD5Init(&mdctx);
626 		MD5Update(&mdctx, nstr, strlen(nstr));
627 		MD5Final(digest, &mdctx);
628 
629 		sc->vsc_config.mac[0] = 0x00;
630 		sc->vsc_config.mac[1] = 0xa0;
631 		sc->vsc_config.mac[2] = 0x98;
632 		sc->vsc_config.mac[3] = digest[0];
633 		sc->vsc_config.mac[4] = digest[1];
634 		sc->vsc_config.mac[5] = digest[2];
635 	}
636 
637 	/* initialize config space */
638 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
639 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
640 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
641 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
642 
643 	pci_lintr_request(pi);
644 
645 	/* link always up */
646 	sc->vsc_config.status = 1;
647 
648 	/* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
649 	if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix()))
650 		return (1);
651 
652 	/* use BAR 0 to map config regs in IO space */
653 	vi_set_io_bar(&sc->vsc_vs, 0);
654 
655 	sc->resetting = 0;
656 
657 	sc->rx_merge = 1;
658 	sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
659 	sc->rx_in_progress = 0;
660 	pthread_mutex_init(&sc->rx_mtx, NULL);
661 
662 	/*
663 	 * Initialize tx semaphore & spawn TX processing thread.
664 	 * As of now, only one thread for TX desc processing is
665 	 * spawned.
666 	 */
667 	sc->tx_in_progress = 0;
668 	pthread_mutex_init(&sc->tx_mtx, NULL);
669 	pthread_cond_init(&sc->tx_cond, NULL);
670 	pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
671 	snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
672 	    pi->pi_func);
673         pthread_set_name_np(sc->tx_tid, tname);
674 
675 	return (0);
676 }
677 
678 static int
679 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
680 {
681 	struct pci_vtnet_softc *sc = vsc;
682 	void *ptr;
683 
684 	if (offset < 6) {
685 		assert(offset + size <= 6);
686 		/*
687 		 * The driver is allowed to change the MAC address
688 		 */
689 		ptr = &sc->vsc_config.mac[offset];
690 		memcpy(ptr, &value, size);
691 	} else {
692 		/* silently ignore other writes */
693 		DPRINTF(("vtnet: write to readonly reg %d\n\r", offset));
694 	}
695 
696 	return (0);
697 }
698 
699 static int
700 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
701 {
702 	struct pci_vtnet_softc *sc = vsc;
703 	void *ptr;
704 
705 	ptr = (uint8_t *)&sc->vsc_config + offset;
706 	memcpy(retval, ptr, size);
707 	return (0);
708 }
709 
710 static void
711 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
712 {
713 	struct pci_vtnet_softc *sc = vsc;
714 
715 	sc->vsc_features = negotiated_features;
716 
717 	if (!(sc->vsc_features & VIRTIO_NET_F_MRG_RXBUF)) {
718 		sc->rx_merge = 0;
719 		/* non-merge rx header is 2 bytes shorter */
720 		sc->rx_vhdrlen -= 2;
721 	}
722 }
723 
724 struct pci_devemu pci_de_vnet = {
725 	.pe_emu = 	"virtio-net",
726 	.pe_init =	pci_vtnet_init,
727 	.pe_barwrite =	vi_pci_write,
728 	.pe_barread =	vi_pci_read
729 };
730 PCI_EMUL_SET(pci_de_vnet);
731