xref: /freebsd/sys/dev/re/if_re.c (revision 9162f64b58d01ec01481d60b6cdc06ffd8e8c7fc)
1 /*-
2  * Copyright (c) 1997, 1998-2003
3  *	Bill Paul <wpaul@windriver.com>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 /*
37  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E PCI NIC driver
38  *
39  * Written by Bill Paul <wpaul@windriver.com>
40  * Senior Networking Software Engineer
41  * Wind River Systems
42  */
43 
44 /*
45  * This driver is designed to support RealTek's next generation of
46  * 10/100 and 10/100/1000 PCI ethernet controllers. There are currently
47  * seven devices in this family: the RTL8139C+, the RTL8169, the RTL8169S,
48  * RTL8110S, the RTL8168, the RTL8111 and the RTL8101E.
49  *
50  * The 8139C+ is a 10/100 ethernet chip. It is backwards compatible
51  * with the older 8139 family, however it also supports a special
52  * C+ mode of operation that provides several new performance enhancing
53  * features. These include:
54  *
55  *	o Descriptor based DMA mechanism. Each descriptor represents
56  *	  a single packet fragment. Data buffers may be aligned on
57  *	  any byte boundary.
58  *
59  *	o 64-bit DMA
60  *
61  *	o TCP/IP checksum offload for both RX and TX
62  *
63  *	o High and normal priority transmit DMA rings
64  *
65  *	o VLAN tag insertion and extraction
66  *
67  *	o TCP large send (segmentation offload)
68  *
69  * Like the 8139, the 8139C+ also has a built-in 10/100 PHY. The C+
70  * programming API is fairly straightforward. The RX filtering, EEPROM
71  * access and PHY access is the same as it is on the older 8139 series
72  * chips.
73  *
74  * The 8169 is a 64-bit 10/100/1000 gigabit ethernet MAC. It has almost the
75  * same programming API and feature set as the 8139C+ with the following
76  * differences and additions:
77  *
78  *	o 1000Mbps mode
79  *
80  *	o Jumbo frames
81  *
82  *	o GMII and TBI ports/registers for interfacing with copper
83  *	  or fiber PHYs
84  *
85  *	o RX and TX DMA rings can have up to 1024 descriptors
86  *	  (the 8139C+ allows a maximum of 64)
87  *
88  *	o Slight differences in register layout from the 8139C+
89  *
90  * The TX start and timer interrupt registers are at different locations
91  * on the 8169 than they are on the 8139C+. Also, the status word in the
92  * RX descriptor has a slightly different bit layout. The 8169 does not
93  * have a built-in PHY. Most reference boards use a Marvell 88E1000 'Alaska'
94  * copper gigE PHY.
95  *
96  * The 8169S/8110S 10/100/1000 devices have built-in copper gigE PHYs
97  * (the 'S' stands for 'single-chip'). These devices have the same
98  * programming API as the older 8169, but also have some vendor-specific
99  * registers for the on-board PHY. The 8110S is a LAN-on-motherboard
100  * part designed to be pin-compatible with the RealTek 8100 10/100 chip.
101  *
102  * This driver takes advantage of the RX and TX checksum offload and
103  * VLAN tag insertion/extraction features. It also implements TX
104  * interrupt moderation using the timer interrupt registers, which
105  * significantly reduces TX interrupt load. There is also support
106  * for jumbo frames, however the 8169/8169S/8110S can not transmit
107  * jumbo frames larger than 7440, so the max MTU possible with this
108  * driver is 7422 bytes.
109  */
110 
111 #ifdef HAVE_KERNEL_OPTION_HEADERS
112 #include "opt_device_polling.h"
113 #endif
114 
115 #include <sys/param.h>
116 #include <sys/endian.h>
117 #include <sys/systm.h>
118 #include <sys/sockio.h>
119 #include <sys/mbuf.h>
120 #include <sys/malloc.h>
121 #include <sys/module.h>
122 #include <sys/kernel.h>
123 #include <sys/socket.h>
124 #include <sys/lock.h>
125 #include <sys/mutex.h>
126 #include <sys/taskqueue.h>
127 
128 #include <net/if.h>
129 #include <net/if_arp.h>
130 #include <net/ethernet.h>
131 #include <net/if_dl.h>
132 #include <net/if_media.h>
133 #include <net/if_types.h>
134 #include <net/if_vlan_var.h>
135 
136 #include <net/bpf.h>
137 
138 #include <machine/bus.h>
139 #include <machine/resource.h>
140 #include <sys/bus.h>
141 #include <sys/rman.h>
142 
143 #include <dev/mii/mii.h>
144 #include <dev/mii/miivar.h>
145 
146 #include <dev/pci/pcireg.h>
147 #include <dev/pci/pcivar.h>
148 
149 #include <pci/if_rlreg.h>
150 
151 MODULE_DEPEND(re, pci, 1, 1, 1);
152 MODULE_DEPEND(re, ether, 1, 1, 1);
153 MODULE_DEPEND(re, miibus, 1, 1, 1);
154 
155 /* "device miibus" required.  See GENERIC if you get errors here. */
156 #include "miibus_if.h"
157 
158 /* Tunables. */
159 static int msi_disable = 1;
160 TUNABLE_INT("hw.re.msi_disable", &msi_disable);
161 
162 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
163 
164 /*
165  * Various supported device vendors/types and their names.
166  */
167 static struct rl_type re_devs[] = {
168 	{ DLINK_VENDORID, DLINK_DEVICEID_528T, 0,
169 	    "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
170 	{ RT_VENDORID, RT_DEVICEID_8139, 0,
171 	    "RealTek 8139C+ 10/100BaseTX" },
172 	{ RT_VENDORID, RT_DEVICEID_8101E, 0,
173 	    "RealTek 8101E/8102E/8102EL PCIe 10/100baseTX" },
174 	{ RT_VENDORID, RT_DEVICEID_8168, 0,
175 	    "RealTek 8168/8168B/8168C/8168CP/8168D/8111B/8111C/8111CP PCIe "
176 	    "Gigabit Ethernet" },
177 	{ RT_VENDORID, RT_DEVICEID_8169, 0,
178 	    "RealTek 8169/8169S/8169SB(L)/8110S/8110SB(L) Gigabit Ethernet" },
179 	{ RT_VENDORID, RT_DEVICEID_8169SC, 0,
180 	    "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
181 	{ COREGA_VENDORID, COREGA_DEVICEID_CGLAPCIGT, 0,
182 	    "Corega CG-LAPCIGT (RTL8169S) Gigabit Ethernet" },
183 	{ LINKSYS_VENDORID, LINKSYS_DEVICEID_EG1032, 0,
184 	    "Linksys EG1032 (RTL8169S) Gigabit Ethernet" },
185 	{ USR_VENDORID, USR_DEVICEID_997902, 0,
186 	    "US Robotics 997902 (RTL8169S) Gigabit Ethernet" }
187 };
188 
189 static struct rl_hwrev re_hwrevs[] = {
190 	{ RL_HWREV_8139, RL_8139,  "" },
191 	{ RL_HWREV_8139A, RL_8139, "A" },
192 	{ RL_HWREV_8139AG, RL_8139, "A-G" },
193 	{ RL_HWREV_8139B, RL_8139, "B" },
194 	{ RL_HWREV_8130, RL_8139, "8130" },
195 	{ RL_HWREV_8139C, RL_8139, "C" },
196 	{ RL_HWREV_8139D, RL_8139, "8139D/8100B/8100C" },
197 	{ RL_HWREV_8139CPLUS, RL_8139CPLUS, "C+"},
198 	{ RL_HWREV_8168_SPIN1, RL_8169, "8168"},
199 	{ RL_HWREV_8169, RL_8169, "8169"},
200 	{ RL_HWREV_8169S, RL_8169, "8169S"},
201 	{ RL_HWREV_8110S, RL_8169, "8110S"},
202 	{ RL_HWREV_8169_8110SB, RL_8169, "8169SB"},
203 	{ RL_HWREV_8169_8110SC, RL_8169, "8169SC"},
204 	{ RL_HWREV_8169_8110SBL, RL_8169, "8169SBL"},
205 	{ RL_HWREV_8100, RL_8139, "8100"},
206 	{ RL_HWREV_8101, RL_8139, "8101"},
207 	{ RL_HWREV_8100E, RL_8169, "8100E"},
208 	{ RL_HWREV_8101E, RL_8169, "8101E"},
209 	{ RL_HWREV_8102E, RL_8169, "8102E"},
210 	{ RL_HWREV_8102EL, RL_8169, "8102EL"},
211 	{ RL_HWREV_8168_SPIN2, RL_8169, "8168"},
212 	{ RL_HWREV_8168_SPIN3, RL_8169, "8168"},
213 	{ RL_HWREV_8168C, RL_8169, "8168C/8111C"},
214 	{ RL_HWREV_8168C_SPIN2, RL_8169, "8168C/8111C"},
215 	{ RL_HWREV_8168CP, RL_8169, "8168CP/8111CP"},
216 	{ RL_HWREV_8168D, RL_8169, "8168D"},
217 	{ 0, 0, NULL }
218 };
219 
220 static int re_probe		(device_t);
221 static int re_attach		(device_t);
222 static int re_detach		(device_t);
223 
224 static int re_encap		(struct rl_softc *, struct mbuf **);
225 
226 static void re_dma_map_addr	(void *, bus_dma_segment_t *, int, int);
227 static int re_allocmem		(device_t, struct rl_softc *);
228 static __inline void re_discard_rxbuf
229 				(struct rl_softc *, int);
230 static int re_newbuf		(struct rl_softc *, int);
231 static int re_rx_list_init	(struct rl_softc *);
232 static int re_tx_list_init	(struct rl_softc *);
233 #ifdef RE_FIXUP_RX
234 static __inline void re_fixup_rx
235 				(struct mbuf *);
236 #endif
237 static int re_rxeof		(struct rl_softc *);
238 static void re_txeof		(struct rl_softc *);
239 #ifdef DEVICE_POLLING
240 static void re_poll		(struct ifnet *, enum poll_cmd, int);
241 static void re_poll_locked	(struct ifnet *, enum poll_cmd, int);
242 #endif
243 static int re_intr		(void *);
244 static void re_tick		(void *);
245 static void re_tx_task		(void *, int);
246 static void re_int_task		(void *, int);
247 static void re_start		(struct ifnet *);
248 static int re_ioctl		(struct ifnet *, u_long, caddr_t);
249 static void re_init		(void *);
250 static void re_init_locked	(struct rl_softc *);
251 static void re_stop		(struct rl_softc *);
252 static void re_watchdog		(struct rl_softc *);
253 static int re_suspend		(device_t);
254 static int re_resume		(device_t);
255 static int re_shutdown		(device_t);
256 static int re_ifmedia_upd	(struct ifnet *);
257 static void re_ifmedia_sts	(struct ifnet *, struct ifmediareq *);
258 
259 static void re_eeprom_putbyte	(struct rl_softc *, int);
260 static void re_eeprom_getword	(struct rl_softc *, int, u_int16_t *);
261 static void re_read_eeprom	(struct rl_softc *, caddr_t, int, int);
262 static int re_gmii_readreg	(device_t, int, int);
263 static int re_gmii_writereg	(device_t, int, int, int);
264 
265 static int re_miibus_readreg	(device_t, int, int);
266 static int re_miibus_writereg	(device_t, int, int, int);
267 static void re_miibus_statchg	(device_t);
268 
269 static void re_setmulti		(struct rl_softc *);
270 static void re_reset		(struct rl_softc *);
271 static void re_setwol		(struct rl_softc *);
272 static void re_clrwol		(struct rl_softc *);
273 
274 #ifdef RE_DIAG
275 static int re_diag		(struct rl_softc *);
276 #endif
277 
278 static device_method_t re_methods[] = {
279 	/* Device interface */
280 	DEVMETHOD(device_probe,		re_probe),
281 	DEVMETHOD(device_attach,	re_attach),
282 	DEVMETHOD(device_detach,	re_detach),
283 	DEVMETHOD(device_suspend,	re_suspend),
284 	DEVMETHOD(device_resume,	re_resume),
285 	DEVMETHOD(device_shutdown,	re_shutdown),
286 
287 	/* bus interface */
288 	DEVMETHOD(bus_print_child,	bus_generic_print_child),
289 	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
290 
291 	/* MII interface */
292 	DEVMETHOD(miibus_readreg,	re_miibus_readreg),
293 	DEVMETHOD(miibus_writereg,	re_miibus_writereg),
294 	DEVMETHOD(miibus_statchg,	re_miibus_statchg),
295 
296 	{ 0, 0 }
297 };
298 
299 static driver_t re_driver = {
300 	"re",
301 	re_methods,
302 	sizeof(struct rl_softc)
303 };
304 
305 static devclass_t re_devclass;
306 
307 DRIVER_MODULE(re, pci, re_driver, re_devclass, 0, 0);
308 DRIVER_MODULE(re, cardbus, re_driver, re_devclass, 0, 0);
309 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
310 
311 #define EE_SET(x)					\
312 	CSR_WRITE_1(sc, RL_EECMD,			\
313 		CSR_READ_1(sc, RL_EECMD) | x)
314 
315 #define EE_CLR(x)					\
316 	CSR_WRITE_1(sc, RL_EECMD,			\
317 		CSR_READ_1(sc, RL_EECMD) & ~x)
318 
319 /*
320  * Send a read command and address to the EEPROM, check for ACK.
321  */
322 static void
323 re_eeprom_putbyte(struct rl_softc *sc, int addr)
324 {
325 	int			d, i;
326 
327 	d = addr | (RL_9346_READ << sc->rl_eewidth);
328 
329 	/*
330 	 * Feed in each bit and strobe the clock.
331 	 */
332 
333 	for (i = 1 << (sc->rl_eewidth + 3); i; i >>= 1) {
334 		if (d & i) {
335 			EE_SET(RL_EE_DATAIN);
336 		} else {
337 			EE_CLR(RL_EE_DATAIN);
338 		}
339 		DELAY(100);
340 		EE_SET(RL_EE_CLK);
341 		DELAY(150);
342 		EE_CLR(RL_EE_CLK);
343 		DELAY(100);
344 	}
345 }
346 
347 /*
348  * Read a word of data stored in the EEPROM at address 'addr.'
349  */
350 static void
351 re_eeprom_getword(struct rl_softc *sc, int addr, u_int16_t *dest)
352 {
353 	int			i;
354 	u_int16_t		word = 0;
355 
356 	/*
357 	 * Send address of word we want to read.
358 	 */
359 	re_eeprom_putbyte(sc, addr);
360 
361 	/*
362 	 * Start reading bits from EEPROM.
363 	 */
364 	for (i = 0x8000; i; i >>= 1) {
365 		EE_SET(RL_EE_CLK);
366 		DELAY(100);
367 		if (CSR_READ_1(sc, RL_EECMD) & RL_EE_DATAOUT)
368 			word |= i;
369 		EE_CLR(RL_EE_CLK);
370 		DELAY(100);
371 	}
372 
373 	*dest = word;
374 }
375 
376 /*
377  * Read a sequence of words from the EEPROM.
378  */
379 static void
380 re_read_eeprom(struct rl_softc *sc, caddr_t dest, int off, int cnt)
381 {
382 	int			i;
383 	u_int16_t		word = 0, *ptr;
384 
385 	CSR_SETBIT_1(sc, RL_EECMD, RL_EEMODE_PROGRAM);
386 
387         DELAY(100);
388 
389 	for (i = 0; i < cnt; i++) {
390 		CSR_SETBIT_1(sc, RL_EECMD, RL_EE_SEL);
391 		re_eeprom_getword(sc, off + i, &word);
392 		CSR_CLRBIT_1(sc, RL_EECMD, RL_EE_SEL);
393 		ptr = (u_int16_t *)(dest + (i * 2));
394                 *ptr = word;
395 	}
396 
397 	CSR_CLRBIT_1(sc, RL_EECMD, RL_EEMODE_PROGRAM);
398 }
399 
400 static int
401 re_gmii_readreg(device_t dev, int phy, int reg)
402 {
403 	struct rl_softc		*sc;
404 	u_int32_t		rval;
405 	int			i;
406 
407 	if (phy != 1)
408 		return (0);
409 
410 	sc = device_get_softc(dev);
411 
412 	/* Let the rgephy driver read the GMEDIASTAT register */
413 
414 	if (reg == RL_GMEDIASTAT) {
415 		rval = CSR_READ_1(sc, RL_GMEDIASTAT);
416 		return (rval);
417 	}
418 
419 	CSR_WRITE_4(sc, RL_PHYAR, reg << 16);
420 
421 	for (i = 0; i < RL_TIMEOUT; i++) {
422 		rval = CSR_READ_4(sc, RL_PHYAR);
423 		if (rval & RL_PHYAR_BUSY)
424 			break;
425 		DELAY(100);
426 	}
427 
428 	if (i == RL_TIMEOUT) {
429 		device_printf(sc->rl_dev, "PHY read failed\n");
430 		return (0);
431 	}
432 
433 	return (rval & RL_PHYAR_PHYDATA);
434 }
435 
436 static int
437 re_gmii_writereg(device_t dev, int phy, int reg, int data)
438 {
439 	struct rl_softc		*sc;
440 	u_int32_t		rval;
441 	int			i;
442 
443 	sc = device_get_softc(dev);
444 
445 	CSR_WRITE_4(sc, RL_PHYAR, (reg << 16) |
446 	    (data & RL_PHYAR_PHYDATA) | RL_PHYAR_BUSY);
447 
448 	for (i = 0; i < RL_TIMEOUT; i++) {
449 		rval = CSR_READ_4(sc, RL_PHYAR);
450 		if (!(rval & RL_PHYAR_BUSY))
451 			break;
452 		DELAY(100);
453 	}
454 
455 	if (i == RL_TIMEOUT) {
456 		device_printf(sc->rl_dev, "PHY write failed\n");
457 		return (0);
458 	}
459 
460 	return (0);
461 }
462 
463 static int
464 re_miibus_readreg(device_t dev, int phy, int reg)
465 {
466 	struct rl_softc		*sc;
467 	u_int16_t		rval = 0;
468 	u_int16_t		re8139_reg = 0;
469 
470 	sc = device_get_softc(dev);
471 
472 	if (sc->rl_type == RL_8169) {
473 		rval = re_gmii_readreg(dev, phy, reg);
474 		return (rval);
475 	}
476 
477 	/* Pretend the internal PHY is only at address 0 */
478 	if (phy) {
479 		return (0);
480 	}
481 	switch (reg) {
482 	case MII_BMCR:
483 		re8139_reg = RL_BMCR;
484 		break;
485 	case MII_BMSR:
486 		re8139_reg = RL_BMSR;
487 		break;
488 	case MII_ANAR:
489 		re8139_reg = RL_ANAR;
490 		break;
491 	case MII_ANER:
492 		re8139_reg = RL_ANER;
493 		break;
494 	case MII_ANLPAR:
495 		re8139_reg = RL_LPAR;
496 		break;
497 	case MII_PHYIDR1:
498 	case MII_PHYIDR2:
499 		return (0);
500 	/*
501 	 * Allow the rlphy driver to read the media status
502 	 * register. If we have a link partner which does not
503 	 * support NWAY, this is the register which will tell
504 	 * us the results of parallel detection.
505 	 */
506 	case RL_MEDIASTAT:
507 		rval = CSR_READ_1(sc, RL_MEDIASTAT);
508 		return (rval);
509 	default:
510 		device_printf(sc->rl_dev, "bad phy register\n");
511 		return (0);
512 	}
513 	rval = CSR_READ_2(sc, re8139_reg);
514 	if (sc->rl_type == RL_8139CPLUS && re8139_reg == RL_BMCR) {
515 		/* 8139C+ has different bit layout. */
516 		rval &= ~(BMCR_LOOP | BMCR_ISO);
517 	}
518 	return (rval);
519 }
520 
521 static int
522 re_miibus_writereg(device_t dev, int phy, int reg, int data)
523 {
524 	struct rl_softc		*sc;
525 	u_int16_t		re8139_reg = 0;
526 	int			rval = 0;
527 
528 	sc = device_get_softc(dev);
529 
530 	if (sc->rl_type == RL_8169) {
531 		rval = re_gmii_writereg(dev, phy, reg, data);
532 		return (rval);
533 	}
534 
535 	/* Pretend the internal PHY is only at address 0 */
536 	if (phy)
537 		return (0);
538 
539 	switch (reg) {
540 	case MII_BMCR:
541 		re8139_reg = RL_BMCR;
542 		if (sc->rl_type == RL_8139CPLUS) {
543 			/* 8139C+ has different bit layout. */
544 			data &= ~(BMCR_LOOP | BMCR_ISO);
545 		}
546 		break;
547 	case MII_BMSR:
548 		re8139_reg = RL_BMSR;
549 		break;
550 	case MII_ANAR:
551 		re8139_reg = RL_ANAR;
552 		break;
553 	case MII_ANER:
554 		re8139_reg = RL_ANER;
555 		break;
556 	case MII_ANLPAR:
557 		re8139_reg = RL_LPAR;
558 		break;
559 	case MII_PHYIDR1:
560 	case MII_PHYIDR2:
561 		return (0);
562 		break;
563 	default:
564 		device_printf(sc->rl_dev, "bad phy register\n");
565 		return (0);
566 	}
567 	CSR_WRITE_2(sc, re8139_reg, data);
568 	return (0);
569 }
570 
571 static void
572 re_miibus_statchg(device_t dev)
573 {
574 	struct rl_softc		*sc;
575 	struct ifnet		*ifp;
576 	struct mii_data		*mii;
577 
578 	sc = device_get_softc(dev);
579 	mii = device_get_softc(sc->rl_miibus);
580 	ifp = sc->rl_ifp;
581 	if (mii == NULL || ifp == NULL ||
582 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
583 		return;
584 
585 	sc->rl_flags &= ~RL_FLAG_LINK;
586 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
587 	    (IFM_ACTIVE | IFM_AVALID)) {
588 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
589 		case IFM_10_T:
590 		case IFM_100_TX:
591 			sc->rl_flags |= RL_FLAG_LINK;
592 			break;
593 		case IFM_1000_T:
594 			if ((sc->rl_flags & RL_FLAG_FASTETHER) != 0)
595 				break;
596 			sc->rl_flags |= RL_FLAG_LINK;
597 			break;
598 		default:
599 			break;
600 		}
601 	}
602 	/*
603 	 * RealTek controllers does not provide any interface to
604 	 * Tx/Rx MACs for resolved speed, duplex and flow-control
605 	 * parameters.
606 	 */
607 }
608 
609 /*
610  * Program the 64-bit multicast hash filter.
611  */
612 static void
613 re_setmulti(struct rl_softc *sc)
614 {
615 	struct ifnet		*ifp;
616 	int			h = 0;
617 	u_int32_t		hashes[2] = { 0, 0 };
618 	struct ifmultiaddr	*ifma;
619 	u_int32_t		rxfilt;
620 	int			mcnt = 0;
621 
622 	RL_LOCK_ASSERT(sc);
623 
624 	ifp = sc->rl_ifp;
625 
626 
627 	rxfilt = CSR_READ_4(sc, RL_RXCFG);
628 	rxfilt &= ~(RL_RXCFG_RX_ALLPHYS | RL_RXCFG_RX_MULTI);
629 	if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
630 		if (ifp->if_flags & IFF_PROMISC)
631 			rxfilt |= RL_RXCFG_RX_ALLPHYS;
632 		/*
633 		 * Unlike other hardwares, we have to explicitly set
634 		 * RL_RXCFG_RX_MULTI to receive multicast frames in
635 		 * promiscuous mode.
636 		 */
637 		rxfilt |= RL_RXCFG_RX_MULTI;
638 		CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
639 		CSR_WRITE_4(sc, RL_MAR0, 0xFFFFFFFF);
640 		CSR_WRITE_4(sc, RL_MAR4, 0xFFFFFFFF);
641 		return;
642 	}
643 
644 	/* first, zot all the existing hash bits */
645 	CSR_WRITE_4(sc, RL_MAR0, 0);
646 	CSR_WRITE_4(sc, RL_MAR4, 0);
647 
648 	/* now program new ones */
649 	IF_ADDR_LOCK(ifp);
650 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
651 		if (ifma->ifma_addr->sa_family != AF_LINK)
652 			continue;
653 		h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
654 		    ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
655 		if (h < 32)
656 			hashes[0] |= (1 << h);
657 		else
658 			hashes[1] |= (1 << (h - 32));
659 		mcnt++;
660 	}
661 	IF_ADDR_UNLOCK(ifp);
662 
663 	if (mcnt)
664 		rxfilt |= RL_RXCFG_RX_MULTI;
665 	else
666 		rxfilt &= ~RL_RXCFG_RX_MULTI;
667 
668 	CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
669 
670 	/*
671 	 * For some unfathomable reason, RealTek decided to reverse
672 	 * the order of the multicast hash registers in the PCI Express
673 	 * parts. This means we have to write the hash pattern in reverse
674 	 * order for those devices.
675 	 */
676 
677 	if ((sc->rl_flags & RL_FLAG_INVMAR) != 0) {
678 		CSR_WRITE_4(sc, RL_MAR0, bswap32(hashes[1]));
679 		CSR_WRITE_4(sc, RL_MAR4, bswap32(hashes[0]));
680 	} else {
681 		CSR_WRITE_4(sc, RL_MAR0, hashes[0]);
682 		CSR_WRITE_4(sc, RL_MAR4, hashes[1]);
683 	}
684 }
685 
686 static void
687 re_reset(struct rl_softc *sc)
688 {
689 	int			i;
690 
691 	RL_LOCK_ASSERT(sc);
692 
693 	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RESET);
694 
695 	for (i = 0; i < RL_TIMEOUT; i++) {
696 		DELAY(10);
697 		if (!(CSR_READ_1(sc, RL_COMMAND) & RL_CMD_RESET))
698 			break;
699 	}
700 	if (i == RL_TIMEOUT)
701 		device_printf(sc->rl_dev, "reset never completed!\n");
702 
703 	if ((sc->rl_flags & RL_FLAG_PHY8169) != 0)
704 		CSR_WRITE_1(sc, 0x82, 1);
705 	if ((sc->rl_flags & RL_FLAG_PHY8110S) != 0) {
706 		CSR_WRITE_1(sc, 0x82, 1);
707 		re_gmii_writereg(sc->rl_dev, 1, 0x0B, 0);
708 	}
709 }
710 
711 #ifdef RE_DIAG
712 
713 /*
714  * The following routine is designed to test for a defect on some
715  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
716  * lines connected to the bus, however for a 32-bit only card, they
717  * should be pulled high. The result of this defect is that the
718  * NIC will not work right if you plug it into a 64-bit slot: DMA
719  * operations will be done with 64-bit transfers, which will fail
720  * because the 64-bit data lines aren't connected.
721  *
722  * There's no way to work around this (short of talking a soldering
723  * iron to the board), however we can detect it. The method we use
724  * here is to put the NIC into digital loopback mode, set the receiver
725  * to promiscuous mode, and then try to send a frame. We then compare
726  * the frame data we sent to what was received. If the data matches,
727  * then the NIC is working correctly, otherwise we know the user has
728  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
729  * slot. In the latter case, there's no way the NIC can work correctly,
730  * so we print out a message on the console and abort the device attach.
731  */
732 
733 static int
734 re_diag(struct rl_softc *sc)
735 {
736 	struct ifnet		*ifp = sc->rl_ifp;
737 	struct mbuf		*m0;
738 	struct ether_header	*eh;
739 	struct rl_desc		*cur_rx;
740 	u_int16_t		status;
741 	u_int32_t		rxstat;
742 	int			total_len, i, error = 0, phyaddr;
743 	u_int8_t		dst[] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
744 	u_int8_t		src[] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
745 
746 	/* Allocate a single mbuf */
747 	MGETHDR(m0, M_DONTWAIT, MT_DATA);
748 	if (m0 == NULL)
749 		return (ENOBUFS);
750 
751 	RL_LOCK(sc);
752 
753 	/*
754 	 * Initialize the NIC in test mode. This sets the chip up
755 	 * so that it can send and receive frames, but performs the
756 	 * following special functions:
757 	 * - Puts receiver in promiscuous mode
758 	 * - Enables digital loopback mode
759 	 * - Leaves interrupts turned off
760 	 */
761 
762 	ifp->if_flags |= IFF_PROMISC;
763 	sc->rl_testmode = 1;
764 	re_init_locked(sc);
765 	sc->rl_flags |= RL_FLAG_LINK;
766 	if (sc->rl_type == RL_8169)
767 		phyaddr = 1;
768 	else
769 		phyaddr = 0;
770 
771 	re_miibus_writereg(sc->rl_dev, phyaddr, MII_BMCR, BMCR_RESET);
772 	for (i = 0; i < RL_TIMEOUT; i++) {
773 		status = re_miibus_readreg(sc->rl_dev, phyaddr, MII_BMCR);
774 		if (!(status & BMCR_RESET))
775 			break;
776 	}
777 
778 	re_miibus_writereg(sc->rl_dev, phyaddr, MII_BMCR, BMCR_LOOP);
779 	CSR_WRITE_2(sc, RL_ISR, RL_INTRS);
780 
781 	DELAY(100000);
782 
783 	/* Put some data in the mbuf */
784 
785 	eh = mtod(m0, struct ether_header *);
786 	bcopy ((char *)&dst, eh->ether_dhost, ETHER_ADDR_LEN);
787 	bcopy ((char *)&src, eh->ether_shost, ETHER_ADDR_LEN);
788 	eh->ether_type = htons(ETHERTYPE_IP);
789 	m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
790 
791 	/*
792 	 * Queue the packet, start transmission.
793 	 * Note: IF_HANDOFF() ultimately calls re_start() for us.
794 	 */
795 
796 	CSR_WRITE_2(sc, RL_ISR, 0xFFFF);
797 	RL_UNLOCK(sc);
798 	/* XXX: re_diag must not be called when in ALTQ mode */
799 	IF_HANDOFF(&ifp->if_snd, m0, ifp);
800 	RL_LOCK(sc);
801 	m0 = NULL;
802 
803 	/* Wait for it to propagate through the chip */
804 
805 	DELAY(100000);
806 	for (i = 0; i < RL_TIMEOUT; i++) {
807 		status = CSR_READ_2(sc, RL_ISR);
808 		CSR_WRITE_2(sc, RL_ISR, status);
809 		if ((status & (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK)) ==
810 		    (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK))
811 			break;
812 		DELAY(10);
813 	}
814 
815 	if (i == RL_TIMEOUT) {
816 		device_printf(sc->rl_dev,
817 		    "diagnostic failed, failed to receive packet in"
818 		    " loopback mode\n");
819 		error = EIO;
820 		goto done;
821 	}
822 
823 	/*
824 	 * The packet should have been dumped into the first
825 	 * entry in the RX DMA ring. Grab it from there.
826 	 */
827 
828 	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
829 	    sc->rl_ldata.rl_rx_list_map,
830 	    BUS_DMASYNC_POSTREAD);
831 	bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
832 	    sc->rl_ldata.rl_rx_desc[0].rx_dmamap,
833 	    BUS_DMASYNC_POSTREAD);
834 	bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag,
835 	    sc->rl_ldata.rl_rx_desc[0].rx_dmamap);
836 
837 	m0 = sc->rl_ldata.rl_rx_desc[0].rx_m;
838 	sc->rl_ldata.rl_rx_desc[0].rx_m = NULL;
839 	eh = mtod(m0, struct ether_header *);
840 
841 	cur_rx = &sc->rl_ldata.rl_rx_list[0];
842 	total_len = RL_RXBYTES(cur_rx);
843 	rxstat = le32toh(cur_rx->rl_cmdstat);
844 
845 	if (total_len != ETHER_MIN_LEN) {
846 		device_printf(sc->rl_dev,
847 		    "diagnostic failed, received short packet\n");
848 		error = EIO;
849 		goto done;
850 	}
851 
852 	/* Test that the received packet data matches what we sent. */
853 
854 	if (bcmp((char *)&eh->ether_dhost, (char *)&dst, ETHER_ADDR_LEN) ||
855 	    bcmp((char *)&eh->ether_shost, (char *)&src, ETHER_ADDR_LEN) ||
856 	    ntohs(eh->ether_type) != ETHERTYPE_IP) {
857 		device_printf(sc->rl_dev, "WARNING, DMA FAILURE!\n");
858 		device_printf(sc->rl_dev, "expected TX data: %6D/%6D/0x%x\n",
859 		    dst, ":", src, ":", ETHERTYPE_IP);
860 		device_printf(sc->rl_dev, "received RX data: %6D/%6D/0x%x\n",
861 		    eh->ether_dhost, ":",  eh->ether_shost, ":",
862 		    ntohs(eh->ether_type));
863 		device_printf(sc->rl_dev, "You may have a defective 32-bit "
864 		    "NIC plugged into a 64-bit PCI slot.\n");
865 		device_printf(sc->rl_dev, "Please re-install the NIC in a "
866 		    "32-bit slot for proper operation.\n");
867 		device_printf(sc->rl_dev, "Read the re(4) man page for more "
868 		    "details.\n");
869 		error = EIO;
870 	}
871 
872 done:
873 	/* Turn interface off, release resources */
874 
875 	sc->rl_testmode = 0;
876 	sc->rl_flags &= ~RL_FLAG_LINK;
877 	ifp->if_flags &= ~IFF_PROMISC;
878 	re_stop(sc);
879 	if (m0 != NULL)
880 		m_freem(m0);
881 
882 	RL_UNLOCK(sc);
883 
884 	return (error);
885 }
886 
887 #endif
888 
889 /*
890  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
891  * IDs against our list and return a device name if we find a match.
892  */
893 static int
894 re_probe(device_t dev)
895 {
896 	struct rl_type		*t;
897 	uint16_t		devid, vendor;
898 	uint16_t		revid, sdevid;
899 	int			i;
900 
901 	vendor = pci_get_vendor(dev);
902 	devid = pci_get_device(dev);
903 	revid = pci_get_revid(dev);
904 	sdevid = pci_get_subdevice(dev);
905 
906 	if (vendor == LINKSYS_VENDORID && devid == LINKSYS_DEVICEID_EG1032) {
907 		if (sdevid != LINKSYS_SUBDEVICE_EG1032_REV3) {
908 			/*
909 			 * Only attach to rev. 3 of the Linksys EG1032 adapter.
910 			 * Rev. 2 is supported by sk(4).
911 			 */
912 			return (ENXIO);
913 		}
914 	}
915 
916 	if (vendor == RT_VENDORID && devid == RT_DEVICEID_8139) {
917 		if (revid != 0x20) {
918 			/* 8139, let rl(4) take care of this device. */
919 			return (ENXIO);
920 		}
921 	}
922 
923 	t = re_devs;
924 	for (i = 0; i < sizeof(re_devs) / sizeof(re_devs[0]); i++, t++) {
925 		if (vendor == t->rl_vid && devid == t->rl_did) {
926 			device_set_desc(dev, t->rl_name);
927 			return (BUS_PROBE_DEFAULT);
928 		}
929 	}
930 
931 	return (ENXIO);
932 }
933 
934 /*
935  * Map a single buffer address.
936  */
937 
938 static void
939 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
940 {
941 	bus_addr_t		*addr;
942 
943 	if (error)
944 		return;
945 
946 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
947 	addr = arg;
948 	*addr = segs->ds_addr;
949 }
950 
951 static int
952 re_allocmem(device_t dev, struct rl_softc *sc)
953 {
954 	bus_size_t		rx_list_size, tx_list_size;
955 	int			error;
956 	int			i;
957 
958 	rx_list_size = sc->rl_ldata.rl_rx_desc_cnt * sizeof(struct rl_desc);
959 	tx_list_size = sc->rl_ldata.rl_tx_desc_cnt * sizeof(struct rl_desc);
960 
961 	/*
962 	 * Allocate the parent bus DMA tag appropriate for PCI.
963 	 * In order to use DAC, RL_CPLUSCMD_PCI_DAC bit of RL_CPLUS_CMD
964 	 * register should be set. However some RealTek chips are known
965 	 * to be buggy on DAC handling, therefore disable DAC by limiting
966 	 * DMA address space to 32bit. PCIe variants of RealTek chips
967 	 * may not have the limitation but I took safer path.
968 	 */
969 	error = bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
970 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
971 	    BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT, 0,
972 	    NULL, NULL, &sc->rl_parent_tag);
973 	if (error) {
974 		device_printf(dev, "could not allocate parent DMA tag\n");
975 		return (error);
976 	}
977 
978 	/*
979 	 * Allocate map for TX mbufs.
980 	 */
981 	error = bus_dma_tag_create(sc->rl_parent_tag, 1, 0,
982 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
983 	    NULL, MCLBYTES * RL_NTXSEGS, RL_NTXSEGS, 4096, 0,
984 	    NULL, NULL, &sc->rl_ldata.rl_tx_mtag);
985 	if (error) {
986 		device_printf(dev, "could not allocate TX DMA tag\n");
987 		return (error);
988 	}
989 
990 	/*
991 	 * Allocate map for RX mbufs.
992 	 */
993 
994 	error = bus_dma_tag_create(sc->rl_parent_tag, sizeof(uint64_t), 0,
995 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
996 	    MCLBYTES, 1, MCLBYTES, 0, NULL, NULL, &sc->rl_ldata.rl_rx_mtag);
997 	if (error) {
998 		device_printf(dev, "could not allocate RX DMA tag\n");
999 		return (error);
1000 	}
1001 
1002 	/*
1003 	 * Allocate map for TX descriptor list.
1004 	 */
1005 	error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
1006 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1007 	    NULL, tx_list_size, 1, tx_list_size, 0,
1008 	    NULL, NULL, &sc->rl_ldata.rl_tx_list_tag);
1009 	if (error) {
1010 		device_printf(dev, "could not allocate TX DMA ring tag\n");
1011 		return (error);
1012 	}
1013 
1014 	/* Allocate DMA'able memory for the TX ring */
1015 
1016 	error = bus_dmamem_alloc(sc->rl_ldata.rl_tx_list_tag,
1017 	    (void **)&sc->rl_ldata.rl_tx_list,
1018 	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO,
1019 	    &sc->rl_ldata.rl_tx_list_map);
1020 	if (error) {
1021 		device_printf(dev, "could not allocate TX DMA ring\n");
1022 		return (error);
1023 	}
1024 
1025 	/* Load the map for the TX ring. */
1026 
1027 	sc->rl_ldata.rl_tx_list_addr = 0;
1028 	error = bus_dmamap_load(sc->rl_ldata.rl_tx_list_tag,
1029 	     sc->rl_ldata.rl_tx_list_map, sc->rl_ldata.rl_tx_list,
1030 	     tx_list_size, re_dma_map_addr,
1031 	     &sc->rl_ldata.rl_tx_list_addr, BUS_DMA_NOWAIT);
1032 	if (error != 0 || sc->rl_ldata.rl_tx_list_addr == 0) {
1033 		device_printf(dev, "could not load TX DMA ring\n");
1034 		return (ENOMEM);
1035 	}
1036 
1037 	/* Create DMA maps for TX buffers */
1038 
1039 	for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
1040 		error = bus_dmamap_create(sc->rl_ldata.rl_tx_mtag, 0,
1041 		    &sc->rl_ldata.rl_tx_desc[i].tx_dmamap);
1042 		if (error) {
1043 			device_printf(dev, "could not create DMA map for TX\n");
1044 			return (error);
1045 		}
1046 	}
1047 
1048 	/*
1049 	 * Allocate map for RX descriptor list.
1050 	 */
1051 	error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
1052 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1053 	    NULL, rx_list_size, 1, rx_list_size, 0,
1054 	    NULL, NULL, &sc->rl_ldata.rl_rx_list_tag);
1055 	if (error) {
1056 		device_printf(dev, "could not create RX DMA ring tag\n");
1057 		return (error);
1058 	}
1059 
1060 	/* Allocate DMA'able memory for the RX ring */
1061 
1062 	error = bus_dmamem_alloc(sc->rl_ldata.rl_rx_list_tag,
1063 	    (void **)&sc->rl_ldata.rl_rx_list,
1064 	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO,
1065 	    &sc->rl_ldata.rl_rx_list_map);
1066 	if (error) {
1067 		device_printf(dev, "could not allocate RX DMA ring\n");
1068 		return (error);
1069 	}
1070 
1071 	/* Load the map for the RX ring. */
1072 
1073 	sc->rl_ldata.rl_rx_list_addr = 0;
1074 	error = bus_dmamap_load(sc->rl_ldata.rl_rx_list_tag,
1075 	     sc->rl_ldata.rl_rx_list_map, sc->rl_ldata.rl_rx_list,
1076 	     rx_list_size, re_dma_map_addr,
1077 	     &sc->rl_ldata.rl_rx_list_addr, BUS_DMA_NOWAIT);
1078 	if (error != 0 || sc->rl_ldata.rl_rx_list_addr == 0) {
1079 		device_printf(dev, "could not load RX DMA ring\n");
1080 		return (ENOMEM);
1081 	}
1082 
1083 	/* Create DMA maps for RX buffers */
1084 
1085 	error = bus_dmamap_create(sc->rl_ldata.rl_rx_mtag, 0,
1086 	    &sc->rl_ldata.rl_rx_sparemap);
1087 	if (error) {
1088 		device_printf(dev, "could not create spare DMA map for RX\n");
1089 		return (error);
1090 	}
1091 	for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1092 		error = bus_dmamap_create(sc->rl_ldata.rl_rx_mtag, 0,
1093 		    &sc->rl_ldata.rl_rx_desc[i].rx_dmamap);
1094 		if (error) {
1095 			device_printf(dev, "could not create DMA map for RX\n");
1096 			return (error);
1097 		}
1098 	}
1099 
1100 	return (0);
1101 }
1102 
1103 /*
1104  * Attach the interface. Allocate softc structures, do ifmedia
1105  * setup and ethernet/BPF attach.
1106  */
1107 static int
1108 re_attach(device_t dev)
1109 {
1110 	u_char			eaddr[ETHER_ADDR_LEN];
1111 	u_int16_t		as[ETHER_ADDR_LEN / 2];
1112 	struct rl_softc		*sc;
1113 	struct ifnet		*ifp;
1114 	struct rl_hwrev		*hw_rev;
1115 	int			hwrev;
1116 	u_int16_t		devid, re_did = 0;
1117 	int			error = 0, rid, i;
1118 	int			msic, reg;
1119 	uint8_t			cfg;
1120 
1121 	sc = device_get_softc(dev);
1122 	sc->rl_dev = dev;
1123 
1124 	mtx_init(&sc->rl_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
1125 	    MTX_DEF);
1126 	callout_init_mtx(&sc->rl_stat_callout, &sc->rl_mtx, 0);
1127 
1128 	/*
1129 	 * Map control/status registers.
1130 	 */
1131 	pci_enable_busmaster(dev);
1132 
1133 	devid = pci_get_device(dev);
1134 	/* Prefer memory space register mapping over IO space. */
1135 	sc->rl_res_id = PCIR_BAR(1);
1136 	sc->rl_res_type = SYS_RES_MEMORY;
1137 	/* RTL8168/8101E seems to use different BARs. */
1138 	if (devid == RT_DEVICEID_8168 || devid == RT_DEVICEID_8101E)
1139 		sc->rl_res_id = PCIR_BAR(2);
1140 	sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
1141 	    &sc->rl_res_id, RF_ACTIVE);
1142 
1143 	if (sc->rl_res == NULL) {
1144 		sc->rl_res_id = PCIR_BAR(0);
1145 		sc->rl_res_type = SYS_RES_IOPORT;
1146 		sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
1147 		    &sc->rl_res_id, RF_ACTIVE);
1148 		if (sc->rl_res == NULL) {
1149 			device_printf(dev, "couldn't map ports/memory\n");
1150 			error = ENXIO;
1151 			goto fail;
1152 		}
1153 	}
1154 
1155 	sc->rl_btag = rman_get_bustag(sc->rl_res);
1156 	sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
1157 
1158 	msic = 0;
1159 	if (pci_find_extcap(dev, PCIY_EXPRESS, &reg) == 0) {
1160 		sc->rl_flags |= RL_FLAG_PCIE;
1161 		msic = pci_msi_count(dev);
1162 		if (bootverbose)
1163 			device_printf(dev, "MSI count : %d\n", msic);
1164 	}
1165 	if (msic == RL_MSI_MESSAGES  && msi_disable == 0) {
1166 		if (pci_alloc_msi(dev, &msic) == 0) {
1167 			if (msic == RL_MSI_MESSAGES) {
1168 				device_printf(dev, "Using %d MSI messages\n",
1169 				    msic);
1170 				sc->rl_flags |= RL_FLAG_MSI;
1171 				/* Explicitly set MSI enable bit. */
1172 				CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1173 				cfg = CSR_READ_1(sc, RL_CFG2);
1174 				cfg |= RL_CFG2_MSI;
1175 				CSR_WRITE_1(sc, RL_CFG2, cfg);
1176 				CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1177 			} else
1178 				pci_release_msi(dev);
1179 		}
1180 	}
1181 
1182 	/* Allocate interrupt */
1183 	if ((sc->rl_flags & RL_FLAG_MSI) == 0) {
1184 		rid = 0;
1185 		sc->rl_irq[0] = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1186 		    RF_SHAREABLE | RF_ACTIVE);
1187 		if (sc->rl_irq[0] == NULL) {
1188 			device_printf(dev, "couldn't allocate IRQ resources\n");
1189 			error = ENXIO;
1190 			goto fail;
1191 		}
1192 	} else {
1193 		for (i = 0, rid = 1; i < RL_MSI_MESSAGES; i++, rid++) {
1194 			sc->rl_irq[i] = bus_alloc_resource_any(dev,
1195 			    SYS_RES_IRQ, &rid, RF_ACTIVE);
1196 			if (sc->rl_irq[i] == NULL) {
1197 				device_printf(dev,
1198 				    "couldn't llocate IRQ resources for "
1199 				    "message %d\n", rid);
1200 				error = ENXIO;
1201 				goto fail;
1202 			}
1203 		}
1204 	}
1205 
1206 	if ((sc->rl_flags & RL_FLAG_MSI) == 0) {
1207 		CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1208 		cfg = CSR_READ_1(sc, RL_CFG2);
1209 		if ((cfg & RL_CFG2_MSI) != 0) {
1210 			device_printf(dev, "turning off MSI enable bit.\n");
1211 			cfg &= ~RL_CFG2_MSI;
1212 			CSR_WRITE_1(sc, RL_CFG2, cfg);
1213 		}
1214 		CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1215 	}
1216 
1217 	/* Reset the adapter. */
1218 	RL_LOCK(sc);
1219 	re_reset(sc);
1220 	RL_UNLOCK(sc);
1221 
1222 	hw_rev = re_hwrevs;
1223 	hwrev = CSR_READ_4(sc, RL_TXCFG);
1224 	device_printf(dev, "Chip rev. 0x%08x\n", hwrev & 0x7c800000);
1225 	device_printf(dev, "MAC rev. 0x%08x\n", hwrev & 0x00700000);
1226 	hwrev &= RL_TXCFG_HWREV;
1227 	while (hw_rev->rl_desc != NULL) {
1228 		if (hw_rev->rl_rev == hwrev) {
1229 			sc->rl_type = hw_rev->rl_type;
1230 			break;
1231 		}
1232 		hw_rev++;
1233 	}
1234 	if (hw_rev->rl_desc == NULL) {
1235 		device_printf(dev, "Unknown H/W revision: 0x%08x\n", hwrev);
1236 		error = ENXIO;
1237 		goto fail;
1238 	}
1239 
1240 	switch (hw_rev->rl_rev) {
1241 	case RL_HWREV_8139CPLUS:
1242 		sc->rl_flags |= RL_FLAG_NOJUMBO | RL_FLAG_FASTETHER;
1243 		break;
1244 	case RL_HWREV_8110S:
1245 		sc->rl_flags |= RL_FLAG_PHY8110S;
1246 		break;
1247 	case RL_HWREV_8100E:
1248 	case RL_HWREV_8101E:
1249 		sc->rl_flags |= RL_FLAG_NOJUMBO | RL_FLAG_INVMAR |
1250 		    RL_FLAG_PHYWAKE | RL_FLAG_FASTETHER;
1251 		break;
1252 	case RL_HWREV_8102E:
1253 	case RL_HWREV_8102EL:
1254 		sc->rl_flags |= RL_FLAG_NOJUMBO | RL_FLAG_INVMAR |
1255 		    RL_FLAG_PHYWAKE | RL_FLAG_PAR | RL_FLAG_DESCV2 |
1256 		    RL_FLAG_MACSTAT | RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP;
1257 		break;
1258 	case RL_HWREV_8168_SPIN1:
1259 	case RL_HWREV_8168_SPIN2:
1260 		sc->rl_flags |= RL_FLAG_WOLRXENB;
1261 		/* FALLTHROUGH */
1262 	case RL_HWREV_8168_SPIN3:
1263 		sc->rl_flags |= RL_FLAG_INVMAR | RL_FLAG_PHYWAKE |
1264 		    RL_FLAG_MACSTAT;
1265 		break;
1266 	case RL_HWREV_8168C_SPIN2:
1267 		sc->rl_flags |= RL_FLAG_MACSLEEP;
1268 		/* FALLTHROUGH */
1269 	case RL_HWREV_8168C:
1270 		if ((hwrev & 0x00700000) == 0x00200000)
1271 			sc->rl_flags |= RL_FLAG_MACSLEEP;
1272 		/* FALLTHROUGH */
1273 	case RL_HWREV_8168CP:
1274 	case RL_HWREV_8168D:
1275 		sc->rl_flags |= RL_FLAG_INVMAR | RL_FLAG_PHYWAKE |
1276 		    RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
1277 		    RL_FLAG_CMDSTOP;
1278 		/*
1279 		 * These controllers support jumbo frame but it seems
1280 		 * that enabling it requires touching additional magic
1281 		 * registers. Depending on MAC revisions some
1282 		 * controllers need to disable checksum offload. So
1283 		 * disable jumbo frame until I have better idea what
1284 		 * it really requires to make it support.
1285 		 * RTL8168C/CP : supports up to 6KB jumbo frame.
1286 		 * RTL8111C/CP : supports up to 9KB jumbo frame.
1287 		 */
1288 		sc->rl_flags |= RL_FLAG_NOJUMBO;
1289 		break;
1290 	case RL_HWREV_8169:
1291 	case RL_HWREV_8169S:
1292 		sc->rl_flags |= RL_FLAG_PHY8169;
1293 		break;
1294 	case RL_HWREV_8169_8110SB:
1295 	case RL_HWREV_8169_8110SC:
1296 	case RL_HWREV_8169_8110SBL:
1297 		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHY8169;
1298 		break;
1299 	default:
1300 		break;
1301 	}
1302 
1303 	/* Enable PME. */
1304 	CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1305 	cfg = CSR_READ_1(sc, RL_CFG1);
1306 	cfg |= RL_CFG1_PME;
1307 	CSR_WRITE_1(sc, RL_CFG1, cfg);
1308 	cfg = CSR_READ_1(sc, RL_CFG5);
1309 	cfg &= RL_CFG5_PME_STS;
1310 	CSR_WRITE_1(sc, RL_CFG5, cfg);
1311 	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1312 
1313 	if ((sc->rl_flags & RL_FLAG_PAR) != 0) {
1314 		/*
1315 		 * XXX Should have a better way to extract station
1316 		 * address from EEPROM.
1317 		 */
1318 		for (i = 0; i < ETHER_ADDR_LEN; i++)
1319 			eaddr[i] = CSR_READ_1(sc, RL_IDR0 + i);
1320 	} else {
1321 		sc->rl_eewidth = RL_9356_ADDR_LEN;
1322 		re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1323 		if (re_did != 0x8129)
1324 			sc->rl_eewidth = RL_9346_ADDR_LEN;
1325 
1326 		/*
1327 		 * Get station address from the EEPROM.
1328 		 */
1329 		re_read_eeprom(sc, (caddr_t)as, RL_EE_EADDR, 3);
1330 		for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1331 			as[i] = le16toh(as[i]);
1332 		bcopy(as, eaddr, sizeof(eaddr));
1333 	}
1334 
1335 	if (sc->rl_type == RL_8169) {
1336 		/* Set RX length mask and number of descriptors. */
1337 		sc->rl_rxlenmask = RL_RDESC_STAT_GFRAGLEN;
1338 		sc->rl_txstart = RL_GTXSTART;
1339 		sc->rl_ldata.rl_tx_desc_cnt = RL_8169_TX_DESC_CNT;
1340 		sc->rl_ldata.rl_rx_desc_cnt = RL_8169_RX_DESC_CNT;
1341 	} else {
1342 		/* Set RX length mask and number of descriptors. */
1343 		sc->rl_rxlenmask = RL_RDESC_STAT_FRAGLEN;
1344 		sc->rl_txstart = RL_TXSTART;
1345 		sc->rl_ldata.rl_tx_desc_cnt = RL_8139_TX_DESC_CNT;
1346 		sc->rl_ldata.rl_rx_desc_cnt = RL_8139_RX_DESC_CNT;
1347 	}
1348 
1349 	error = re_allocmem(dev, sc);
1350 	if (error)
1351 		goto fail;
1352 
1353 	ifp = sc->rl_ifp = if_alloc(IFT_ETHER);
1354 	if (ifp == NULL) {
1355 		device_printf(dev, "can not if_alloc()\n");
1356 		error = ENOSPC;
1357 		goto fail;
1358 	}
1359 
1360 	/* Take controller out of deep sleep mode. */
1361 	if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
1362 		if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
1363 			CSR_WRITE_1(sc, RL_GPIO,
1364 			    CSR_READ_1(sc, RL_GPIO) | 0x01);
1365 		else
1366 			CSR_WRITE_1(sc, RL_GPIO,
1367 			    CSR_READ_1(sc, RL_GPIO) & ~0x01);
1368 	}
1369 
1370 	/* Take PHY out of power down mode. */
1371 	if ((sc->rl_flags & RL_FLAG_PHYWAKE) != 0) {
1372 		re_gmii_writereg(dev, 1, 0x1f, 0);
1373 		re_gmii_writereg(dev, 1, 0x0e, 0);
1374 	}
1375 
1376 	/* Do MII setup */
1377 	if (mii_phy_probe(dev, &sc->rl_miibus,
1378 	    re_ifmedia_upd, re_ifmedia_sts)) {
1379 		device_printf(dev, "MII without any phy!\n");
1380 		error = ENXIO;
1381 		goto fail;
1382 	}
1383 
1384 	ifp->if_softc = sc;
1385 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1386 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1387 	ifp->if_ioctl = re_ioctl;
1388 	ifp->if_start = re_start;
1389 	ifp->if_hwassist = RE_CSUM_FEATURES;
1390 	ifp->if_capabilities = IFCAP_HWCSUM;
1391 	ifp->if_capenable = ifp->if_capabilities;
1392 	ifp->if_init = re_init;
1393 	IFQ_SET_MAXLEN(&ifp->if_snd, RL_IFQ_MAXLEN);
1394 	ifp->if_snd.ifq_drv_maxlen = RL_IFQ_MAXLEN;
1395 	IFQ_SET_READY(&ifp->if_snd);
1396 
1397 	TASK_INIT(&sc->rl_txtask, 1, re_tx_task, ifp);
1398 	TASK_INIT(&sc->rl_inttask, 0, re_int_task, sc);
1399 
1400 	/*
1401 	 * XXX
1402 	 * Still have no idea how to make TSO work on 8168C, 8168CP,
1403 	 * 8111C and 8111CP.
1404 	 */
1405 	if ((sc->rl_flags & RL_FLAG_DESCV2) == 0) {
1406 		ifp->if_hwassist |= CSUM_TSO;
1407 		ifp->if_capabilities |= IFCAP_TSO4;
1408 	}
1409 
1410 	/*
1411 	 * Call MI attach routine.
1412 	 */
1413 	ether_ifattach(ifp, eaddr);
1414 
1415 	/* VLAN capability setup */
1416 	ifp->if_capabilities |= IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1417 	if (ifp->if_capabilities & IFCAP_HWCSUM)
1418 		ifp->if_capabilities |= IFCAP_VLAN_HWCSUM;
1419 	/* Enable WOL if PM is supported. */
1420 	if (pci_find_extcap(sc->rl_dev, PCIY_PMG, &reg) == 0)
1421 		ifp->if_capabilities |= IFCAP_WOL;
1422 	ifp->if_capenable = ifp->if_capabilities;
1423 	/*
1424 	 * Don't enable TSO by default. Under certain
1425 	 * circumtances the controller generated corrupted
1426 	 * packets in TSO size.
1427 	 */
1428 	ifp->if_hwassist &= ~CSUM_TSO;
1429 	ifp->if_capenable &= ~IFCAP_TSO4;
1430 #ifdef DEVICE_POLLING
1431 	ifp->if_capabilities |= IFCAP_POLLING;
1432 #endif
1433 	/*
1434 	 * Tell the upper layer(s) we support long frames.
1435 	 * Must appear after the call to ether_ifattach() because
1436 	 * ether_ifattach() sets ifi_hdrlen to the default value.
1437 	 */
1438 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
1439 
1440 #ifdef RE_DIAG
1441 	/*
1442 	 * Perform hardware diagnostic on the original RTL8169.
1443 	 * Some 32-bit cards were incorrectly wired and would
1444 	 * malfunction if plugged into a 64-bit slot.
1445 	 */
1446 
1447 	if (hwrev == RL_HWREV_8169) {
1448 		error = re_diag(sc);
1449 		if (error) {
1450 			device_printf(dev,
1451 		    	"attach aborted due to hardware diag failure\n");
1452 			ether_ifdetach(ifp);
1453 			goto fail;
1454 		}
1455 	}
1456 #endif
1457 
1458 	/* Hook interrupt last to avoid having to lock softc */
1459 	if ((sc->rl_flags & RL_FLAG_MSI) == 0)
1460 		error = bus_setup_intr(dev, sc->rl_irq[0],
1461 		    INTR_TYPE_NET | INTR_MPSAFE, re_intr, NULL, sc,
1462 		    &sc->rl_intrhand[0]);
1463 	else {
1464 		for (i = 0; i < RL_MSI_MESSAGES; i++) {
1465 			error = bus_setup_intr(dev, sc->rl_irq[i],
1466 			    INTR_TYPE_NET | INTR_MPSAFE, re_intr, NULL, sc,
1467 		    	    &sc->rl_intrhand[i]);
1468 			if (error != 0)
1469 				break;
1470 		}
1471 	}
1472 	if (error) {
1473 		device_printf(dev, "couldn't set up irq\n");
1474 		ether_ifdetach(ifp);
1475 	}
1476 
1477 fail:
1478 
1479 	if (error)
1480 		re_detach(dev);
1481 
1482 	return (error);
1483 }
1484 
1485 /*
1486  * Shutdown hardware and free up resources. This can be called any
1487  * time after the mutex has been initialized. It is called in both
1488  * the error case in attach and the normal detach case so it needs
1489  * to be careful about only freeing resources that have actually been
1490  * allocated.
1491  */
1492 static int
1493 re_detach(device_t dev)
1494 {
1495 	struct rl_softc		*sc;
1496 	struct ifnet		*ifp;
1497 	int			i, rid;
1498 
1499 	sc = device_get_softc(dev);
1500 	ifp = sc->rl_ifp;
1501 	KASSERT(mtx_initialized(&sc->rl_mtx), ("re mutex not initialized"));
1502 
1503 	/* These should only be active if attach succeeded */
1504 	if (device_is_attached(dev)) {
1505 #ifdef DEVICE_POLLING
1506 		if (ifp->if_capenable & IFCAP_POLLING)
1507 			ether_poll_deregister(ifp);
1508 #endif
1509 		RL_LOCK(sc);
1510 #if 0
1511 		sc->suspended = 1;
1512 #endif
1513 		re_stop(sc);
1514 		RL_UNLOCK(sc);
1515 		callout_drain(&sc->rl_stat_callout);
1516 		taskqueue_drain(taskqueue_fast, &sc->rl_inttask);
1517 		taskqueue_drain(taskqueue_fast, &sc->rl_txtask);
1518 		/*
1519 		 * Force off the IFF_UP flag here, in case someone
1520 		 * still had a BPF descriptor attached to this
1521 		 * interface. If they do, ether_ifdetach() will cause
1522 		 * the BPF code to try and clear the promisc mode
1523 		 * flag, which will bubble down to re_ioctl(),
1524 		 * which will try to call re_init() again. This will
1525 		 * turn the NIC back on and restart the MII ticker,
1526 		 * which will panic the system when the kernel tries
1527 		 * to invoke the re_tick() function that isn't there
1528 		 * anymore.
1529 		 */
1530 		ifp->if_flags &= ~IFF_UP;
1531 		ether_ifdetach(ifp);
1532 	}
1533 	if (sc->rl_miibus)
1534 		device_delete_child(dev, sc->rl_miibus);
1535 	bus_generic_detach(dev);
1536 
1537 	/*
1538 	 * The rest is resource deallocation, so we should already be
1539 	 * stopped here.
1540 	 */
1541 
1542 	for (i = 0; i < RL_MSI_MESSAGES; i++) {
1543 		if (sc->rl_intrhand[i] != NULL) {
1544 			bus_teardown_intr(dev, sc->rl_irq[i],
1545 			    sc->rl_intrhand[i]);
1546 			sc->rl_intrhand[i] = NULL;
1547 		}
1548 	}
1549 	if (ifp != NULL)
1550 		if_free(ifp);
1551 	if ((sc->rl_flags & RL_FLAG_MSI) == 0) {
1552 		if (sc->rl_irq[0] != NULL) {
1553 			bus_release_resource(dev, SYS_RES_IRQ, 0,
1554 			    sc->rl_irq[0]);
1555 			sc->rl_irq[0] = NULL;
1556 		}
1557 	} else {
1558 		for (i = 0, rid = 1; i < RL_MSI_MESSAGES; i++, rid++) {
1559 			if (sc->rl_irq[i] != NULL) {
1560 				bus_release_resource(dev, SYS_RES_IRQ, rid,
1561 				    sc->rl_irq[i]);
1562 				sc->rl_irq[i] = NULL;
1563 			}
1564 		}
1565 		pci_release_msi(dev);
1566 	}
1567 	if (sc->rl_res)
1568 		bus_release_resource(dev, sc->rl_res_type, sc->rl_res_id,
1569 		    sc->rl_res);
1570 
1571 	/* Unload and free the RX DMA ring memory and map */
1572 
1573 	if (sc->rl_ldata.rl_rx_list_tag) {
1574 		bus_dmamap_unload(sc->rl_ldata.rl_rx_list_tag,
1575 		    sc->rl_ldata.rl_rx_list_map);
1576 		bus_dmamem_free(sc->rl_ldata.rl_rx_list_tag,
1577 		    sc->rl_ldata.rl_rx_list,
1578 		    sc->rl_ldata.rl_rx_list_map);
1579 		bus_dma_tag_destroy(sc->rl_ldata.rl_rx_list_tag);
1580 	}
1581 
1582 	/* Unload and free the TX DMA ring memory and map */
1583 
1584 	if (sc->rl_ldata.rl_tx_list_tag) {
1585 		bus_dmamap_unload(sc->rl_ldata.rl_tx_list_tag,
1586 		    sc->rl_ldata.rl_tx_list_map);
1587 		bus_dmamem_free(sc->rl_ldata.rl_tx_list_tag,
1588 		    sc->rl_ldata.rl_tx_list,
1589 		    sc->rl_ldata.rl_tx_list_map);
1590 		bus_dma_tag_destroy(sc->rl_ldata.rl_tx_list_tag);
1591 	}
1592 
1593 	/* Destroy all the RX and TX buffer maps */
1594 
1595 	if (sc->rl_ldata.rl_tx_mtag) {
1596 		for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++)
1597 			bus_dmamap_destroy(sc->rl_ldata.rl_tx_mtag,
1598 			    sc->rl_ldata.rl_tx_desc[i].tx_dmamap);
1599 		bus_dma_tag_destroy(sc->rl_ldata.rl_tx_mtag);
1600 	}
1601 	if (sc->rl_ldata.rl_rx_mtag) {
1602 		for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++)
1603 			bus_dmamap_destroy(sc->rl_ldata.rl_rx_mtag,
1604 			    sc->rl_ldata.rl_rx_desc[i].rx_dmamap);
1605 		if (sc->rl_ldata.rl_rx_sparemap)
1606 			bus_dmamap_destroy(sc->rl_ldata.rl_rx_mtag,
1607 			    sc->rl_ldata.rl_rx_sparemap);
1608 		bus_dma_tag_destroy(sc->rl_ldata.rl_rx_mtag);
1609 	}
1610 
1611 	/* Unload and free the stats buffer and map */
1612 
1613 	if (sc->rl_ldata.rl_stag) {
1614 		bus_dmamap_unload(sc->rl_ldata.rl_stag,
1615 		    sc->rl_ldata.rl_rx_list_map);
1616 		bus_dmamem_free(sc->rl_ldata.rl_stag,
1617 		    sc->rl_ldata.rl_stats,
1618 		    sc->rl_ldata.rl_smap);
1619 		bus_dma_tag_destroy(sc->rl_ldata.rl_stag);
1620 	}
1621 
1622 	if (sc->rl_parent_tag)
1623 		bus_dma_tag_destroy(sc->rl_parent_tag);
1624 
1625 	mtx_destroy(&sc->rl_mtx);
1626 
1627 	return (0);
1628 }
1629 
1630 static __inline void
1631 re_discard_rxbuf(struct rl_softc *sc, int idx)
1632 {
1633 	struct rl_desc		*desc;
1634 	struct rl_rxdesc	*rxd;
1635 	uint32_t		cmdstat;
1636 
1637 	rxd = &sc->rl_ldata.rl_rx_desc[idx];
1638 	desc = &sc->rl_ldata.rl_rx_list[idx];
1639 	desc->rl_vlanctl = 0;
1640 	cmdstat = rxd->rx_size;
1641 	if (idx == sc->rl_ldata.rl_rx_desc_cnt - 1)
1642 		cmdstat |= RL_RDESC_CMD_EOR;
1643 	desc->rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
1644 }
1645 
1646 static int
1647 re_newbuf(struct rl_softc *sc, int idx)
1648 {
1649 	struct mbuf		*m;
1650 	struct rl_rxdesc	*rxd;
1651 	bus_dma_segment_t	segs[1];
1652 	bus_dmamap_t		map;
1653 	struct rl_desc		*desc;
1654 	uint32_t		cmdstat;
1655 	int			error, nsegs;
1656 
1657 	m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1658 	if (m == NULL)
1659 		return (ENOBUFS);
1660 
1661 	m->m_len = m->m_pkthdr.len = MCLBYTES;
1662 #ifdef RE_FIXUP_RX
1663 	/*
1664 	 * This is part of an evil trick to deal with non-x86 platforms.
1665 	 * The RealTek chip requires RX buffers to be aligned on 64-bit
1666 	 * boundaries, but that will hose non-x86 machines. To get around
1667 	 * this, we leave some empty space at the start of each buffer
1668 	 * and for non-x86 hosts, we copy the buffer back six bytes
1669 	 * to achieve word alignment. This is slightly more efficient
1670 	 * than allocating a new buffer, copying the contents, and
1671 	 * discarding the old buffer.
1672 	 */
1673 	m_adj(m, RE_ETHER_ALIGN);
1674 #endif
1675 	error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_rx_mtag,
1676 	    sc->rl_ldata.rl_rx_sparemap, m, segs, &nsegs, BUS_DMA_NOWAIT);
1677 	if (error != 0) {
1678 		m_freem(m);
1679 		return (ENOBUFS);
1680 	}
1681 	KASSERT(nsegs == 1, ("%s: %d segment returned!", __func__, nsegs));
1682 
1683 	rxd = &sc->rl_ldata.rl_rx_desc[idx];
1684 	if (rxd->rx_m != NULL) {
1685 		bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap,
1686 		    BUS_DMASYNC_POSTREAD);
1687 		bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap);
1688 	}
1689 
1690 	rxd->rx_m = m;
1691 	map = rxd->rx_dmamap;
1692 	rxd->rx_dmamap = sc->rl_ldata.rl_rx_sparemap;
1693 	rxd->rx_size = segs[0].ds_len;
1694 	sc->rl_ldata.rl_rx_sparemap = map;
1695 	bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap,
1696 	    BUS_DMASYNC_PREREAD);
1697 
1698 	desc = &sc->rl_ldata.rl_rx_list[idx];
1699 	desc->rl_vlanctl = 0;
1700 	desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[0].ds_addr));
1701 	desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[0].ds_addr));
1702 	cmdstat = segs[0].ds_len;
1703 	if (idx == sc->rl_ldata.rl_rx_desc_cnt - 1)
1704 		cmdstat |= RL_RDESC_CMD_EOR;
1705 	desc->rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
1706 
1707 	return (0);
1708 }
1709 
1710 #ifdef RE_FIXUP_RX
1711 static __inline void
1712 re_fixup_rx(struct mbuf *m)
1713 {
1714 	int                     i;
1715 	uint16_t                *src, *dst;
1716 
1717 	src = mtod(m, uint16_t *);
1718 	dst = src - (RE_ETHER_ALIGN - ETHER_ALIGN) / sizeof *src;
1719 
1720 	for (i = 0; i < (m->m_len / sizeof(uint16_t) + 1); i++)
1721 		*dst++ = *src++;
1722 
1723 	m->m_data -= RE_ETHER_ALIGN - ETHER_ALIGN;
1724 }
1725 #endif
1726 
1727 static int
1728 re_tx_list_init(struct rl_softc *sc)
1729 {
1730 	struct rl_desc		*desc;
1731 	int			i;
1732 
1733 	RL_LOCK_ASSERT(sc);
1734 
1735 	bzero(sc->rl_ldata.rl_tx_list,
1736 	    sc->rl_ldata.rl_tx_desc_cnt * sizeof(struct rl_desc));
1737 	for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++)
1738 		sc->rl_ldata.rl_tx_desc[i].tx_m = NULL;
1739 	/* Set EOR. */
1740 	desc = &sc->rl_ldata.rl_tx_list[sc->rl_ldata.rl_tx_desc_cnt - 1];
1741 	desc->rl_cmdstat |= htole32(RL_TDESC_CMD_EOR);
1742 
1743 	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
1744 	    sc->rl_ldata.rl_tx_list_map,
1745 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1746 
1747 	sc->rl_ldata.rl_tx_prodidx = 0;
1748 	sc->rl_ldata.rl_tx_considx = 0;
1749 	sc->rl_ldata.rl_tx_free = sc->rl_ldata.rl_tx_desc_cnt;
1750 
1751 	return (0);
1752 }
1753 
1754 static int
1755 re_rx_list_init(struct rl_softc *sc)
1756 {
1757 	int			error, i;
1758 
1759 	bzero(sc->rl_ldata.rl_rx_list,
1760 	    sc->rl_ldata.rl_rx_desc_cnt * sizeof(struct rl_desc));
1761 	for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1762 		sc->rl_ldata.rl_rx_desc[i].rx_m = NULL;
1763 		if ((error = re_newbuf(sc, i)) != 0)
1764 			return (error);
1765 	}
1766 
1767 	/* Flush the RX descriptors */
1768 
1769 	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1770 	    sc->rl_ldata.rl_rx_list_map,
1771 	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1772 
1773 	sc->rl_ldata.rl_rx_prodidx = 0;
1774 	sc->rl_head = sc->rl_tail = NULL;
1775 
1776 	return (0);
1777 }
1778 
1779 /*
1780  * RX handler for C+ and 8169. For the gigE chips, we support
1781  * the reception of jumbo frames that have been fragmented
1782  * across multiple 2K mbuf cluster buffers.
1783  */
1784 static int
1785 re_rxeof(struct rl_softc *sc)
1786 {
1787 	struct mbuf		*m;
1788 	struct ifnet		*ifp;
1789 	int			i, total_len;
1790 	struct rl_desc		*cur_rx;
1791 	u_int32_t		rxstat, rxvlan;
1792 	int			maxpkt = 16;
1793 
1794 	RL_LOCK_ASSERT(sc);
1795 
1796 	ifp = sc->rl_ifp;
1797 
1798 	/* Invalidate the descriptor memory */
1799 
1800 	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1801 	    sc->rl_ldata.rl_rx_list_map,
1802 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1803 
1804 	for (i = sc->rl_ldata.rl_rx_prodidx; maxpkt > 0;
1805 	    i = RL_RX_DESC_NXT(sc, i)) {
1806 		cur_rx = &sc->rl_ldata.rl_rx_list[i];
1807 		rxstat = le32toh(cur_rx->rl_cmdstat);
1808 		if ((rxstat & RL_RDESC_STAT_OWN) != 0)
1809 			break;
1810 		total_len = rxstat & sc->rl_rxlenmask;
1811 		rxvlan = le32toh(cur_rx->rl_vlanctl);
1812 		m = sc->rl_ldata.rl_rx_desc[i].rx_m;
1813 
1814 		if (!(rxstat & RL_RDESC_STAT_EOF)) {
1815 			if (re_newbuf(sc, i) != 0) {
1816 				/*
1817 				 * If this is part of a multi-fragment packet,
1818 				 * discard all the pieces.
1819 				 */
1820 				if (sc->rl_head != NULL) {
1821 					m_freem(sc->rl_head);
1822 					sc->rl_head = sc->rl_tail = NULL;
1823 				}
1824 				re_discard_rxbuf(sc, i);
1825 				continue;
1826 			}
1827 			m->m_len = RE_RX_DESC_BUFLEN;
1828 			if (sc->rl_head == NULL)
1829 				sc->rl_head = sc->rl_tail = m;
1830 			else {
1831 				m->m_flags &= ~M_PKTHDR;
1832 				sc->rl_tail->m_next = m;
1833 				sc->rl_tail = m;
1834 			}
1835 			continue;
1836 		}
1837 
1838 		/*
1839 		 * NOTE: for the 8139C+, the frame length field
1840 		 * is always 12 bits in size, but for the gigE chips,
1841 		 * it is 13 bits (since the max RX frame length is 16K).
1842 		 * Unfortunately, all 32 bits in the status word
1843 		 * were already used, so to make room for the extra
1844 		 * length bit, RealTek took out the 'frame alignment
1845 		 * error' bit and shifted the other status bits
1846 		 * over one slot. The OWN, EOR, FS and LS bits are
1847 		 * still in the same places. We have already extracted
1848 		 * the frame length and checked the OWN bit, so rather
1849 		 * than using an alternate bit mapping, we shift the
1850 		 * status bits one space to the right so we can evaluate
1851 		 * them using the 8169 status as though it was in the
1852 		 * same format as that of the 8139C+.
1853 		 */
1854 		if (sc->rl_type == RL_8169)
1855 			rxstat >>= 1;
1856 
1857 		/*
1858 		 * if total_len > 2^13-1, both _RXERRSUM and _GIANT will be
1859 		 * set, but if CRC is clear, it will still be a valid frame.
1860 		 */
1861 		if (rxstat & RL_RDESC_STAT_RXERRSUM && !(total_len > 8191 &&
1862 		    (rxstat & RL_RDESC_STAT_ERRS) == RL_RDESC_STAT_GIANT)) {
1863 			ifp->if_ierrors++;
1864 			/*
1865 			 * If this is part of a multi-fragment packet,
1866 			 * discard all the pieces.
1867 			 */
1868 			if (sc->rl_head != NULL) {
1869 				m_freem(sc->rl_head);
1870 				sc->rl_head = sc->rl_tail = NULL;
1871 			}
1872 			re_discard_rxbuf(sc, i);
1873 			continue;
1874 		}
1875 
1876 		/*
1877 		 * If allocating a replacement mbuf fails,
1878 		 * reload the current one.
1879 		 */
1880 
1881 		if (re_newbuf(sc, i) != 0) {
1882 			ifp->if_iqdrops++;
1883 			if (sc->rl_head != NULL) {
1884 				m_freem(sc->rl_head);
1885 				sc->rl_head = sc->rl_tail = NULL;
1886 			}
1887 			re_discard_rxbuf(sc, i);
1888 			continue;
1889 		}
1890 
1891 		if (sc->rl_head != NULL) {
1892 			m->m_len = total_len % RE_RX_DESC_BUFLEN;
1893 			if (m->m_len == 0)
1894 				m->m_len = RE_RX_DESC_BUFLEN;
1895 			/*
1896 			 * Special case: if there's 4 bytes or less
1897 			 * in this buffer, the mbuf can be discarded:
1898 			 * the last 4 bytes is the CRC, which we don't
1899 			 * care about anyway.
1900 			 */
1901 			if (m->m_len <= ETHER_CRC_LEN) {
1902 				sc->rl_tail->m_len -=
1903 				    (ETHER_CRC_LEN - m->m_len);
1904 				m_freem(m);
1905 			} else {
1906 				m->m_len -= ETHER_CRC_LEN;
1907 				m->m_flags &= ~M_PKTHDR;
1908 				sc->rl_tail->m_next = m;
1909 			}
1910 			m = sc->rl_head;
1911 			sc->rl_head = sc->rl_tail = NULL;
1912 			m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1913 		} else
1914 			m->m_pkthdr.len = m->m_len =
1915 			    (total_len - ETHER_CRC_LEN);
1916 
1917 #ifdef RE_FIXUP_RX
1918 		re_fixup_rx(m);
1919 #endif
1920 		ifp->if_ipackets++;
1921 		m->m_pkthdr.rcvif = ifp;
1922 
1923 		/* Do RX checksumming if enabled */
1924 
1925 		if (ifp->if_capenable & IFCAP_RXCSUM) {
1926 			if ((sc->rl_flags & RL_FLAG_DESCV2) == 0) {
1927 				/* Check IP header checksum */
1928 				if (rxstat & RL_RDESC_STAT_PROTOID)
1929 					m->m_pkthdr.csum_flags |=
1930 					    CSUM_IP_CHECKED;
1931 				if (!(rxstat & RL_RDESC_STAT_IPSUMBAD))
1932 					m->m_pkthdr.csum_flags |=
1933 					    CSUM_IP_VALID;
1934 
1935 				/* Check TCP/UDP checksum */
1936 				if ((RL_TCPPKT(rxstat) &&
1937 				    !(rxstat & RL_RDESC_STAT_TCPSUMBAD)) ||
1938 				    (RL_UDPPKT(rxstat) &&
1939 				     !(rxstat & RL_RDESC_STAT_UDPSUMBAD))) {
1940 					m->m_pkthdr.csum_flags |=
1941 						CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
1942 					m->m_pkthdr.csum_data = 0xffff;
1943 				}
1944 			} else {
1945 				/*
1946 				 * RTL8168C/RTL816CP/RTL8111C/RTL8111CP
1947 				 */
1948 				if ((rxstat & RL_RDESC_STAT_PROTOID) &&
1949 				    (rxvlan & RL_RDESC_IPV4))
1950 					m->m_pkthdr.csum_flags |=
1951 					    CSUM_IP_CHECKED;
1952 				if (!(rxstat & RL_RDESC_STAT_IPSUMBAD) &&
1953 				    (rxvlan & RL_RDESC_IPV4))
1954 					m->m_pkthdr.csum_flags |=
1955 					    CSUM_IP_VALID;
1956 				if (((rxstat & RL_RDESC_STAT_TCP) &&
1957 				    !(rxstat & RL_RDESC_STAT_TCPSUMBAD)) ||
1958 				    ((rxstat & RL_RDESC_STAT_UDP) &&
1959 				    !(rxstat & RL_RDESC_STAT_UDPSUMBAD))) {
1960 					m->m_pkthdr.csum_flags |=
1961 						CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
1962 					m->m_pkthdr.csum_data = 0xffff;
1963 				}
1964 			}
1965 		}
1966 		maxpkt--;
1967 		if (rxvlan & RL_RDESC_VLANCTL_TAG) {
1968 			m->m_pkthdr.ether_vtag =
1969 			    bswap16((rxvlan & RL_RDESC_VLANCTL_DATA));
1970 			m->m_flags |= M_VLANTAG;
1971 		}
1972 		RL_UNLOCK(sc);
1973 		(*ifp->if_input)(ifp, m);
1974 		RL_LOCK(sc);
1975 	}
1976 
1977 	/* Flush the RX DMA ring */
1978 
1979 	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1980 	    sc->rl_ldata.rl_rx_list_map,
1981 	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1982 
1983 	sc->rl_ldata.rl_rx_prodidx = i;
1984 
1985 	if (maxpkt)
1986 		return(EAGAIN);
1987 
1988 	return(0);
1989 }
1990 
1991 static void
1992 re_txeof(struct rl_softc *sc)
1993 {
1994 	struct ifnet		*ifp;
1995 	struct rl_txdesc	*txd;
1996 	u_int32_t		txstat;
1997 	int			cons;
1998 
1999 	cons = sc->rl_ldata.rl_tx_considx;
2000 	if (cons == sc->rl_ldata.rl_tx_prodidx)
2001 		return;
2002 
2003 	ifp = sc->rl_ifp;
2004 	/* Invalidate the TX descriptor list */
2005 	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
2006 	    sc->rl_ldata.rl_tx_list_map,
2007 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2008 
2009 	for (; cons != sc->rl_ldata.rl_tx_prodidx;
2010 	    cons = RL_TX_DESC_NXT(sc, cons)) {
2011 		txstat = le32toh(sc->rl_ldata.rl_tx_list[cons].rl_cmdstat);
2012 		if (txstat & RL_TDESC_STAT_OWN)
2013 			break;
2014 		/*
2015 		 * We only stash mbufs in the last descriptor
2016 		 * in a fragment chain, which also happens to
2017 		 * be the only place where the TX status bits
2018 		 * are valid.
2019 		 */
2020 		if (txstat & RL_TDESC_CMD_EOF) {
2021 			txd = &sc->rl_ldata.rl_tx_desc[cons];
2022 			bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
2023 			    txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
2024 			bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag,
2025 			    txd->tx_dmamap);
2026 			KASSERT(txd->tx_m != NULL,
2027 			    ("%s: freeing NULL mbufs!", __func__));
2028 			m_freem(txd->tx_m);
2029 			txd->tx_m = NULL;
2030 			if (txstat & (RL_TDESC_STAT_EXCESSCOL|
2031 			    RL_TDESC_STAT_COLCNT))
2032 				ifp->if_collisions++;
2033 			if (txstat & RL_TDESC_STAT_TXERRSUM)
2034 				ifp->if_oerrors++;
2035 			else
2036 				ifp->if_opackets++;
2037 		}
2038 		sc->rl_ldata.rl_tx_free++;
2039 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2040 	}
2041 	sc->rl_ldata.rl_tx_considx = cons;
2042 
2043 	/* No changes made to the TX ring, so no flush needed */
2044 
2045 	if (sc->rl_ldata.rl_tx_free != sc->rl_ldata.rl_tx_desc_cnt) {
2046 #ifdef RE_TX_MODERATION
2047 		/*
2048 		 * If not all descriptors have been reaped yet, reload
2049 		 * the timer so that we will eventually get another
2050 		 * interrupt that will cause us to re-enter this routine.
2051 		 * This is done in case the transmitter has gone idle.
2052 		 */
2053 		CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2054 #endif
2055 	} else
2056 		sc->rl_watchdog_timer = 0;
2057 }
2058 
2059 static void
2060 re_tick(void *xsc)
2061 {
2062 	struct rl_softc		*sc;
2063 	struct mii_data		*mii;
2064 
2065 	sc = xsc;
2066 
2067 	RL_LOCK_ASSERT(sc);
2068 
2069 	mii = device_get_softc(sc->rl_miibus);
2070 	mii_tick(mii);
2071 	if ((sc->rl_flags & RL_FLAG_LINK) == 0)
2072 		re_miibus_statchg(sc->rl_dev);
2073 	re_watchdog(sc);
2074 	callout_reset(&sc->rl_stat_callout, hz, re_tick, sc);
2075 }
2076 
2077 #ifdef DEVICE_POLLING
2078 static void
2079 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
2080 {
2081 	struct rl_softc *sc = ifp->if_softc;
2082 
2083 	RL_LOCK(sc);
2084 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2085 		re_poll_locked(ifp, cmd, count);
2086 	RL_UNLOCK(sc);
2087 }
2088 
2089 static void
2090 re_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
2091 {
2092 	struct rl_softc *sc = ifp->if_softc;
2093 
2094 	RL_LOCK_ASSERT(sc);
2095 
2096 	sc->rxcycles = count;
2097 	re_rxeof(sc);
2098 	re_txeof(sc);
2099 
2100 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2101 		taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_txtask);
2102 
2103 	if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
2104 		u_int16_t       status;
2105 
2106 		status = CSR_READ_2(sc, RL_ISR);
2107 		if (status == 0xffff)
2108 			return;
2109 		if (status)
2110 			CSR_WRITE_2(sc, RL_ISR, status);
2111 		if ((status & (RL_ISR_TX_OK | RL_ISR_TX_DESC_UNAVAIL)) &&
2112 		    (sc->rl_flags & RL_FLAG_PCIE))
2113 			CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2114 
2115 		/*
2116 		 * XXX check behaviour on receiver stalls.
2117 		 */
2118 
2119 		if (status & RL_ISR_SYSTEM_ERR)
2120 			re_init_locked(sc);
2121 	}
2122 }
2123 #endif /* DEVICE_POLLING */
2124 
2125 static int
2126 re_intr(void *arg)
2127 {
2128 	struct rl_softc		*sc;
2129 	uint16_t		status;
2130 
2131 	sc = arg;
2132 
2133 	status = CSR_READ_2(sc, RL_ISR);
2134 	if (status == 0xFFFF || (status & RL_INTRS_CPLUS) == 0)
2135                 return (FILTER_STRAY);
2136 	CSR_WRITE_2(sc, RL_IMR, 0);
2137 
2138 	taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_inttask);
2139 
2140 	return (FILTER_HANDLED);
2141 }
2142 
2143 static void
2144 re_int_task(void *arg, int npending)
2145 {
2146 	struct rl_softc		*sc;
2147 	struct ifnet		*ifp;
2148 	u_int16_t		status;
2149 	int			rval = 0;
2150 
2151 	sc = arg;
2152 	ifp = sc->rl_ifp;
2153 
2154 	RL_LOCK(sc);
2155 
2156 	status = CSR_READ_2(sc, RL_ISR);
2157         CSR_WRITE_2(sc, RL_ISR, status);
2158 
2159 	if (sc->suspended ||
2160 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2161 		RL_UNLOCK(sc);
2162 		return;
2163 	}
2164 
2165 #ifdef DEVICE_POLLING
2166 	if  (ifp->if_capenable & IFCAP_POLLING) {
2167 		RL_UNLOCK(sc);
2168 		return;
2169 	}
2170 #endif
2171 
2172 	if (status & (RL_ISR_RX_OK|RL_ISR_RX_ERR|RL_ISR_FIFO_OFLOW))
2173 		rval = re_rxeof(sc);
2174 
2175 	/*
2176 	 * Some chips will ignore a second TX request issued
2177 	 * while an existing transmission is in progress. If
2178 	 * the transmitter goes idle but there are still
2179 	 * packets waiting to be sent, we need to restart the
2180 	 * channel here to flush them out. This only seems to
2181 	 * be required with the PCIe devices.
2182 	 */
2183 	if ((status & (RL_ISR_TX_OK | RL_ISR_TX_DESC_UNAVAIL)) &&
2184 	    (sc->rl_flags & RL_FLAG_PCIE))
2185 		CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2186 	if (status & (
2187 #ifdef RE_TX_MODERATION
2188 	    RL_ISR_TIMEOUT_EXPIRED|
2189 #else
2190 	    RL_ISR_TX_OK|
2191 #endif
2192 	    RL_ISR_TX_ERR|RL_ISR_TX_DESC_UNAVAIL))
2193 		re_txeof(sc);
2194 
2195 	if (status & RL_ISR_SYSTEM_ERR)
2196 		re_init_locked(sc);
2197 
2198 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2199 		taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_txtask);
2200 
2201 	RL_UNLOCK(sc);
2202 
2203         if ((CSR_READ_2(sc, RL_ISR) & RL_INTRS_CPLUS) || rval) {
2204 		taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_inttask);
2205 		return;
2206 	}
2207 
2208 	CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
2209 }
2210 
2211 static int
2212 re_encap(struct rl_softc *sc, struct mbuf **m_head)
2213 {
2214 	struct rl_txdesc	*txd, *txd_last;
2215 	bus_dma_segment_t	segs[RL_NTXSEGS];
2216 	bus_dmamap_t		map;
2217 	struct mbuf		*m_new;
2218 	struct rl_desc		*desc;
2219 	int			nsegs, prod;
2220 	int			i, error, ei, si;
2221 	int			padlen;
2222 	uint32_t		cmdstat, csum_flags, vlanctl;
2223 
2224 	RL_LOCK_ASSERT(sc);
2225 	M_ASSERTPKTHDR((*m_head));
2226 
2227 	/*
2228 	 * With some of the RealTek chips, using the checksum offload
2229 	 * support in conjunction with the autopadding feature results
2230 	 * in the transmission of corrupt frames. For example, if we
2231 	 * need to send a really small IP fragment that's less than 60
2232 	 * bytes in size, and IP header checksumming is enabled, the
2233 	 * resulting ethernet frame that appears on the wire will
2234 	 * have garbled payload. To work around this, if TX IP checksum
2235 	 * offload is enabled, we always manually pad short frames out
2236 	 * to the minimum ethernet frame size.
2237 	 */
2238 	if ((sc->rl_flags & RL_FLAG_DESCV2) == 0 &&
2239 	    (*m_head)->m_pkthdr.len < RL_IP4CSUMTX_PADLEN &&
2240 	    ((*m_head)->m_pkthdr.csum_flags & CSUM_IP) != 0) {
2241 		padlen = RL_MIN_FRAMELEN - (*m_head)->m_pkthdr.len;
2242 		if (M_WRITABLE(*m_head) == 0) {
2243 			/* Get a writable copy. */
2244 			m_new = m_dup(*m_head, M_DONTWAIT);
2245 			m_freem(*m_head);
2246 			if (m_new == NULL) {
2247 				*m_head = NULL;
2248 				return (ENOBUFS);
2249 			}
2250 			*m_head = m_new;
2251 		}
2252 		if ((*m_head)->m_next != NULL ||
2253 		    M_TRAILINGSPACE(*m_head) < padlen) {
2254 			m_new = m_defrag(*m_head, M_DONTWAIT);
2255 			if (m_new == NULL) {
2256 				m_freem(*m_head);
2257 				*m_head = NULL;
2258 				return (ENOBUFS);
2259 			}
2260 		} else
2261 			m_new = *m_head;
2262 
2263 		/*
2264 		 * Manually pad short frames, and zero the pad space
2265 		 * to avoid leaking data.
2266 		 */
2267 		bzero(mtod(m_new, char *) + m_new->m_pkthdr.len, padlen);
2268 		m_new->m_pkthdr.len += padlen;
2269 		m_new->m_len = m_new->m_pkthdr.len;
2270 		*m_head = m_new;
2271 	}
2272 
2273 	prod = sc->rl_ldata.rl_tx_prodidx;
2274 	txd = &sc->rl_ldata.rl_tx_desc[prod];
2275 	error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap,
2276 	    *m_head, segs, &nsegs, BUS_DMA_NOWAIT);
2277 	if (error == EFBIG) {
2278 		m_new = m_collapse(*m_head, M_DONTWAIT, RL_NTXSEGS);
2279 		if (m_new == NULL) {
2280 			m_freem(*m_head);
2281 			*m_head = NULL;
2282 			return (ENOBUFS);
2283 		}
2284 		*m_head = m_new;
2285 		error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_tx_mtag,
2286 		    txd->tx_dmamap, *m_head, segs, &nsegs, BUS_DMA_NOWAIT);
2287 		if (error != 0) {
2288 			m_freem(*m_head);
2289 			*m_head = NULL;
2290 			return (error);
2291 		}
2292 	} else if (error != 0)
2293 		return (error);
2294 	if (nsegs == 0) {
2295 		m_freem(*m_head);
2296 		*m_head = NULL;
2297 		return (EIO);
2298 	}
2299 
2300 	/* Check for number of available descriptors. */
2301 	if (sc->rl_ldata.rl_tx_free - nsegs <= 1) {
2302 		bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap);
2303 		return (ENOBUFS);
2304 	}
2305 
2306 	bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap,
2307 	    BUS_DMASYNC_PREWRITE);
2308 
2309 	/*
2310 	 * Set up checksum offload. Note: checksum offload bits must
2311 	 * appear in all descriptors of a multi-descriptor transmit
2312 	 * attempt. This is according to testing done with an 8169
2313 	 * chip. This is a requirement.
2314 	 */
2315 	vlanctl = 0;
2316 	csum_flags = 0;
2317 	if (((*m_head)->m_pkthdr.csum_flags & CSUM_TSO) != 0)
2318 		csum_flags = RL_TDESC_CMD_LGSEND |
2319 		    ((uint32_t)(*m_head)->m_pkthdr.tso_segsz <<
2320 		    RL_TDESC_CMD_MSSVAL_SHIFT);
2321 	else {
2322 		/*
2323 		 * Unconditionally enable IP checksum if TCP or UDP
2324 		 * checksum is required. Otherwise, TCP/UDP checksum
2325 		 * does't make effects.
2326 		 */
2327 		if (((*m_head)->m_pkthdr.csum_flags & RE_CSUM_FEATURES) != 0) {
2328 			if ((sc->rl_flags & RL_FLAG_DESCV2) == 0) {
2329 				csum_flags |= RL_TDESC_CMD_IPCSUM;
2330 				if (((*m_head)->m_pkthdr.csum_flags &
2331 				    CSUM_TCP) != 0)
2332 					csum_flags |= RL_TDESC_CMD_TCPCSUM;
2333 				if (((*m_head)->m_pkthdr.csum_flags &
2334 				    CSUM_UDP) != 0)
2335 					csum_flags |= RL_TDESC_CMD_UDPCSUM;
2336 			} else {
2337 				vlanctl |= RL_TDESC_CMD_IPCSUMV2;
2338 				if (((*m_head)->m_pkthdr.csum_flags &
2339 				    CSUM_TCP) != 0)
2340 					vlanctl |= RL_TDESC_CMD_TCPCSUMV2;
2341 				if (((*m_head)->m_pkthdr.csum_flags &
2342 				    CSUM_UDP) != 0)
2343 					vlanctl |= RL_TDESC_CMD_UDPCSUMV2;
2344 			}
2345 		}
2346 	}
2347 
2348 	/*
2349 	 * Set up hardware VLAN tagging. Note: vlan tag info must
2350 	 * appear in all descriptors of a multi-descriptor
2351 	 * transmission attempt.
2352 	 */
2353 	if ((*m_head)->m_flags & M_VLANTAG)
2354 		vlanctl |= bswap16((*m_head)->m_pkthdr.ether_vtag) |
2355 		    RL_TDESC_VLANCTL_TAG;
2356 
2357 	si = prod;
2358 	for (i = 0; i < nsegs; i++, prod = RL_TX_DESC_NXT(sc, prod)) {
2359 		desc = &sc->rl_ldata.rl_tx_list[prod];
2360 		desc->rl_vlanctl = htole32(vlanctl);
2361 		desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[i].ds_addr));
2362 		desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[i].ds_addr));
2363 		cmdstat = segs[i].ds_len;
2364 		if (i != 0)
2365 			cmdstat |= RL_TDESC_CMD_OWN;
2366 		if (prod == sc->rl_ldata.rl_tx_desc_cnt - 1)
2367 			cmdstat |= RL_TDESC_CMD_EOR;
2368 		desc->rl_cmdstat = htole32(cmdstat | csum_flags);
2369 		sc->rl_ldata.rl_tx_free--;
2370 	}
2371 	/* Update producer index. */
2372 	sc->rl_ldata.rl_tx_prodidx = prod;
2373 
2374 	/* Set EOF on the last descriptor. */
2375 	ei = RL_TX_DESC_PRV(sc, prod);
2376 	desc = &sc->rl_ldata.rl_tx_list[ei];
2377 	desc->rl_cmdstat |= htole32(RL_TDESC_CMD_EOF);
2378 
2379 	desc = &sc->rl_ldata.rl_tx_list[si];
2380 	/* Set SOF and transfer ownership of packet to the chip. */
2381 	desc->rl_cmdstat |= htole32(RL_TDESC_CMD_OWN | RL_TDESC_CMD_SOF);
2382 
2383 	/*
2384 	 * Insure that the map for this transmission
2385 	 * is placed at the array index of the last descriptor
2386 	 * in this chain.  (Swap last and first dmamaps.)
2387 	 */
2388 	txd_last = &sc->rl_ldata.rl_tx_desc[ei];
2389 	map = txd->tx_dmamap;
2390 	txd->tx_dmamap = txd_last->tx_dmamap;
2391 	txd_last->tx_dmamap = map;
2392 	txd_last->tx_m = *m_head;
2393 
2394 	return (0);
2395 }
2396 
2397 static void
2398 re_tx_task(void *arg, int npending)
2399 {
2400 	struct ifnet		*ifp;
2401 
2402 	ifp = arg;
2403 	re_start(ifp);
2404 }
2405 
2406 /*
2407  * Main transmit routine for C+ and gigE NICs.
2408  */
2409 static void
2410 re_start(struct ifnet *ifp)
2411 {
2412 	struct rl_softc		*sc;
2413 	struct mbuf		*m_head;
2414 	int			queued;
2415 
2416 	sc = ifp->if_softc;
2417 
2418 	RL_LOCK(sc);
2419 
2420 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
2421 	    IFF_DRV_RUNNING || (sc->rl_flags & RL_FLAG_LINK) == 0) {
2422 		RL_UNLOCK(sc);
2423 		return;
2424 	}
2425 
2426 	for (queued = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) &&
2427 	    sc->rl_ldata.rl_tx_free > 1;) {
2428 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
2429 		if (m_head == NULL)
2430 			break;
2431 
2432 		if (re_encap(sc, &m_head) != 0) {
2433 			if (m_head == NULL)
2434 				break;
2435 			IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
2436 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2437 			break;
2438 		}
2439 
2440 		/*
2441 		 * If there's a BPF listener, bounce a copy of this frame
2442 		 * to him.
2443 		 */
2444 		ETHER_BPF_MTAP(ifp, m_head);
2445 
2446 		queued++;
2447 	}
2448 
2449 	if (queued == 0) {
2450 #ifdef RE_TX_MODERATION
2451 		if (sc->rl_ldata.rl_tx_free != sc->rl_ldata.rl_tx_desc_cnt)
2452 			CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2453 #endif
2454 		RL_UNLOCK(sc);
2455 		return;
2456 	}
2457 
2458 	/* Flush the TX descriptors */
2459 
2460 	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
2461 	    sc->rl_ldata.rl_tx_list_map,
2462 	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
2463 
2464 	CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2465 
2466 #ifdef RE_TX_MODERATION
2467 	/*
2468 	 * Use the countdown timer for interrupt moderation.
2469 	 * 'TX done' interrupts are disabled. Instead, we reset the
2470 	 * countdown timer, which will begin counting until it hits
2471 	 * the value in the TIMERINT register, and then trigger an
2472 	 * interrupt. Each time we write to the TIMERCNT register,
2473 	 * the timer count is reset to 0.
2474 	 */
2475 	CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2476 #endif
2477 
2478 	/*
2479 	 * Set a timeout in case the chip goes out to lunch.
2480 	 */
2481 	sc->rl_watchdog_timer = 5;
2482 
2483 	RL_UNLOCK(sc);
2484 }
2485 
2486 static void
2487 re_init(void *xsc)
2488 {
2489 	struct rl_softc		*sc = xsc;
2490 
2491 	RL_LOCK(sc);
2492 	re_init_locked(sc);
2493 	RL_UNLOCK(sc);
2494 }
2495 
2496 static void
2497 re_init_locked(struct rl_softc *sc)
2498 {
2499 	struct ifnet		*ifp = sc->rl_ifp;
2500 	struct mii_data		*mii;
2501 	u_int32_t		rxcfg = 0;
2502 	uint16_t		cfg;
2503 	union {
2504 		uint32_t align_dummy;
2505 		u_char eaddr[ETHER_ADDR_LEN];
2506         } eaddr;
2507 
2508 	RL_LOCK_ASSERT(sc);
2509 
2510 	mii = device_get_softc(sc->rl_miibus);
2511 
2512 	/*
2513 	 * Cancel pending I/O and free all RX/TX buffers.
2514 	 */
2515 	re_stop(sc);
2516 
2517 	/* Put controller into known state. */
2518 	re_reset(sc);
2519 
2520 	/*
2521 	 * Enable C+ RX and TX mode, as well as VLAN stripping and
2522 	 * RX checksum offload. We must configure the C+ register
2523 	 * before all others.
2524 	 */
2525 	cfg = RL_CPLUSCMD_PCI_MRW;
2526 	if ((ifp->if_capenable & IFCAP_RXCSUM) != 0)
2527 		cfg |= RL_CPLUSCMD_RXCSUM_ENB;
2528 	if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0)
2529 		cfg |= RL_CPLUSCMD_VLANSTRIP;
2530 	if ((sc->rl_flags & RL_FLAG_MACSTAT) != 0) {
2531 		cfg |= RL_CPLUSCMD_MACSTAT_DIS;
2532 		/* XXX magic. */
2533 		cfg |= 0x0001;
2534 	} else
2535 		cfg |= RL_CPLUSCMD_RXENB | RL_CPLUSCMD_TXENB;
2536 	CSR_WRITE_2(sc, RL_CPLUS_CMD, cfg);
2537 	/*
2538 	 * Disable TSO if interface MTU size is greater than MSS
2539 	 * allowed in controller.
2540 	 */
2541 	if (ifp->if_mtu > RL_TSO_MTU && (ifp->if_capenable & IFCAP_TSO4) != 0) {
2542 		ifp->if_capenable &= ~IFCAP_TSO4;
2543 		ifp->if_hwassist &= ~CSUM_TSO;
2544 	}
2545 
2546 	/*
2547 	 * Init our MAC address.  Even though the chipset
2548 	 * documentation doesn't mention it, we need to enter "Config
2549 	 * register write enable" mode to modify the ID registers.
2550 	 */
2551 	/* Copy MAC address on stack to align. */
2552 	bcopy(IF_LLADDR(ifp), eaddr.eaddr, ETHER_ADDR_LEN);
2553 	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_WRITECFG);
2554 	CSR_WRITE_4(sc, RL_IDR0,
2555 	    htole32(*(u_int32_t *)(&eaddr.eaddr[0])));
2556 	CSR_WRITE_4(sc, RL_IDR4,
2557 	    htole32(*(u_int32_t *)(&eaddr.eaddr[4])));
2558 	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
2559 
2560 	/*
2561 	 * For C+ mode, initialize the RX descriptors and mbufs.
2562 	 */
2563 	re_rx_list_init(sc);
2564 	re_tx_list_init(sc);
2565 
2566 	/*
2567 	 * Load the addresses of the RX and TX lists into the chip.
2568 	 */
2569 
2570 	CSR_WRITE_4(sc, RL_RXLIST_ADDR_HI,
2571 	    RL_ADDR_HI(sc->rl_ldata.rl_rx_list_addr));
2572 	CSR_WRITE_4(sc, RL_RXLIST_ADDR_LO,
2573 	    RL_ADDR_LO(sc->rl_ldata.rl_rx_list_addr));
2574 
2575 	CSR_WRITE_4(sc, RL_TXLIST_ADDR_HI,
2576 	    RL_ADDR_HI(sc->rl_ldata.rl_tx_list_addr));
2577 	CSR_WRITE_4(sc, RL_TXLIST_ADDR_LO,
2578 	    RL_ADDR_LO(sc->rl_ldata.rl_tx_list_addr));
2579 
2580 	/*
2581 	 * Enable transmit and receive.
2582 	 */
2583 	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
2584 
2585 	/*
2586 	 * Set the initial TX and RX configuration.
2587 	 */
2588 	if (sc->rl_testmode) {
2589 		if (sc->rl_type == RL_8169)
2590 			CSR_WRITE_4(sc, RL_TXCFG,
2591 			    RL_TXCFG_CONFIG|RL_LOOPTEST_ON);
2592 		else
2593 			CSR_WRITE_4(sc, RL_TXCFG,
2594 			    RL_TXCFG_CONFIG|RL_LOOPTEST_ON_CPLUS);
2595 	} else
2596 		CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
2597 
2598 	CSR_WRITE_1(sc, RL_EARLY_TX_THRESH, 16);
2599 
2600 	CSR_WRITE_4(sc, RL_RXCFG, RL_RXCFG_CONFIG);
2601 
2602 	/* Set the individual bit to receive frames for this host only. */
2603 	rxcfg = CSR_READ_4(sc, RL_RXCFG);
2604 	rxcfg |= RL_RXCFG_RX_INDIV;
2605 
2606 	/* If we want promiscuous mode, set the allframes bit. */
2607 	if (ifp->if_flags & IFF_PROMISC)
2608 		rxcfg |= RL_RXCFG_RX_ALLPHYS;
2609 	else
2610 		rxcfg &= ~RL_RXCFG_RX_ALLPHYS;
2611 	CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
2612 
2613 	/*
2614 	 * Set capture broadcast bit to capture broadcast frames.
2615 	 */
2616 	if (ifp->if_flags & IFF_BROADCAST)
2617 		rxcfg |= RL_RXCFG_RX_BROAD;
2618 	else
2619 		rxcfg &= ~RL_RXCFG_RX_BROAD;
2620 	CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
2621 
2622 	/*
2623 	 * Program the multicast filter, if necessary.
2624 	 */
2625 	re_setmulti(sc);
2626 
2627 #ifdef DEVICE_POLLING
2628 	/*
2629 	 * Disable interrupts if we are polling.
2630 	 */
2631 	if (ifp->if_capenable & IFCAP_POLLING)
2632 		CSR_WRITE_2(sc, RL_IMR, 0);
2633 	else	/* otherwise ... */
2634 #endif
2635 
2636 	/*
2637 	 * Enable interrupts.
2638 	 */
2639 	if (sc->rl_testmode)
2640 		CSR_WRITE_2(sc, RL_IMR, 0);
2641 	else
2642 		CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
2643 	CSR_WRITE_2(sc, RL_ISR, RL_INTRS_CPLUS);
2644 
2645 	/* Set initial TX threshold */
2646 	sc->rl_txthresh = RL_TX_THRESH_INIT;
2647 
2648 	/* Start RX/TX process. */
2649 	CSR_WRITE_4(sc, RL_MISSEDPKT, 0);
2650 #ifdef notdef
2651 	/* Enable receiver and transmitter. */
2652 	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
2653 #endif
2654 
2655 #ifdef RE_TX_MODERATION
2656 	/*
2657 	 * Initialize the timer interrupt register so that
2658 	 * a timer interrupt will be generated once the timer
2659 	 * reaches a certain number of ticks. The timer is
2660 	 * reloaded on each transmit. This gives us TX interrupt
2661 	 * moderation, which dramatically improves TX frame rate.
2662 	 */
2663 	if (sc->rl_type == RL_8169)
2664 		CSR_WRITE_4(sc, RL_TIMERINT_8169, 0x800);
2665 	else
2666 		CSR_WRITE_4(sc, RL_TIMERINT, 0x400);
2667 #endif
2668 
2669 	/*
2670 	 * For 8169 gigE NICs, set the max allowed RX packet
2671 	 * size so we can receive jumbo frames.
2672 	 */
2673 	if (sc->rl_type == RL_8169)
2674 		CSR_WRITE_2(sc, RL_MAXRXPKTLEN, 16383);
2675 
2676 	if (sc->rl_testmode)
2677 		return;
2678 
2679 	mii_mediachg(mii);
2680 
2681 	CSR_WRITE_1(sc, RL_CFG1, CSR_READ_1(sc, RL_CFG1) | RL_CFG1_DRVLOAD);
2682 
2683 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2684 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2685 
2686 	sc->rl_flags &= ~RL_FLAG_LINK;
2687 	sc->rl_watchdog_timer = 0;
2688 	callout_reset(&sc->rl_stat_callout, hz, re_tick, sc);
2689 }
2690 
2691 /*
2692  * Set media options.
2693  */
2694 static int
2695 re_ifmedia_upd(struct ifnet *ifp)
2696 {
2697 	struct rl_softc		*sc;
2698 	struct mii_data		*mii;
2699 	int			error;
2700 
2701 	sc = ifp->if_softc;
2702 	mii = device_get_softc(sc->rl_miibus);
2703 	RL_LOCK(sc);
2704 	error = mii_mediachg(mii);
2705 	RL_UNLOCK(sc);
2706 
2707 	return (error);
2708 }
2709 
2710 /*
2711  * Report current media status.
2712  */
2713 static void
2714 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2715 {
2716 	struct rl_softc		*sc;
2717 	struct mii_data		*mii;
2718 
2719 	sc = ifp->if_softc;
2720 	mii = device_get_softc(sc->rl_miibus);
2721 
2722 	RL_LOCK(sc);
2723 	mii_pollstat(mii);
2724 	RL_UNLOCK(sc);
2725 	ifmr->ifm_active = mii->mii_media_active;
2726 	ifmr->ifm_status = mii->mii_media_status;
2727 }
2728 
2729 static int
2730 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
2731 {
2732 	struct rl_softc		*sc = ifp->if_softc;
2733 	struct ifreq		*ifr = (struct ifreq *) data;
2734 	struct mii_data		*mii;
2735 	int			error = 0;
2736 
2737 	switch (command) {
2738 	case SIOCSIFMTU:
2739 		if (ifr->ifr_mtu < ETHERMIN || ifr->ifr_mtu > RL_JUMBO_MTU) {
2740 			error = EINVAL;
2741 			break;
2742 		}
2743 		if ((sc->rl_flags & RL_FLAG_NOJUMBO) != 0 &&
2744 		    ifr->ifr_mtu > RL_MAX_FRAMELEN) {
2745 			error = EINVAL;
2746 			break;
2747 		}
2748 		RL_LOCK(sc);
2749 		if (ifp->if_mtu != ifr->ifr_mtu)
2750 			ifp->if_mtu = ifr->ifr_mtu;
2751 		if (ifp->if_mtu > RL_TSO_MTU &&
2752 		    (ifp->if_capenable & IFCAP_TSO4) != 0) {
2753 			ifp->if_capenable &= ~IFCAP_TSO4;
2754 			ifp->if_hwassist &= ~CSUM_TSO;
2755 		}
2756 		RL_UNLOCK(sc);
2757 		break;
2758 	case SIOCSIFFLAGS:
2759 		RL_LOCK(sc);
2760 		if ((ifp->if_flags & IFF_UP) != 0) {
2761 			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
2762 				if (((ifp->if_flags ^ sc->rl_if_flags)
2763 				    & (IFF_PROMISC | IFF_ALLMULTI)) != 0)
2764 					re_setmulti(sc);
2765 			} else
2766 				re_init_locked(sc);
2767 		} else {
2768 			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
2769 				re_stop(sc);
2770 		}
2771 		sc->rl_if_flags = ifp->if_flags;
2772 		RL_UNLOCK(sc);
2773 		break;
2774 	case SIOCADDMULTI:
2775 	case SIOCDELMULTI:
2776 		RL_LOCK(sc);
2777 		re_setmulti(sc);
2778 		RL_UNLOCK(sc);
2779 		break;
2780 	case SIOCGIFMEDIA:
2781 	case SIOCSIFMEDIA:
2782 		mii = device_get_softc(sc->rl_miibus);
2783 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2784 		break;
2785 	case SIOCSIFCAP:
2786 	    {
2787 		int mask, reinit;
2788 
2789 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2790 		reinit = 0;
2791 #ifdef DEVICE_POLLING
2792 		if (mask & IFCAP_POLLING) {
2793 			if (ifr->ifr_reqcap & IFCAP_POLLING) {
2794 				error = ether_poll_register(re_poll, ifp);
2795 				if (error)
2796 					return(error);
2797 				RL_LOCK(sc);
2798 				/* Disable interrupts */
2799 				CSR_WRITE_2(sc, RL_IMR, 0x0000);
2800 				ifp->if_capenable |= IFCAP_POLLING;
2801 				RL_UNLOCK(sc);
2802 			} else {
2803 				error = ether_poll_deregister(ifp);
2804 				/* Enable interrupts. */
2805 				RL_LOCK(sc);
2806 				CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
2807 				ifp->if_capenable &= ~IFCAP_POLLING;
2808 				RL_UNLOCK(sc);
2809 			}
2810 		}
2811 #endif /* DEVICE_POLLING */
2812 		if (mask & IFCAP_HWCSUM) {
2813 			ifp->if_capenable ^= IFCAP_HWCSUM;
2814 			if (ifp->if_capenable & IFCAP_TXCSUM)
2815 				ifp->if_hwassist |= RE_CSUM_FEATURES;
2816 			else
2817 				ifp->if_hwassist &= ~RE_CSUM_FEATURES;
2818 			reinit = 1;
2819 		}
2820 		if (mask & IFCAP_VLAN_HWTAGGING) {
2821 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2822 			reinit = 1;
2823 		}
2824 		if (mask & IFCAP_TSO4) {
2825 			ifp->if_capenable ^= IFCAP_TSO4;
2826 			if ((IFCAP_TSO4 & ifp->if_capenable) &&
2827 			    (IFCAP_TSO4 & ifp->if_capabilities))
2828 				ifp->if_hwassist |= CSUM_TSO;
2829 			else
2830 				ifp->if_hwassist &= ~CSUM_TSO;
2831 			if (ifp->if_mtu > RL_TSO_MTU &&
2832 			    (ifp->if_capenable & IFCAP_TSO4) != 0) {
2833 				ifp->if_capenable &= ~IFCAP_TSO4;
2834 				ifp->if_hwassist &= ~CSUM_TSO;
2835 			}
2836 		}
2837 		if ((mask & IFCAP_WOL) != 0 &&
2838 		    (ifp->if_capabilities & IFCAP_WOL) != 0) {
2839 			if ((mask & IFCAP_WOL_UCAST) != 0)
2840 				ifp->if_capenable ^= IFCAP_WOL_UCAST;
2841 			if ((mask & IFCAP_WOL_MCAST) != 0)
2842 				ifp->if_capenable ^= IFCAP_WOL_MCAST;
2843 			if ((mask & IFCAP_WOL_MAGIC) != 0)
2844 				ifp->if_capenable ^= IFCAP_WOL_MAGIC;
2845 		}
2846 		if (reinit && ifp->if_drv_flags & IFF_DRV_RUNNING)
2847 			re_init(sc);
2848 		VLAN_CAPABILITIES(ifp);
2849 	    }
2850 		break;
2851 	default:
2852 		error = ether_ioctl(ifp, command, data);
2853 		break;
2854 	}
2855 
2856 	return (error);
2857 }
2858 
2859 static void
2860 re_watchdog(struct rl_softc *sc)
2861 {
2862 	struct ifnet		*ifp;
2863 
2864 	RL_LOCK_ASSERT(sc);
2865 
2866 	if (sc->rl_watchdog_timer == 0 || --sc->rl_watchdog_timer != 0)
2867 		return;
2868 
2869 	ifp = sc->rl_ifp;
2870 	re_txeof(sc);
2871 	if (sc->rl_ldata.rl_tx_free == sc->rl_ldata.rl_tx_desc_cnt) {
2872 		if_printf(ifp, "watchdog timeout (missed Tx interrupts) "
2873 		    "-- recovering\n");
2874 		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2875 			taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_txtask);
2876 		return;
2877 	}
2878 
2879 	if_printf(ifp, "watchdog timeout\n");
2880 	ifp->if_oerrors++;
2881 
2882 	re_rxeof(sc);
2883 	re_init_locked(sc);
2884 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2885 		taskqueue_enqueue_fast(taskqueue_fast, &sc->rl_txtask);
2886 }
2887 
2888 /*
2889  * Stop the adapter and free any mbufs allocated to the
2890  * RX and TX lists.
2891  */
2892 static void
2893 re_stop(struct rl_softc *sc)
2894 {
2895 	int			i;
2896 	struct ifnet		*ifp;
2897 	struct rl_txdesc	*txd;
2898 	struct rl_rxdesc	*rxd;
2899 
2900 	RL_LOCK_ASSERT(sc);
2901 
2902 	ifp = sc->rl_ifp;
2903 
2904 	sc->rl_watchdog_timer = 0;
2905 	callout_stop(&sc->rl_stat_callout);
2906 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2907 
2908 	if ((sc->rl_flags & RL_FLAG_CMDSTOP) != 0)
2909 		CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_STOPREQ | RL_CMD_TX_ENB |
2910 		    RL_CMD_RX_ENB);
2911 	else
2912 		CSR_WRITE_1(sc, RL_COMMAND, 0x00);
2913 	DELAY(1000);
2914 	CSR_WRITE_2(sc, RL_IMR, 0x0000);
2915 	CSR_WRITE_2(sc, RL_ISR, 0xFFFF);
2916 
2917 	if (sc->rl_head != NULL) {
2918 		m_freem(sc->rl_head);
2919 		sc->rl_head = sc->rl_tail = NULL;
2920 	}
2921 
2922 	/* Free the TX list buffers. */
2923 
2924 	for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
2925 		txd = &sc->rl_ldata.rl_tx_desc[i];
2926 		if (txd->tx_m != NULL) {
2927 			bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
2928 			    txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
2929 			bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag,
2930 			    txd->tx_dmamap);
2931 			m_freem(txd->tx_m);
2932 			txd->tx_m = NULL;
2933 		}
2934 	}
2935 
2936 	/* Free the RX list buffers. */
2937 
2938 	for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
2939 		rxd = &sc->rl_ldata.rl_rx_desc[i];
2940 		if (rxd->rx_m != NULL) {
2941 			bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
2942 			    rxd->rx_dmamap, BUS_DMASYNC_POSTREAD);
2943 			bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag,
2944 			    rxd->rx_dmamap);
2945 			m_freem(rxd->rx_m);
2946 			rxd->rx_m = NULL;
2947 		}
2948 	}
2949 }
2950 
2951 /*
2952  * Device suspend routine.  Stop the interface and save some PCI
2953  * settings in case the BIOS doesn't restore them properly on
2954  * resume.
2955  */
2956 static int
2957 re_suspend(device_t dev)
2958 {
2959 	struct rl_softc		*sc;
2960 
2961 	sc = device_get_softc(dev);
2962 
2963 	RL_LOCK(sc);
2964 	re_stop(sc);
2965 	re_setwol(sc);
2966 	sc->suspended = 1;
2967 	RL_UNLOCK(sc);
2968 
2969 	return (0);
2970 }
2971 
2972 /*
2973  * Device resume routine.  Restore some PCI settings in case the BIOS
2974  * doesn't, re-enable busmastering, and restart the interface if
2975  * appropriate.
2976  */
2977 static int
2978 re_resume(device_t dev)
2979 {
2980 	struct rl_softc		*sc;
2981 	struct ifnet		*ifp;
2982 
2983 	sc = device_get_softc(dev);
2984 
2985 	RL_LOCK(sc);
2986 
2987 	ifp = sc->rl_ifp;
2988 	/* Take controller out of sleep mode. */
2989 	if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
2990 		if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
2991 			CSR_WRITE_1(sc, RL_GPIO,
2992 			    CSR_READ_1(sc, RL_GPIO) | 0x01);
2993 	}
2994 
2995 	/* reinitialize interface if necessary */
2996 	if (ifp->if_flags & IFF_UP)
2997 		re_init_locked(sc);
2998 
2999 	/*
3000 	 * Clear WOL matching such that normal Rx filtering
3001 	 * wouldn't interfere with WOL patterns.
3002 	 */
3003 	re_clrwol(sc);
3004 	sc->suspended = 0;
3005 	RL_UNLOCK(sc);
3006 
3007 	return (0);
3008 }
3009 
3010 /*
3011  * Stop all chip I/O so that the kernel's probe routines don't
3012  * get confused by errant DMAs when rebooting.
3013  */
3014 static int
3015 re_shutdown(device_t dev)
3016 {
3017 	struct rl_softc		*sc;
3018 
3019 	sc = device_get_softc(dev);
3020 
3021 	RL_LOCK(sc);
3022 	re_stop(sc);
3023 	/*
3024 	 * Mark interface as down since otherwise we will panic if
3025 	 * interrupt comes in later on, which can happen in some
3026 	 * cases.
3027 	 */
3028 	sc->rl_ifp->if_flags &= ~IFF_UP;
3029 	re_setwol(sc);
3030 	RL_UNLOCK(sc);
3031 
3032 	return (0);
3033 }
3034 
3035 static void
3036 re_setwol(struct rl_softc *sc)
3037 {
3038 	struct ifnet		*ifp;
3039 	int			pmc;
3040 	uint16_t		pmstat;
3041 	uint8_t			v;
3042 
3043 	RL_LOCK_ASSERT(sc);
3044 
3045 	if (pci_find_extcap(sc->rl_dev, PCIY_PMG, &pmc) != 0)
3046 		return;
3047 
3048 	ifp = sc->rl_ifp;
3049 	/* Put controller into sleep mode. */
3050 	if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
3051 		if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
3052 			CSR_WRITE_1(sc, RL_GPIO,
3053 			    CSR_READ_1(sc, RL_GPIO) & ~0x01);
3054 	}
3055 	if ((ifp->if_capenable & IFCAP_WOL) != 0 &&
3056 	    (sc->rl_flags & RL_FLAG_WOLRXENB) != 0)
3057 		CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RX_ENB);
3058 	/* Enable config register write. */
3059 	CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
3060 
3061 	/* Enable PME. */
3062 	v = CSR_READ_1(sc, RL_CFG1);
3063 	v &= ~RL_CFG1_PME;
3064 	if ((ifp->if_capenable & IFCAP_WOL) != 0)
3065 		v |= RL_CFG1_PME;
3066 	CSR_WRITE_1(sc, RL_CFG1, v);
3067 
3068 	v = CSR_READ_1(sc, RL_CFG3);
3069 	v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
3070 	if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
3071 		v |= RL_CFG3_WOL_MAGIC;
3072 	CSR_WRITE_1(sc, RL_CFG3, v);
3073 
3074 	/* Config register write done. */
3075 	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3076 
3077 	v = CSR_READ_1(sc, RL_CFG5);
3078 	v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST);
3079 	v &= ~RL_CFG5_WOL_LANWAKE;
3080 	if ((ifp->if_capenable & IFCAP_WOL_UCAST) != 0)
3081 		v |= RL_CFG5_WOL_UCAST;
3082 	if ((ifp->if_capenable & IFCAP_WOL_MCAST) != 0)
3083 		v |= RL_CFG5_WOL_MCAST | RL_CFG5_WOL_BCAST;
3084 	if ((ifp->if_capenable & IFCAP_WOL) != 0)
3085 		v |= RL_CFG5_WOL_LANWAKE;
3086 	CSR_WRITE_1(sc, RL_CFG5, v);
3087 
3088 	/*
3089 	 * It seems that hardware resets its link speed to 100Mbps in
3090 	 * power down mode so switching to 100Mbps in driver is not
3091 	 * needed.
3092 	 */
3093 
3094 	/* Request PME if WOL is requested. */
3095 	pmstat = pci_read_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, 2);
3096 	pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
3097 	if ((ifp->if_capenable & IFCAP_WOL) != 0)
3098 		pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
3099 	pci_write_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, pmstat, 2);
3100 }
3101 
3102 static void
3103 re_clrwol(struct rl_softc *sc)
3104 {
3105 	int			pmc;
3106 	uint8_t			v;
3107 
3108 	RL_LOCK_ASSERT(sc);
3109 
3110 	if (pci_find_extcap(sc->rl_dev, PCIY_PMG, &pmc) != 0)
3111 		return;
3112 
3113 	/* Enable config register write. */
3114 	CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
3115 
3116 	v = CSR_READ_1(sc, RL_CFG3);
3117 	v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
3118 	CSR_WRITE_1(sc, RL_CFG3, v);
3119 
3120 	/* Config register write done. */
3121 	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3122 
3123 	v = CSR_READ_1(sc, RL_CFG5);
3124 	v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST);
3125 	v &= ~RL_CFG5_WOL_LANWAKE;
3126 	CSR_WRITE_1(sc, RL_CFG5, v);
3127 }
3128