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