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