xref: /freebsd/usr.sbin/bhyve/pci_e82545.c (revision b9f654b163bce26de79705e77b872427c9f2afa1)
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2016 Alexander Motin <mav@FreeBSD.org>
5  * Copyright (c) 2015 Peter Grehan <grehan@freebsd.org>
6  * Copyright (c) 2013 Jeremiah Lott, Avere Systems
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer
14  *    in this position and unchanged.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/types.h>
36 #ifndef WITHOUT_CAPSICUM
37 #include <sys/capsicum.h>
38 #endif
39 #include <sys/limits.h>
40 #include <sys/ioctl.h>
41 #include <sys/uio.h>
42 #include <net/ethernet.h>
43 #include <netinet/in.h>
44 #include <netinet/tcp.h>
45 
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
48 #endif
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <md5.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <sysexits.h>
57 #include <unistd.h>
58 #include <pthread.h>
59 #include <pthread_np.h>
60 
61 #include "e1000_regs.h"
62 #include "e1000_defines.h"
63 #include "mii.h"
64 
65 #include "bhyverun.h"
66 #include "pci_emul.h"
67 #include "mevent.h"
68 #include "net_utils.h"
69 
70 /* Hardware/register definitions XXX: move some to common code. */
71 #define E82545_VENDOR_ID_INTEL			0x8086
72 #define E82545_DEV_ID_82545EM_COPPER		0x100F
73 #define E82545_SUBDEV_ID			0x1008
74 
75 #define E82545_REVISION_4			4
76 
77 #define E82545_MDIC_DATA_MASK			0x0000FFFF
78 #define E82545_MDIC_OP_MASK			0x0c000000
79 #define E82545_MDIC_IE				0x20000000
80 
81 #define E82545_EECD_FWE_DIS	0x00000010 /* Flash writes disabled */
82 #define E82545_EECD_FWE_EN	0x00000020 /* Flash writes enabled */
83 #define E82545_EECD_FWE_MASK	0x00000030 /* Flash writes mask */
84 
85 #define E82545_BAR_REGISTER			0
86 #define E82545_BAR_REGISTER_LEN			(128*1024)
87 #define E82545_BAR_FLASH			1
88 #define E82545_BAR_FLASH_LEN			(64*1024)
89 #define E82545_BAR_IO				2
90 #define E82545_BAR_IO_LEN			8
91 
92 #define E82545_IOADDR				0x00000000
93 #define E82545_IODATA				0x00000004
94 #define E82545_IO_REGISTER_MAX			0x0001FFFF
95 #define E82545_IO_FLASH_BASE			0x00080000
96 #define E82545_IO_FLASH_MAX			0x000FFFFF
97 
98 #define E82545_ARRAY_ENTRY(reg, offset)		(reg + (offset<<2))
99 #define E82545_RAR_MAX				15
100 #define E82545_MTA_MAX				127
101 #define E82545_VFTA_MAX				127
102 
103 /* Slightly modified from the driver versions, hardcoded for 3 opcode bits,
104  * followed by 6 address bits.
105  * TODO: make opcode bits and addr bits configurable?
106  * NVM Commands - Microwire */
107 #define E82545_NVM_OPCODE_BITS	3
108 #define E82545_NVM_ADDR_BITS	6
109 #define E82545_NVM_DATA_BITS	16
110 #define E82545_NVM_OPADDR_BITS	(E82545_NVM_OPCODE_BITS + E82545_NVM_ADDR_BITS)
111 #define E82545_NVM_ADDR_MASK	((1 << E82545_NVM_ADDR_BITS)-1)
112 #define E82545_NVM_OPCODE_MASK	\
113     (((1 << E82545_NVM_OPCODE_BITS) - 1) << E82545_NVM_ADDR_BITS)
114 #define E82545_NVM_OPCODE_READ	(0x6 << E82545_NVM_ADDR_BITS)	/* read */
115 #define E82545_NVM_OPCODE_WRITE	(0x5 << E82545_NVM_ADDR_BITS)	/* write */
116 #define E82545_NVM_OPCODE_ERASE	(0x7 << E82545_NVM_ADDR_BITS)	/* erase */
117 #define	E82545_NVM_OPCODE_EWEN	(0x4 << E82545_NVM_ADDR_BITS)	/* wr-enable */
118 
119 #define	E82545_NVM_EEPROM_SIZE	64 /* 64 * 16-bit values == 128K */
120 
121 #define E1000_ICR_SRPD		0x00010000
122 
123 /* This is an arbitrary number.  There is no hard limit on the chip. */
124 #define I82545_MAX_TXSEGS	64
125 
126 /* Legacy receive descriptor */
127 struct e1000_rx_desc {
128 	uint64_t buffer_addr;	/* Address of the descriptor's data buffer */
129 	uint16_t length;	/* Length of data DMAed into data buffer */
130 	uint16_t csum;		/* Packet checksum */
131 	uint8_t	 status;       	/* Descriptor status */
132 	uint8_t  errors;	/* Descriptor Errors */
133 	uint16_t special;
134 };
135 
136 /* Transmit descriptor types */
137 #define	E1000_TXD_MASK		(E1000_TXD_CMD_DEXT | 0x00F00000)
138 #define E1000_TXD_TYP_L		(0)
139 #define E1000_TXD_TYP_C		(E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_C)
140 #define E1000_TXD_TYP_D		(E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)
141 
142 /* Legacy transmit descriptor */
143 struct e1000_tx_desc {
144 	uint64_t buffer_addr;   /* Address of the descriptor's data buffer */
145 	union {
146 		uint32_t data;
147 		struct {
148 			uint16_t length;  /* Data buffer length */
149 			uint8_t  cso;  /* Checksum offset */
150 			uint8_t  cmd;  /* Descriptor control */
151 		} flags;
152 	} lower;
153 	union {
154 		uint32_t data;
155 		struct {
156 			uint8_t status; /* Descriptor status */
157 			uint8_t css;  /* Checksum start */
158 			uint16_t special;
159 		} fields;
160 	} upper;
161 };
162 
163 /* Context descriptor */
164 struct e1000_context_desc {
165 	union {
166 		uint32_t ip_config;
167 		struct {
168 			uint8_t ipcss;  /* IP checksum start */
169 			uint8_t ipcso;  /* IP checksum offset */
170 			uint16_t ipcse;  /* IP checksum end */
171 		} ip_fields;
172 	} lower_setup;
173 	union {
174 		uint32_t tcp_config;
175 		struct {
176 			uint8_t tucss;  /* TCP checksum start */
177 			uint8_t tucso;  /* TCP checksum offset */
178 			uint16_t tucse;  /* TCP checksum end */
179 		} tcp_fields;
180 	} upper_setup;
181 	uint32_t cmd_and_length;
182 	union {
183 		uint32_t data;
184 		struct {
185 			uint8_t status;  /* Descriptor status */
186 			uint8_t hdr_len;  /* Header length */
187 			uint16_t mss;  /* Maximum segment size */
188 		} fields;
189 	} tcp_seg_setup;
190 };
191 
192 /* Data descriptor */
193 struct e1000_data_desc {
194 	uint64_t buffer_addr;  /* Address of the descriptor's buffer address */
195 	union {
196 		uint32_t data;
197 		struct {
198 			uint16_t length;  /* Data buffer length */
199 			uint8_t typ_len_ext;
200 			uint8_t cmd;
201 		} flags;
202 	} lower;
203 	union {
204 		uint32_t data;
205 		struct {
206 			uint8_t status;  /* Descriptor status */
207 			uint8_t popts;  /* Packet Options */
208 			uint16_t special;
209 		} fields;
210 	} upper;
211 };
212 
213 union e1000_tx_udesc {
214 	struct e1000_tx_desc td;
215 	struct e1000_context_desc cd;
216 	struct e1000_data_desc dd;
217 };
218 
219 /* Tx checksum info for a packet. */
220 struct ck_info {
221 	int	ck_valid;	/* ck_info is valid */
222 	uint8_t	ck_start;	/* start byte of cksum calcuation */
223 	uint8_t	ck_off;		/* offset of cksum insertion */
224 	uint16_t ck_len;	/* length of cksum calc: 0 is to packet-end */
225 };
226 
227 /*
228  * Debug printf
229  */
230 static int e82545_debug = 0;
231 #define DPRINTF(msg,params...) if (e82545_debug) fprintf(stderr, "e82545: " msg, params)
232 #define WPRINTF(msg,params...) fprintf(stderr, "e82545: " msg, params)
233 
234 #define	MIN(a,b) (((a)<(b))?(a):(b))
235 #define	MAX(a,b) (((a)>(b))?(a):(b))
236 
237 /* s/w representation of the RAL/RAH regs */
238 struct  eth_uni {
239 	int		eu_valid;
240 	int		eu_addrsel;
241 	struct ether_addr eu_eth;
242 };
243 
244 
245 struct e82545_softc {
246 	struct pci_devinst *esc_pi;
247 	struct vmctx	*esc_ctx;
248 	struct mevent   *esc_mevp;
249 	struct mevent   *esc_mevpitr;
250 	pthread_mutex_t	esc_mtx;
251 	struct ether_addr esc_mac;
252 	int		esc_tapfd;
253 
254 	/* General */
255 	uint32_t	esc_CTRL;	/* x0000 device ctl */
256 	uint32_t	esc_FCAL;	/* x0028 flow ctl addr lo */
257 	uint32_t	esc_FCAH;	/* x002C flow ctl addr hi */
258 	uint32_t	esc_FCT;	/* x0030 flow ctl type */
259 	uint32_t	esc_VET;	/* x0038 VLAN eth type */
260 	uint32_t	esc_FCTTV;	/* x0170 flow ctl tx timer */
261 	uint32_t	esc_LEDCTL;	/* x0E00 LED control */
262 	uint32_t	esc_PBA;	/* x1000 pkt buffer allocation */
263 
264 	/* Interrupt control */
265 	int		esc_irq_asserted;
266 	uint32_t	esc_ICR;	/* x00C0 cause read/clear */
267 	uint32_t	esc_ITR;	/* x00C4 intr throttling */
268 	uint32_t	esc_ICS;	/* x00C8 cause set */
269 	uint32_t	esc_IMS;	/* x00D0 mask set/read */
270 	uint32_t	esc_IMC;	/* x00D8 mask clear */
271 
272 	/* Transmit */
273 	union e1000_tx_udesc *esc_txdesc;
274 	struct e1000_context_desc esc_txctx;
275 	pthread_t	esc_tx_tid;
276 	pthread_cond_t	esc_tx_cond;
277 	int		esc_tx_enabled;
278 	int		esc_tx_active;
279 	uint32_t	esc_TXCW;	/* x0178 transmit config */
280 	uint32_t	esc_TCTL;	/* x0400 transmit ctl */
281 	uint32_t	esc_TIPG;	/* x0410 inter-packet gap */
282 	uint16_t	esc_AIT;	/* x0458 Adaptive Interframe Throttle */
283 	uint64_t	esc_tdba;      	/* verified 64-bit desc table addr */
284 	uint32_t	esc_TDBAL;	/* x3800 desc table addr, low bits */
285 	uint32_t	esc_TDBAH;	/* x3804 desc table addr, hi 32-bits */
286 	uint32_t	esc_TDLEN;	/* x3808 # descriptors in bytes */
287 	uint16_t	esc_TDH;	/* x3810 desc table head idx */
288 	uint16_t	esc_TDHr;	/* internal read version of TDH */
289 	uint16_t	esc_TDT;	/* x3818 desc table tail idx */
290 	uint32_t	esc_TIDV;	/* x3820 intr delay */
291 	uint32_t	esc_TXDCTL;	/* x3828 desc control */
292 	uint32_t	esc_TADV;	/* x382C intr absolute delay */
293 
294 	/* L2 frame acceptance */
295 	struct eth_uni	esc_uni[16];	/* 16 x unicast MAC addresses */
296 	uint32_t	esc_fmcast[128]; /* Multicast filter bit-match */
297 	uint32_t	esc_fvlan[128]; /* VLAN 4096-bit filter */
298 
299 	/* Receive */
300 	struct e1000_rx_desc *esc_rxdesc;
301 	pthread_cond_t	esc_rx_cond;
302 	int		esc_rx_enabled;
303 	int		esc_rx_active;
304 	int		esc_rx_loopback;
305 	uint32_t	esc_RCTL;	/* x0100 receive ctl */
306 	uint32_t	esc_FCRTL;	/* x2160 flow cntl thresh, low */
307 	uint32_t	esc_FCRTH;	/* x2168 flow cntl thresh, hi */
308 	uint64_t	esc_rdba;	/* verified 64-bit desc table addr */
309 	uint32_t	esc_RDBAL;	/* x2800 desc table addr, low bits */
310 	uint32_t	esc_RDBAH;	/* x2804 desc table addr, hi 32-bits*/
311 	uint32_t	esc_RDLEN;	/* x2808 #descriptors */
312 	uint16_t	esc_RDH;	/* x2810 desc table head idx */
313 	uint16_t	esc_RDT;	/* x2818 desc table tail idx */
314 	uint32_t	esc_RDTR;	/* x2820 intr delay */
315 	uint32_t	esc_RXDCTL;	/* x2828 desc control */
316 	uint32_t	esc_RADV;	/* x282C intr absolute delay */
317 	uint32_t	esc_RSRPD;	/* x2C00 recv small packet detect */
318 	uint32_t	esc_RXCSUM;     /* x5000 receive cksum ctl */
319 
320 	/* IO Port register access */
321 	uint32_t io_addr;
322 
323 	/* Shadow copy of MDIC */
324 	uint32_t mdi_control;
325 	/* Shadow copy of EECD */
326 	uint32_t eeprom_control;
327 	/* Latest NVM in/out */
328 	uint16_t nvm_data;
329 	uint16_t nvm_opaddr;
330 	/* stats */
331 	uint32_t missed_pkt_count; /* dropped for no room in rx queue */
332 	uint32_t pkt_rx_by_size[6];
333 	uint32_t pkt_tx_by_size[6];
334 	uint32_t good_pkt_rx_count;
335 	uint32_t bcast_pkt_rx_count;
336 	uint32_t mcast_pkt_rx_count;
337 	uint32_t good_pkt_tx_count;
338 	uint32_t bcast_pkt_tx_count;
339 	uint32_t mcast_pkt_tx_count;
340 	uint32_t oversize_rx_count;
341 	uint32_t tso_tx_count;
342 	uint64_t good_octets_rx;
343 	uint64_t good_octets_tx;
344 	uint64_t missed_octets; /* counts missed and oversized */
345 
346 	uint8_t nvm_bits:6; /* number of bits remaining in/out */
347 	uint8_t nvm_mode:2;
348 #define E82545_NVM_MODE_OPADDR  0x0
349 #define E82545_NVM_MODE_DATAIN  0x1
350 #define E82545_NVM_MODE_DATAOUT 0x2
351 	/* EEPROM data */
352 	uint16_t eeprom_data[E82545_NVM_EEPROM_SIZE];
353 };
354 
355 static void e82545_reset(struct e82545_softc *sc, int dev);
356 static void e82545_rx_enable(struct e82545_softc *sc);
357 static void e82545_rx_disable(struct e82545_softc *sc);
358 static void e82545_tap_callback(int fd, enum ev_type type, void *param);
359 static void e82545_tx_start(struct e82545_softc *sc);
360 static void e82545_tx_enable(struct e82545_softc *sc);
361 static void e82545_tx_disable(struct e82545_softc *sc);
362 
363 static inline int
364 e82545_size_stat_index(uint32_t size)
365 {
366 	if (size <= 64) {
367 		return 0;
368 	} else if (size >= 1024) {
369 		return 5;
370 	} else {
371 		/* should be 1-4 */
372 		return (ffs(size) - 6);
373 	}
374 }
375 
376 static void
377 e82545_init_eeprom(struct e82545_softc *sc)
378 {
379 	uint16_t checksum, i;
380 
381         /* mac addr */
382 	sc->eeprom_data[NVM_MAC_ADDR] = ((uint16_t)sc->esc_mac.octet[0]) |
383 		(((uint16_t)sc->esc_mac.octet[1]) << 8);
384 	sc->eeprom_data[NVM_MAC_ADDR+1] = ((uint16_t)sc->esc_mac.octet[2]) |
385 		(((uint16_t)sc->esc_mac.octet[3]) << 8);
386 	sc->eeprom_data[NVM_MAC_ADDR+2] = ((uint16_t)sc->esc_mac.octet[4]) |
387 		(((uint16_t)sc->esc_mac.octet[5]) << 8);
388 
389 	/* pci ids */
390 	sc->eeprom_data[NVM_SUB_DEV_ID] = E82545_SUBDEV_ID;
391 	sc->eeprom_data[NVM_SUB_VEN_ID] = E82545_VENDOR_ID_INTEL;
392 	sc->eeprom_data[NVM_DEV_ID] = E82545_DEV_ID_82545EM_COPPER;
393 	sc->eeprom_data[NVM_VEN_ID] = E82545_VENDOR_ID_INTEL;
394 
395 	/* fill in the checksum */
396         checksum = 0;
397 	for (i = 0; i < NVM_CHECKSUM_REG; i++) {
398 		checksum += sc->eeprom_data[i];
399 	}
400 	checksum = NVM_SUM - checksum;
401 	sc->eeprom_data[NVM_CHECKSUM_REG] = checksum;
402 	DPRINTF("eeprom checksum: 0x%x\r\n", checksum);
403 }
404 
405 static void
406 e82545_write_mdi(struct e82545_softc *sc, uint8_t reg_addr,
407 			uint8_t phy_addr, uint32_t data)
408 {
409 	DPRINTF("Write mdi reg:0x%x phy:0x%x data: 0x%x\r\n", reg_addr, phy_addr, data);
410 }
411 
412 static uint32_t
413 e82545_read_mdi(struct e82545_softc *sc, uint8_t reg_addr,
414 			uint8_t phy_addr)
415 {
416 	//DPRINTF("Read mdi reg:0x%x phy:0x%x\r\n", reg_addr, phy_addr);
417 	switch (reg_addr) {
418 	case PHY_STATUS:
419 		return (MII_SR_LINK_STATUS | MII_SR_AUTONEG_CAPS |
420 			MII_SR_AUTONEG_COMPLETE);
421 	case PHY_AUTONEG_ADV:
422 		return NWAY_AR_SELECTOR_FIELD;
423 	case PHY_LP_ABILITY:
424 		return 0;
425 	case PHY_1000T_STATUS:
426 		return (SR_1000T_LP_FD_CAPS | SR_1000T_REMOTE_RX_STATUS |
427 			SR_1000T_LOCAL_RX_STATUS);
428 	case PHY_ID1:
429 		return (M88E1011_I_PHY_ID >> 16) & 0xFFFF;
430 	case PHY_ID2:
431 		return (M88E1011_I_PHY_ID | E82545_REVISION_4) & 0xFFFF;
432 	default:
433 		DPRINTF("Unknown mdi read reg:0x%x phy:0x%x\r\n", reg_addr, phy_addr);
434 		return 0;
435 	}
436 	/* not reached */
437 }
438 
439 static void
440 e82545_eecd_strobe(struct e82545_softc *sc)
441 {
442 	/* Microwire state machine */
443 	/*
444 	DPRINTF("eeprom state machine srtobe "
445 		"0x%x 0x%x 0x%x 0x%x\r\n",
446 		sc->nvm_mode, sc->nvm_bits,
447 		sc->nvm_opaddr, sc->nvm_data);*/
448 
449 	if (sc->nvm_bits == 0) {
450 		DPRINTF("eeprom state machine not expecting data! "
451 			"0x%x 0x%x 0x%x 0x%x\r\n",
452 			sc->nvm_mode, sc->nvm_bits,
453 			sc->nvm_opaddr, sc->nvm_data);
454 		return;
455 	}
456 	sc->nvm_bits--;
457 	if (sc->nvm_mode == E82545_NVM_MODE_DATAOUT) {
458 		/* shifting out */
459 		if (sc->nvm_data & 0x8000) {
460 			sc->eeprom_control |= E1000_EECD_DO;
461 		} else {
462 			sc->eeprom_control &= ~E1000_EECD_DO;
463 		}
464 		sc->nvm_data <<= 1;
465 		if (sc->nvm_bits == 0) {
466 			/* read done, back to opcode mode. */
467 			sc->nvm_opaddr = 0;
468 			sc->nvm_mode = E82545_NVM_MODE_OPADDR;
469 			sc->nvm_bits = E82545_NVM_OPADDR_BITS;
470 		}
471 	} else if (sc->nvm_mode == E82545_NVM_MODE_DATAIN) {
472 		/* shifting in */
473 		sc->nvm_data <<= 1;
474 		if (sc->eeprom_control & E1000_EECD_DI) {
475 			sc->nvm_data |= 1;
476 		}
477 		if (sc->nvm_bits == 0) {
478 			/* eeprom write */
479 			uint16_t op = sc->nvm_opaddr & E82545_NVM_OPCODE_MASK;
480 			uint16_t addr = sc->nvm_opaddr & E82545_NVM_ADDR_MASK;
481 			if (op != E82545_NVM_OPCODE_WRITE) {
482 				DPRINTF("Illegal eeprom write op 0x%x\r\n",
483 					sc->nvm_opaddr);
484 			} else if (addr >= E82545_NVM_EEPROM_SIZE) {
485 				DPRINTF("Illegal eeprom write addr 0x%x\r\n",
486 					sc->nvm_opaddr);
487 			} else {
488 				DPRINTF("eeprom write eeprom[0x%x] = 0x%x\r\n",
489 				addr, sc->nvm_data);
490 				sc->eeprom_data[addr] = sc->nvm_data;
491 			}
492 			/* back to opcode mode */
493 			sc->nvm_opaddr = 0;
494 			sc->nvm_mode = E82545_NVM_MODE_OPADDR;
495 			sc->nvm_bits = E82545_NVM_OPADDR_BITS;
496 		}
497 	} else if (sc->nvm_mode == E82545_NVM_MODE_OPADDR) {
498 		sc->nvm_opaddr <<= 1;
499 		if (sc->eeprom_control & E1000_EECD_DI) {
500 			sc->nvm_opaddr |= 1;
501 		}
502 		if (sc->nvm_bits == 0) {
503 			uint16_t op = sc->nvm_opaddr & E82545_NVM_OPCODE_MASK;
504 			switch (op) {
505 			case E82545_NVM_OPCODE_EWEN:
506 				DPRINTF("eeprom write enable: 0x%x\r\n",
507 					sc->nvm_opaddr);
508 				/* back to opcode mode */
509 				sc->nvm_opaddr = 0;
510 				sc->nvm_mode = E82545_NVM_MODE_OPADDR;
511 				sc->nvm_bits = E82545_NVM_OPADDR_BITS;
512 				break;
513 			case E82545_NVM_OPCODE_READ:
514 			{
515 				uint16_t addr = sc->nvm_opaddr &
516 					E82545_NVM_ADDR_MASK;
517 				sc->nvm_mode = E82545_NVM_MODE_DATAOUT;
518 				sc->nvm_bits = E82545_NVM_DATA_BITS;
519 				if (addr < E82545_NVM_EEPROM_SIZE) {
520 					sc->nvm_data = sc->eeprom_data[addr];
521 					DPRINTF("eeprom read: eeprom[0x%x] = 0x%x\r\n",
522 						addr, sc->nvm_data);
523 				} else {
524 					DPRINTF("eeprom illegal read: 0x%x\r\n",
525 						sc->nvm_opaddr);
526 					sc->nvm_data = 0;
527 				}
528 				break;
529 			}
530 			case E82545_NVM_OPCODE_WRITE:
531 				sc->nvm_mode = E82545_NVM_MODE_DATAIN;
532 				sc->nvm_bits = E82545_NVM_DATA_BITS;
533 				sc->nvm_data = 0;
534 				break;
535 			default:
536 				DPRINTF("eeprom unknown op: 0x%x\r\r",
537 					sc->nvm_opaddr);
538 				/* back to opcode mode */
539 				sc->nvm_opaddr = 0;
540 				sc->nvm_mode = E82545_NVM_MODE_OPADDR;
541 				sc->nvm_bits = E82545_NVM_OPADDR_BITS;
542 			}
543 		}
544 	} else {
545 		DPRINTF("eeprom state machine wrong state! "
546 			"0x%x 0x%x 0x%x 0x%x\r\n",
547 			sc->nvm_mode, sc->nvm_bits,
548 			sc->nvm_opaddr, sc->nvm_data);
549 	}
550 }
551 
552 static void
553 e82545_itr_callback(int fd, enum ev_type type, void *param)
554 {
555 	uint32_t new;
556 	struct e82545_softc *sc = param;
557 
558 	pthread_mutex_lock(&sc->esc_mtx);
559 	new = sc->esc_ICR & sc->esc_IMS;
560 	if (new && !sc->esc_irq_asserted) {
561 		DPRINTF("itr callback: lintr assert %x\r\n", new);
562 		sc->esc_irq_asserted = 1;
563 		pci_lintr_assert(sc->esc_pi);
564 	} else {
565 		mevent_delete(sc->esc_mevpitr);
566 		sc->esc_mevpitr = NULL;
567 	}
568 	pthread_mutex_unlock(&sc->esc_mtx);
569 }
570 
571 static void
572 e82545_icr_assert(struct e82545_softc *sc, uint32_t bits)
573 {
574 	uint32_t new;
575 
576 	DPRINTF("icr assert: 0x%x\r\n", bits);
577 
578 	/*
579 	 * An interrupt is only generated if bits are set that
580 	 * aren't already in the ICR, these bits are unmasked,
581 	 * and there isn't an interrupt already pending.
582 	 */
583 	new = bits & ~sc->esc_ICR & sc->esc_IMS;
584 	sc->esc_ICR |= bits;
585 
586 	if (new == 0) {
587 		DPRINTF("icr assert: masked %x, ims %x\r\n", new, sc->esc_IMS);
588 	} else if (sc->esc_mevpitr != NULL) {
589 		DPRINTF("icr assert: throttled %x, ims %x\r\n", new, sc->esc_IMS);
590 	} else if (!sc->esc_irq_asserted) {
591 		DPRINTF("icr assert: lintr assert %x\r\n", new);
592 		sc->esc_irq_asserted = 1;
593 		pci_lintr_assert(sc->esc_pi);
594 		if (sc->esc_ITR != 0) {
595 			sc->esc_mevpitr = mevent_add(
596 			    (sc->esc_ITR + 3905) / 3906,  /* 256ns -> 1ms */
597 			    EVF_TIMER, e82545_itr_callback, sc);
598 		}
599 	}
600 }
601 
602 static void
603 e82545_ims_change(struct e82545_softc *sc, uint32_t bits)
604 {
605 	uint32_t new;
606 
607 	/*
608 	 * Changing the mask may allow previously asserted
609 	 * but masked interrupt requests to generate an interrupt.
610 	 */
611 	new = bits & sc->esc_ICR & ~sc->esc_IMS;
612 	sc->esc_IMS |= bits;
613 
614 	if (new == 0) {
615 		DPRINTF("ims change: masked %x, ims %x\r\n", new, sc->esc_IMS);
616 	} else if (sc->esc_mevpitr != NULL) {
617 		DPRINTF("ims change: throttled %x, ims %x\r\n", new, sc->esc_IMS);
618 	} else if (!sc->esc_irq_asserted) {
619 		DPRINTF("ims change: lintr assert %x\n\r", new);
620 		sc->esc_irq_asserted = 1;
621 		pci_lintr_assert(sc->esc_pi);
622 		if (sc->esc_ITR != 0) {
623 			sc->esc_mevpitr = mevent_add(
624 			    (sc->esc_ITR + 3905) / 3906,  /* 256ns -> 1ms */
625 			    EVF_TIMER, e82545_itr_callback, sc);
626 		}
627 	}
628 }
629 
630 static void
631 e82545_icr_deassert(struct e82545_softc *sc, uint32_t bits)
632 {
633 
634 	DPRINTF("icr deassert: 0x%x\r\n", bits);
635 	sc->esc_ICR &= ~bits;
636 
637 	/*
638 	 * If there are no longer any interrupt sources and there
639 	 * was an asserted interrupt, clear it
640 	 */
641 	if (sc->esc_irq_asserted && !(sc->esc_ICR & sc->esc_IMS)) {
642 		DPRINTF("icr deassert: lintr deassert %x\r\n", bits);
643 		pci_lintr_deassert(sc->esc_pi);
644 		sc->esc_irq_asserted = 0;
645 	}
646 }
647 
648 static void
649 e82545_intr_write(struct e82545_softc *sc, uint32_t offset, uint32_t value)
650 {
651 
652 	DPRINTF("intr_write: off %x, val %x\n\r", offset, value);
653 
654 	switch (offset) {
655 	case E1000_ICR:
656 		e82545_icr_deassert(sc, value);
657 		break;
658 	case E1000_ITR:
659 		sc->esc_ITR = value;
660 		break;
661 	case E1000_ICS:
662 		sc->esc_ICS = value;	/* not used: store for debug */
663 		e82545_icr_assert(sc, value);
664 		break;
665 	case E1000_IMS:
666 		e82545_ims_change(sc, value);
667 		break;
668 	case E1000_IMC:
669 		sc->esc_IMC = value;	/* for debug */
670 		sc->esc_IMS &= ~value;
671 		// XXX clear interrupts if all ICR bits now masked
672 		// and interrupt was pending ?
673 		break;
674 	default:
675 		break;
676 	}
677 }
678 
679 static uint32_t
680 e82545_intr_read(struct e82545_softc *sc, uint32_t offset)
681 {
682 	uint32_t retval;
683 
684 	retval = 0;
685 
686 	DPRINTF("intr_read: off %x\n\r", offset);
687 
688 	switch (offset) {
689 	case E1000_ICR:
690 		retval = sc->esc_ICR;
691 		sc->esc_ICR = 0;
692 		e82545_icr_deassert(sc, ~0);
693 		break;
694 	case E1000_ITR:
695 		retval = sc->esc_ITR;
696 		break;
697 	case E1000_ICS:
698 		/* write-only register */
699 		break;
700 	case E1000_IMS:
701 		retval = sc->esc_IMS;
702 		break;
703 	case E1000_IMC:
704 		/* write-only register */
705 		break;
706 	default:
707 		break;
708 	}
709 
710 	return (retval);
711 }
712 
713 static void
714 e82545_devctl(struct e82545_softc *sc, uint32_t val)
715 {
716 
717 	sc->esc_CTRL = val & ~E1000_CTRL_RST;
718 
719 	if (val & E1000_CTRL_RST) {
720 		DPRINTF("e1k: s/w reset, ctl %x\n", val);
721 		e82545_reset(sc, 1);
722 	}
723 	/* XXX check for phy reset ? */
724 }
725 
726 static void
727 e82545_rx_update_rdba(struct e82545_softc *sc)
728 {
729 
730 	/* XXX verify desc base/len within phys mem range */
731 	sc->esc_rdba = (uint64_t)sc->esc_RDBAH << 32 |
732 	    sc->esc_RDBAL;
733 
734 	/* Cache host mapping of guest descriptor array */
735 	sc->esc_rxdesc = paddr_guest2host(sc->esc_ctx,
736 	    sc->esc_rdba, sc->esc_RDLEN);
737 }
738 
739 static void
740 e82545_rx_ctl(struct e82545_softc *sc, uint32_t val)
741 {
742 	int on;
743 
744 	on = ((val & E1000_RCTL_EN) == E1000_RCTL_EN);
745 
746 	/* Save RCTL after stripping reserved bits 31:27,24,21,14,11:10,0 */
747 	sc->esc_RCTL = val & ~0xF9204c01;
748 
749 	DPRINTF("rx_ctl - %s RCTL %x, val %x\n",
750 		on ? "on" : "off", sc->esc_RCTL, val);
751 
752 	/* state change requested */
753 	if (on != sc->esc_rx_enabled) {
754 		if (on) {
755 			/* Catch disallowed/unimplemented settings */
756 			//assert(!(val & E1000_RCTL_LBM_TCVR));
757 
758 			if (sc->esc_RCTL & E1000_RCTL_LBM_TCVR) {
759 				sc->esc_rx_loopback = 1;
760 			} else {
761 				sc->esc_rx_loopback = 0;
762 			}
763 
764 			e82545_rx_update_rdba(sc);
765 			e82545_rx_enable(sc);
766 		} else {
767 			e82545_rx_disable(sc);
768 			sc->esc_rx_loopback = 0;
769 			sc->esc_rdba = 0;
770 			sc->esc_rxdesc = NULL;
771 		}
772 	}
773 }
774 
775 static void
776 e82545_tx_update_tdba(struct e82545_softc *sc)
777 {
778 
779 	/* XXX verify desc base/len within phys mem range */
780 	sc->esc_tdba = (uint64_t)sc->esc_TDBAH << 32 | sc->esc_TDBAL;
781 
782 	/* Cache host mapping of guest descriptor array */
783 	sc->esc_txdesc = paddr_guest2host(sc->esc_ctx, sc->esc_tdba,
784             sc->esc_TDLEN);
785 }
786 
787 static void
788 e82545_tx_ctl(struct e82545_softc *sc, uint32_t val)
789 {
790 	int on;
791 
792 	on = ((val & E1000_TCTL_EN) == E1000_TCTL_EN);
793 
794 	/* ignore TCTL_EN settings that don't change state */
795 	if (on == sc->esc_tx_enabled)
796 		return;
797 
798 	if (on) {
799 		e82545_tx_update_tdba(sc);
800 		e82545_tx_enable(sc);
801 	} else {
802 		e82545_tx_disable(sc);
803 		sc->esc_tdba = 0;
804 		sc->esc_txdesc = NULL;
805 	}
806 
807 	/* Save TCTL value after stripping reserved bits 31:25,23,2,0 */
808 	sc->esc_TCTL = val & ~0xFE800005;
809 }
810 
811 int
812 e82545_bufsz(uint32_t rctl)
813 {
814 
815 	switch (rctl & (E1000_RCTL_BSEX | E1000_RCTL_SZ_256)) {
816 	case (E1000_RCTL_SZ_2048): return (2048);
817 	case (E1000_RCTL_SZ_1024): return (1024);
818 	case (E1000_RCTL_SZ_512): return (512);
819 	case (E1000_RCTL_SZ_256): return (256);
820 	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_16384): return (16384);
821 	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_8192): return (8192);
822 	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_4096): return (4096);
823 	}
824 	return (256);	/* Forbidden value. */
825 }
826 
827 static uint8_t dummybuf[2048];
828 
829 /* XXX one packet at a time until this is debugged */
830 static void
831 e82545_tap_callback(int fd, enum ev_type type, void *param)
832 {
833 	struct e82545_softc *sc = param;
834 	struct e1000_rx_desc *rxd;
835 	struct iovec vec[64];
836 	int left, len, lim, maxpktsz, maxpktdesc, bufsz, i, n, size;
837 	uint32_t cause = 0;
838 	uint16_t *tp, tag, head;
839 
840 	pthread_mutex_lock(&sc->esc_mtx);
841 	DPRINTF("rx_run: head %x, tail %x\r\n", sc->esc_RDH, sc->esc_RDT);
842 
843 	if (!sc->esc_rx_enabled || sc->esc_rx_loopback) {
844 		DPRINTF("rx disabled (!%d || %d) -- packet(s) dropped\r\n",
845 		    sc->esc_rx_enabled, sc->esc_rx_loopback);
846 		while (read(sc->esc_tapfd, dummybuf, sizeof(dummybuf)) > 0) {
847 		}
848 		goto done1;
849 	}
850 	bufsz = e82545_bufsz(sc->esc_RCTL);
851 	maxpktsz = (sc->esc_RCTL & E1000_RCTL_LPE) ? 16384 : 1522;
852 	maxpktdesc = (maxpktsz + bufsz - 1) / bufsz;
853 	size = sc->esc_RDLEN / 16;
854 	head = sc->esc_RDH;
855 	left = (size + sc->esc_RDT - head) % size;
856 	if (left < maxpktdesc) {
857 		DPRINTF("rx overflow (%d < %d) -- packet(s) dropped\r\n",
858 		    left, maxpktdesc);
859 		while (read(sc->esc_tapfd, dummybuf, sizeof(dummybuf)) > 0) {
860 		}
861 		goto done1;
862 	}
863 
864 	sc->esc_rx_active = 1;
865 	pthread_mutex_unlock(&sc->esc_mtx);
866 
867 	for (lim = size / 4; lim > 0 && left >= maxpktdesc; lim -= n) {
868 
869 		/* Grab rx descriptor pointed to by the head pointer */
870 		for (i = 0; i < maxpktdesc; i++) {
871 			rxd = &sc->esc_rxdesc[(head + i) % size];
872 			vec[i].iov_base = paddr_guest2host(sc->esc_ctx,
873 			    rxd->buffer_addr, bufsz);
874 			vec[i].iov_len = bufsz;
875 		}
876 		len = readv(sc->esc_tapfd, vec, maxpktdesc);
877 		if (len <= 0) {
878 			DPRINTF("tap: readv() returned %d\n", len);
879 			goto done;
880 		}
881 
882 		/*
883 		 * Adjust the packet length based on whether the CRC needs
884 		 * to be stripped or if the packet is less than the minimum
885 		 * eth packet size.
886 		 */
887 		if (len < ETHER_MIN_LEN - ETHER_CRC_LEN)
888 			len = ETHER_MIN_LEN - ETHER_CRC_LEN;
889 		if (!(sc->esc_RCTL & E1000_RCTL_SECRC))
890 			len += ETHER_CRC_LEN;
891 		n = (len + bufsz - 1) / bufsz;
892 
893 		DPRINTF("packet read %d bytes, %d segs, head %d\r\n",
894 		    len, n, head);
895 
896 		/* Apply VLAN filter. */
897 		tp = (uint16_t *)vec[0].iov_base + 6;
898 		if ((sc->esc_RCTL & E1000_RCTL_VFE) &&
899 		    (ntohs(tp[0]) == sc->esc_VET)) {
900 			tag = ntohs(tp[1]) & 0x0fff;
901 			if ((sc->esc_fvlan[tag >> 5] &
902 			    (1 << (tag & 0x1f))) != 0) {
903 				DPRINTF("known VLAN %d\r\n", tag);
904 			} else {
905 				DPRINTF("unknown VLAN %d\r\n", tag);
906 				n = 0;
907 				continue;
908 			}
909 		}
910 
911 		/* Update all consumed descriptors. */
912 		for (i = 0; i < n - 1; i++) {
913 			rxd = &sc->esc_rxdesc[(head + i) % size];
914 			rxd->length = bufsz;
915 			rxd->csum = 0;
916 			rxd->errors = 0;
917 			rxd->special = 0;
918 			rxd->status = E1000_RXD_STAT_DD;
919 		}
920 		rxd = &sc->esc_rxdesc[(head + i) % size];
921 		rxd->length = len % bufsz;
922 		rxd->csum = 0;
923 		rxd->errors = 0;
924 		rxd->special = 0;
925 		/* XXX signal no checksum for now */
926 		rxd->status = E1000_RXD_STAT_PIF | E1000_RXD_STAT_IXSM |
927 		    E1000_RXD_STAT_EOP | E1000_RXD_STAT_DD;
928 
929 		/* Schedule receive interrupts. */
930 		if (len <= sc->esc_RSRPD) {
931 			cause |= E1000_ICR_SRPD | E1000_ICR_RXT0;
932 		} else {
933 			/* XXX: RDRT and RADV timers should be here. */
934 			cause |= E1000_ICR_RXT0;
935 		}
936 
937 		head = (head + n) % size;
938 		left -= n;
939 	}
940 
941 done:
942 	pthread_mutex_lock(&sc->esc_mtx);
943 	sc->esc_rx_active = 0;
944 	if (sc->esc_rx_enabled == 0)
945 		pthread_cond_signal(&sc->esc_rx_cond);
946 
947 	sc->esc_RDH = head;
948 	/* Respect E1000_RCTL_RDMTS */
949 	left = (size + sc->esc_RDT - head) % size;
950 	if (left < (size >> (((sc->esc_RCTL >> 8) & 3) + 1)))
951 		cause |= E1000_ICR_RXDMT0;
952 	/* Assert all accumulated interrupts. */
953 	if (cause != 0)
954 		e82545_icr_assert(sc, cause);
955 done1:
956 	DPRINTF("rx_run done: head %x, tail %x\r\n", sc->esc_RDH, sc->esc_RDT);
957 	pthread_mutex_unlock(&sc->esc_mtx);
958 }
959 
960 static uint16_t
961 e82545_carry(uint32_t sum)
962 {
963 
964 	sum = (sum & 0xFFFF) + (sum >> 16);
965 	if (sum > 0xFFFF)
966 		sum -= 0xFFFF;
967 	return (sum);
968 }
969 
970 static uint16_t
971 e82545_buf_checksum(uint8_t *buf, int len)
972 {
973 	int i;
974 	uint32_t sum = 0;
975 
976 	/* Checksum all the pairs of bytes first... */
977 	for (i = 0; i < (len & ~1U); i += 2)
978 		sum += *((u_int16_t *)(buf + i));
979 
980 	/*
981 	 * If there's a single byte left over, checksum it, too.
982 	 * Network byte order is big-endian, so the remaining byte is
983 	 * the high byte.
984 	 */
985 	if (i < len)
986 		sum += htons(buf[i] << 8);
987 
988 	return (e82545_carry(sum));
989 }
990 
991 static uint16_t
992 e82545_iov_checksum(struct iovec *iov, int iovcnt, int off, int len)
993 {
994 	int now, odd;
995 	uint32_t sum = 0, s;
996 
997 	/* Skip completely unneeded vectors. */
998 	while (iovcnt > 0 && iov->iov_len <= off && off > 0) {
999 		off -= iov->iov_len;
1000 		iov++;
1001 		iovcnt--;
1002 	}
1003 
1004 	/* Calculate checksum of requested range. */
1005 	odd = 0;
1006 	while (len > 0 && iovcnt > 0) {
1007 		now = MIN(len, iov->iov_len - off);
1008 		s = e82545_buf_checksum(iov->iov_base + off, now);
1009 		sum += odd ? (s << 8) : s;
1010 		odd ^= (now & 1);
1011 		len -= now;
1012 		off = 0;
1013 		iov++;
1014 		iovcnt--;
1015 	}
1016 
1017 	return (e82545_carry(sum));
1018 }
1019 
1020 /*
1021  * Return the transmit descriptor type.
1022  */
1023 int
1024 e82545_txdesc_type(uint32_t lower)
1025 {
1026 	int type;
1027 
1028 	type = 0;
1029 
1030 	if (lower & E1000_TXD_CMD_DEXT)
1031 		type = lower & E1000_TXD_MASK;
1032 
1033 	return (type);
1034 }
1035 
1036 static void
1037 e82545_transmit_checksum(struct iovec *iov, int iovcnt, struct ck_info *ck)
1038 {
1039 	uint16_t cksum;
1040 	int cklen;
1041 
1042 	DPRINTF("tx cksum: iovcnt/s/off/len %d/%d/%d/%d\r\n",
1043 	    iovcnt, ck->ck_start, ck->ck_off, ck->ck_len);
1044 	cklen = ck->ck_len ? ck->ck_len - ck->ck_start + 1 : INT_MAX;
1045 	cksum = e82545_iov_checksum(iov, iovcnt, ck->ck_start, cklen);
1046 	*(uint16_t *)((uint8_t *)iov[0].iov_base + ck->ck_off) = ~cksum;
1047 }
1048 
1049 static void
1050 e82545_transmit_backend(struct e82545_softc *sc, struct iovec *iov, int iovcnt)
1051 {
1052 
1053 	if (sc->esc_tapfd == -1)
1054 		return;
1055 
1056 	(void) writev(sc->esc_tapfd, iov, iovcnt);
1057 }
1058 
1059 static void
1060 e82545_transmit_done(struct e82545_softc *sc, uint16_t head, uint16_t tail,
1061     uint16_t dsize, int *tdwb)
1062 {
1063 	union e1000_tx_udesc *dsc;
1064 
1065 	for ( ; head != tail; head = (head + 1) % dsize) {
1066 		dsc = &sc->esc_txdesc[head];
1067 		if (dsc->td.lower.data & E1000_TXD_CMD_RS) {
1068 			dsc->td.upper.data |= E1000_TXD_STAT_DD;
1069 			*tdwb = 1;
1070 		}
1071 	}
1072 }
1073 
1074 static int
1075 e82545_transmit(struct e82545_softc *sc, uint16_t head, uint16_t tail,
1076     uint16_t dsize, uint16_t *rhead, int *tdwb)
1077 {
1078 	uint8_t *hdr, *hdrp;
1079 	struct iovec iovb[I82545_MAX_TXSEGS + 2];
1080 	struct iovec tiov[I82545_MAX_TXSEGS + 2];
1081 	struct e1000_context_desc *cd;
1082 	struct ck_info ckinfo[2];
1083 	struct iovec *iov;
1084 	union  e1000_tx_udesc *dsc;
1085 	int desc, dtype, len, ntype, iovcnt, tlen, hdrlen, vlen, tcp, tso;
1086 	int mss, paylen, seg, tiovcnt, left, now, nleft, nnow, pv, pvoff;
1087 	uint32_t tcpsum, tcpseq;
1088 	uint16_t ipcs, tcpcs, ipid, ohead;
1089 
1090 	ckinfo[0].ck_valid = ckinfo[1].ck_valid = 0;
1091 	iovcnt = 0;
1092 	tlen = 0;
1093 	ntype = 0;
1094 	tso = 0;
1095 	ohead = head;
1096 
1097 	/* iovb[0/1] may be used for writable copy of headers. */
1098 	iov = &iovb[2];
1099 
1100 	for (desc = 0; ; desc++, head = (head + 1) % dsize) {
1101 		if (head == tail) {
1102 			*rhead = head;
1103 			return (0);
1104 		}
1105 		dsc = &sc->esc_txdesc[head];
1106 		dtype = e82545_txdesc_type(dsc->td.lower.data);
1107 
1108 		if (desc == 0) {
1109 			switch (dtype) {
1110 			case E1000_TXD_TYP_C:
1111 				DPRINTF("tx ctxt desc idx %d: %016jx "
1112 				    "%08x%08x\r\n",
1113 				    head, dsc->td.buffer_addr,
1114 				    dsc->td.upper.data, dsc->td.lower.data);
1115 				/* Save context and return */
1116 				sc->esc_txctx = dsc->cd;
1117 				goto done;
1118 			case E1000_TXD_TYP_L:
1119 				DPRINTF("tx legacy desc idx %d: %08x%08x\r\n",
1120 				    head, dsc->td.upper.data, dsc->td.lower.data);
1121 				/*
1122 				 * legacy cksum start valid in first descriptor
1123 				 */
1124 				ntype = dtype;
1125 				ckinfo[0].ck_start = dsc->td.upper.fields.css;
1126 				break;
1127 			case E1000_TXD_TYP_D:
1128 				DPRINTF("tx data desc idx %d: %08x%08x\r\n",
1129 				    head, dsc->td.upper.data, dsc->td.lower.data);
1130 				ntype = dtype;
1131 				break;
1132 			default:
1133 				break;
1134 			}
1135 		} else {
1136 			/* Descriptor type must be consistent */
1137 			assert(dtype == ntype);
1138 			DPRINTF("tx next desc idx %d: %08x%08x\r\n",
1139 			    head, dsc->td.upper.data, dsc->td.lower.data);
1140 		}
1141 
1142 		len = (dtype == E1000_TXD_TYP_L) ? dsc->td.lower.flags.length :
1143 		    dsc->dd.lower.data & 0xFFFFF;
1144 
1145 		if (len > 0) {
1146 			/* Strip checksum supplied by guest. */
1147 			if ((dsc->td.lower.data & E1000_TXD_CMD_EOP) != 0 &&
1148 			    (dsc->td.lower.data & E1000_TXD_CMD_IFCS) == 0)
1149 				len -= 2;
1150 			tlen += len;
1151 			if (iovcnt < I82545_MAX_TXSEGS) {
1152 				iov[iovcnt].iov_base = paddr_guest2host(
1153 				    sc->esc_ctx, dsc->td.buffer_addr, len);
1154 				iov[iovcnt].iov_len = len;
1155 			}
1156 			iovcnt++;
1157 		}
1158 
1159 		/*
1160 		 * Pull out info that is valid in the final descriptor
1161 		 * and exit descriptor loop.
1162 		 */
1163 		if (dsc->td.lower.data & E1000_TXD_CMD_EOP) {
1164 			if (dtype == E1000_TXD_TYP_L) {
1165 				if (dsc->td.lower.data & E1000_TXD_CMD_IC) {
1166 					ckinfo[0].ck_valid = 1;
1167 					ckinfo[0].ck_off =
1168 					    dsc->td.lower.flags.cso;
1169 					ckinfo[0].ck_len = 0;
1170 				}
1171 			} else {
1172 				cd = &sc->esc_txctx;
1173 				if (dsc->dd.lower.data & E1000_TXD_CMD_TSE)
1174 					tso = 1;
1175 				if (dsc->dd.upper.fields.popts &
1176 				    E1000_TXD_POPTS_IXSM)
1177 					ckinfo[0].ck_valid = 1;
1178 				if (dsc->dd.upper.fields.popts &
1179 				    E1000_TXD_POPTS_IXSM || tso) {
1180 					ckinfo[0].ck_start =
1181 					    cd->lower_setup.ip_fields.ipcss;
1182 					ckinfo[0].ck_off =
1183 					    cd->lower_setup.ip_fields.ipcso;
1184 					ckinfo[0].ck_len =
1185 					    cd->lower_setup.ip_fields.ipcse;
1186 				}
1187 				if (dsc->dd.upper.fields.popts &
1188 				    E1000_TXD_POPTS_TXSM)
1189 					ckinfo[1].ck_valid = 1;
1190 				if (dsc->dd.upper.fields.popts &
1191 				    E1000_TXD_POPTS_TXSM || tso) {
1192 					ckinfo[1].ck_start =
1193 					    cd->upper_setup.tcp_fields.tucss;
1194 					ckinfo[1].ck_off =
1195 					    cd->upper_setup.tcp_fields.tucso;
1196 					ckinfo[1].ck_len =
1197 					    cd->upper_setup.tcp_fields.tucse;
1198 				}
1199 			}
1200 			break;
1201 		}
1202 	}
1203 
1204 	if (iovcnt > I82545_MAX_TXSEGS) {
1205 		WPRINTF("tx too many descriptors (%d > %d) -- dropped\r\n",
1206 		    iovcnt, I82545_MAX_TXSEGS);
1207 		goto done;
1208 	}
1209 
1210 	hdrlen = vlen = 0;
1211 	/* Estimate writable space for VLAN header insertion. */
1212 	if ((sc->esc_CTRL & E1000_CTRL_VME) &&
1213 	    (dsc->td.lower.data & E1000_TXD_CMD_VLE)) {
1214 		hdrlen = ETHER_ADDR_LEN*2;
1215 		vlen = ETHER_VLAN_ENCAP_LEN;
1216 	}
1217 	if (!tso) {
1218 		/* Estimate required writable space for checksums. */
1219 		if (ckinfo[0].ck_valid)
1220 			hdrlen = MAX(hdrlen, ckinfo[0].ck_off + 2);
1221 		if (ckinfo[1].ck_valid)
1222 			hdrlen = MAX(hdrlen, ckinfo[1].ck_off + 2);
1223 		/* Round up writable space to the first vector. */
1224 		if (hdrlen != 0 && iov[0].iov_len > hdrlen &&
1225 		    iov[0].iov_len < hdrlen + 100)
1226 			hdrlen = iov[0].iov_len;
1227 	} else {
1228 		/* In case of TSO header length provided by software. */
1229 		hdrlen = sc->esc_txctx.tcp_seg_setup.fields.hdr_len;
1230 	}
1231 
1232 	/* Allocate, fill and prepend writable header vector. */
1233 	if (hdrlen != 0) {
1234 		hdr = __builtin_alloca(hdrlen + vlen);
1235 		hdr += vlen;
1236 		for (left = hdrlen, hdrp = hdr; left > 0;
1237 		    left -= now, hdrp += now) {
1238 			now = MIN(left, iov->iov_len);
1239 			memcpy(hdrp, iov->iov_base, now);
1240 			iov->iov_base += now;
1241 			iov->iov_len -= now;
1242 			if (iov->iov_len == 0) {
1243 				iov++;
1244 				iovcnt--;
1245 			}
1246 		}
1247 		iov--;
1248 		iovcnt++;
1249 		iov->iov_base = hdr;
1250 		iov->iov_len = hdrlen;
1251 	}
1252 
1253 	/* Insert VLAN tag. */
1254 	if (vlen != 0) {
1255 		hdr -= ETHER_VLAN_ENCAP_LEN;
1256 		memmove(hdr, hdr + ETHER_VLAN_ENCAP_LEN, ETHER_ADDR_LEN*2);
1257 		hdrlen += ETHER_VLAN_ENCAP_LEN;
1258 		hdr[ETHER_ADDR_LEN*2 + 0] = sc->esc_VET >> 8;
1259 		hdr[ETHER_ADDR_LEN*2 + 1] = sc->esc_VET & 0xff;
1260 		hdr[ETHER_ADDR_LEN*2 + 2] = dsc->td.upper.fields.special >> 8;
1261 		hdr[ETHER_ADDR_LEN*2 + 3] = dsc->td.upper.fields.special & 0xff;
1262 		iov->iov_base = hdr;
1263 		iov->iov_len += ETHER_VLAN_ENCAP_LEN;
1264 		/* Correct checksum offsets after VLAN tag insertion. */
1265 		ckinfo[0].ck_start += ETHER_VLAN_ENCAP_LEN;
1266 		ckinfo[0].ck_off += ETHER_VLAN_ENCAP_LEN;
1267 		if (ckinfo[0].ck_len != 0)
1268 			ckinfo[0].ck_len += ETHER_VLAN_ENCAP_LEN;
1269 		ckinfo[1].ck_start += ETHER_VLAN_ENCAP_LEN;
1270 		ckinfo[1].ck_off += ETHER_VLAN_ENCAP_LEN;
1271 		if (ckinfo[1].ck_len != 0)
1272 			ckinfo[1].ck_len += ETHER_VLAN_ENCAP_LEN;
1273 	}
1274 
1275 	/* Simple non-TSO case. */
1276 	if (!tso) {
1277 		/* Calculate checksums and transmit. */
1278 		if (ckinfo[0].ck_valid)
1279 			e82545_transmit_checksum(iov, iovcnt, &ckinfo[0]);
1280 		if (ckinfo[1].ck_valid)
1281 			e82545_transmit_checksum(iov, iovcnt, &ckinfo[1]);
1282 		e82545_transmit_backend(sc, iov, iovcnt);
1283 		goto done;
1284 	}
1285 
1286 	/* Doing TSO. */
1287 	tcp = (sc->esc_txctx.cmd_and_length & E1000_TXD_CMD_TCP) != 0;
1288 	mss = sc->esc_txctx.tcp_seg_setup.fields.mss;
1289 	paylen = (sc->esc_txctx.cmd_and_length & 0x000fffff);
1290 	DPRINTF("tx %s segmentation offload %d+%d/%d bytes %d iovs\r\n",
1291 	    tcp ? "TCP" : "UDP", hdrlen, paylen, mss, iovcnt);
1292 	ipid = ntohs(*(uint16_t *)&hdr[ckinfo[0].ck_start + 4]);
1293 	tcpseq = ntohl(*(uint32_t *)&hdr[ckinfo[1].ck_start + 4]);
1294 	ipcs = *(uint16_t *)&hdr[ckinfo[0].ck_off];
1295 	tcpcs = 0;
1296 	if (ckinfo[1].ck_valid)	/* Save partial pseudo-header checksum. */
1297 		tcpcs = *(uint16_t *)&hdr[ckinfo[1].ck_off];
1298 	pv = 1;
1299 	pvoff = 0;
1300 	for (seg = 0, left = paylen; left > 0; seg++, left -= now) {
1301 		now = MIN(left, mss);
1302 
1303 		/* Construct IOVs for the segment. */
1304 		/* Include whole original header. */
1305 		tiov[0].iov_base = hdr;
1306 		tiov[0].iov_len = hdrlen;
1307 		tiovcnt = 1;
1308 		/* Include respective part of payload IOV. */
1309 		for (nleft = now; pv < iovcnt && nleft > 0; nleft -= nnow) {
1310 			nnow = MIN(nleft, iov[pv].iov_len - pvoff);
1311 			tiov[tiovcnt].iov_base = iov[pv].iov_base + pvoff;
1312 			tiov[tiovcnt++].iov_len = nnow;
1313 			if (pvoff + nnow == iov[pv].iov_len) {
1314 				pv++;
1315 				pvoff = 0;
1316 			} else
1317 				pvoff += nnow;
1318 		}
1319 		DPRINTF("tx segment %d %d+%d bytes %d iovs\r\n",
1320 		    seg, hdrlen, now, tiovcnt);
1321 
1322 		/* Update IP header. */
1323 		if (sc->esc_txctx.cmd_and_length & E1000_TXD_CMD_IP) {
1324 			/* IPv4 -- set length and ID */
1325 			*(uint16_t *)&hdr[ckinfo[0].ck_start + 2] =
1326 			    htons(hdrlen - ckinfo[0].ck_start + now);
1327 			*(uint16_t *)&hdr[ckinfo[0].ck_start + 4] =
1328 			    htons(ipid + seg);
1329 		} else {
1330 			/* IPv6 -- set length */
1331 			*(uint16_t *)&hdr[ckinfo[0].ck_start + 4] =
1332 			    htons(hdrlen - ckinfo[0].ck_start - 40 +
1333 				  now);
1334 		}
1335 
1336 		/* Update pseudo-header checksum. */
1337 		tcpsum = tcpcs;
1338 		tcpsum += htons(hdrlen - ckinfo[1].ck_start + now);
1339 
1340 		/* Update TCP/UDP headers. */
1341 		if (tcp) {
1342 			/* Update sequence number and FIN/PUSH flags. */
1343 			*(uint32_t *)&hdr[ckinfo[1].ck_start + 4] =
1344 			    htonl(tcpseq + paylen - left);
1345 			if (now < left) {
1346 				hdr[ckinfo[1].ck_start + 13] &=
1347 				    ~(TH_FIN | TH_PUSH);
1348 			}
1349 		} else {
1350 			/* Update payload length. */
1351 			*(uint32_t *)&hdr[ckinfo[1].ck_start + 4] =
1352 			    hdrlen - ckinfo[1].ck_start + now;
1353 		}
1354 
1355 		/* Calculate checksums and transmit. */
1356 		if (ckinfo[0].ck_valid) {
1357 			*(uint16_t *)&hdr[ckinfo[0].ck_off] = ipcs;
1358 			e82545_transmit_checksum(tiov, tiovcnt, &ckinfo[0]);
1359 		}
1360 		if (ckinfo[1].ck_valid) {
1361 			*(uint16_t *)&hdr[ckinfo[1].ck_off] =
1362 			    e82545_carry(tcpsum);
1363 			e82545_transmit_checksum(tiov, tiovcnt, &ckinfo[1]);
1364 		}
1365 		e82545_transmit_backend(sc, tiov, tiovcnt);
1366 	}
1367 
1368 done:
1369 	head = (head + 1) % dsize;
1370 	e82545_transmit_done(sc, ohead, head, dsize, tdwb);
1371 
1372 	*rhead = head;
1373 	return (desc + 1);
1374 }
1375 
1376 static void
1377 e82545_tx_run(struct e82545_softc *sc)
1378 {
1379 	uint32_t cause;
1380 	uint16_t head, rhead, tail, size;
1381 	int lim, tdwb, sent;
1382 
1383 	head = sc->esc_TDH;
1384 	tail = sc->esc_TDT;
1385 	size = sc->esc_TDLEN / 16;
1386 	DPRINTF("tx_run: head %x, rhead %x, tail %x\r\n",
1387 	    sc->esc_TDH, sc->esc_TDHr, sc->esc_TDT);
1388 
1389 	pthread_mutex_unlock(&sc->esc_mtx);
1390 	rhead = head;
1391 	tdwb = 0;
1392 	for (lim = size / 4; sc->esc_tx_enabled && lim > 0; lim -= sent) {
1393 		sent = e82545_transmit(sc, head, tail, size, &rhead, &tdwb);
1394 		if (sent == 0)
1395 			break;
1396 		head = rhead;
1397 	}
1398 	pthread_mutex_lock(&sc->esc_mtx);
1399 
1400 	sc->esc_TDH = head;
1401 	sc->esc_TDHr = rhead;
1402 	cause = 0;
1403 	if (tdwb)
1404 		cause |= E1000_ICR_TXDW;
1405 	if (lim != size / 4 && sc->esc_TDH == sc->esc_TDT)
1406 		cause |= E1000_ICR_TXQE;
1407 	if (cause)
1408 		e82545_icr_assert(sc, cause);
1409 
1410 	DPRINTF("tx_run done: head %x, rhead %x, tail %x\r\n",
1411 	    sc->esc_TDH, sc->esc_TDHr, sc->esc_TDT);
1412 }
1413 
1414 static _Noreturn void *
1415 e82545_tx_thread(void *param)
1416 {
1417 	struct e82545_softc *sc = param;
1418 
1419 	pthread_mutex_lock(&sc->esc_mtx);
1420 	for (;;) {
1421 		while (!sc->esc_tx_enabled || sc->esc_TDHr == sc->esc_TDT) {
1422 			if (sc->esc_tx_enabled && sc->esc_TDHr != sc->esc_TDT)
1423 				break;
1424 			sc->esc_tx_active = 0;
1425 			if (sc->esc_tx_enabled == 0)
1426 				pthread_cond_signal(&sc->esc_tx_cond);
1427 			pthread_cond_wait(&sc->esc_tx_cond, &sc->esc_mtx);
1428 		}
1429 		sc->esc_tx_active = 1;
1430 
1431 		/* Process some tx descriptors.  Lock dropped inside. */
1432 		e82545_tx_run(sc);
1433 	}
1434 }
1435 
1436 static void
1437 e82545_tx_start(struct e82545_softc *sc)
1438 {
1439 
1440 	if (sc->esc_tx_active == 0)
1441 		pthread_cond_signal(&sc->esc_tx_cond);
1442 }
1443 
1444 static void
1445 e82545_tx_enable(struct e82545_softc *sc)
1446 {
1447 
1448 	sc->esc_tx_enabled = 1;
1449 }
1450 
1451 static void
1452 e82545_tx_disable(struct e82545_softc *sc)
1453 {
1454 
1455 	sc->esc_tx_enabled = 0;
1456 	while (sc->esc_tx_active)
1457 		pthread_cond_wait(&sc->esc_tx_cond, &sc->esc_mtx);
1458 }
1459 
1460 static void
1461 e82545_rx_enable(struct e82545_softc *sc)
1462 {
1463 
1464 	sc->esc_rx_enabled = 1;
1465 }
1466 
1467 static void
1468 e82545_rx_disable(struct e82545_softc *sc)
1469 {
1470 
1471 	sc->esc_rx_enabled = 0;
1472 	while (sc->esc_rx_active)
1473 		pthread_cond_wait(&sc->esc_rx_cond, &sc->esc_mtx);
1474 }
1475 
1476 static void
1477 e82545_write_ra(struct e82545_softc *sc, int reg, uint32_t wval)
1478 {
1479 	struct eth_uni *eu;
1480 	int idx;
1481 
1482 	idx = reg >> 1;
1483 	assert(idx < 15);
1484 
1485 	eu = &sc->esc_uni[idx];
1486 
1487 	if (reg & 0x1) {
1488 		/* RAH */
1489 		eu->eu_valid = ((wval & E1000_RAH_AV) == E1000_RAH_AV);
1490 		eu->eu_addrsel = (wval >> 16) & 0x3;
1491 		eu->eu_eth.octet[5] = wval >> 8;
1492 		eu->eu_eth.octet[4] = wval;
1493 	} else {
1494 		/* RAL */
1495 		eu->eu_eth.octet[3] = wval >> 24;
1496 		eu->eu_eth.octet[2] = wval >> 16;
1497 		eu->eu_eth.octet[1] = wval >> 8;
1498 		eu->eu_eth.octet[0] = wval;
1499 	}
1500 }
1501 
1502 static uint32_t
1503 e82545_read_ra(struct e82545_softc *sc, int reg)
1504 {
1505 	struct eth_uni *eu;
1506 	uint32_t retval;
1507 	int idx;
1508 
1509 	idx = reg >> 1;
1510 	assert(idx < 15);
1511 
1512 	eu = &sc->esc_uni[idx];
1513 
1514 	if (reg & 0x1) {
1515 		/* RAH */
1516 		retval = (eu->eu_valid << 31) |
1517 			 (eu->eu_addrsel << 16) |
1518 			 (eu->eu_eth.octet[5] << 8) |
1519 			 eu->eu_eth.octet[4];
1520 	} else {
1521 		/* RAL */
1522 		retval = (eu->eu_eth.octet[3] << 24) |
1523 			 (eu->eu_eth.octet[2] << 16) |
1524 			 (eu->eu_eth.octet[1] << 8) |
1525 			 eu->eu_eth.octet[0];
1526 	}
1527 
1528 	return (retval);
1529 }
1530 
1531 static void
1532 e82545_write_register(struct e82545_softc *sc, uint32_t offset, uint32_t value)
1533 {
1534 	int ridx;
1535 
1536 	if (offset & 0x3) {
1537 		DPRINTF("Unaligned register write offset:0x%x value:0x%x\r\n", offset, value);
1538 		return;
1539 	}
1540 	DPRINTF("Register write: 0x%x value: 0x%x\r\n", offset, value);
1541 
1542 	switch (offset) {
1543 	case E1000_CTRL:
1544 	case E1000_CTRL_DUP:
1545 		e82545_devctl(sc, value);
1546 		break;
1547 	case E1000_FCAL:
1548 		sc->esc_FCAL = value;
1549 		break;
1550 	case E1000_FCAH:
1551 		sc->esc_FCAH = value & ~0xFFFF0000;
1552 		break;
1553 	case E1000_FCT:
1554 		sc->esc_FCT = value & ~0xFFFF0000;
1555 		break;
1556 	case E1000_VET:
1557 		sc->esc_VET = value & ~0xFFFF0000;
1558 		break;
1559 	case E1000_FCTTV:
1560 		sc->esc_FCTTV = value & ~0xFFFF0000;
1561 		break;
1562 	case E1000_LEDCTL:
1563 		sc->esc_LEDCTL = value & ~0x30303000;
1564 		break;
1565 	case E1000_PBA:
1566 		sc->esc_PBA = value & 0x0000FF80;
1567 		break;
1568 	case E1000_ICR:
1569 	case E1000_ITR:
1570 	case E1000_ICS:
1571 	case E1000_IMS:
1572 	case E1000_IMC:
1573 		e82545_intr_write(sc, offset, value);
1574 		break;
1575 	case E1000_RCTL:
1576 		e82545_rx_ctl(sc, value);
1577 		break;
1578 	case E1000_FCRTL:
1579 		sc->esc_FCRTL = value & ~0xFFFF0007;
1580 		break;
1581 	case E1000_FCRTH:
1582 		sc->esc_FCRTH = value & ~0xFFFF0007;
1583 		break;
1584 	case E1000_RDBAL(0):
1585 		sc->esc_RDBAL = value & ~0xF;
1586 		if (sc->esc_rx_enabled) {
1587 			/* Apparently legal: update cached address */
1588 			e82545_rx_update_rdba(sc);
1589 		}
1590 		break;
1591 	case E1000_RDBAH(0):
1592 		assert(!sc->esc_rx_enabled);
1593 		sc->esc_RDBAH = value;
1594 		break;
1595 	case E1000_RDLEN(0):
1596 		assert(!sc->esc_rx_enabled);
1597 		sc->esc_RDLEN = value & ~0xFFF0007F;
1598 		break;
1599 	case E1000_RDH(0):
1600 		/* XXX should only ever be zero ? Range check ? */
1601 		sc->esc_RDH = value;
1602 		break;
1603 	case E1000_RDT(0):
1604 		/* XXX if this opens up the rx ring, do something ? */
1605 		sc->esc_RDT = value;
1606 		break;
1607 	case E1000_RDTR:
1608 		/* ignore FPD bit 31 */
1609 		sc->esc_RDTR = value & ~0xFFFF0000;
1610 		break;
1611 	case E1000_RXDCTL(0):
1612 		sc->esc_RXDCTL = value & ~0xFEC0C0C0;
1613 		break;
1614 	case E1000_RADV:
1615 		sc->esc_RADV = value & ~0xFFFF0000;
1616 		break;
1617 	case E1000_RSRPD:
1618 		sc->esc_RSRPD = value & ~0xFFFFF000;
1619 		break;
1620 	case E1000_RXCSUM:
1621 		sc->esc_RXCSUM = value & ~0xFFFFF800;
1622 		break;
1623 	case E1000_TXCW:
1624 		sc->esc_TXCW = value & ~0x3FFF0000;
1625 		break;
1626 	case E1000_TCTL:
1627 		e82545_tx_ctl(sc, value);
1628 		break;
1629 	case E1000_TIPG:
1630 		sc->esc_TIPG = value;
1631 		break;
1632 	case E1000_AIT:
1633 		sc->esc_AIT = value;
1634 		break;
1635 	case E1000_TDBAL(0):
1636 		sc->esc_TDBAL = value & ~0xF;
1637 		if (sc->esc_tx_enabled) {
1638 			/* Apparently legal */
1639 			e82545_tx_update_tdba(sc);
1640 		}
1641 		break;
1642 	case E1000_TDBAH(0):
1643 		//assert(!sc->esc_tx_enabled);
1644 		sc->esc_TDBAH = value;
1645 		break;
1646 	case E1000_TDLEN(0):
1647 		//assert(!sc->esc_tx_enabled);
1648 		sc->esc_TDLEN = value & ~0xFFF0007F;
1649 		break;
1650 	case E1000_TDH(0):
1651 		//assert(!sc->esc_tx_enabled);
1652 		/* XXX should only ever be zero ? Range check ? */
1653 		sc->esc_TDHr = sc->esc_TDH = value;
1654 		break;
1655 	case E1000_TDT(0):
1656 		/* XXX range check ? */
1657 		sc->esc_TDT = value;
1658 		if (sc->esc_tx_enabled)
1659 			e82545_tx_start(sc);
1660 		break;
1661 	case E1000_TIDV:
1662 		sc->esc_TIDV = value & ~0xFFFF0000;
1663 		break;
1664 	case E1000_TXDCTL(0):
1665 		//assert(!sc->esc_tx_enabled);
1666 		sc->esc_TXDCTL = value & ~0xC0C0C0;
1667 		break;
1668 	case E1000_TADV:
1669 		sc->esc_TADV = value & ~0xFFFF0000;
1670 		break;
1671 	case E1000_RAL(0) ... E1000_RAH(15):
1672 		/* convert to u32 offset */
1673 		ridx = (offset - E1000_RAL(0)) >> 2;
1674 		e82545_write_ra(sc, ridx, value);
1675 		break;
1676 	case E1000_MTA ... (E1000_MTA + (127*4)):
1677 		sc->esc_fmcast[(offset - E1000_MTA) >> 2] = value;
1678 		break;
1679 	case E1000_VFTA ... (E1000_VFTA + (127*4)):
1680 		sc->esc_fvlan[(offset - E1000_VFTA) >> 2] = value;
1681 		break;
1682 	case E1000_EECD:
1683 	{
1684 		//DPRINTF("EECD write 0x%x -> 0x%x\r\n", sc->eeprom_control, value);
1685 		/* edge triggered low->high */
1686 		uint32_t eecd_strobe = ((sc->eeprom_control & E1000_EECD_SK) ?
1687 			0 : (value & E1000_EECD_SK));
1688 		uint32_t eecd_mask = (E1000_EECD_SK|E1000_EECD_CS|
1689 					E1000_EECD_DI|E1000_EECD_REQ);
1690 		sc->eeprom_control &= ~eecd_mask;
1691 		sc->eeprom_control |= (value & eecd_mask);
1692 		/* grant/revoke immediately */
1693 		if (value & E1000_EECD_REQ) {
1694 			sc->eeprom_control |= E1000_EECD_GNT;
1695 		} else {
1696                         sc->eeprom_control &= ~E1000_EECD_GNT;
1697 		}
1698 		if (eecd_strobe && (sc->eeprom_control & E1000_EECD_CS)) {
1699 			e82545_eecd_strobe(sc);
1700 		}
1701 		return;
1702 	}
1703 	case E1000_MDIC:
1704 	{
1705 		uint8_t reg_addr = (uint8_t)((value & E1000_MDIC_REG_MASK) >>
1706 						E1000_MDIC_REG_SHIFT);
1707 		uint8_t phy_addr = (uint8_t)((value & E1000_MDIC_PHY_MASK) >>
1708 						E1000_MDIC_PHY_SHIFT);
1709 		sc->mdi_control =
1710 			(value & ~(E1000_MDIC_ERROR|E1000_MDIC_DEST));
1711 		if ((value & E1000_MDIC_READY) != 0) {
1712 			DPRINTF("Incorrect MDIC ready bit: 0x%x\r\n", value);
1713 			return;
1714 		}
1715 		switch (value & E82545_MDIC_OP_MASK) {
1716 		case E1000_MDIC_OP_READ:
1717 			sc->mdi_control &= ~E82545_MDIC_DATA_MASK;
1718 			sc->mdi_control |= e82545_read_mdi(sc, reg_addr, phy_addr);
1719 			break;
1720 		case E1000_MDIC_OP_WRITE:
1721 			e82545_write_mdi(sc, reg_addr, phy_addr,
1722 				value & E82545_MDIC_DATA_MASK);
1723 			break;
1724 		default:
1725 			DPRINTF("Unknown MDIC op: 0x%x\r\n", value);
1726 			return;
1727 		}
1728 		/* TODO: barrier? */
1729 		sc->mdi_control |= E1000_MDIC_READY;
1730 		if (value & E82545_MDIC_IE) {
1731 			// TODO: generate interrupt
1732 		}
1733 		return;
1734 	}
1735 	case E1000_MANC:
1736 	case E1000_STATUS:
1737 		return;
1738 	default:
1739 		DPRINTF("Unknown write register: 0x%x value:%x\r\n", offset, value);
1740 		return;
1741 	}
1742 }
1743 
1744 static uint32_t
1745 e82545_read_register(struct e82545_softc *sc, uint32_t offset)
1746 {
1747 	uint32_t retval;
1748 	int ridx;
1749 
1750 	if (offset & 0x3) {
1751 		DPRINTF("Unaligned register read offset:0x%x\r\n", offset);
1752 		return 0;
1753 	}
1754 
1755 	DPRINTF("Register read: 0x%x\r\n", offset);
1756 
1757 	switch (offset) {
1758 	case E1000_CTRL:
1759 		retval = sc->esc_CTRL;
1760 		break;
1761 	case E1000_STATUS:
1762 		retval = E1000_STATUS_FD | E1000_STATUS_LU |
1763 		    E1000_STATUS_SPEED_1000;
1764 		break;
1765 	case E1000_FCAL:
1766 		retval = sc->esc_FCAL;
1767 		break;
1768 	case E1000_FCAH:
1769 		retval = sc->esc_FCAH;
1770 		break;
1771 	case E1000_FCT:
1772 		retval = sc->esc_FCT;
1773 		break;
1774 	case E1000_VET:
1775 		retval = sc->esc_VET;
1776 		break;
1777 	case E1000_FCTTV:
1778 		retval = sc->esc_FCTTV;
1779 		break;
1780 	case E1000_LEDCTL:
1781 		retval = sc->esc_LEDCTL;
1782 		break;
1783 	case E1000_PBA:
1784 		retval = sc->esc_PBA;
1785 		break;
1786 	case E1000_ICR:
1787 	case E1000_ITR:
1788 	case E1000_ICS:
1789 	case E1000_IMS:
1790 	case E1000_IMC:
1791 		retval = e82545_intr_read(sc, offset);
1792 		break;
1793 	case E1000_RCTL:
1794 		retval = sc->esc_RCTL;
1795 		break;
1796 	case E1000_FCRTL:
1797 		retval = sc->esc_FCRTL;
1798 		break;
1799 	case E1000_FCRTH:
1800 		retval = sc->esc_FCRTH;
1801 		break;
1802 	case E1000_RDBAL(0):
1803 		retval = sc->esc_RDBAL;
1804 		break;
1805 	case E1000_RDBAH(0):
1806 		retval = sc->esc_RDBAH;
1807 		break;
1808 	case E1000_RDLEN(0):
1809 		retval = sc->esc_RDLEN;
1810 		break;
1811 	case E1000_RDH(0):
1812 		retval = sc->esc_RDH;
1813 		break;
1814 	case E1000_RDT(0):
1815 		retval = sc->esc_RDT;
1816 		break;
1817 	case E1000_RDTR:
1818 		retval = sc->esc_RDTR;
1819 		break;
1820 	case E1000_RXDCTL(0):
1821 		retval = sc->esc_RXDCTL;
1822 		break;
1823 	case E1000_RADV:
1824 		retval = sc->esc_RADV;
1825 		break;
1826 	case E1000_RSRPD:
1827 		retval = sc->esc_RSRPD;
1828 		break;
1829 	case E1000_RXCSUM:
1830 		retval = sc->esc_RXCSUM;
1831 		break;
1832 	case E1000_TXCW:
1833 		retval = sc->esc_TXCW;
1834 		break;
1835 	case E1000_TCTL:
1836 		retval = sc->esc_TCTL;
1837 		break;
1838 	case E1000_TIPG:
1839 		retval = sc->esc_TIPG;
1840 		break;
1841 	case E1000_AIT:
1842 		retval = sc->esc_AIT;
1843 		break;
1844 	case E1000_TDBAL(0):
1845 		retval = sc->esc_TDBAL;
1846 		break;
1847 	case E1000_TDBAH(0):
1848 		retval = sc->esc_TDBAH;
1849 		break;
1850 	case E1000_TDLEN(0):
1851 		retval = sc->esc_TDLEN;
1852 		break;
1853 	case E1000_TDH(0):
1854 		retval = sc->esc_TDH;
1855 		break;
1856 	case E1000_TDT(0):
1857 		retval = sc->esc_TDT;
1858 		break;
1859 	case E1000_TIDV:
1860 		retval = sc->esc_TIDV;
1861 		break;
1862 	case E1000_TXDCTL(0):
1863 		retval = sc->esc_TXDCTL;
1864 		break;
1865 	case E1000_TADV:
1866 		retval = sc->esc_TADV;
1867 		break;
1868 	case E1000_RAL(0) ... E1000_RAH(15):
1869 		/* convert to u32 offset */
1870 		ridx = (offset - E1000_RAL(0)) >> 2;
1871 		retval = e82545_read_ra(sc, ridx);
1872 		break;
1873 	case E1000_MTA ... (E1000_MTA + (127*4)):
1874 		retval = sc->esc_fmcast[(offset - E1000_MTA) >> 2];
1875 		break;
1876 	case E1000_VFTA ... (E1000_VFTA + (127*4)):
1877 		retval = sc->esc_fvlan[(offset - E1000_VFTA) >> 2];
1878 		break;
1879 	case E1000_EECD:
1880 		//DPRINTF("EECD read %x\r\n", sc->eeprom_control);
1881 		retval = sc->eeprom_control;
1882 		break;
1883 	case E1000_MDIC:
1884 		retval = sc->mdi_control;
1885 		break;
1886 	case E1000_MANC:
1887 		retval = 0;
1888 		break;
1889 	/* stats that we emulate. */
1890 	case E1000_MPC:
1891 		retval = sc->missed_pkt_count;
1892 		break;
1893 	case E1000_PRC64:
1894 		retval = sc->pkt_rx_by_size[0];
1895 		break;
1896 	case E1000_PRC127:
1897 		retval = sc->pkt_rx_by_size[1];
1898 		break;
1899 	case E1000_PRC255:
1900 		retval = sc->pkt_rx_by_size[2];
1901 		break;
1902 	case E1000_PRC511:
1903 		retval = sc->pkt_rx_by_size[3];
1904 		break;
1905 	case E1000_PRC1023:
1906 		retval = sc->pkt_rx_by_size[4];
1907 		break;
1908 	case E1000_PRC1522:
1909 		retval = sc->pkt_rx_by_size[5];
1910 		break;
1911 	case E1000_GPRC:
1912 		retval = sc->good_pkt_rx_count;
1913 		break;
1914 	case E1000_BPRC:
1915 		retval = sc->bcast_pkt_rx_count;
1916 		break;
1917 	case E1000_MPRC:
1918 		retval = sc->mcast_pkt_rx_count;
1919 		break;
1920 	case E1000_GPTC:
1921 	case E1000_TPT:
1922 		retval = sc->good_pkt_tx_count;
1923 		break;
1924 	case E1000_GORCL:
1925 		retval = (uint32_t)sc->good_octets_rx;
1926 		break;
1927 	case E1000_GORCH:
1928 		retval = (uint32_t)(sc->good_octets_rx >> 32);
1929 		break;
1930 	case E1000_TOTL:
1931 	case E1000_GOTCL:
1932 		retval = (uint32_t)sc->good_octets_tx;
1933 		break;
1934 	case E1000_TOTH:
1935 	case E1000_GOTCH:
1936 		retval = (uint32_t)(sc->good_octets_tx >> 32);
1937 		break;
1938 	case E1000_ROC:
1939 		retval = sc->oversize_rx_count;
1940 		break;
1941 	case E1000_TORL:
1942 		retval = (uint32_t)(sc->good_octets_rx + sc->missed_octets);
1943 		break;
1944 	case E1000_TORH:
1945 		retval = (uint32_t)((sc->good_octets_rx +
1946 		    sc->missed_octets) >> 32);
1947 		break;
1948 	case E1000_TPR:
1949 		retval = sc->good_pkt_rx_count + sc->missed_pkt_count +
1950 		    sc->oversize_rx_count;
1951 		break;
1952 	case E1000_PTC64:
1953 		retval = sc->pkt_tx_by_size[0];
1954 		break;
1955 	case E1000_PTC127:
1956 		retval = sc->pkt_tx_by_size[1];
1957 		break;
1958 	case E1000_PTC255:
1959 		retval = sc->pkt_tx_by_size[2];
1960 		break;
1961 	case E1000_PTC511:
1962 		retval = sc->pkt_tx_by_size[3];
1963 		break;
1964 	case E1000_PTC1023:
1965 		retval = sc->pkt_tx_by_size[4];
1966 		break;
1967 	case E1000_PTC1522:
1968 		retval = sc->pkt_tx_by_size[5];
1969 		break;
1970 	case E1000_MPTC:
1971 		retval = sc->mcast_pkt_tx_count;
1972 		break;
1973 	case E1000_BPTC:
1974 		retval = sc->bcast_pkt_tx_count;
1975 		break;
1976 	case E1000_TSCTC:
1977 		retval = sc->tso_tx_count;
1978 		break;
1979 	/* stats that are always 0. */
1980 	case E1000_CRCERRS:
1981 	case E1000_ALGNERRC:
1982 	case E1000_SYMERRS:
1983 	case E1000_RXERRC:
1984 	case E1000_SCC:
1985 	case E1000_ECOL:
1986 	case E1000_MCC:
1987 	case E1000_LATECOL:
1988 	case E1000_COLC:
1989 	case E1000_DC:
1990 	case E1000_TNCRS:
1991 	case E1000_SEC:
1992 	case E1000_CEXTERR:
1993 	case E1000_RLEC:
1994 	case E1000_XONRXC:
1995 	case E1000_XONTXC:
1996 	case E1000_XOFFRXC:
1997 	case E1000_XOFFTXC:
1998 	case E1000_FCRUC:
1999 	case E1000_RNBC:
2000 	case E1000_RUC:
2001 	case E1000_RFC:
2002 	case E1000_RJC:
2003 	case E1000_MGTPRC:
2004 	case E1000_MGTPDC:
2005 	case E1000_MGTPTC:
2006 	case E1000_TSCTFC:
2007 		retval = 0;
2008 		break;
2009 	default:
2010 		DPRINTF("Unknown read register: 0x%x\r\n", offset);
2011 		retval = 0;
2012 		break;
2013 	}
2014 
2015 	return (retval);
2016 }
2017 
2018 static void
2019 e82545_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2020 	     uint64_t offset, int size, uint64_t value)
2021 {
2022 	struct e82545_softc *sc;
2023 
2024 	//DPRINTF("Write bar:%d offset:0x%lx value:0x%lx size:%d\r\n", baridx, offset, value, size);
2025 
2026 	sc = pi->pi_arg;
2027 
2028 	pthread_mutex_lock(&sc->esc_mtx);
2029 
2030 	switch (baridx) {
2031 	case E82545_BAR_IO:
2032 		switch (offset) {
2033 		case E82545_IOADDR:
2034 			if (size != 4) {
2035 				DPRINTF("Wrong io addr write sz:%d value:0x%lx\r\n", size, value);
2036 			} else
2037 				sc->io_addr = (uint32_t)value;
2038 			break;
2039 		case E82545_IODATA:
2040 			if (size != 4) {
2041 				DPRINTF("Wrong io data write size:%d value:0x%lx\r\n", size, value);
2042 			} else if (sc->io_addr > E82545_IO_REGISTER_MAX) {
2043 				DPRINTF("Non-register io write addr:0x%x value:0x%lx\r\n", sc->io_addr, value);
2044 			} else
2045 				e82545_write_register(sc, sc->io_addr,
2046 						      (uint32_t)value);
2047 			break;
2048 		default:
2049 			DPRINTF("Unknown io bar write offset:0x%lx value:0x%lx size:%d\r\n", offset, value, size);
2050 			break;
2051 		}
2052 		break;
2053 	case E82545_BAR_REGISTER:
2054 		if (size != 4) {
2055 			DPRINTF("Wrong register write size:%d offset:0x%lx value:0x%lx\r\n", size, offset, value);
2056 		} else
2057 			e82545_write_register(sc, (uint32_t)offset,
2058 					      (uint32_t)value);
2059 		break;
2060 	default:
2061 		DPRINTF("Unknown write bar:%d off:0x%lx val:0x%lx size:%d\r\n",
2062 			baridx, offset, value, size);
2063 	}
2064 
2065 	pthread_mutex_unlock(&sc->esc_mtx);
2066 }
2067 
2068 static uint64_t
2069 e82545_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2070 	    uint64_t offset, int size)
2071 {
2072 	struct e82545_softc *sc;
2073 	uint64_t retval;
2074 
2075 	//DPRINTF("Read  bar:%d offset:0x%lx size:%d\r\n", baridx, offset, size);
2076 	sc = pi->pi_arg;
2077 	retval = 0;
2078 
2079 	pthread_mutex_lock(&sc->esc_mtx);
2080 
2081 	switch (baridx) {
2082 	case E82545_BAR_IO:
2083 		switch (offset) {
2084 		case E82545_IOADDR:
2085 			if (size != 4) {
2086 				DPRINTF("Wrong io addr read sz:%d\r\n", size);
2087 			} else
2088 				retval = sc->io_addr;
2089 			break;
2090 		case E82545_IODATA:
2091 			if (size != 4) {
2092 				DPRINTF("Wrong io data read sz:%d\r\n", size);
2093 			}
2094 			if (sc->io_addr > E82545_IO_REGISTER_MAX) {
2095 				DPRINTF("Non-register io read addr:0x%x\r\n",
2096 					sc->io_addr);
2097 			} else
2098 				retval = e82545_read_register(sc, sc->io_addr);
2099 			break;
2100 		default:
2101 			DPRINTF("Unknown io bar read offset:0x%lx size:%d\r\n",
2102 				offset, size);
2103 			break;
2104 		}
2105 		break;
2106 	case E82545_BAR_REGISTER:
2107 		if (size != 4) {
2108 			DPRINTF("Wrong register read size:%d offset:0x%lx\r\n",
2109 				size, offset);
2110 		} else
2111 			retval = e82545_read_register(sc, (uint32_t)offset);
2112 		break;
2113 	default:
2114 		DPRINTF("Unknown read bar:%d offset:0x%lx size:%d\r\n",
2115 			baridx, offset, size);
2116 		break;
2117 	}
2118 
2119 	pthread_mutex_unlock(&sc->esc_mtx);
2120 
2121 	return (retval);
2122 }
2123 
2124 static void
2125 e82545_reset(struct e82545_softc *sc, int drvr)
2126 {
2127 	int i;
2128 
2129 	e82545_rx_disable(sc);
2130 	e82545_tx_disable(sc);
2131 
2132 	/* clear outstanding interrupts */
2133 	if (sc->esc_irq_asserted)
2134 		pci_lintr_deassert(sc->esc_pi);
2135 
2136 	/* misc */
2137 	if (!drvr) {
2138 		sc->esc_FCAL = 0;
2139 		sc->esc_FCAH = 0;
2140 		sc->esc_FCT = 0;
2141 		sc->esc_VET = 0;
2142 		sc->esc_FCTTV = 0;
2143 	}
2144 	sc->esc_LEDCTL = 0x07061302;
2145 	sc->esc_PBA = 0x00100030;
2146 
2147 	/* start nvm in opcode mode. */
2148 	sc->nvm_opaddr = 0;
2149 	sc->nvm_mode = E82545_NVM_MODE_OPADDR;
2150 	sc->nvm_bits = E82545_NVM_OPADDR_BITS;
2151 	sc->eeprom_control = E1000_EECD_PRES | E82545_EECD_FWE_EN;
2152 	e82545_init_eeprom(sc);
2153 
2154 	/* interrupt */
2155 	sc->esc_ICR = 0;
2156 	sc->esc_ITR = 250;
2157 	sc->esc_ICS = 0;
2158 	sc->esc_IMS = 0;
2159 	sc->esc_IMC = 0;
2160 
2161 	/* L2 filters */
2162 	if (!drvr) {
2163 		memset(sc->esc_fvlan, 0, sizeof(sc->esc_fvlan));
2164 		memset(sc->esc_fmcast, 0, sizeof(sc->esc_fmcast));
2165 		memset(sc->esc_uni, 0, sizeof(sc->esc_uni));
2166 
2167 		/* XXX not necessary on 82545 ?? */
2168 		sc->esc_uni[0].eu_valid = 1;
2169 		memcpy(sc->esc_uni[0].eu_eth.octet, sc->esc_mac.octet,
2170 		    ETHER_ADDR_LEN);
2171 	} else {
2172 		/* Clear RAH valid bits */
2173 		for (i = 0; i < 16; i++)
2174 			sc->esc_uni[i].eu_valid = 0;
2175 	}
2176 
2177 	/* receive */
2178 	if (!drvr) {
2179 		sc->esc_RDBAL = 0;
2180 		sc->esc_RDBAH = 0;
2181 	}
2182 	sc->esc_RCTL = 0;
2183 	sc->esc_FCRTL = 0;
2184 	sc->esc_FCRTH = 0;
2185 	sc->esc_RDLEN = 0;
2186 	sc->esc_RDH = 0;
2187 	sc->esc_RDT = 0;
2188 	sc->esc_RDTR = 0;
2189 	sc->esc_RXDCTL = (1 << 24) | (1 << 16); /* default GRAN/WTHRESH */
2190 	sc->esc_RADV = 0;
2191 	sc->esc_RXCSUM = 0;
2192 
2193 	/* transmit */
2194 	if (!drvr) {
2195 		sc->esc_TDBAL = 0;
2196 		sc->esc_TDBAH = 0;
2197 		sc->esc_TIPG = 0;
2198 		sc->esc_AIT = 0;
2199 		sc->esc_TIDV = 0;
2200 		sc->esc_TADV = 0;
2201 	}
2202 	sc->esc_tdba = 0;
2203 	sc->esc_txdesc = NULL;
2204 	sc->esc_TXCW = 0;
2205 	sc->esc_TCTL = 0;
2206 	sc->esc_TDLEN = 0;
2207 	sc->esc_TDT = 0;
2208 	sc->esc_TDHr = sc->esc_TDH = 0;
2209 	sc->esc_TXDCTL = 0;
2210 }
2211 
2212 static void
2213 e82545_open_tap(struct e82545_softc *sc, char *opts)
2214 {
2215 	char tbuf[80];
2216 #ifndef WITHOUT_CAPSICUM
2217 	cap_rights_t rights;
2218 #endif
2219 
2220 	if (opts == NULL) {
2221 		sc->esc_tapfd = -1;
2222 		return;
2223 	}
2224 
2225 	strcpy(tbuf, "/dev/");
2226 	strlcat(tbuf, opts, sizeof(tbuf));
2227 
2228 	sc->esc_tapfd = open(tbuf, O_RDWR);
2229 	if (sc->esc_tapfd == -1) {
2230 		DPRINTF("unable to open tap device %s\n", opts);
2231 		exit(4);
2232 	}
2233 
2234 	/*
2235 	 * Set non-blocking and register for read
2236 	 * notifications with the event loop
2237 	 */
2238 	int opt = 1;
2239 	if (ioctl(sc->esc_tapfd, FIONBIO, &opt) < 0) {
2240 		WPRINTF("tap device O_NONBLOCK failed: %d\n", errno);
2241 		close(sc->esc_tapfd);
2242 		sc->esc_tapfd = -1;
2243 	}
2244 
2245 #ifndef WITHOUT_CAPSICUM
2246 	cap_rights_init(&rights, CAP_EVENT, CAP_READ, CAP_WRITE);
2247 	if (caph_rights_limit(sc->esc_tapfd, &rights) == -1)
2248 		errx(EX_OSERR, "Unable to apply rights for sandbox");
2249 #endif
2250 
2251 	sc->esc_mevp = mevent_add(sc->esc_tapfd,
2252 				  EVF_READ,
2253 				  e82545_tap_callback,
2254 				  sc);
2255 	if (sc->esc_mevp == NULL) {
2256 		DPRINTF("Could not register mevent %d\n", EVF_READ);
2257 		close(sc->esc_tapfd);
2258 		sc->esc_tapfd = -1;
2259 	}
2260 }
2261 
2262 static int
2263 e82545_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2264 {
2265 	char nstr[80];
2266 	struct e82545_softc *sc;
2267 	char *devname;
2268 	char *vtopts;
2269 	int mac_provided;
2270 
2271 	DPRINTF("Loading with options: %s\r\n", opts);
2272 
2273 	/* Setup our softc */
2274 	sc = calloc(1, sizeof(*sc));
2275 
2276 	pi->pi_arg = sc;
2277 	sc->esc_pi = pi;
2278 	sc->esc_ctx = ctx;
2279 
2280 	pthread_mutex_init(&sc->esc_mtx, NULL);
2281 	pthread_cond_init(&sc->esc_rx_cond, NULL);
2282 	pthread_cond_init(&sc->esc_tx_cond, NULL);
2283 	pthread_create(&sc->esc_tx_tid, NULL, e82545_tx_thread, sc);
2284 	snprintf(nstr, sizeof(nstr), "e82545-%d:%d tx", pi->pi_slot,
2285 	    pi->pi_func);
2286         pthread_set_name_np(sc->esc_tx_tid, nstr);
2287 
2288 	pci_set_cfgdata16(pi, PCIR_DEVICE, E82545_DEV_ID_82545EM_COPPER);
2289 	pci_set_cfgdata16(pi, PCIR_VENDOR, E82545_VENDOR_ID_INTEL);
2290 	pci_set_cfgdata8(pi,  PCIR_CLASS, PCIC_NETWORK);
2291 	pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_NETWORK_ETHERNET);
2292 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, E82545_SUBDEV_ID);
2293 	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, E82545_VENDOR_ID_INTEL);
2294 
2295 	pci_set_cfgdata8(pi,  PCIR_HDRTYPE, PCIM_HDRTYPE_NORMAL);
2296 	pci_set_cfgdata8(pi,  PCIR_INTPIN, 0x1);
2297 
2298 	/* TODO: this card also supports msi, but the freebsd driver for it
2299 	 * does not, so I have not implemented it. */
2300 	pci_lintr_request(pi);
2301 
2302 	pci_emul_alloc_bar(pi, E82545_BAR_REGISTER, PCIBAR_MEM32,
2303 		E82545_BAR_REGISTER_LEN);
2304 	pci_emul_alloc_bar(pi, E82545_BAR_FLASH, PCIBAR_MEM32,
2305 		E82545_BAR_FLASH_LEN);
2306 	pci_emul_alloc_bar(pi, E82545_BAR_IO, PCIBAR_IO,
2307 		E82545_BAR_IO_LEN);
2308 
2309 	/*
2310 	 * Attempt to open the tap device and read the MAC address
2311 	 * if specified.  Copied from virtio-net, slightly modified.
2312 	 */
2313 	mac_provided = 0;
2314 	sc->esc_tapfd = -1;
2315 	if (opts != NULL) {
2316 		int err;
2317 
2318 		devname = vtopts = strdup(opts);
2319 		(void) strsep(&vtopts, ",");
2320 
2321 		if (vtopts != NULL) {
2322 			err = net_parsemac(vtopts, sc->esc_mac.octet);
2323 			if (err != 0) {
2324 				free(devname);
2325 				return (err);
2326 			}
2327 			mac_provided = 1;
2328 		}
2329 
2330 		if (strncmp(devname, "tap", 3) == 0 ||
2331 		    strncmp(devname, "vmnet", 5) == 0)
2332 			e82545_open_tap(sc, devname);
2333 
2334 		free(devname);
2335 	}
2336 
2337 	if (!mac_provided) {
2338 		net_genmac(pi, sc->esc_mac.octet);
2339 	}
2340 
2341 	/* H/w initiated reset */
2342 	e82545_reset(sc, 0);
2343 
2344 	return (0);
2345 }
2346 
2347 struct pci_devemu pci_de_e82545 = {
2348 	.pe_emu = 	"e1000",
2349 	.pe_init =	e82545_init,
2350 	.pe_barwrite =	e82545_write,
2351 	.pe_barread =	e82545_read
2352 };
2353 PCI_EMUL_SET(pci_de_e82545);
2354 
2355