xref: /dflybsd-src/sys/dev/netif/re/if_re.c (revision cb8d752c91e50d49493e6841a71a3add51e2f2da)
1 /*
2  * Copyright (c) 2004
3  *	Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
4  *
5  * Copyright (c) 1997, 1998-2003
6  *	Bill Paul <wpaul@windriver.com>.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by Bill Paul.
19  * 4. Neither the name of the author nor the names of any co-contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33  * THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * $FreeBSD: src/sys/dev/re/if_re.c,v 1.25 2004/06/09 14:34:01 naddy Exp $
36  * $DragonFly: src/sys/dev/netif/re/if_re.c,v 1.46 2008/07/27 10:06:56 sephe Exp $
37  */
38 
39 /*
40  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E PCI NIC driver
41  *
42  * Written by Bill Paul <wpaul@windriver.com>
43  * Senior Networking Software Engineer
44  * Wind River Systems
45  */
46 
47 /*
48  * This driver is designed to support RealTek's next generation of
49  * 10/100 and 10/100/1000 PCI ethernet controllers. There are currently
50  * seven devices in this family: the RTL8139C+, the RTL8169, the RTL8169S,
51  * RTL8110S, the RTL8168, the RTL8111 and the RTL8101E.
52  *
53  * The 8139C+ is a 10/100 ethernet chip. It is backwards compatible
54  * with the older 8139 family, however it also supports a special
55  * C+ mode of operation that provides several new performance enhancing
56  * features. These include:
57  *
58  *	o Descriptor based DMA mechanism. Each descriptor represents
59  *	  a single packet fragment. Data buffers may be aligned on
60  *	  any byte boundary.
61  *
62  *	o 64-bit DMA
63  *
64  *	o TCP/IP checksum offload for both RX and TX
65  *
66  *	o High and normal priority transmit DMA rings
67  *
68  *	o VLAN tag insertion and extraction
69  *
70  *	o TCP large send (segmentation offload)
71  *
72  * Like the 8139, the 8139C+ also has a built-in 10/100 PHY. The C+
73  * programming API is fairly straightforward. The RX filtering, EEPROM
74  * access and PHY access is the same as it is on the older 8139 series
75  * chips.
76  *
77  * The 8169 is a 64-bit 10/100/1000 gigabit ethernet MAC. It has almost the
78  * same programming API and feature set as the 8139C+ with the following
79  * differences and additions:
80  *
81  *	o 1000Mbps mode
82  *
83  *	o Jumbo frames
84  *
85  * 	o GMII and TBI ports/registers for interfacing with copper
86  *	  or fiber PHYs
87  *
88  *      o RX and TX DMA rings can have up to 1024 descriptors
89  *        (the 8139C+ allows a maximum of 64)
90  *
91  *	o Slight differences in register layout from the 8139C+
92  *
93  * The TX start and timer interrupt registers are at different locations
94  * on the 8169 than they are on the 8139C+. Also, the status word in the
95  * RX descriptor has a slightly different bit layout. The 8169 does not
96  * have a built-in PHY. Most reference boards use a Marvell 88E1000 'Alaska'
97  * copper gigE PHY.
98  *
99  * The 8169S/8110S 10/100/1000 devices have built-in copper gigE PHYs
100  * (the 'S' stands for 'single-chip'). These devices have the same
101  * programming API as the older 8169, but also have some vendor-specific
102  * registers for the on-board PHY. The 8110S is a LAN-on-motherboard
103  * part designed to be pin-compatible with the RealTek 8100 10/100 chip.
104  *
105  * This driver takes advantage of the RX and TX checksum offload and
106  * VLAN tag insertion/extraction features. It also implements TX
107  * interrupt moderation using the timer interrupt registers, which
108  * significantly reduces TX interrupt load. There is also support
109  * for jumbo frames, however the 8169/8169S/8110S can not transmit
110  * jumbo frames larger than 7440, so the max MTU possible with this
111  * driver is 7422 bytes.
112  */
113 
114 #include "opt_polling.h"
115 #include "opt_ethernet.h"
116 
117 #include <sys/param.h>
118 #include <sys/bus.h>
119 #include <sys/endian.h>
120 #include <sys/kernel.h>
121 #include <sys/interrupt.h>
122 #include <sys/malloc.h>
123 #include <sys/mbuf.h>
124 #include <sys/rman.h>
125 #include <sys/serialize.h>
126 #include <sys/socket.h>
127 #include <sys/sockio.h>
128 #include <sys/sysctl.h>
129 
130 #include <net/bpf.h>
131 #include <net/ethernet.h>
132 #include <net/if.h>
133 #include <net/ifq_var.h>
134 #include <net/if_arp.h>
135 #include <net/if_dl.h>
136 #include <net/if_media.h>
137 #include <net/if_types.h>
138 #include <net/vlan/if_vlan_var.h>
139 #include <net/vlan/if_vlan_ether.h>
140 
141 #include <dev/netif/mii_layer/mii.h>
142 #include <dev/netif/mii_layer/miivar.h>
143 
144 #include <bus/pci/pcidevs.h>
145 #include <bus/pci/pcireg.h>
146 #include <bus/pci/pcivar.h>
147 
148 /* "device miibus" required.  See GENERIC if you get errors here. */
149 #include "miibus_if.h"
150 
151 #include <dev/netif/re/if_rereg.h>
152 #include <dev/netif/re/if_revar.h>
153 
154 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
155 #if 0
156 #define RE_DISABLE_HWCSUM
157 #endif
158 
159 /*
160  * Various supported device vendors/types and their names.
161  */
162 static const struct re_type re_devs[] = {
163 	{ PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE528T, RE_HWREV_8169S,
164 		"D-Link DGE-528(T) Gigabit Ethernet Adapter" },
165 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139, RE_HWREV_8139CPLUS,
166 		"RealTek 8139C+ 10/100BaseTX" },
167 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E, RE_HWREV_8101E,
168 		"RealTek 8101E PCIe 10/100baseTX" },
169 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN1,
170 		"RealTek 8168/8111B PCIe Gigabit Ethernet" },
171 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN2,
172 		"RealTek 8168/8111B PCIe Gigabit Ethernet" },
173 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN3,
174 		"RealTek 8168B/8111B PCIe Gigabit Ethernet" },
175 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168C,
176 		"RealTek 8168C/8111C PCIe Gigabit Ethernet" },
177 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169,
178 		"RealTek 8169 Gigabit Ethernet" },
179 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169S,
180 		"RealTek 8169S Single-chip Gigabit Ethernet" },
181 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SB,
182 		"RealTek 8169SB/8110SB Single-chip Gigabit Ethernet" },
183 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SC,
184 		"RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
185 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169SC, RE_HWREV_8169_8110SC,
186 		"RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
187 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8110S,
188 		"RealTek 8110S Single-chip Gigabit Ethernet" },
189 	{ PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CG_LAPCIGT, RE_HWREV_8169S,
190 		"Corega CG-LAPCIGT Gigabit Ethernet" },
191 	{ PCI_VENDOR_LINKSYS, PCI_PRODUCT_LINKSYS_EG1032, RE_HWREV_8169S,
192 		"Linksys EG1032 Gigabit Ethernet" },
193 	{ PCI_VENDOR_USR2, PCI_PRODUCT_USR2_997902, RE_HWREV_8169S,
194 		"US Robotics 997902 Gigabit Ethernet" },
195 	{ 0, 0, 0, NULL }
196 };
197 
198 static const struct re_hwrev re_hwrevs[] = {
199 	{ RE_HWREV_8139CPLUS,	RE_8139CPLUS,	RE_F_HASMPC,	"C+" },
200 	{ RE_HWREV_8168_SPIN1,	RE_8169,	RE_F_PCIE,	"8168" },
201 	{ RE_HWREV_8168_SPIN2,	RE_8169,	RE_F_PCIE,	"8168" },
202 	{ RE_HWREV_8168_SPIN3,	RE_8169,	RE_F_PCIE,	"8168" },
203 	{ RE_HWREV_8168C,	RE_8169,	RE_F_PCIE,	"8168C" },
204 	{ RE_HWREV_8169,	RE_8169,	RE_F_HASMPC,	"8169" },
205 	{ RE_HWREV_8169S,	RE_8169,	RE_F_HASMPC,	"8169S" },
206 	{ RE_HWREV_8110S,	RE_8169,	RE_F_HASMPC,	"8110S" },
207 	{ RE_HWREV_8169_8110SB,	RE_8169,	RE_F_HASMPC,	"8169SB" },
208 	{ RE_HWREV_8169_8110SC,	RE_8169,	0,		"8169SC" },
209 	{ RE_HWREV_8100E,	RE_8169,	RE_F_HASMPC,	"8100E" },
210 	{ RE_HWREV_8101E,	RE_8169,	RE_F_PCIE,	"8101E" },
211 	{ 0, 0, 0, NULL }
212 };
213 
214 static int	re_probe(device_t);
215 static int	re_attach(device_t);
216 static int	re_detach(device_t);
217 static int	re_suspend(device_t);
218 static int	re_resume(device_t);
219 static void	re_shutdown(device_t);
220 
221 static int	re_encap(struct re_softc *, struct mbuf **, int *, int *);
222 
223 static void	re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
224 static void	re_dma_map_desc(void *, bus_dma_segment_t *, int,
225 				bus_size_t, int);
226 static int	re_allocmem(device_t, struct re_softc *);
227 static int	re_newbuf(struct re_softc *, int, struct mbuf *);
228 static int	re_rx_list_init(struct re_softc *);
229 static int	re_tx_list_init(struct re_softc *);
230 static void	re_rxeof(struct re_softc *);
231 static void	re_txeof(struct re_softc *);
232 static void	re_intr(void *);
233 static void	re_tick(void *);
234 static void	re_tick_serialized(void *);
235 
236 static void	re_start(struct ifnet *);
237 static int	re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
238 static void	re_init(void *);
239 static void	re_stop(struct re_softc *);
240 static void	re_watchdog(struct ifnet *);
241 static int	re_ifmedia_upd(struct ifnet *);
242 static void	re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
243 
244 static void	re_eeprom_putbyte(struct re_softc *, int);
245 static void	re_eeprom_getword(struct re_softc *, int, u_int16_t *);
246 static void	re_read_eeprom(struct re_softc *, caddr_t, int, int);
247 static int	re_gmii_readreg(device_t, int, int);
248 static int	re_gmii_writereg(device_t, int, int, int);
249 
250 static int	re_miibus_readreg(device_t, int, int);
251 static int	re_miibus_writereg(device_t, int, int, int);
252 static void	re_miibus_statchg(device_t);
253 
254 static void	re_setmulti(struct re_softc *);
255 static void	re_reset(struct re_softc *);
256 
257 #ifdef RE_DIAG
258 static int	re_diag(struct re_softc *);
259 #endif
260 
261 #ifdef DEVICE_POLLING
262 static void	re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
263 #endif
264 
265 static int	re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS);
266 
267 static device_method_t re_methods[] = {
268 	/* Device interface */
269 	DEVMETHOD(device_probe,		re_probe),
270 	DEVMETHOD(device_attach,	re_attach),
271 	DEVMETHOD(device_detach,	re_detach),
272 	DEVMETHOD(device_suspend,	re_suspend),
273 	DEVMETHOD(device_resume,	re_resume),
274 	DEVMETHOD(device_shutdown,	re_shutdown),
275 
276 	/* bus interface */
277 	DEVMETHOD(bus_print_child,	bus_generic_print_child),
278 	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
279 
280 	/* MII interface */
281 	DEVMETHOD(miibus_readreg,	re_miibus_readreg),
282 	DEVMETHOD(miibus_writereg,	re_miibus_writereg),
283 	DEVMETHOD(miibus_statchg,	re_miibus_statchg),
284 
285 	{ 0, 0 }
286 };
287 
288 static driver_t re_driver = {
289 	"re",
290 	re_methods,
291 	sizeof(struct re_softc)
292 };
293 
294 static devclass_t re_devclass;
295 
296 DECLARE_DUMMY_MODULE(if_re);
297 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
298 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
299 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
300 
301 #define EE_SET(x)	\
302 	CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
303 
304 #define EE_CLR(x)	\
305 	CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
306 
307 /*
308  * Send a read command and address to the EEPROM, check for ACK.
309  */
310 static void
311 re_eeprom_putbyte(struct re_softc *sc, int addr)
312 {
313 	int d, i;
314 
315 	d = addr | (RE_9346_READ << sc->re_eewidth);
316 
317 	/*
318 	 * Feed in each bit and strobe the clock.
319 	 */
320 	for (i = 1 << (sc->re_eewidth + 3); i; i >>= 1) {
321 		if (d & i)
322 			EE_SET(RE_EE_DATAIN);
323 		else
324 			EE_CLR(RE_EE_DATAIN);
325 		DELAY(100);
326 		EE_SET(RE_EE_CLK);
327 		DELAY(150);
328 		EE_CLR(RE_EE_CLK);
329 		DELAY(100);
330 	}
331 }
332 
333 /*
334  * Read a word of data stored in the EEPROM at address 'addr.'
335  */
336 static void
337 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
338 {
339 	int i;
340 	uint16_t word = 0;
341 
342 	/*
343 	 * Send address of word we want to read.
344 	 */
345 	re_eeprom_putbyte(sc, addr);
346 
347 	/*
348 	 * Start reading bits from EEPROM.
349 	 */
350 	for (i = 0x8000; i != 0; i >>= 1) {
351 		EE_SET(RE_EE_CLK);
352 		DELAY(100);
353 		if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
354 			word |= i;
355 		EE_CLR(RE_EE_CLK);
356 		DELAY(100);
357 	}
358 
359 	*dest = word;
360 }
361 
362 /*
363  * Read a sequence of words from the EEPROM.
364  */
365 static void
366 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt)
367 {
368 	int i;
369 	uint16_t word = 0, *ptr;
370 
371 	CSR_SETBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
372 	DELAY(100);
373 
374 	for (i = 0; i < cnt; i++) {
375 		CSR_SETBIT_1(sc, RE_EECMD, RE_EE_SEL);
376 		re_eeprom_getword(sc, off + i, &word);
377 		CSR_CLRBIT_1(sc, RE_EECMD, RE_EE_SEL);
378 		ptr = (uint16_t *)(dest + (i * 2));
379 		*ptr = word;
380 	}
381 
382 	CSR_CLRBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
383 }
384 
385 static int
386 re_gmii_readreg(device_t dev, int phy, int reg)
387 {
388 	struct re_softc *sc = device_get_softc(dev);
389 	u_int32_t rval;
390 	int i;
391 
392 	if (phy != 1)
393 		return(0);
394 
395 	/* Let the rgephy driver read the GMEDIASTAT register */
396 
397 	if (reg == RE_GMEDIASTAT)
398 		return(CSR_READ_1(sc, RE_GMEDIASTAT));
399 
400 	CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
401 	DELAY(1000);
402 
403 	for (i = 0; i < RE_TIMEOUT; i++) {
404 		rval = CSR_READ_4(sc, RE_PHYAR);
405 		if (rval & RE_PHYAR_BUSY)
406 			break;
407 		DELAY(100);
408 	}
409 
410 	if (i == RE_TIMEOUT) {
411 		device_printf(dev, "PHY read failed\n");
412 		return(0);
413 	}
414 
415 	return(rval & RE_PHYAR_PHYDATA);
416 }
417 
418 static int
419 re_gmii_writereg(device_t dev, int phy, int reg, int data)
420 {
421 	struct re_softc *sc = device_get_softc(dev);
422 	uint32_t rval;
423 	int i;
424 
425 	CSR_WRITE_4(sc, RE_PHYAR,
426 		    (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
427 	DELAY(1000);
428 
429 	for (i = 0; i < RE_TIMEOUT; i++) {
430 		rval = CSR_READ_4(sc, RE_PHYAR);
431 		if ((rval & RE_PHYAR_BUSY) == 0)
432 			break;
433 		DELAY(100);
434 	}
435 
436 	if (i == RE_TIMEOUT)
437 		device_printf(dev, "PHY write failed\n");
438 
439 	return(0);
440 }
441 
442 static int
443 re_miibus_readreg(device_t dev, int phy, int reg)
444 {
445 	struct re_softc	*sc = device_get_softc(dev);
446 	uint16_t rval = 0;
447 	uint16_t re8139_reg = 0;
448 
449 	if (sc->re_type == RE_8169) {
450 		rval = re_gmii_readreg(dev, phy, reg);
451 		return(rval);
452 	}
453 
454 	/* Pretend the internal PHY is only at address 0 */
455 	if (phy)
456 		return(0);
457 
458 	switch(reg) {
459 	case MII_BMCR:
460 		re8139_reg = RE_BMCR;
461 		break;
462 	case MII_BMSR:
463 		re8139_reg = RE_BMSR;
464 		break;
465 	case MII_ANAR:
466 		re8139_reg = RE_ANAR;
467 		break;
468 	case MII_ANER:
469 		re8139_reg = RE_ANER;
470 		break;
471 	case MII_ANLPAR:
472 		re8139_reg = RE_LPAR;
473 		break;
474 	case MII_PHYIDR1:
475 	case MII_PHYIDR2:
476 		return(0);
477 	/*
478 	 * Allow the rlphy driver to read the media status
479 	 * register. If we have a link partner which does not
480 	 * support NWAY, this is the register which will tell
481 	 * us the results of parallel detection.
482 	 */
483 	case RE_MEDIASTAT:
484 		return(CSR_READ_1(sc, RE_MEDIASTAT));
485 	default:
486 		device_printf(dev, "bad phy register\n");
487 		return(0);
488 	}
489 	rval = CSR_READ_2(sc, re8139_reg);
490 	if (sc->re_type == RE_8139CPLUS && re8139_reg == RE_BMCR) {
491 		/* 8139C+ has different bit layout. */
492 		rval &= ~(BMCR_LOOP | BMCR_ISO);
493 	}
494 	return(rval);
495 }
496 
497 static int
498 re_miibus_writereg(device_t dev, int phy, int reg, int data)
499 {
500 	struct re_softc *sc= device_get_softc(dev);
501 	u_int16_t re8139_reg = 0;
502 
503 	if (sc->re_type == RE_8169)
504 		return(re_gmii_writereg(dev, phy, reg, data));
505 
506 	/* Pretend the internal PHY is only at address 0 */
507 	if (phy)
508 		return(0);
509 
510 	switch(reg) {
511 	case MII_BMCR:
512 		re8139_reg = RE_BMCR;
513 		if (sc->re_type == RE_8139CPLUS) {
514 			/* 8139C+ has different bit layout. */
515 			data &= ~(BMCR_LOOP | BMCR_ISO);
516 		}
517 		break;
518 	case MII_BMSR:
519 		re8139_reg = RE_BMSR;
520 		break;
521 	case MII_ANAR:
522 		re8139_reg = RE_ANAR;
523 		break;
524 	case MII_ANER:
525 		re8139_reg = RE_ANER;
526 		break;
527 	case MII_ANLPAR:
528 		re8139_reg = RE_LPAR;
529 		break;
530 	case MII_PHYIDR1:
531 	case MII_PHYIDR2:
532 		return(0);
533 	default:
534 		device_printf(dev, "bad phy register\n");
535 		return(0);
536 	}
537 	CSR_WRITE_2(sc, re8139_reg, data);
538 	return(0);
539 }
540 
541 static void
542 re_miibus_statchg(device_t dev)
543 {
544 }
545 
546 /*
547  * Program the 64-bit multicast hash filter.
548  */
549 static void
550 re_setmulti(struct re_softc *sc)
551 {
552 	struct ifnet *ifp = &sc->arpcom.ac_if;
553 	int h = 0;
554 	uint32_t hashes[2] = { 0, 0 };
555 	struct ifmultiaddr *ifma;
556 	uint32_t rxfilt;
557 	int mcnt = 0;
558 
559 	rxfilt = CSR_READ_4(sc, RE_RXCFG);
560 
561 	if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
562 		rxfilt |= RE_RXCFG_RX_MULTI;
563 		CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
564 		CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
565 		CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
566 		return;
567 	}
568 
569 	/* first, zot all the existing hash bits */
570 	CSR_WRITE_4(sc, RE_MAR0, 0);
571 	CSR_WRITE_4(sc, RE_MAR4, 0);
572 
573 	/* now program new ones */
574 	LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
575 		if (ifma->ifma_addr->sa_family != AF_LINK)
576 			continue;
577 		h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
578 		    ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
579 		if (h < 32)
580 			hashes[0] |= (1 << h);
581 		else
582 			hashes[1] |= (1 << (h - 32));
583 		mcnt++;
584 	}
585 
586 	if (mcnt)
587 		rxfilt |= RE_RXCFG_RX_MULTI;
588 	else
589 		rxfilt &= ~RE_RXCFG_RX_MULTI;
590 
591 	CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
592 
593 	/*
594 	 * For some unfathomable reason, RealTek decided to reverse
595 	 * the order of the multicast hash registers in the PCI Express
596 	 * parts. This means we have to write the hash pattern in reverse
597 	 * order for those devices.
598 	 */
599 	if (sc->re_flags & RE_F_PCIE) {
600 		CSR_WRITE_4(sc, RE_MAR0, bswap32(hashes[0]));
601 		CSR_WRITE_4(sc, RE_MAR4, bswap32(hashes[1]));
602 	} else {
603 		CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
604 		CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
605 	}
606 }
607 
608 static void
609 re_reset(struct re_softc *sc)
610 {
611 	int i;
612 
613 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
614 
615 	for (i = 0; i < RE_TIMEOUT; i++) {
616 		DELAY(10);
617 		if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
618 			break;
619 	}
620 	if (i == RE_TIMEOUT)
621 		if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
622 
623 	CSR_WRITE_1(sc, 0x82, 1);
624 }
625 
626 #ifdef RE_DIAG
627 /*
628  * The following routine is designed to test for a defect on some
629  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
630  * lines connected to the bus, however for a 32-bit only card, they
631  * should be pulled high. The result of this defect is that the
632  * NIC will not work right if you plug it into a 64-bit slot: DMA
633  * operations will be done with 64-bit transfers, which will fail
634  * because the 64-bit data lines aren't connected.
635  *
636  * There's no way to work around this (short of talking a soldering
637  * iron to the board), however we can detect it. The method we use
638  * here is to put the NIC into digital loopback mode, set the receiver
639  * to promiscuous mode, and then try to send a frame. We then compare
640  * the frame data we sent to what was received. If the data matches,
641  * then the NIC is working correctly, otherwise we know the user has
642  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
643  * slot. In the latter case, there's no way the NIC can work correctly,
644  * so we print out a message on the console and abort the device attach.
645  */
646 
647 static int
648 re_diag(struct re_softc *sc)
649 {
650 	struct ifnet *ifp = &sc->arpcom.ac_if;
651 	struct mbuf *m0;
652 	struct ether_header *eh;
653 	struct re_desc *cur_rx;
654 	uint16_t status;
655 	uint32_t rxstat;
656 	int total_len, i, error = 0, phyaddr;
657 	uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
658 	uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
659 
660 	/* Allocate a single mbuf */
661 
662 	MGETHDR(m0, MB_DONTWAIT, MT_DATA);
663 	if (m0 == NULL)
664 		return(ENOBUFS);
665 
666 	/*
667 	 * Initialize the NIC in test mode. This sets the chip up
668 	 * so that it can send and receive frames, but performs the
669 	 * following special functions:
670 	 * - Puts receiver in promiscuous mode
671 	 * - Enables digital loopback mode
672 	 * - Leaves interrupts turned off
673 	 */
674 
675 	ifp->if_flags |= IFF_PROMISC;
676 	sc->re_testmode = 1;
677 	re_reset(sc);
678 	re_init(sc);
679 	sc->re_link = 1;
680 	if (sc->re_type == RE_8169)
681 		phyaddr = 1;
682 	else
683 		phyaddr = 0;
684 
685 	re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_RESET);
686 	for (i = 0; i < RE_TIMEOUT; i++) {
687 		status = re_miibus_readreg(sc->re_dev, phyaddr, MII_BMCR);
688 		if (!(status & BMCR_RESET))
689 			break;
690 	}
691 
692 	re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_LOOP);
693 	CSR_WRITE_2(sc, RE_ISR, RE_INTRS_DIAG);
694 
695 	DELAY(100000);
696 
697 	/* Put some data in the mbuf */
698 
699 	eh = mtod(m0, struct ether_header *);
700 	bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
701 	bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
702 	eh->ether_type = htons(ETHERTYPE_IP);
703 	m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
704 
705 	/*
706 	 * Queue the packet, start transmission.
707 	 * Note: ifq_handoff() ultimately calls re_start() for us.
708 	 */
709 
710 	CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
711 	error = ifq_handoff(ifp, m0, NULL);
712 	if (error) {
713 		m0 = NULL;
714 		goto done;
715 	}
716 	m0 = NULL;
717 
718 	/* Wait for it to propagate through the chip */
719 
720 	DELAY(100000);
721 	for (i = 0; i < RE_TIMEOUT; i++) {
722 		status = CSR_READ_2(sc, RE_ISR);
723 		CSR_WRITE_2(sc, RE_ISR, status);
724 		if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
725 		    (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
726 			break;
727 		DELAY(10);
728 	}
729 
730 	if (i == RE_TIMEOUT) {
731 		if_printf(ifp, "diagnostic failed to receive packet "
732 			  "in loopback mode\n");
733 		error = EIO;
734 		goto done;
735 	}
736 
737 	/*
738 	 * The packet should have been dumped into the first
739 	 * entry in the RX DMA ring. Grab it from there.
740 	 */
741 
742 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
743 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
744 	bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0],
745 			BUS_DMASYNC_POSTWRITE);
746 	bus_dmamap_unload(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0]);
747 
748 	m0 = sc->re_ldata.re_rx_mbuf[0];
749 	sc->re_ldata.re_rx_mbuf[0] = NULL;
750 	eh = mtod(m0, struct ether_header *);
751 
752 	cur_rx = &sc->re_ldata.re_rx_list[0];
753 	total_len = RE_RXBYTES(cur_rx);
754 	rxstat = le32toh(cur_rx->re_cmdstat);
755 
756 	if (total_len != ETHER_MIN_LEN) {
757 		if_printf(ifp, "diagnostic failed, received short packet\n");
758 		error = EIO;
759 		goto done;
760 	}
761 
762 	/* Test that the received packet data matches what we sent. */
763 
764 	if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
765 	    bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
766 	    be16toh(eh->ether_type) != ETHERTYPE_IP) {
767 		if_printf(ifp, "WARNING, DMA FAILURE!\n");
768 		if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
769 		    dst, ":", src, ":", ETHERTYPE_IP);
770 		if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
771 		    eh->ether_dhost, ":",  eh->ether_shost, ":",
772 		    ntohs(eh->ether_type));
773 		if_printf(ifp, "You may have a defective 32-bit NIC plugged "
774 		    "into a 64-bit PCI slot.\n");
775 		if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
776 		    "for proper operation.\n");
777 		if_printf(ifp, "Read the re(4) man page for more details.\n");
778 		error = EIO;
779 	}
780 
781 done:
782 	/* Turn interface off, release resources */
783 
784 	sc->re_testmode = 0;
785 	sc->re_link = 0;
786 	ifp->if_flags &= ~IFF_PROMISC;
787 	re_stop(sc);
788 	if (m0 != NULL)
789 		m_freem(m0);
790 
791 	return (error);
792 }
793 #endif	/* RE_DIAG */
794 
795 /*
796  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
797  * IDs against our list and return a device name if we find a match.
798  */
799 static int
800 re_probe(device_t dev)
801 {
802 	const struct re_type *t;
803 	struct re_softc *sc;
804 	int rid;
805 	uint32_t hwrev;
806 	uint16_t vendor, product;
807 
808 	t = re_devs;
809 
810 	vendor = pci_get_vendor(dev);
811 	product = pci_get_device(dev);
812 
813 	/*
814 	 * Only attach to rev.3 of the Linksys EG1032 adapter.
815 	 * Rev.2 is supported by sk(4).
816 	 */
817 	if (vendor == PCI_VENDOR_LINKSYS &&
818 	    product == PCI_PRODUCT_LINKSYS_EG1032 &&
819 	    pci_get_subdevice(dev) != PCI_SUBDEVICE_LINKSYS_EG1032_REV3)
820 			return ENXIO;
821 
822 	for (t = re_devs; t->re_name != NULL; t++) {
823 		if (product == t->re_did && vendor == t->re_vid)
824 			break;
825 	}
826 
827 	/*
828 	 * Check if we found a RealTek device.
829 	 */
830 	if (t->re_name == NULL)
831 		return(ENXIO);
832 
833 	/*
834 	 * Temporarily map the I/O space so we can read the chip ID register.
835 	 */
836 	sc = kmalloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
837 	rid = RE_PCI_LOIO;
838 	sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
839 					    RF_ACTIVE);
840 	if (sc->re_res == NULL) {
841 		device_printf(dev, "couldn't map ports/memory\n");
842 		kfree(sc, M_TEMP);
843 		return(ENXIO);
844 	}
845 
846 	sc->re_btag = rman_get_bustag(sc->re_res);
847 	sc->re_bhandle = rman_get_bushandle(sc->re_res);
848 
849 	hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
850 	bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
851 	kfree(sc, M_TEMP);
852 
853 	/*
854 	 * and continue matching for the specific chip...
855 	 */
856 	for (; t->re_name != NULL; t++) {
857 		if (product == t->re_did && vendor == t->re_vid &&
858 		    t->re_basetype == hwrev) {
859 			device_set_desc(dev, t->re_name);
860 			return(0);
861 		}
862 	}
863 
864 	if (bootverbose)
865 		kprintf("re: unknown hwrev %#x\n", hwrev);
866 	return(ENXIO);
867 }
868 
869 /*
870  * This routine takes the segment list provided as the result of
871  * a bus_dma_map_load() operation and assigns the addresses/lengths
872  * to RealTek DMA descriptors. This can be called either by the RX
873  * code or the TX code. In the RX case, we'll probably wind up mapping
874  * at most one segment. For the TX case, there could be any number of
875  * segments since TX packets may span multiple mbufs. In either case,
876  * if the number of segments is larger than the re_maxsegs limit
877  * specified by the caller, we abort the mapping operation. Sadly,
878  * whoever designed the buffer mapping API did not provide a way to
879  * return an error from here, so we have to fake it a bit.
880  */
881 
882 static void
883 re_dma_map_desc(void *arg, bus_dma_segment_t *segs, int nseg,
884 		bus_size_t mapsize, int error)
885 {
886 	struct re_dmaload_arg *ctx;
887 	struct re_desc *d = NULL;
888 	int i = 0, idx;
889 	uint32_t cmdstat;
890 
891 	if (error)
892 		return;
893 
894 	ctx = arg;
895 
896 	/* Signal error to caller if there's too many segments */
897 	if (nseg > ctx->re_maxsegs) {
898 		ctx->re_maxsegs = 0;
899 		return;
900 	}
901 
902 	/*
903 	 * Map the segment array into descriptors. Note that we set the
904 	 * start-of-frame and end-of-frame markers for either TX or RX, but
905 	 * they really only have meaning in the TX case. (In the RX case,
906 	 * it's the chip that tells us where packets begin and end.)
907 	 * We also keep track of the end of the ring and set the
908 	 * end-of-ring bits as needed, and we set the ownership bits
909 	 * in all except the very first descriptor. (The caller will
910 	 * set this descriptor later when it start transmission or
911 	 * reception.)
912 	 */
913 	idx = ctx->re_idx;
914 	for (;;) {
915 		d = &ctx->re_ring[idx];
916 		if (le32toh(d->re_cmdstat) & RE_RDESC_STAT_OWN) {
917 			ctx->re_maxsegs = 0;
918 			return;
919 		}
920 		cmdstat = segs[i].ds_len;
921 		d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
922 		d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
923 		if (i == 0)
924 			cmdstat |= RE_TDESC_CMD_SOF;
925 		else
926 			cmdstat |= RE_TDESC_CMD_OWN;
927 		if (idx == (RE_RX_DESC_CNT - 1))
928 			cmdstat |= RE_TDESC_CMD_EOR;
929 		d->re_cmdstat = htole32(cmdstat | ctx->re_flags);
930 		i++;
931 		if (i == nseg)
932 			break;
933 		RE_DESC_INC(idx);
934 	}
935 
936 	d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
937 	ctx->re_maxsegs = nseg;
938 	ctx->re_idx = idx;
939 }
940 
941 /*
942  * Map a single buffer address.
943  */
944 
945 static void
946 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
947 {
948 	uint32_t *addr;
949 
950 	if (error)
951 		return;
952 
953 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
954 	addr = arg;
955 	*addr = segs->ds_addr;
956 }
957 
958 static int
959 re_allocmem(device_t dev, struct re_softc *sc)
960 {
961 	int error, i, nseg;
962 
963 	/*
964 	 * Allocate map for RX mbufs.
965 	 */
966 	nseg = 32;
967 	error = bus_dma_tag_create(sc->re_parent_tag, ETHER_ALIGN, 0,
968 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
969 	    NULL, MCLBYTES * nseg, nseg, MCLBYTES, BUS_DMA_ALLOCNOW,
970 	    &sc->re_ldata.re_mtag);
971 	if (error) {
972 		device_printf(dev, "could not allocate dma tag\n");
973 		return(error);
974 	}
975 
976 	/*
977 	 * Allocate map for TX descriptor list.
978 	 */
979 	error = bus_dma_tag_create(sc->re_parent_tag, RE_RING_ALIGN,
980 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
981             NULL, RE_TX_LIST_SZ, 1, RE_TX_LIST_SZ, BUS_DMA_ALLOCNOW,
982 	    &sc->re_ldata.re_tx_list_tag);
983 	if (error) {
984 		device_printf(dev, "could not allocate dma tag\n");
985 		return(error);
986 	}
987 
988 	/* Allocate DMA'able memory for the TX ring */
989 
990         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
991 	    (void **)&sc->re_ldata.re_tx_list, BUS_DMA_WAITOK | BUS_DMA_ZERO,
992             &sc->re_ldata.re_tx_list_map);
993         if (error) {
994 		device_printf(dev, "could not allocate TX ring\n");
995                 return(error);
996 	}
997 
998 	/* Load the map for the TX ring. */
999 
1000 	error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
1001 	     sc->re_ldata.re_tx_list_map, sc->re_ldata.re_tx_list,
1002 	     RE_TX_LIST_SZ, re_dma_map_addr,
1003 	     &sc->re_ldata.re_tx_list_addr, BUS_DMA_NOWAIT);
1004 	if (error) {
1005 		device_printf(dev, "could not get address of TX ring\n");
1006 		return(error);
1007 	}
1008 
1009 	/* Create DMA maps for TX buffers */
1010 
1011 	for (i = 0; i < RE_TX_DESC_CNT; i++) {
1012 		error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1013 			    &sc->re_ldata.re_tx_dmamap[i]);
1014 		if (error) {
1015 			device_printf(dev, "can't create DMA map for TX\n");
1016 			return(error);
1017 		}
1018 	}
1019 
1020 	/*
1021 	 * Allocate map for RX descriptor list.
1022 	 */
1023 	error = bus_dma_tag_create(sc->re_parent_tag, RE_RING_ALIGN,
1024 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1025             NULL, RE_RX_LIST_SZ, 1, RE_RX_LIST_SZ, BUS_DMA_ALLOCNOW,
1026 	    &sc->re_ldata.re_rx_list_tag);
1027 	if (error) {
1028 		device_printf(dev, "could not allocate dma tag\n");
1029 		return(error);
1030 	}
1031 
1032 	/* Allocate DMA'able memory for the RX ring */
1033 
1034         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
1035 	    (void **)&sc->re_ldata.re_rx_list, BUS_DMA_WAITOK | BUS_DMA_ZERO,
1036             &sc->re_ldata.re_rx_list_map);
1037         if (error) {
1038 		device_printf(dev, "could not allocate RX ring\n");
1039                 return(error);
1040 	}
1041 
1042 	/* Load the map for the RX ring. */
1043 
1044 	error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
1045 	     sc->re_ldata.re_rx_list_map, sc->re_ldata.re_rx_list,
1046 	     RE_RX_LIST_SZ, re_dma_map_addr,
1047 	     &sc->re_ldata.re_rx_list_addr, BUS_DMA_NOWAIT);
1048 	if (error) {
1049 		device_printf(dev, "could not get address of RX ring\n");
1050 		return(error);
1051 	}
1052 
1053 	/* Create DMA maps for RX buffers */
1054 
1055 	for (i = 0; i < RE_RX_DESC_CNT; i++) {
1056 		error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1057 			    &sc->re_ldata.re_rx_dmamap[i]);
1058 		if (error) {
1059 			device_printf(dev, "can't create DMA map for RX\n");
1060 			return(ENOMEM);
1061 		}
1062 	}
1063 
1064 	return(0);
1065 }
1066 
1067 /*
1068  * Attach the interface. Allocate softc structures, do ifmedia
1069  * setup and ethernet/BPF attach.
1070  */
1071 static int
1072 re_attach(device_t dev)
1073 {
1074 	struct re_softc	*sc = device_get_softc(dev);
1075 	struct ifnet *ifp;
1076 	const struct re_hwrev *hw_rev;
1077 	uint8_t eaddr[ETHER_ADDR_LEN];
1078 	uint16_t as[ETHER_ADDR_LEN / 2];
1079 	uint16_t re_did = 0;
1080 	uint32_t hwrev;
1081 	int error = 0, rid, i;
1082 
1083 	callout_init(&sc->re_timer);
1084 #ifdef RE_DIAG
1085 	sc->re_dev = dev;
1086 #endif
1087 
1088 	RE_ENABLE_TX_MODERATION(sc);
1089 
1090 	sysctl_ctx_init(&sc->re_sysctl_ctx);
1091 	sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1092 					     SYSCTL_STATIC_CHILDREN(_hw),
1093 					     OID_AUTO,
1094 					     device_get_nameunit(dev),
1095 					     CTLFLAG_RD, 0, "");
1096 	if (sc->re_sysctl_tree == NULL) {
1097 		device_printf(dev, "can't add sysctl node\n");
1098 		error = ENXIO;
1099 		goto fail;
1100 	}
1101 	SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1102 			SYSCTL_CHILDREN(sc->re_sysctl_tree),
1103 			OID_AUTO, "tx_moderation",
1104 			CTLTYPE_INT | CTLFLAG_RW,
1105 			sc, 0, re_sysctl_tx_moderation, "I",
1106 			"Enable/Disable TX moderation");
1107 
1108 #ifndef BURN_BRIDGES
1109 	/*
1110 	 * Handle power management nonsense.
1111 	 */
1112 
1113 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1114 		uint32_t membase, irq;
1115 
1116 		/* Save important PCI config data. */
1117 		membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1118 		irq = pci_read_config(dev, PCIR_INTLINE, 4);
1119 
1120 		/* Reset the power state. */
1121 		device_printf(dev, "chip is in D%d power mode "
1122 		    "-- setting to D0\n", pci_get_powerstate(dev));
1123 
1124 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1125 
1126 		/* Restore PCI config data. */
1127 		pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1128 		pci_write_config(dev, PCIR_INTLINE, irq, 4);
1129 	}
1130 #endif
1131 	/*
1132 	 * Map control/status registers.
1133 	 */
1134 	pci_enable_busmaster(dev);
1135 
1136 	rid = RE_PCI_LOIO;
1137 	sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1138 					    RF_ACTIVE);
1139 
1140 	if (sc->re_res == NULL) {
1141 		device_printf(dev, "couldn't map ports\n");
1142 		error = ENXIO;
1143 		goto fail;
1144 	}
1145 
1146 	sc->re_btag = rman_get_bustag(sc->re_res);
1147 	sc->re_bhandle = rman_get_bushandle(sc->re_res);
1148 
1149 	/* Allocate interrupt */
1150 	rid = 0;
1151 	sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1152 					    RF_SHAREABLE | RF_ACTIVE);
1153 
1154 	if (sc->re_irq == NULL) {
1155 		device_printf(dev, "couldn't map interrupt\n");
1156 		error = ENXIO;
1157 		goto fail;
1158 	}
1159 
1160 	/* Reset the adapter. */
1161 	re_reset(sc);
1162 
1163 	hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
1164 	for (hw_rev = re_hwrevs; hw_rev->re_desc != NULL; hw_rev++) {
1165 		if (hw_rev->re_rev == hwrev) {
1166 			sc->re_type = hw_rev->re_type;
1167 			sc->re_flags = hw_rev->re_flags;
1168 			break;
1169 		}
1170 	}
1171 
1172 	sc->re_eewidth = 6;
1173 	re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1174 	if (re_did != 0x8129)
1175 	        sc->re_eewidth = 8;
1176 
1177 	/*
1178 	 * Get station address from the EEPROM.
1179 	 */
1180 	re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
1181 	for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1182 		as[i] = le16toh(as[i]);
1183 	bcopy(as, eaddr, sizeof(eaddr));
1184 
1185 	if (sc->re_type == RE_8169) {
1186 		/* Set RX length mask */
1187 		sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1188 		sc->re_txstart = RE_GTXSTART;
1189 	} else {
1190 		/* Set RX length mask */
1191 		sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1192 		sc->re_txstart = RE_TXSTART;
1193 	}
1194 
1195 	/*
1196 	 * Allocate the parent bus DMA tag appropriate for PCI.
1197 	 */
1198 #define RE_NSEG_NEW 32
1199 	error = bus_dma_tag_create(NULL,	/* parent */
1200 			1, 0,			/* alignment, boundary */
1201 			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1202 			BUS_SPACE_MAXADDR,	/* highaddr */
1203 			NULL, NULL,		/* filter, filterarg */
1204 			MAXBSIZE, RE_NSEG_NEW,	/* maxsize, nsegments */
1205 			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1206 			BUS_DMA_ALLOCNOW,	/* flags */
1207 			&sc->re_parent_tag);
1208 	if (error)
1209 		goto fail;
1210 
1211 	error = re_allocmem(dev, sc);
1212 
1213 	if (error)
1214 		goto fail;
1215 
1216 	/* Do MII setup */
1217 	if (mii_phy_probe(dev, &sc->re_miibus,
1218 	    re_ifmedia_upd, re_ifmedia_sts)) {
1219 		device_printf(dev, "MII without any phy!\n");
1220 		error = ENXIO;
1221 		goto fail;
1222 	}
1223 
1224 	ifp = &sc->arpcom.ac_if;
1225 	ifp->if_softc = sc;
1226 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1227 	ifp->if_mtu = ETHERMTU;
1228 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1229 	ifp->if_ioctl = re_ioctl;
1230 	ifp->if_start = re_start;
1231 	ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1232 	if (hwrev != RE_HWREV_8168C)	/* XXX does not work yet */
1233 		ifp->if_capabilities |= IFCAP_HWCSUM;
1234 #ifdef DEVICE_POLLING
1235 	ifp->if_poll = re_poll;
1236 #endif
1237 	ifp->if_watchdog = re_watchdog;
1238 	ifp->if_init = re_init;
1239 	if (sc->re_type == RE_8169)
1240 		ifp->if_baudrate = 1000000000;
1241 	else
1242 		ifp->if_baudrate = 100000000;
1243 	ifq_set_maxlen(&ifp->if_snd, RE_IFQ_MAXLEN);
1244 	ifq_set_ready(&ifp->if_snd);
1245 
1246 #ifdef RE_DISABLE_HWCSUM
1247 	ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1248 	ifp->if_hwassist = 0;
1249 #else
1250 	ifp->if_capenable = ifp->if_capabilities;
1251 	if (ifp->if_capabilities & IFCAP_HWCSUM)
1252 		ifp->if_hwassist = RE_CSUM_FEATURES;
1253 	else
1254 		ifp->if_hwassist = 0;
1255 #endif	/* RE_DISABLE_HWCSUM */
1256 
1257 	/*
1258 	 * Call MI attach routine.
1259 	 */
1260 	ether_ifattach(ifp, eaddr, NULL);
1261 
1262 #ifdef RE_DIAG
1263 	/*
1264 	 * Perform hardware diagnostic on the original RTL8169.
1265 	 * Some 32-bit cards were incorrectly wired and would
1266 	 * malfunction if plugged into a 64-bit slot.
1267 	 */
1268 	if (hwrev == RE_HWREV_8169) {
1269 		lwkt_serialize_enter(ifp->if_serializer);
1270 		error = re_diag(sc);
1271 		lwkt_serialize_exit(ifp->if_serializer);
1272 
1273 		if (error) {
1274 			device_printf(dev, "hardware diagnostic failure\n");
1275 			ether_ifdetach(ifp);
1276 			goto fail;
1277 		}
1278 	}
1279 #endif	/* RE_DIAG */
1280 
1281 	/* Hook interrupt last to avoid having to lock softc */
1282 	error = bus_setup_intr(dev, sc->re_irq, INTR_NETSAFE, re_intr, sc,
1283 			       &sc->re_intrhand, ifp->if_serializer);
1284 
1285 	if (error) {
1286 		device_printf(dev, "couldn't set up irq\n");
1287 		ether_ifdetach(ifp);
1288 		goto fail;
1289 	}
1290 
1291 	ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1292 	KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1293 
1294 fail:
1295 	if (error)
1296 		re_detach(dev);
1297 
1298 	return (error);
1299 }
1300 
1301 /*
1302  * Shutdown hardware and free up resources. This can be called any
1303  * time after the mutex has been initialized. It is called in both
1304  * the error case in attach and the normal detach case so it needs
1305  * to be careful about only freeing resources that have actually been
1306  * allocated.
1307  */
1308 static int
1309 re_detach(device_t dev)
1310 {
1311 	struct re_softc *sc = device_get_softc(dev);
1312 	struct ifnet *ifp = &sc->arpcom.ac_if;
1313 	int i;
1314 
1315 	/* These should only be active if attach succeeded */
1316 	if (device_is_attached(dev)) {
1317 		lwkt_serialize_enter(ifp->if_serializer);
1318 		re_stop(sc);
1319 		bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1320 		lwkt_serialize_exit(ifp->if_serializer);
1321 
1322 		ether_ifdetach(ifp);
1323 	}
1324 	if (sc->re_miibus)
1325 		device_delete_child(dev, sc->re_miibus);
1326 	bus_generic_detach(dev);
1327 
1328 	if (sc->re_irq)
1329 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1330 	if (sc->re_res) {
1331 		bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1332 				     sc->re_res);
1333 	}
1334 
1335 	/* Unload and free the RX DMA ring memory and map */
1336 
1337 	if (sc->re_ldata.re_rx_list_tag) {
1338 		bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1339 		    sc->re_ldata.re_rx_list_map);
1340 		bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1341 		    sc->re_ldata.re_rx_list,
1342 		    sc->re_ldata.re_rx_list_map);
1343 		bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1344 	}
1345 
1346 	/* Unload and free the TX DMA ring memory and map */
1347 
1348 	if (sc->re_ldata.re_tx_list_tag) {
1349 		bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1350 		    sc->re_ldata.re_tx_list_map);
1351 		bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1352 		    sc->re_ldata.re_tx_list,
1353 		    sc->re_ldata.re_tx_list_map);
1354 		bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1355 	}
1356 
1357 	/* Destroy all the RX and TX buffer maps */
1358 
1359 	if (sc->re_ldata.re_mtag) {
1360 		for (i = 0; i < RE_TX_DESC_CNT; i++)
1361 			bus_dmamap_destroy(sc->re_ldata.re_mtag,
1362 			    sc->re_ldata.re_tx_dmamap[i]);
1363 		for (i = 0; i < RE_RX_DESC_CNT; i++)
1364 			bus_dmamap_destroy(sc->re_ldata.re_mtag,
1365 			    sc->re_ldata.re_rx_dmamap[i]);
1366 		bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1367 	}
1368 
1369 	/* Unload and free the stats buffer and map */
1370 
1371 	if (sc->re_ldata.re_stag) {
1372 		bus_dmamap_unload(sc->re_ldata.re_stag,
1373 		    sc->re_ldata.re_rx_list_map);
1374 		bus_dmamem_free(sc->re_ldata.re_stag,
1375 		    sc->re_ldata.re_stats,
1376 		    sc->re_ldata.re_smap);
1377 		bus_dma_tag_destroy(sc->re_ldata.re_stag);
1378 	}
1379 
1380 	if (sc->re_parent_tag)
1381 		bus_dma_tag_destroy(sc->re_parent_tag);
1382 
1383 	return(0);
1384 }
1385 
1386 static int
1387 re_newbuf(struct re_softc *sc, int idx, struct mbuf *m)
1388 {
1389 	struct re_dmaload_arg arg;
1390 	struct mbuf *n = NULL;
1391 	int error;
1392 
1393 	if (m == NULL) {
1394 		n = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1395 		if (n == NULL)
1396 			return(ENOBUFS);
1397 		m = n;
1398 	} else
1399 		m->m_data = m->m_ext.ext_buf;
1400 
1401 	m->m_len = m->m_pkthdr.len = MCLBYTES;
1402 
1403 	/*
1404 	 * NOTE:
1405 	 * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1406 	 * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1407 	 */
1408 
1409 	arg.sc = sc;
1410 	arg.re_idx = idx;
1411 	arg.re_maxsegs = 1;
1412 	arg.re_flags = 0;
1413 	arg.re_ring = sc->re_ldata.re_rx_list;
1414 
1415         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1416 	    sc->re_ldata.re_rx_dmamap[idx], m, re_dma_map_desc,
1417 	    &arg, BUS_DMA_NOWAIT);
1418 	if (error || arg.re_maxsegs != 1) {
1419 		if (n != NULL)
1420 			m_freem(n);
1421 		return (ENOMEM);
1422 	}
1423 
1424 	sc->re_ldata.re_rx_list[idx].re_cmdstat |= htole32(RE_RDESC_CMD_OWN);
1425 	sc->re_ldata.re_rx_mbuf[idx] = m;
1426 
1427         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[idx],
1428 		        BUS_DMASYNC_PREREAD);
1429 
1430 	return(0);
1431 }
1432 
1433 static int
1434 re_tx_list_init(struct re_softc *sc)
1435 {
1436 	bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ);
1437 	bzero(&sc->re_ldata.re_tx_mbuf, RE_TX_DESC_CNT * sizeof(struct mbuf *));
1438 
1439 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1440 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1441 	sc->re_ldata.re_tx_prodidx = 0;
1442 	sc->re_ldata.re_tx_considx = 0;
1443 	sc->re_ldata.re_tx_free = RE_TX_DESC_CNT;
1444 
1445 	return(0);
1446 }
1447 
1448 static int
1449 re_rx_list_init(struct re_softc *sc)
1450 {
1451 	int i, error;
1452 
1453 	bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ);
1454 	bzero(&sc->re_ldata.re_rx_mbuf, RE_RX_DESC_CNT * sizeof(struct mbuf *));
1455 
1456 	for (i = 0; i < RE_RX_DESC_CNT; i++) {
1457 		error = re_newbuf(sc, i, NULL);
1458 		if (error)
1459 			return(error);
1460 	}
1461 
1462 	/* Flush the RX descriptors */
1463 
1464 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1465 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1466 
1467 	sc->re_ldata.re_rx_prodidx = 0;
1468 	sc->re_head = sc->re_tail = NULL;
1469 
1470 	return(0);
1471 }
1472 
1473 /*
1474  * RX handler for C+ and 8169. For the gigE chips, we support
1475  * the reception of jumbo frames that have been fragmented
1476  * across multiple 2K mbuf cluster buffers.
1477  */
1478 static void
1479 re_rxeof(struct re_softc *sc)
1480 {
1481 	struct ifnet *ifp = &sc->arpcom.ac_if;
1482 	struct mbuf *m;
1483 	struct re_desc 	*cur_rx;
1484 	uint32_t rxstat, rxvlan;
1485 	int i, total_len;
1486 #ifdef ETHER_INPUT_CHAIN
1487 	struct mbuf_chain chain[MAXCPU];
1488 #endif
1489 
1490 	/* Invalidate the descriptor memory */
1491 
1492 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1493 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1494 
1495 #ifdef ETHER_INPUT_CHAIN
1496 	ether_input_chain_init(chain);
1497 #endif
1498 
1499 	for (i = sc->re_ldata.re_rx_prodidx;
1500 	     RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0 ; RE_DESC_INC(i)) {
1501 		cur_rx = &sc->re_ldata.re_rx_list[i];
1502 		m = sc->re_ldata.re_rx_mbuf[i];
1503 		total_len = RE_RXBYTES(cur_rx);
1504 		rxstat = le32toh(cur_rx->re_cmdstat);
1505 		rxvlan = le32toh(cur_rx->re_vlanctl);
1506 
1507 		/* Invalidate the RX mbuf and unload its map */
1508 
1509 		bus_dmamap_sync(sc->re_ldata.re_mtag,
1510 				sc->re_ldata.re_rx_dmamap[i],
1511 				BUS_DMASYNC_POSTWRITE);
1512 		bus_dmamap_unload(sc->re_ldata.re_mtag,
1513 				  sc->re_ldata.re_rx_dmamap[i]);
1514 
1515 		if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1516 			m->m_len = MCLBYTES - ETHER_ALIGN;
1517 			if (sc->re_head == NULL) {
1518 				sc->re_head = sc->re_tail = m;
1519 			} else {
1520 				sc->re_tail->m_next = m;
1521 				sc->re_tail = m;
1522 			}
1523 			re_newbuf(sc, i, NULL);
1524 			continue;
1525 		}
1526 
1527 		/*
1528 		 * NOTE: for the 8139C+, the frame length field
1529 		 * is always 12 bits in size, but for the gigE chips,
1530 		 * it is 13 bits (since the max RX frame length is 16K).
1531 		 * Unfortunately, all 32 bits in the status word
1532 		 * were already used, so to make room for the extra
1533 		 * length bit, RealTek took out the 'frame alignment
1534 		 * error' bit and shifted the other status bits
1535 		 * over one slot. The OWN, EOR, FS and LS bits are
1536 		 * still in the same places. We have already extracted
1537 		 * the frame length and checked the OWN bit, so rather
1538 		 * than using an alternate bit mapping, we shift the
1539 		 * status bits one space to the right so we can evaluate
1540 		 * them using the 8169 status as though it was in the
1541 		 * same format as that of the 8139C+.
1542 		 */
1543 		if (sc->re_type == RE_8169)
1544 			rxstat >>= 1;
1545 
1546 		if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1547 			ifp->if_ierrors++;
1548 			/*
1549 			 * If this is part of a multi-fragment packet,
1550 			 * discard all the pieces.
1551 			 */
1552 			if (sc->re_head != NULL) {
1553 				m_freem(sc->re_head);
1554 				sc->re_head = sc->re_tail = NULL;
1555 			}
1556 			re_newbuf(sc, i, m);
1557 			continue;
1558 		}
1559 
1560 		/*
1561 		 * If allocating a replacement mbuf fails,
1562 		 * reload the current one.
1563 		 */
1564 
1565 		if (re_newbuf(sc, i, NULL)) {
1566 			ifp->if_ierrors++;
1567 			if (sc->re_head != NULL) {
1568 				m_freem(sc->re_head);
1569 				sc->re_head = sc->re_tail = NULL;
1570 			}
1571 			re_newbuf(sc, i, m);
1572 			continue;
1573 		}
1574 
1575 		if (sc->re_head != NULL) {
1576 			m->m_len = total_len % (MCLBYTES - ETHER_ALIGN);
1577 			/*
1578 			 * Special case: if there's 4 bytes or less
1579 			 * in this buffer, the mbuf can be discarded:
1580 			 * the last 4 bytes is the CRC, which we don't
1581 			 * care about anyway.
1582 			 */
1583 			if (m->m_len <= ETHER_CRC_LEN) {
1584 				sc->re_tail->m_len -=
1585 				    (ETHER_CRC_LEN - m->m_len);
1586 				m_freem(m);
1587 			} else {
1588 				m->m_len -= ETHER_CRC_LEN;
1589 				sc->re_tail->m_next = m;
1590 			}
1591 			m = sc->re_head;
1592 			sc->re_head = sc->re_tail = NULL;
1593 			m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1594 		} else
1595 			m->m_pkthdr.len = m->m_len =
1596 			    (total_len - ETHER_CRC_LEN);
1597 
1598 		ifp->if_ipackets++;
1599 		m->m_pkthdr.rcvif = ifp;
1600 
1601 		/* Do RX checksumming if enabled */
1602 
1603 		if (ifp->if_capenable & IFCAP_RXCSUM) {
1604 
1605 			/* Check IP header checksum */
1606 			if (rxstat & RE_RDESC_STAT_PROTOID)
1607 				m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1608 			if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1609 				m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1610 
1611 			/* Check TCP/UDP checksum */
1612 			if ((RE_TCPPKT(rxstat) &&
1613 			    (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1614 			    (RE_UDPPKT(rxstat) &&
1615 			    (rxstat & RE_RDESC_STAT_UDPSUMBAD)) == 0) {
1616 				m->m_pkthdr.csum_flags |=
1617 				    CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1618 				    CSUM_FRAG_NOT_CHECKED;
1619 				m->m_pkthdr.csum_data = 0xffff;
1620 			}
1621 		}
1622 
1623 		if (rxvlan & RE_RDESC_VLANCTL_TAG) {
1624 			m->m_flags |= M_VLANTAG;
1625 			m->m_pkthdr.ether_vlantag =
1626 				be16toh((rxvlan & RE_RDESC_VLANCTL_DATA));
1627 		}
1628 #ifdef ETHER_INPUT_CHAIN
1629 		ether_input_chain2(ifp, m, chain);
1630 #else
1631 		ifp->if_input(ifp, m);
1632 #endif
1633 	}
1634 
1635 #ifdef ETHER_INPUT_CHAIN
1636 	ether_input_dispatch(chain);
1637 #endif
1638 
1639 	/* Flush the RX DMA ring */
1640 
1641 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1642 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1643 
1644 	sc->re_ldata.re_rx_prodidx = i;
1645 }
1646 
1647 static void
1648 re_txeof(struct re_softc *sc)
1649 {
1650 	struct ifnet *ifp = &sc->arpcom.ac_if;
1651 	uint32_t txstat;
1652 	int idx;
1653 
1654 	/* Invalidate the TX descriptor list */
1655 
1656 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1657 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
1658 
1659 	for (idx = sc->re_ldata.re_tx_considx;
1660 	     sc->re_ldata.re_tx_free < RE_TX_DESC_CNT; RE_DESC_INC(idx)) {
1661 		txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
1662 		if (txstat & RE_TDESC_CMD_OWN)
1663 			break;
1664 
1665 		sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
1666 
1667 		/*
1668 		 * We only stash mbufs in the last descriptor
1669 		 * in a fragment chain, which also happens to
1670 		 * be the only place where the TX status bits
1671 		 * are valid.
1672 		 */
1673 		if (txstat & RE_TDESC_CMD_EOF) {
1674 			m_freem(sc->re_ldata.re_tx_mbuf[idx]);
1675 			sc->re_ldata.re_tx_mbuf[idx] = NULL;
1676 			bus_dmamap_unload(sc->re_ldata.re_mtag,
1677 			    sc->re_ldata.re_tx_dmamap[idx]);
1678 			if (txstat & (RE_TDESC_STAT_EXCESSCOL|
1679 			    RE_TDESC_STAT_COLCNT))
1680 				ifp->if_collisions++;
1681 			if (txstat & RE_TDESC_STAT_TXERRSUM)
1682 				ifp->if_oerrors++;
1683 			else
1684 				ifp->if_opackets++;
1685 		}
1686 		sc->re_ldata.re_tx_free++;
1687 	}
1688 
1689 	/* No changes made to the TX ring, so no flush needed */
1690 	if (sc->re_ldata.re_tx_free) {
1691 		sc->re_ldata.re_tx_considx = idx;
1692 		ifp->if_flags &= ~IFF_OACTIVE;
1693 		ifp->if_timer = 0;
1694 	}
1695 
1696 	/*
1697 	 * Some chips will ignore a second TX request issued while an
1698 	 * existing transmission is in progress. If the transmitter goes
1699 	 * idle but there are still packets waiting to be sent, we need
1700 	 * to restart the channel here to flush them out. This only seems
1701 	 * to be required with the PCIe devices.
1702 	 */
1703 	if (sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1704 		CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
1705 
1706 	/*
1707 	 * If not all descriptors have been released reaped yet,
1708 	 * reload the timer so that we will eventually get another
1709 	 * interrupt that will cause us to re-enter this routine.
1710 	 * This is done in case the transmitter has gone idle.
1711 	 */
1712 	if (RE_TX_MODERATION_IS_ENABLED(sc) &&
1713 	    sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1714                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1715 }
1716 
1717 static void
1718 re_tick(void *xsc)
1719 {
1720 	struct re_softc *sc = xsc;
1721 
1722 	lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
1723 	re_tick_serialized(xsc);
1724 	lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
1725 }
1726 
1727 static void
1728 re_tick_serialized(void *xsc)
1729 {
1730 	struct re_softc *sc = xsc;
1731 	struct ifnet *ifp = &sc->arpcom.ac_if;
1732 	struct mii_data *mii;
1733 
1734 	ASSERT_SERIALIZED(ifp->if_serializer);
1735 
1736 	mii = device_get_softc(sc->re_miibus);
1737 	mii_tick(mii);
1738 	if (sc->re_link) {
1739 		if (!(mii->mii_media_status & IFM_ACTIVE))
1740 			sc->re_link = 0;
1741 	} else {
1742 		if (mii->mii_media_status & IFM_ACTIVE &&
1743 		    IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1744 			sc->re_link = 1;
1745 			if (!ifq_is_empty(&ifp->if_snd))
1746 				if_devstart(ifp);
1747 		}
1748 	}
1749 
1750 	callout_reset(&sc->re_timer, hz, re_tick, sc);
1751 }
1752 
1753 #ifdef DEVICE_POLLING
1754 
1755 static void
1756 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1757 {
1758 	struct re_softc *sc = ifp->if_softc;
1759 
1760 	ASSERT_SERIALIZED(ifp->if_serializer);
1761 
1762 	switch(cmd) {
1763 	case POLL_REGISTER:
1764 		/* disable interrupts */
1765 		CSR_WRITE_2(sc, RE_IMR, 0x0000);
1766 		break;
1767 	case POLL_DEREGISTER:
1768 		/* enable interrupts */
1769 		CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
1770 		break;
1771 	default:
1772 		sc->rxcycles = count;
1773 		re_rxeof(sc);
1774 		re_txeof(sc);
1775 
1776 		if (!ifq_is_empty(&ifp->if_snd))
1777 			if_devstart(ifp);
1778 
1779 		if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1780 			uint16_t       status;
1781 
1782 			status = CSR_READ_2(sc, RE_ISR);
1783 			if (status == 0xffff)
1784 				return;
1785 			if (status)
1786 				CSR_WRITE_2(sc, RE_ISR, status);
1787 
1788 			/*
1789 			 * XXX check behaviour on receiver stalls.
1790 			 */
1791 
1792 			if (status & RE_ISR_SYSTEM_ERR) {
1793 				re_reset(sc);
1794 				re_init(sc);
1795 			}
1796 		}
1797 		break;
1798 	}
1799 }
1800 #endif /* DEVICE_POLLING */
1801 
1802 static void
1803 re_intr(void *arg)
1804 {
1805 	struct re_softc	*sc = arg;
1806 	struct ifnet *ifp = &sc->arpcom.ac_if;
1807 	uint16_t status;
1808 
1809 	ASSERT_SERIALIZED(ifp->if_serializer);
1810 
1811 	if (sc->suspended || (ifp->if_flags & IFF_UP) == 0)
1812 		return;
1813 
1814 	for (;;) {
1815 		status = CSR_READ_2(sc, RE_ISR);
1816 		/* If the card has gone away the read returns 0xffff. */
1817 		if (status == 0xffff)
1818 			break;
1819 		if (status)
1820 			CSR_WRITE_2(sc, RE_ISR, status);
1821 
1822 		if ((status & sc->re_intrs) == 0)
1823 			break;
1824 
1825 		if (status & (RE_ISR_RX_OK | RE_ISR_RX_ERR | RE_ISR_FIFO_OFLOW))
1826 			re_rxeof(sc);
1827 
1828 		if ((status & sc->re_tx_ack) ||
1829 		    (status & RE_ISR_TX_ERR) ||
1830 		    (status & RE_ISR_TX_DESC_UNAVAIL))
1831 			re_txeof(sc);
1832 
1833 		if (status & RE_ISR_SYSTEM_ERR) {
1834 			re_reset(sc);
1835 			re_init(sc);
1836 		}
1837 
1838 		if (status & RE_ISR_LINKCHG) {
1839 			callout_stop(&sc->re_timer);
1840 			re_tick_serialized(sc);
1841 		}
1842 	}
1843 
1844 	if (!ifq_is_empty(&ifp->if_snd))
1845 		if_devstart(ifp);
1846 }
1847 
1848 static int
1849 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx, int *called_defrag)
1850 {
1851 	struct ifnet *ifp = &sc->arpcom.ac_if;
1852 	struct mbuf *m, *m_new = NULL;
1853 	struct re_dmaload_arg	arg;
1854 	bus_dmamap_t		map;
1855 	int			error;
1856 
1857 	KASSERT(sc->re_ldata.re_tx_free > 4, ("not enough free TX desc\n"));
1858 
1859 	*called_defrag = 0;
1860 	m = *m_head;
1861 
1862 	/*
1863 	 * Set up checksum offload. Note: checksum offload bits must
1864 	 * appear in all descriptors of a multi-descriptor transmit
1865 	 * attempt. (This is according to testing done with an 8169
1866 	 * chip. I'm not sure if this is a requirement or a bug.)
1867 	 */
1868 
1869 	arg.re_flags = 0;
1870 
1871 	if (m->m_pkthdr.csum_flags & CSUM_IP)
1872 		arg.re_flags |= RE_TDESC_CMD_IPCSUM;
1873 	if (m->m_pkthdr.csum_flags & CSUM_TCP)
1874 		arg.re_flags |= RE_TDESC_CMD_TCPCSUM;
1875 	if (m->m_pkthdr.csum_flags & CSUM_UDP)
1876 		arg.re_flags |= RE_TDESC_CMD_UDPCSUM;
1877 
1878 	arg.sc = sc;
1879 	arg.re_idx = *idx;
1880 	arg.re_maxsegs = sc->re_ldata.re_tx_free;
1881 	if (arg.re_maxsegs > 4)
1882 		arg.re_maxsegs -= 4;
1883 	arg.re_ring = sc->re_ldata.re_tx_list;
1884 
1885 	map = sc->re_ldata.re_tx_dmamap[*idx];
1886 
1887 	/*
1888 	 * With some of the RealTek chips, using the checksum offload
1889 	 * support in conjunction with the autopadding feature results
1890 	 * in the transmission of corrupt frames. For example, if we
1891 	 * need to send a really small IP fragment that's less than 60
1892 	 * bytes in size, and IP header checksumming is enabled, the
1893 	 * resulting ethernet frame that appears on the wire will
1894 	 * have garbled payload. To work around this, if TX checksum
1895 	 * offload is enabled, we always manually pad short frames out
1896 	 * to the minimum ethernet frame size. We do this by pretending
1897 	 * the mbuf chain has too many fragments so the coalescing code
1898 	 * below can assemble the packet into a single buffer that's
1899 	 * padded out to the mininum frame size.
1900 	 *
1901 	 * Note: this appears unnecessary for TCP, and doing it for TCP
1902 	 * with PCIe adapters seems to result in bad checksums.
1903 	 */
1904 	if (arg.re_flags && !(arg.re_flags & RE_TDESC_CMD_TCPCSUM) &&
1905 	    m->m_pkthdr.len < RE_MIN_FRAMELEN) {
1906 		error = EFBIG;
1907 	} else {
1908 		error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map,
1909 		    m, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1910 	}
1911 
1912 	if (error && error != EFBIG) {
1913 		if_printf(ifp, "can't map mbuf (error %d)\n", error);
1914 		return(ENOBUFS);
1915 	}
1916 
1917 	/* Too many segments to map, coalesce into a single mbuf */
1918 
1919 	if (error || arg.re_maxsegs == 0) {
1920 		m_new = m_defrag_nofree(m, MB_DONTWAIT);
1921 		if (m_new == NULL) {
1922 			return(1);
1923 		} else {
1924 			m = m_new;
1925 			*m_head = m;
1926 		}
1927 
1928 		/*
1929 		 * Manually pad short frames, and zero the pad space
1930 		 * to avoid leaking data.
1931 		 */
1932 		if (m_new->m_pkthdr.len < RE_MIN_FRAMELEN) {
1933 			bzero(mtod(m_new, char *) + m_new->m_pkthdr.len,
1934 			    RE_MIN_FRAMELEN - m_new->m_pkthdr.len);
1935 			m_new->m_pkthdr.len += RE_MIN_FRAMELEN -
1936 			    m_new->m_pkthdr.len;
1937 			m_new->m_len = m_new->m_pkthdr.len;
1938 		}
1939 
1940 		*called_defrag = 1;
1941 		arg.sc = sc;
1942 		arg.re_idx = *idx;
1943 		arg.re_maxsegs = sc->re_ldata.re_tx_free;
1944 		arg.re_ring = sc->re_ldata.re_tx_list;
1945 
1946 		error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map,
1947 		    m, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1948 		if (error) {
1949 			m_freem(m);
1950 			if_printf(ifp, "can't map mbuf (error %d)\n", error);
1951 			return(EFBIG);
1952 		}
1953 	}
1954 
1955 	/*
1956 	 * Insure that the map for this transmission
1957 	 * is placed at the array index of the last descriptor
1958 	 * in this chain.
1959 	 */
1960 	sc->re_ldata.re_tx_dmamap[*idx] =
1961 	    sc->re_ldata.re_tx_dmamap[arg.re_idx];
1962 	sc->re_ldata.re_tx_dmamap[arg.re_idx] = map;
1963 
1964 	sc->re_ldata.re_tx_mbuf[arg.re_idx] = m;
1965 	sc->re_ldata.re_tx_free -= arg.re_maxsegs;
1966 
1967 	/*
1968 	 * Set up hardware VLAN tagging. Note: vlan tag info must
1969 	 * appear in the first descriptor of a multi-descriptor
1970 	 * transmission attempt.
1971 	 */
1972 
1973 	if (m->m_flags & M_VLANTAG) {
1974 		sc->re_ldata.re_tx_list[*idx].re_vlanctl =
1975 		    htole32(htobe16(m->m_pkthdr.ether_vlantag) |
1976 		    	    RE_TDESC_VLANCTL_TAG);
1977 	}
1978 
1979 	/* Transfer ownership of packet to the chip. */
1980 
1981 	sc->re_ldata.re_tx_list[arg.re_idx].re_cmdstat |=
1982 	    htole32(RE_TDESC_CMD_OWN);
1983 	if (*idx != arg.re_idx)
1984 		sc->re_ldata.re_tx_list[*idx].re_cmdstat |=
1985 		    htole32(RE_TDESC_CMD_OWN);
1986 
1987 	RE_DESC_INC(arg.re_idx);
1988 	*idx = arg.re_idx;
1989 
1990 	return(0);
1991 }
1992 
1993 /*
1994  * Main transmit routine for C+ and gigE NICs.
1995  */
1996 
1997 static void
1998 re_start(struct ifnet *ifp)
1999 {
2000 	struct re_softc	*sc = ifp->if_softc;
2001 	struct mbuf *m_head;
2002 	struct mbuf *m_head2;
2003 	int called_defrag, idx, need_trans;
2004 
2005 	ASSERT_SERIALIZED(ifp->if_serializer);
2006 
2007 	if (!sc->re_link) {
2008 		ifq_purge(&ifp->if_snd);
2009 		return;
2010 	}
2011 
2012 	if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2013 		return;
2014 
2015 	idx = sc->re_ldata.re_tx_prodidx;
2016 
2017 	need_trans = 0;
2018 	while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2019 		if (sc->re_ldata.re_tx_free <= 4) {
2020 			ifp->if_flags |= IFF_OACTIVE;
2021 			break;
2022 		}
2023 
2024 		m_head = ifq_dequeue(&ifp->if_snd, NULL);
2025 		if (m_head == NULL)
2026 			break;
2027 
2028 		m_head2 = m_head;
2029 		if (re_encap(sc, &m_head2, &idx, &called_defrag)) {
2030 			/*
2031 			 * If we could not encapsulate the defragged packet,
2032 			 * the returned m_head2 is garbage and we must dequeue
2033 			 * and throw away the original packet.
2034 			 */
2035 			if (called_defrag)
2036 				m_freem(m_head);
2037 			ifp->if_flags |= IFF_OACTIVE;
2038 			break;
2039 		}
2040 
2041 		/*
2042 		 * Clean out the packet we encapsulated.  If we defragged
2043 		 * the packet the m_head2 is the one that got encapsulated
2044 		 * and the original must be thrown away.  Otherwise m_head2
2045 		 * *IS* the original.
2046 		 */
2047 		if (called_defrag)
2048 			m_freem(m_head);
2049 		need_trans = 1;
2050 
2051 		/*
2052 		 * If there's a BPF listener, bounce a copy of this frame
2053 		 * to him.
2054 		 */
2055 		ETHER_BPF_MTAP(ifp, m_head2);
2056 	}
2057 
2058 	if (!need_trans) {
2059 		if (RE_TX_MODERATION_IS_ENABLED(sc) &&
2060 		    sc->re_ldata.re_tx_free != RE_TX_DESC_CNT)
2061 			CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2062 		return;
2063 	}
2064 
2065 	/* Flush the TX descriptors */
2066 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2067 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2068 
2069 	sc->re_ldata.re_tx_prodidx = idx;
2070 
2071 	/*
2072 	 * RealTek put the TX poll request register in a different
2073 	 * location on the 8169 gigE chip. I don't know why.
2074 	 */
2075 	CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2076 
2077 	if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2078 		/*
2079 		 * Use the countdown timer for interrupt moderation.
2080 		 * 'TX done' interrupts are disabled. Instead, we reset the
2081 		 * countdown timer, which will begin counting until it hits
2082 		 * the value in the TIMERINT register, and then trigger an
2083 		 * interrupt. Each time we write to the TIMERCNT register,
2084 		 * the timer count is reset to 0.
2085 		 */
2086 		CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2087 	}
2088 
2089 	/*
2090 	 * Set a timeout in case the chip goes out to lunch.
2091 	 */
2092 	ifp->if_timer = 5;
2093 }
2094 
2095 static void
2096 re_init(void *xsc)
2097 {
2098 	struct re_softc *sc = xsc;
2099 	struct ifnet *ifp = &sc->arpcom.ac_if;
2100 	struct mii_data *mii;
2101 	uint32_t rxcfg = 0;
2102 
2103 	ASSERT_SERIALIZED(ifp->if_serializer);
2104 
2105 	mii = device_get_softc(sc->re_miibus);
2106 
2107 	/*
2108 	 * Cancel pending I/O and free all RX/TX buffers.
2109 	 */
2110 	re_stop(sc);
2111 
2112 	/*
2113 	 * Enable C+ RX and TX mode, as well as VLAN stripping and
2114 	 * RX checksum offload. We must configure the C+ register
2115 	 * before all others.
2116 	 */
2117 	CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2118 		    RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2119 		    (ifp->if_capenable & IFCAP_RXCSUM ?
2120 		     RE_CPLUSCMD_RXCSUM_ENB : 0));
2121 
2122 	/*
2123 	 * Init our MAC address.  Even though the chipset
2124 	 * documentation doesn't mention it, we need to enter "Config
2125 	 * register write enable" mode to modify the ID registers.
2126 	 */
2127 	CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2128 	CSR_WRITE_4(sc, RE_IDR0,
2129 	    htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2130 	CSR_WRITE_2(sc, RE_IDR4,
2131 	    htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2132 	CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2133 
2134 	/*
2135 	 * For C+ mode, initialize the RX descriptors and mbufs.
2136 	 */
2137 	re_rx_list_init(sc);
2138 	re_tx_list_init(sc);
2139 
2140 	/*
2141 	 * Load the addresses of the RX and TX lists into the chip.
2142 	 */
2143 	CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2144 	    RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2145 	CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2146 	    RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2147 
2148 	CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2149 	    RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2150 	CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2151 	    RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2152 
2153 	/*
2154 	 * Enable transmit and receive.
2155 	 */
2156 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2157 
2158 	/*
2159 	 * Set the initial TX and RX configuration.
2160 	 */
2161 	if (sc->re_testmode) {
2162 		if (sc->re_type == RE_8169)
2163 			CSR_WRITE_4(sc, RE_TXCFG,
2164 				    RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2165 		else
2166 			CSR_WRITE_4(sc, RE_TXCFG,
2167 				    RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2168 	} else
2169 		CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2170 
2171 	CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, 16);
2172 
2173 	CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2174 
2175 	/* Set the individual bit to receive frames for this host only. */
2176 	rxcfg = CSR_READ_4(sc, RE_RXCFG);
2177 	rxcfg |= RE_RXCFG_RX_INDIV;
2178 
2179 	/* If we want promiscuous mode, set the allframes bit. */
2180 	if (ifp->if_flags & IFF_PROMISC) {
2181 		rxcfg |= RE_RXCFG_RX_ALLPHYS;
2182 		CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2183 	} else {
2184 		rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2185 		CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2186 	}
2187 
2188 	/*
2189 	 * Set capture broadcast bit to capture broadcast frames.
2190 	 */
2191 	if (ifp->if_flags & IFF_BROADCAST) {
2192 		rxcfg |= RE_RXCFG_RX_BROAD;
2193 		CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2194 	} else {
2195 		rxcfg &= ~RE_RXCFG_RX_BROAD;
2196 		CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2197 	}
2198 
2199 	/*
2200 	 * Program the multicast filter, if necessary.
2201 	 */
2202 	re_setmulti(sc);
2203 
2204 #ifdef DEVICE_POLLING
2205 	/*
2206 	 * Disable interrupts if we are polling.
2207 	 */
2208 	if (ifp->if_flags & IFF_POLLING)
2209 		CSR_WRITE_2(sc, RE_IMR, 0);
2210 	else	/* otherwise ... */
2211 #endif /* DEVICE_POLLING */
2212 	/*
2213 	 * Enable interrupts.
2214 	 */
2215 	if (sc->re_testmode)
2216 		CSR_WRITE_2(sc, RE_IMR, 0);
2217 	else
2218 		CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
2219 	CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2220 
2221 	/* Set initial TX threshold */
2222 	sc->re_txthresh = RE_TX_THRESH_INIT;
2223 
2224 	/* Start RX/TX process. */
2225 	if (sc->re_flags & RE_F_HASMPC)
2226 		CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2227 #ifdef notdef
2228 	/* Enable receiver and transmitter. */
2229 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2230 #endif
2231 
2232 	if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2233 		/*
2234 		 * Initialize the timer interrupt register so that
2235 		 * a timer interrupt will be generated once the timer
2236 		 * reaches a certain number of ticks. The timer is
2237 		 * reloaded on each transmit. This gives us TX interrupt
2238 		 * moderation, which dramatically improves TX frame rate.
2239 		 */
2240 		if (sc->re_type == RE_8169)
2241 			CSR_WRITE_4(sc, RE_TIMERINT_8169, 0x800);
2242 		else
2243 			CSR_WRITE_4(sc, RE_TIMERINT, 0x400);
2244 	}
2245 
2246 	/*
2247 	 * For 8169 gigE NICs, set the max allowed RX packet
2248 	 * size so we can receive jumbo frames.
2249 	 */
2250 	if (sc->re_type == RE_8169)
2251 		CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2252 
2253 	if (sc->re_testmode) {
2254 		return;
2255 	}
2256 
2257 	mii_mediachg(mii);
2258 
2259 	CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2260 
2261 	ifp->if_flags |= IFF_RUNNING;
2262 	ifp->if_flags &= ~IFF_OACTIVE;
2263 
2264 	sc->re_link = 0;
2265 	callout_reset(&sc->re_timer, hz, re_tick, sc);
2266 }
2267 
2268 /*
2269  * Set media options.
2270  */
2271 static int
2272 re_ifmedia_upd(struct ifnet *ifp)
2273 {
2274 	struct re_softc *sc = ifp->if_softc;
2275 	struct mii_data *mii;
2276 
2277 	ASSERT_SERIALIZED(ifp->if_serializer);
2278 
2279 	mii = device_get_softc(sc->re_miibus);
2280 	mii_mediachg(mii);
2281 
2282 	return(0);
2283 }
2284 
2285 /*
2286  * Report current media status.
2287  */
2288 static void
2289 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2290 {
2291 	struct re_softc *sc = ifp->if_softc;
2292 	struct mii_data *mii;
2293 
2294 	ASSERT_SERIALIZED(ifp->if_serializer);
2295 
2296 	mii = device_get_softc(sc->re_miibus);
2297 
2298 	mii_pollstat(mii);
2299 	ifmr->ifm_active = mii->mii_media_active;
2300 	ifmr->ifm_status = mii->mii_media_status;
2301 }
2302 
2303 static int
2304 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2305 {
2306 	struct re_softc *sc = ifp->if_softc;
2307 	struct ifreq *ifr = (struct ifreq *) data;
2308 	struct mii_data *mii;
2309 	int error = 0;
2310 
2311 	ASSERT_SERIALIZED(ifp->if_serializer);
2312 
2313 	switch(command) {
2314 	case SIOCSIFMTU:
2315 		if (ifr->ifr_mtu > RE_JUMBO_MTU)
2316 			error = EINVAL;
2317 		ifp->if_mtu = ifr->ifr_mtu;
2318 		break;
2319 	case SIOCSIFFLAGS:
2320 		if (ifp->if_flags & IFF_UP)
2321 			re_init(sc);
2322 		else if (ifp->if_flags & IFF_RUNNING)
2323 			re_stop(sc);
2324 		break;
2325 	case SIOCADDMULTI:
2326 	case SIOCDELMULTI:
2327 		re_setmulti(sc);
2328 		error = 0;
2329 		break;
2330 	case SIOCGIFMEDIA:
2331 	case SIOCSIFMEDIA:
2332 		mii = device_get_softc(sc->re_miibus);
2333 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2334 		break;
2335 	case SIOCSIFCAP:
2336 		ifp->if_capenable &= ~(IFCAP_HWCSUM);
2337 		ifp->if_capenable |=
2338 		    ifr->ifr_reqcap & (IFCAP_HWCSUM);
2339 		if (ifp->if_capenable & IFCAP_TXCSUM)
2340 			ifp->if_hwassist = RE_CSUM_FEATURES;
2341 		else
2342 			ifp->if_hwassist = 0;
2343 		if (ifp->if_flags & IFF_RUNNING)
2344 			re_init(sc);
2345 		break;
2346 	default:
2347 		error = ether_ioctl(ifp, command, data);
2348 		break;
2349 	}
2350 	return(error);
2351 }
2352 
2353 static void
2354 re_watchdog(struct ifnet *ifp)
2355 {
2356 	struct re_softc *sc = ifp->if_softc;
2357 
2358 	ASSERT_SERIALIZED(ifp->if_serializer);
2359 
2360 	if_printf(ifp, "watchdog timeout\n");
2361 
2362 	ifp->if_oerrors++;
2363 
2364 	re_txeof(sc);
2365 	re_rxeof(sc);
2366 
2367 	re_init(sc);
2368 
2369 	if (!ifq_is_empty(&ifp->if_snd))
2370 		if_devstart(ifp);
2371 }
2372 
2373 /*
2374  * Stop the adapter and free any mbufs allocated to the
2375  * RX and TX lists.
2376  */
2377 static void
2378 re_stop(struct re_softc *sc)
2379 {
2380 	struct ifnet *ifp = &sc->arpcom.ac_if;
2381 	int i;
2382 
2383 	ASSERT_SERIALIZED(ifp->if_serializer);
2384 
2385 	ifp->if_timer = 0;
2386 	callout_stop(&sc->re_timer);
2387 
2388 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2389 
2390 	CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2391 	CSR_WRITE_2(sc, RE_IMR, 0x0000);
2392 	CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2393 
2394 	if (sc->re_head != NULL) {
2395 		m_freem(sc->re_head);
2396 		sc->re_head = sc->re_tail = NULL;
2397 	}
2398 
2399 	/* Free the TX list buffers. */
2400 	for (i = 0; i < RE_TX_DESC_CNT; i++) {
2401 		if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2402 			bus_dmamap_unload(sc->re_ldata.re_mtag,
2403 					  sc->re_ldata.re_tx_dmamap[i]);
2404 			m_freem(sc->re_ldata.re_tx_mbuf[i]);
2405 			sc->re_ldata.re_tx_mbuf[i] = NULL;
2406 		}
2407 	}
2408 
2409 	/* Free the RX list buffers. */
2410 	for (i = 0; i < RE_RX_DESC_CNT; i++) {
2411 		if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2412 			bus_dmamap_unload(sc->re_ldata.re_mtag,
2413 					  sc->re_ldata.re_rx_dmamap[i]);
2414 			m_freem(sc->re_ldata.re_rx_mbuf[i]);
2415 			sc->re_ldata.re_rx_mbuf[i] = NULL;
2416 		}
2417 	}
2418 }
2419 
2420 /*
2421  * Device suspend routine.  Stop the interface and save some PCI
2422  * settings in case the BIOS doesn't restore them properly on
2423  * resume.
2424  */
2425 static int
2426 re_suspend(device_t dev)
2427 {
2428 #ifndef BURN_BRIDGES
2429 	int i;
2430 #endif
2431 	struct re_softc *sc = device_get_softc(dev);
2432 	struct ifnet *ifp = &sc->arpcom.ac_if;
2433 
2434 	lwkt_serialize_enter(ifp->if_serializer);
2435 
2436 	re_stop(sc);
2437 
2438 #ifndef BURN_BRIDGES
2439 	for (i = 0; i < 5; i++)
2440 		sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2441 	sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2442 	sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2443 	sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2444 	sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2445 #endif
2446 
2447 	sc->suspended = 1;
2448 
2449 	lwkt_serialize_exit(ifp->if_serializer);
2450 
2451 	return (0);
2452 }
2453 
2454 /*
2455  * Device resume routine.  Restore some PCI settings in case the BIOS
2456  * doesn't, re-enable busmastering, and restart the interface if
2457  * appropriate.
2458  */
2459 static int
2460 re_resume(device_t dev)
2461 {
2462 	struct re_softc *sc = device_get_softc(dev);
2463 	struct ifnet *ifp = &sc->arpcom.ac_if;
2464 #ifndef BURN_BRIDGES
2465 	int i;
2466 #endif
2467 
2468 	lwkt_serialize_enter(ifp->if_serializer);
2469 
2470 #ifndef BURN_BRIDGES
2471 	/* better way to do this? */
2472 	for (i = 0; i < 5; i++)
2473 		pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2474 	pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2475 	pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2476 	pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2477 	pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2478 
2479 	/* reenable busmastering */
2480 	pci_enable_busmaster(dev);
2481 	pci_enable_io(dev, SYS_RES_IOPORT);
2482 #endif
2483 
2484 	/* reinitialize interface if necessary */
2485 	if (ifp->if_flags & IFF_UP)
2486 		re_init(sc);
2487 
2488 	sc->suspended = 0;
2489 
2490 	lwkt_serialize_exit(ifp->if_serializer);
2491 
2492 	return (0);
2493 }
2494 
2495 /*
2496  * Stop all chip I/O so that the kernel's probe routines don't
2497  * get confused by errant DMAs when rebooting.
2498  */
2499 static void
2500 re_shutdown(device_t dev)
2501 {
2502 	struct re_softc *sc = device_get_softc(dev);
2503 	struct ifnet *ifp = &sc->arpcom.ac_if;
2504 
2505 	lwkt_serialize_enter(ifp->if_serializer);
2506 	re_stop(sc);
2507 	lwkt_serialize_exit(ifp->if_serializer);
2508 }
2509 
2510 static int
2511 re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS)
2512 {
2513 	struct re_softc *sc = arg1;
2514 	struct ifnet *ifp = &sc->arpcom.ac_if;
2515 	int error = 0, mod, mod_old;
2516 
2517 	lwkt_serialize_enter(ifp->if_serializer);
2518 
2519 	mod_old = mod = RE_TX_MODERATION_IS_ENABLED(sc);
2520 
2521 	error = sysctl_handle_int(oidp, &mod, 0, req);
2522 	if (error || req->newptr == NULL || mod == mod_old)
2523 		goto back;
2524 	if (mod != 0 && mod != 1) {
2525 		error = EINVAL;
2526 		goto back;
2527 	}
2528 
2529 	if (mod)
2530 		RE_ENABLE_TX_MODERATION(sc);
2531 	else
2532 		RE_DISABLE_TX_MODERATION(sc);
2533 
2534 	if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) == (IFF_RUNNING | IFF_UP))
2535 		re_init(sc);
2536 back:
2537 	lwkt_serialize_exit(ifp->if_serializer);
2538 	return error;
2539 }
2540