if_re.c revision 148887
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 148887 2005-08-09 10:20:02Z rwatson $");
35
36/*
37 * RealTek 8139C+/8169/8169S/8110S 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 * four devices in this family: the RTL8139C+, the RTL8169, the RTL8169S
48 * and the RTL8110S.
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#include <sys/param.h>
112#include <sys/endian.h>
113#include <sys/systm.h>
114#include <sys/sockio.h>
115#include <sys/mbuf.h>
116#include <sys/malloc.h>
117#include <sys/module.h>
118#include <sys/kernel.h>
119#include <sys/socket.h>
120
121#include <net/if.h>
122#include <net/if_arp.h>
123#include <net/ethernet.h>
124#include <net/if_dl.h>
125#include <net/if_media.h>
126#include <net/if_types.h>
127#include <net/if_vlan_var.h>
128
129#include <net/bpf.h>
130
131#include <machine/bus.h>
132#include <machine/resource.h>
133#include <sys/bus.h>
134#include <sys/rman.h>
135
136#include <dev/mii/mii.h>
137#include <dev/mii/miivar.h>
138
139#include <dev/pci/pcireg.h>
140#include <dev/pci/pcivar.h>
141
142MODULE_DEPEND(re, pci, 1, 1, 1);
143MODULE_DEPEND(re, ether, 1, 1, 1);
144MODULE_DEPEND(re, miibus, 1, 1, 1);
145
146/* "controller miibus0" required.  See GENERIC if you get errors here. */
147#include "miibus_if.h"
148
149/*
150 * Default to using PIO access for this driver.
151 */
152#define RE_USEIOSPACE
153
154#include <pci/if_rlreg.h>
155
156#define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
157
158/*
159 * Various supported device vendors/types and their names.
160 */
161static struct rl_type re_devs[] = {
162	{ DLINK_VENDORID, DLINK_DEVICEID_528T, RL_HWREV_8169S,
163		"D-Link DGE-528(T) Gigabit Ethernet Adapter" },
164	{ RT_VENDORID, RT_DEVICEID_8139, RL_HWREV_8139CPLUS,
165		"RealTek 8139C+ 10/100BaseTX" },
166	{ RT_VENDORID, RT_DEVICEID_8169, RL_HWREV_8169,
167		"RealTek 8169 Gigabit Ethernet" },
168	{ RT_VENDORID, RT_DEVICEID_8169, RL_HWREV_8169S,
169		"RealTek 8169S Single-chip Gigabit Ethernet" },
170	{ RT_VENDORID, RT_DEVICEID_8169, RL_HWREV_8169SB,
171		"RealTek 8169SB Single-chip Gigabit Ethernet" },
172	{ RT_VENDORID, RT_DEVICEID_8169, RL_HWREV_8110S,
173		"RealTek 8110S Single-chip Gigabit Ethernet" },
174	{ COREGA_VENDORID, COREGA_DEVICEID_CGLAPCIGT, RL_HWREV_8169S,
175		"Corega CG-LAPCIGT (RTL8169S) Gigabit Ethernet" },
176	{ 0, 0, 0, NULL }
177};
178
179static struct rl_hwrev re_hwrevs[] = {
180	{ RL_HWREV_8139, RL_8139,  "" },
181	{ RL_HWREV_8139A, RL_8139, "A" },
182	{ RL_HWREV_8139AG, RL_8139, "A-G" },
183	{ RL_HWREV_8139B, RL_8139, "B" },
184	{ RL_HWREV_8130, RL_8139, "8130" },
185	{ RL_HWREV_8139C, RL_8139, "C" },
186	{ RL_HWREV_8139D, RL_8139, "8139D/8100B/8100C" },
187	{ RL_HWREV_8139CPLUS, RL_8139CPLUS, "C+"},
188	{ RL_HWREV_8169, RL_8169, "8169"},
189	{ RL_HWREV_8169S, RL_8169, "8169S"},
190	{ RL_HWREV_8169SB, RL_8169, "8169SB"},
191	{ RL_HWREV_8110S, RL_8169, "8110S"},
192	{ RL_HWREV_8100, RL_8139, "8100"},
193	{ RL_HWREV_8101, RL_8139, "8101"},
194	{ 0, 0, NULL }
195};
196
197static int re_probe		(device_t);
198static int re_attach		(device_t);
199static int re_detach		(device_t);
200
201static int re_encap		(struct rl_softc *, struct mbuf **, int *);
202
203static void re_dma_map_addr	(void *, bus_dma_segment_t *, int, int);
204static void re_dma_map_desc	(void *, bus_dma_segment_t *, int,
205				    bus_size_t, int);
206static int re_allocmem		(device_t, struct rl_softc *);
207static int re_newbuf		(struct rl_softc *, int, struct mbuf *);
208static int re_rx_list_init	(struct rl_softc *);
209static int re_tx_list_init	(struct rl_softc *);
210#ifdef RE_FIXUP_RX
211static __inline void re_fixup_rx
212				(struct mbuf *);
213#endif
214static void re_rxeof		(struct rl_softc *);
215static void re_txeof		(struct rl_softc *);
216#ifdef DEVICE_POLLING
217static void re_poll		(struct ifnet *, enum poll_cmd, int);
218static void re_poll_locked	(struct ifnet *, enum poll_cmd, int);
219#endif
220static void re_intr		(void *);
221static void re_tick		(void *);
222static void re_tick_locked	(struct rl_softc *);
223static void re_start		(struct ifnet *);
224static void re_start_locked	(struct ifnet *);
225static int re_ioctl		(struct ifnet *, u_long, caddr_t);
226static void re_init		(void *);
227static void re_init_locked	(struct rl_softc *);
228static void re_stop		(struct rl_softc *);
229static void re_watchdog		(struct ifnet *);
230static int re_suspend		(device_t);
231static int re_resume		(device_t);
232static void re_shutdown		(device_t);
233static int re_ifmedia_upd	(struct ifnet *);
234static void re_ifmedia_sts	(struct ifnet *, struct ifmediareq *);
235
236static void re_eeprom_putbyte	(struct rl_softc *, int);
237static void re_eeprom_getword	(struct rl_softc *, int, u_int16_t *);
238static void re_read_eeprom	(struct rl_softc *, caddr_t, int, int, int);
239static int re_gmii_readreg	(device_t, int, int);
240static int re_gmii_writereg	(device_t, int, int, int);
241
242static int re_miibus_readreg	(device_t, int, int);
243static int re_miibus_writereg	(device_t, int, int, int);
244static void re_miibus_statchg	(device_t);
245
246static void re_setmulti		(struct rl_softc *);
247static void re_reset		(struct rl_softc *);
248
249static int re_diag		(struct rl_softc *);
250
251#ifdef RE_USEIOSPACE
252#define RL_RES			SYS_RES_IOPORT
253#define RL_RID			RL_PCI_LOIO
254#else
255#define RL_RES			SYS_RES_MEMORY
256#define RL_RID			RL_PCI_LOMEM
257#endif
258
259static device_method_t re_methods[] = {
260	/* Device interface */
261	DEVMETHOD(device_probe,		re_probe),
262	DEVMETHOD(device_attach,	re_attach),
263	DEVMETHOD(device_detach,	re_detach),
264	DEVMETHOD(device_suspend,	re_suspend),
265	DEVMETHOD(device_resume,	re_resume),
266	DEVMETHOD(device_shutdown,	re_shutdown),
267
268	/* bus interface */
269	DEVMETHOD(bus_print_child,	bus_generic_print_child),
270	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
271
272	/* MII interface */
273	DEVMETHOD(miibus_readreg,	re_miibus_readreg),
274	DEVMETHOD(miibus_writereg,	re_miibus_writereg),
275	DEVMETHOD(miibus_statchg,	re_miibus_statchg),
276
277	{ 0, 0 }
278};
279
280static driver_t re_driver = {
281	"re",
282	re_methods,
283	sizeof(struct rl_softc)
284};
285
286static devclass_t re_devclass;
287
288DRIVER_MODULE(re, pci, re_driver, re_devclass, 0, 0);
289DRIVER_MODULE(re, cardbus, re_driver, re_devclass, 0, 0);
290DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
291
292#define EE_SET(x)					\
293	CSR_WRITE_1(sc, RL_EECMD,			\
294		CSR_READ_1(sc, RL_EECMD) | x)
295
296#define EE_CLR(x)					\
297	CSR_WRITE_1(sc, RL_EECMD,			\
298		CSR_READ_1(sc, RL_EECMD) & ~x)
299
300/*
301 * Send a read command and address to the EEPROM, check for ACK.
302 */
303static void
304re_eeprom_putbyte(sc, addr)
305	struct rl_softc		*sc;
306	int			addr;
307{
308	register int		d, i;
309
310	d = addr | sc->rl_eecmd_read;
311
312	/*
313	 * Feed in each bit and strobe the clock.
314	 */
315	for (i = 0x400; i; i >>= 1) {
316		if (d & i) {
317			EE_SET(RL_EE_DATAIN);
318		} else {
319			EE_CLR(RL_EE_DATAIN);
320		}
321		DELAY(100);
322		EE_SET(RL_EE_CLK);
323		DELAY(150);
324		EE_CLR(RL_EE_CLK);
325		DELAY(100);
326	}
327}
328
329/*
330 * Read a word of data stored in the EEPROM at address 'addr.'
331 */
332static void
333re_eeprom_getword(sc, addr, dest)
334	struct rl_softc		*sc;
335	int			addr;
336	u_int16_t		*dest;
337{
338	register int		i;
339	u_int16_t		word = 0;
340
341	/* Enter EEPROM access mode. */
342	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
343
344	/*
345	 * Send address of word we want to read.
346	 */
347	re_eeprom_putbyte(sc, addr);
348
349	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
350
351	/*
352	 * Start reading bits from EEPROM.
353	 */
354	for (i = 0x8000; i; i >>= 1) {
355		EE_SET(RL_EE_CLK);
356		DELAY(100);
357		if (CSR_READ_1(sc, RL_EECMD) & RL_EE_DATAOUT)
358			word |= i;
359		EE_CLR(RL_EE_CLK);
360		DELAY(100);
361	}
362
363	/* Turn off EEPROM access mode. */
364	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
365
366	*dest = word;
367}
368
369/*
370 * Read a sequence of words from the EEPROM.
371 */
372static void
373re_read_eeprom(sc, dest, off, cnt, swap)
374	struct rl_softc		*sc;
375	caddr_t			dest;
376	int			off;
377	int			cnt;
378	int			swap;
379{
380	int			i;
381	u_int16_t		word = 0, *ptr;
382
383	for (i = 0; i < cnt; i++) {
384		re_eeprom_getword(sc, off + i, &word);
385		ptr = (u_int16_t *)(dest + (i * 2));
386		if (swap)
387			*ptr = ntohs(word);
388		else
389			*ptr = word;
390	}
391}
392
393static int
394re_gmii_readreg(dev, phy, reg)
395	device_t		dev;
396	int			phy, reg;
397{
398	struct rl_softc		*sc;
399	u_int32_t		rval;
400	int			i;
401
402	if (phy != 1)
403		return (0);
404
405	sc = device_get_softc(dev);
406
407	/* Let the rgephy driver read the GMEDIASTAT register */
408
409	if (reg == RL_GMEDIASTAT) {
410		rval = CSR_READ_1(sc, RL_GMEDIASTAT);
411		return (rval);
412	}
413
414	CSR_WRITE_4(sc, RL_PHYAR, reg << 16);
415	DELAY(1000);
416
417	for (i = 0; i < RL_TIMEOUT; i++) {
418		rval = CSR_READ_4(sc, RL_PHYAR);
419		if (rval & RL_PHYAR_BUSY)
420			break;
421		DELAY(100);
422	}
423
424	if (i == RL_TIMEOUT) {
425		printf ("re%d: PHY read failed\n", sc->rl_unit);
426		return (0);
427	}
428
429	return (rval & RL_PHYAR_PHYDATA);
430}
431
432static int
433re_gmii_writereg(dev, phy, reg, data)
434	device_t		dev;
435	int			phy, reg, data;
436{
437	struct rl_softc		*sc;
438	u_int32_t		rval;
439	int			i;
440
441	sc = device_get_softc(dev);
442
443	CSR_WRITE_4(sc, RL_PHYAR, (reg << 16) |
444	    (data & RL_PHYAR_PHYDATA) | RL_PHYAR_BUSY);
445	DELAY(1000);
446
447	for (i = 0; i < RL_TIMEOUT; i++) {
448		rval = CSR_READ_4(sc, RL_PHYAR);
449		if (!(rval & RL_PHYAR_BUSY))
450			break;
451		DELAY(100);
452	}
453
454	if (i == RL_TIMEOUT) {
455		printf ("re%d: PHY write failed\n", sc->rl_unit);
456		return (0);
457	}
458
459	return (0);
460}
461
462static int
463re_miibus_readreg(dev, phy, reg)
464	device_t		dev;
465	int			phy, reg;
466{
467	struct rl_softc		*sc;
468	u_int16_t		rval = 0;
469	u_int16_t		re8139_reg = 0;
470
471	sc = device_get_softc(dev);
472
473	if (sc->rl_type == RL_8169) {
474		rval = re_gmii_readreg(dev, phy, reg);
475		return (rval);
476	}
477
478	/* Pretend the internal PHY is only at address 0 */
479	if (phy) {
480		return (0);
481	}
482	switch (reg) {
483	case MII_BMCR:
484		re8139_reg = RL_BMCR;
485		break;
486	case MII_BMSR:
487		re8139_reg = RL_BMSR;
488		break;
489	case MII_ANAR:
490		re8139_reg = RL_ANAR;
491		break;
492	case MII_ANER:
493		re8139_reg = RL_ANER;
494		break;
495	case MII_ANLPAR:
496		re8139_reg = RL_LPAR;
497		break;
498	case MII_PHYIDR1:
499	case MII_PHYIDR2:
500		return (0);
501	/*
502	 * Allow the rlphy driver to read the media status
503	 * register. If we have a link partner which does not
504	 * support NWAY, this is the register which will tell
505	 * us the results of parallel detection.
506	 */
507	case RL_MEDIASTAT:
508		rval = CSR_READ_1(sc, RL_MEDIASTAT);
509		return (rval);
510	default:
511		printf("re%d: bad phy register\n", sc->rl_unit);
512		return (0);
513	}
514	rval = CSR_READ_2(sc, re8139_reg);
515	return (rval);
516}
517
518static int
519re_miibus_writereg(dev, phy, reg, data)
520	device_t		dev;
521	int			phy, reg, data;
522{
523	struct rl_softc		*sc;
524	u_int16_t		re8139_reg = 0;
525	int			rval = 0;
526
527	sc = device_get_softc(dev);
528
529	if (sc->rl_type == RL_8169) {
530		rval = re_gmii_writereg(dev, phy, reg, data);
531		return (rval);
532	}
533
534	/* Pretend the internal PHY is only at address 0 */
535	if (phy)
536		return (0);
537
538	switch (reg) {
539	case MII_BMCR:
540		re8139_reg = RL_BMCR;
541		break;
542	case MII_BMSR:
543		re8139_reg = RL_BMSR;
544		break;
545	case MII_ANAR:
546		re8139_reg = RL_ANAR;
547		break;
548	case MII_ANER:
549		re8139_reg = RL_ANER;
550		break;
551	case MII_ANLPAR:
552		re8139_reg = RL_LPAR;
553		break;
554	case MII_PHYIDR1:
555	case MII_PHYIDR2:
556		return (0);
557		break;
558	default:
559		printf("re%d: bad phy register\n", sc->rl_unit);
560		return (0);
561	}
562	CSR_WRITE_2(sc, re8139_reg, data);
563	return (0);
564}
565
566static void
567re_miibus_statchg(dev)
568	device_t		dev;
569{
570
571}
572
573/*
574 * Program the 64-bit multicast hash filter.
575 */
576static void
577re_setmulti(sc)
578	struct rl_softc		*sc;
579{
580	struct ifnet		*ifp;
581	int			h = 0;
582	u_int32_t		hashes[2] = { 0, 0 };
583	struct ifmultiaddr	*ifma;
584	u_int32_t		rxfilt;
585	int			mcnt = 0;
586
587	RL_LOCK_ASSERT(sc);
588
589	ifp = sc->rl_ifp;
590
591	rxfilt = CSR_READ_4(sc, RL_RXCFG);
592
593	if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
594		rxfilt |= RL_RXCFG_RX_MULTI;
595		CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
596		CSR_WRITE_4(sc, RL_MAR0, 0xFFFFFFFF);
597		CSR_WRITE_4(sc, RL_MAR4, 0xFFFFFFFF);
598		return;
599	}
600
601	/* first, zot all the existing hash bits */
602	CSR_WRITE_4(sc, RL_MAR0, 0);
603	CSR_WRITE_4(sc, RL_MAR4, 0);
604
605	/* now program new ones */
606	IF_ADDR_LOCK(ifp);
607	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
608		if (ifma->ifma_addr->sa_family != AF_LINK)
609			continue;
610		h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
611		    ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
612		if (h < 32)
613			hashes[0] |= (1 << h);
614		else
615			hashes[1] |= (1 << (h - 32));
616		mcnt++;
617	}
618	IF_ADDR_UNLOCK(ifp);
619
620	if (mcnt)
621		rxfilt |= RL_RXCFG_RX_MULTI;
622	else
623		rxfilt &= ~RL_RXCFG_RX_MULTI;
624
625	CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
626	CSR_WRITE_4(sc, RL_MAR0, hashes[0]);
627	CSR_WRITE_4(sc, RL_MAR4, hashes[1]);
628}
629
630static void
631re_reset(sc)
632	struct rl_softc		*sc;
633{
634	register int		i;
635
636	RL_LOCK_ASSERT(sc);
637
638	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RESET);
639
640	for (i = 0; i < RL_TIMEOUT; i++) {
641		DELAY(10);
642		if (!(CSR_READ_1(sc, RL_COMMAND) & RL_CMD_RESET))
643			break;
644	}
645	if (i == RL_TIMEOUT)
646		printf("re%d: reset never completed!\n", sc->rl_unit);
647
648	CSR_WRITE_1(sc, 0x82, 1);
649}
650
651/*
652 * The following routine is designed to test for a defect on some
653 * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
654 * lines connected to the bus, however for a 32-bit only card, they
655 * should be pulled high. The result of this defect is that the
656 * NIC will not work right if you plug it into a 64-bit slot: DMA
657 * operations will be done with 64-bit transfers, which will fail
658 * because the 64-bit data lines aren't connected.
659 *
660 * There's no way to work around this (short of talking a soldering
661 * iron to the board), however we can detect it. The method we use
662 * here is to put the NIC into digital loopback mode, set the receiver
663 * to promiscuous mode, and then try to send a frame. We then compare
664 * the frame data we sent to what was received. If the data matches,
665 * then the NIC is working correctly, otherwise we know the user has
666 * a defective NIC which has been mistakenly plugged into a 64-bit PCI
667 * slot. In the latter case, there's no way the NIC can work correctly,
668 * so we print out a message on the console and abort the device attach.
669 */
670
671static int
672re_diag(sc)
673	struct rl_softc		*sc;
674{
675	struct ifnet		*ifp = sc->rl_ifp;
676	struct mbuf		*m0;
677	struct ether_header	*eh;
678	struct rl_desc		*cur_rx;
679	u_int16_t		status;
680	u_int32_t		rxstat;
681	int			total_len, i, error = 0;
682	u_int8_t		dst[] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
683	u_int8_t		src[] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
684
685	/* Allocate a single mbuf */
686	MGETHDR(m0, M_DONTWAIT, MT_DATA);
687	if (m0 == NULL)
688		return (ENOBUFS);
689
690	RL_LOCK(sc);
691
692	/*
693	 * Initialize the NIC in test mode. This sets the chip up
694	 * so that it can send and receive frames, but performs the
695	 * following special functions:
696	 * - Puts receiver in promiscuous mode
697	 * - Enables digital loopback mode
698	 * - Leaves interrupts turned off
699	 */
700
701	ifp->if_flags |= IFF_PROMISC;
702	sc->rl_testmode = 1;
703	re_init_locked(sc);
704	re_stop(sc);
705	DELAY(100000);
706	re_init_locked(sc);
707
708	/* Put some data in the mbuf */
709
710	eh = mtod(m0, struct ether_header *);
711	bcopy ((char *)&dst, eh->ether_dhost, ETHER_ADDR_LEN);
712	bcopy ((char *)&src, eh->ether_shost, ETHER_ADDR_LEN);
713	eh->ether_type = htons(ETHERTYPE_IP);
714	m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
715
716	/*
717	 * Queue the packet, start transmission.
718	 * Note: IF_HANDOFF() ultimately calls re_start() for us.
719	 */
720
721	CSR_WRITE_2(sc, RL_ISR, 0xFFFF);
722	RL_UNLOCK(sc);
723	/* XXX: re_diag must not be called when in ALTQ mode */
724	IF_HANDOFF(&ifp->if_snd, m0, ifp);
725	RL_LOCK(sc);
726	m0 = NULL;
727
728	/* Wait for it to propagate through the chip */
729
730	DELAY(100000);
731	for (i = 0; i < RL_TIMEOUT; i++) {
732		status = CSR_READ_2(sc, RL_ISR);
733		if ((status & (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK)) ==
734		    (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK))
735			break;
736		DELAY(10);
737	}
738
739	if (i == RL_TIMEOUT) {
740		printf("re%d: diagnostic failed, failed to receive packet "
741		    "in loopback mode\n", sc->rl_unit);
742		error = EIO;
743		goto done;
744	}
745
746	/*
747	 * The packet should have been dumped into the first
748	 * entry in the RX DMA ring. Grab it from there.
749	 */
750
751	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
752	    sc->rl_ldata.rl_rx_list_map,
753	    BUS_DMASYNC_POSTREAD);
754	bus_dmamap_sync(sc->rl_ldata.rl_mtag,
755	    sc->rl_ldata.rl_rx_dmamap[0],
756	    BUS_DMASYNC_POSTWRITE);
757	bus_dmamap_unload(sc->rl_ldata.rl_mtag,
758	    sc->rl_ldata.rl_rx_dmamap[0]);
759
760	m0 = sc->rl_ldata.rl_rx_mbuf[0];
761	sc->rl_ldata.rl_rx_mbuf[0] = NULL;
762	eh = mtod(m0, struct ether_header *);
763
764	cur_rx = &sc->rl_ldata.rl_rx_list[0];
765	total_len = RL_RXBYTES(cur_rx);
766	rxstat = le32toh(cur_rx->rl_cmdstat);
767
768	if (total_len != ETHER_MIN_LEN) {
769		printf("re%d: diagnostic failed, received short packet\n",
770		    sc->rl_unit);
771		error = EIO;
772		goto done;
773	}
774
775	/* Test that the received packet data matches what we sent. */
776
777	if (bcmp((char *)&eh->ether_dhost, (char *)&dst, ETHER_ADDR_LEN) ||
778	    bcmp((char *)&eh->ether_shost, (char *)&src, ETHER_ADDR_LEN) ||
779	    ntohs(eh->ether_type) != ETHERTYPE_IP) {
780		printf("re%d: WARNING, DMA FAILURE!\n", sc->rl_unit);
781		printf("re%d: expected TX data: %6D/%6D/0x%x\n", sc->rl_unit,
782		    dst, ":", src, ":", ETHERTYPE_IP);
783		printf("re%d: received RX data: %6D/%6D/0x%x\n", sc->rl_unit,
784		    eh->ether_dhost, ":",  eh->ether_shost, ":",
785		    ntohs(eh->ether_type));
786		printf("re%d: You may have a defective 32-bit NIC plugged "
787		    "into a 64-bit PCI slot.\n", sc->rl_unit);
788		printf("re%d: Please re-install the NIC in a 32-bit slot "
789		    "for proper operation.\n", sc->rl_unit);
790		printf("re%d: Read the re(4) man page for more details.\n",
791		    sc->rl_unit);
792		error = EIO;
793	}
794
795done:
796	/* Turn interface off, release resources */
797
798	sc->rl_testmode = 0;
799	ifp->if_flags &= ~IFF_PROMISC;
800	re_stop(sc);
801	if (m0 != NULL)
802		m_freem(m0);
803
804	RL_UNLOCK(sc);
805
806	return (error);
807}
808
809/*
810 * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
811 * IDs against our list and return a device name if we find a match.
812 */
813static int
814re_probe(dev)
815	device_t		dev;
816{
817	struct rl_type		*t;
818	struct rl_softc		*sc;
819	int			rid;
820	u_int32_t		hwrev;
821
822	t = re_devs;
823	sc = device_get_softc(dev);
824
825	while (t->rl_name != NULL) {
826		if ((pci_get_vendor(dev) == t->rl_vid) &&
827		    (pci_get_device(dev) == t->rl_did)) {
828
829			/*
830			 * Temporarily map the I/O space
831			 * so we can read the chip ID register.
832			 */
833			rid = RL_RID;
834			sc->rl_res = bus_alloc_resource_any(dev, RL_RES, &rid,
835			    RF_ACTIVE);
836			if (sc->rl_res == NULL) {
837				device_printf(dev,
838				    "couldn't map ports/memory\n");
839				return (ENXIO);
840			}
841			sc->rl_btag = rman_get_bustag(sc->rl_res);
842			sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
843			hwrev = CSR_READ_4(sc, RL_TXCFG) & RL_TXCFG_HWREV;
844			bus_release_resource(dev, RL_RES,
845			    RL_RID, sc->rl_res);
846			if (t->rl_basetype == hwrev) {
847				device_set_desc(dev, t->rl_name);
848				return (BUS_PROBE_DEFAULT);
849			}
850		}
851		t++;
852	}
853
854	return (ENXIO);
855}
856
857/*
858 * This routine takes the segment list provided as the result of
859 * a bus_dma_map_load() operation and assigns the addresses/lengths
860 * to RealTek DMA descriptors. This can be called either by the RX
861 * code or the TX code. In the RX case, we'll probably wind up mapping
862 * at most one segment. For the TX case, there could be any number of
863 * segments since TX packets may span multiple mbufs. In either case,
864 * if the number of segments is larger than the rl_maxsegs limit
865 * specified by the caller, we abort the mapping operation. Sadly,
866 * whoever designed the buffer mapping API did not provide a way to
867 * return an error from here, so we have to fake it a bit.
868 */
869
870static void
871re_dma_map_desc(arg, segs, nseg, mapsize, error)
872	void			*arg;
873	bus_dma_segment_t	*segs;
874	int			nseg;
875	bus_size_t		mapsize;
876	int			error;
877{
878	struct rl_dmaload_arg	*ctx;
879	struct rl_desc		*d = NULL;
880	int			i = 0, idx;
881
882	if (error)
883		return;
884
885	ctx = arg;
886
887	/* Signal error to caller if there's too many segments */
888	if (nseg > ctx->rl_maxsegs) {
889		ctx->rl_maxsegs = 0;
890		return;
891	}
892
893	/*
894	 * Map the segment array into descriptors. Note that we set the
895	 * start-of-frame and end-of-frame markers for either TX or RX, but
896	 * they really only have meaning in the TX case. (In the RX case,
897	 * it's the chip that tells us where packets begin and end.)
898	 * We also keep track of the end of the ring and set the
899	 * end-of-ring bits as needed, and we set the ownership bits
900	 * in all except the very first descriptor. (The caller will
901	 * set this descriptor later when it start transmission or
902	 * reception.)
903	 */
904	idx = ctx->rl_idx;
905	for (;;) {
906		u_int32_t		cmdstat;
907		d = &ctx->rl_ring[idx];
908		if (le32toh(d->rl_cmdstat) & RL_RDESC_STAT_OWN) {
909			ctx->rl_maxsegs = 0;
910			return;
911		}
912		cmdstat = segs[i].ds_len;
913		d->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[i].ds_addr));
914		d->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[i].ds_addr));
915		if (i == 0)
916			cmdstat |= RL_TDESC_CMD_SOF;
917		else
918			cmdstat |= RL_TDESC_CMD_OWN;
919		if (idx == (RL_RX_DESC_CNT - 1))
920			cmdstat |= RL_TDESC_CMD_EOR;
921		d->rl_cmdstat = htole32(cmdstat | ctx->rl_flags);
922		i++;
923		if (i == nseg)
924			break;
925		RL_DESC_INC(idx);
926	}
927
928	d->rl_cmdstat |= htole32(RL_TDESC_CMD_EOF);
929	ctx->rl_maxsegs = nseg;
930	ctx->rl_idx = idx;
931}
932
933/*
934 * Map a single buffer address.
935 */
936
937static void
938re_dma_map_addr(arg, segs, nseg, error)
939	void			*arg;
940	bus_dma_segment_t	*segs;
941	int			nseg;
942	int			error;
943{
944	bus_addr_t		*addr;
945
946	if (error)
947		return;
948
949	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
950	addr = arg;
951	*addr = segs->ds_addr;
952}
953
954static int
955re_allocmem(dev, sc)
956	device_t		dev;
957	struct rl_softc		*sc;
958{
959	int			error;
960	int			nseg;
961	int			i;
962
963	/*
964	 * Allocate map for RX mbufs.
965	 */
966	nseg = 32;
967	error = bus_dma_tag_create(sc->rl_parent_tag, ETHER_ALIGN, 0,
968	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
969	    NULL, MCLBYTES * nseg, nseg, MCLBYTES, BUS_DMA_ALLOCNOW,
970	    NULL, NULL, &sc->rl_ldata.rl_mtag);
971	if (error) {
972		device_printf(dev, "could not allocate dma tag\n");
973		return (ENOMEM);
974	}
975
976	/*
977	 * Allocate map for TX descriptor list.
978	 */
979	error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
980	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
981	    NULL, RL_TX_LIST_SZ, 1, RL_TX_LIST_SZ, BUS_DMA_ALLOCNOW,
982	    NULL, NULL, &sc->rl_ldata.rl_tx_list_tag);
983	if (error) {
984		device_printf(dev, "could not allocate dma tag\n");
985		return (ENOMEM);
986	}
987
988	/* Allocate DMA'able memory for the TX ring */
989
990	error = bus_dmamem_alloc(sc->rl_ldata.rl_tx_list_tag,
991	    (void **)&sc->rl_ldata.rl_tx_list, BUS_DMA_NOWAIT | BUS_DMA_ZERO,
992	    &sc->rl_ldata.rl_tx_list_map);
993	if (error)
994		return (ENOMEM);
995
996	/* Load the map for the TX ring. */
997
998	error = bus_dmamap_load(sc->rl_ldata.rl_tx_list_tag,
999	     sc->rl_ldata.rl_tx_list_map, sc->rl_ldata.rl_tx_list,
1000	     RL_TX_LIST_SZ, re_dma_map_addr,
1001	     &sc->rl_ldata.rl_tx_list_addr, BUS_DMA_NOWAIT);
1002
1003	/* Create DMA maps for TX buffers */
1004
1005	for (i = 0; i < RL_TX_DESC_CNT; i++) {
1006		error = bus_dmamap_create(sc->rl_ldata.rl_mtag, 0,
1007			    &sc->rl_ldata.rl_tx_dmamap[i]);
1008		if (error) {
1009			device_printf(dev, "can't create DMA map for TX\n");
1010			return (ENOMEM);
1011		}
1012	}
1013
1014	/*
1015	 * Allocate map for RX descriptor list.
1016	 */
1017	error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
1018	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1019	    NULL, RL_RX_LIST_SZ, 1, RL_RX_LIST_SZ, BUS_DMA_ALLOCNOW,
1020	    NULL, NULL, &sc->rl_ldata.rl_rx_list_tag);
1021	if (error) {
1022		device_printf(dev, "could not allocate dma tag\n");
1023		return (ENOMEM);
1024	}
1025
1026	/* Allocate DMA'able memory for the RX ring */
1027
1028	error = bus_dmamem_alloc(sc->rl_ldata.rl_rx_list_tag,
1029	    (void **)&sc->rl_ldata.rl_rx_list, BUS_DMA_NOWAIT | BUS_DMA_ZERO,
1030	    &sc->rl_ldata.rl_rx_list_map);
1031	if (error)
1032		return (ENOMEM);
1033
1034	/* Load the map for the RX ring. */
1035
1036	error = bus_dmamap_load(sc->rl_ldata.rl_rx_list_tag,
1037	     sc->rl_ldata.rl_rx_list_map, sc->rl_ldata.rl_rx_list,
1038	     RL_RX_LIST_SZ, re_dma_map_addr,
1039	     &sc->rl_ldata.rl_rx_list_addr, BUS_DMA_NOWAIT);
1040
1041	/* Create DMA maps for RX buffers */
1042
1043	for (i = 0; i < RL_RX_DESC_CNT; i++) {
1044		error = bus_dmamap_create(sc->rl_ldata.rl_mtag, 0,
1045			    &sc->rl_ldata.rl_rx_dmamap[i]);
1046		if (error) {
1047			device_printf(dev, "can't create DMA map for RX\n");
1048			return (ENOMEM);
1049		}
1050	}
1051
1052	return (0);
1053}
1054
1055/*
1056 * Attach the interface. Allocate softc structures, do ifmedia
1057 * setup and ethernet/BPF attach.
1058 */
1059static int
1060re_attach(dev)
1061	device_t		dev;
1062{
1063	u_char			eaddr[ETHER_ADDR_LEN];
1064	u_int16_t		as[3];
1065	struct rl_softc		*sc;
1066	struct ifnet		*ifp;
1067	struct rl_hwrev		*hw_rev;
1068	int			hwrev;
1069	u_int16_t		re_did = 0;
1070	int			unit, error = 0, rid, i;
1071
1072	sc = device_get_softc(dev);
1073	unit = device_get_unit(dev);
1074
1075	mtx_init(&sc->rl_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
1076	    MTX_DEF);
1077	/*
1078	 * Map control/status registers.
1079	 */
1080	pci_enable_busmaster(dev);
1081
1082	rid = RL_RID;
1083	sc->rl_res = bus_alloc_resource_any(dev, RL_RES, &rid,
1084	    RF_ACTIVE);
1085
1086	if (sc->rl_res == NULL) {
1087		printf ("re%d: couldn't map ports/memory\n", unit);
1088		error = ENXIO;
1089		goto fail;
1090	}
1091
1092	sc->rl_btag = rman_get_bustag(sc->rl_res);
1093	sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
1094
1095	/* Allocate interrupt */
1096	rid = 0;
1097	sc->rl_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1098	    RF_SHAREABLE | RF_ACTIVE);
1099
1100	if (sc->rl_irq == NULL) {
1101		printf("re%d: couldn't map interrupt\n", unit);
1102		error = ENXIO;
1103		goto fail;
1104	}
1105
1106	/* Reset the adapter. */
1107	RL_LOCK(sc);
1108	re_reset(sc);
1109	RL_UNLOCK(sc);
1110
1111	hw_rev = re_hwrevs;
1112	hwrev = CSR_READ_4(sc, RL_TXCFG) & RL_TXCFG_HWREV;
1113	while (hw_rev->rl_desc != NULL) {
1114		if (hw_rev->rl_rev == hwrev) {
1115			sc->rl_type = hw_rev->rl_type;
1116			break;
1117		}
1118		hw_rev++;
1119	}
1120
1121	if (sc->rl_type == RL_8169) {
1122
1123		/* Set RX length mask */
1124
1125		sc->rl_rxlenmask = RL_RDESC_STAT_GFRAGLEN;
1126
1127		/* Force station address autoload from the EEPROM */
1128
1129		CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_AUTOLOAD);
1130		for (i = 0; i < RL_TIMEOUT; i++) {
1131			if (!(CSR_READ_1(sc, RL_EECMD) & RL_EEMODE_AUTOLOAD))
1132				break;
1133			DELAY(100);
1134		}
1135		if (i == RL_TIMEOUT)
1136			printf ("re%d: eeprom autoload timed out\n", unit);
1137
1138			for (i = 0; i < ETHER_ADDR_LEN; i++)
1139				eaddr[i] = CSR_READ_1(sc, RL_IDR0 + i);
1140	} else {
1141
1142		/* Set RX length mask */
1143
1144		sc->rl_rxlenmask = RL_RDESC_STAT_FRAGLEN;
1145
1146		sc->rl_eecmd_read = RL_EECMD_READ_6BIT;
1147		re_read_eeprom(sc, (caddr_t)&re_did, 0, 1, 0);
1148		if (re_did != 0x8129)
1149			sc->rl_eecmd_read = RL_EECMD_READ_8BIT;
1150
1151		/*
1152		 * Get station address from the EEPROM.
1153		 */
1154		re_read_eeprom(sc, (caddr_t)as, RL_EE_EADDR, 3, 0);
1155		for (i = 0; i < 3; i++) {
1156			eaddr[(i * 2) + 0] = as[i] & 0xff;
1157			eaddr[(i * 2) + 1] = as[i] >> 8;
1158		}
1159	}
1160
1161	sc->rl_unit = unit;
1162
1163	/*
1164	 * Allocate the parent bus DMA tag appropriate for PCI.
1165	 */
1166#define RL_NSEG_NEW 32
1167	error = bus_dma_tag_create(NULL,	/* parent */
1168			1, 0,			/* alignment, boundary */
1169			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1170			BUS_SPACE_MAXADDR,	/* highaddr */
1171			NULL, NULL,		/* filter, filterarg */
1172			MAXBSIZE, RL_NSEG_NEW,	/* maxsize, nsegments */
1173			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1174			BUS_DMA_ALLOCNOW,	/* flags */
1175			NULL, NULL,		/* lockfunc, lockarg */
1176			&sc->rl_parent_tag);
1177	if (error)
1178		goto fail;
1179
1180	error = re_allocmem(dev, sc);
1181
1182	if (error)
1183		goto fail;
1184
1185	ifp = sc->rl_ifp = if_alloc(IFT_ETHER);
1186	if (ifp == NULL) {
1187		printf("re%d: can not if_alloc()\n", sc->rl_unit);
1188		error = ENOSPC;
1189		goto fail;
1190	}
1191
1192	/* Do MII setup */
1193	if (mii_phy_probe(dev, &sc->rl_miibus,
1194	    re_ifmedia_upd, re_ifmedia_sts)) {
1195		printf("re%d: MII without any phy!\n", sc->rl_unit);
1196		error = ENXIO;
1197		goto fail;
1198	}
1199
1200	ifp->if_softc = sc;
1201	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1202	ifp->if_mtu = ETHERMTU;
1203	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1204	ifp->if_ioctl = re_ioctl;
1205	ifp->if_capabilities = IFCAP_VLAN_MTU;
1206	ifp->if_start = re_start;
1207	ifp->if_hwassist = /*RE_CSUM_FEATURES*/0;
1208	ifp->if_capabilities |= IFCAP_HWCSUM|IFCAP_VLAN_HWTAGGING;
1209#ifdef DEVICE_POLLING
1210	ifp->if_capabilities |= IFCAP_POLLING;
1211#endif
1212	ifp->if_watchdog = re_watchdog;
1213	ifp->if_init = re_init;
1214	if (sc->rl_type == RL_8169)
1215		ifp->if_baudrate = 1000000000;
1216	else
1217		ifp->if_baudrate = 100000000;
1218	IFQ_SET_MAXLEN(&ifp->if_snd,  RL_IFQ_MAXLEN);
1219	ifp->if_snd.ifq_drv_maxlen = RL_IFQ_MAXLEN;
1220	IFQ_SET_READY(&ifp->if_snd);
1221	ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1222
1223	callout_handle_init(&sc->rl_stat_ch);
1224
1225	/*
1226	 * Call MI attach routine.
1227	 */
1228	ether_ifattach(ifp, eaddr);
1229
1230	/* Perform hardware diagnostic. */
1231	error = re_diag(sc);
1232
1233	if (error) {
1234		printf("re%d: attach aborted due to hardware diag failure\n",
1235		    unit);
1236		ether_ifdetach(ifp);
1237		if_free(ifp);
1238		goto fail;
1239	}
1240
1241	/* Hook interrupt last to avoid having to lock softc */
1242	error = bus_setup_intr(dev, sc->rl_irq, INTR_TYPE_NET | INTR_MPSAFE,
1243	    re_intr, sc, &sc->rl_intrhand);
1244	if (error) {
1245		printf("re%d: couldn't set up irq\n", unit);
1246		ether_ifdetach(ifp);
1247		if_free(ifp);
1248	}
1249
1250fail:
1251	if (error)
1252		re_detach(dev);
1253
1254	return (error);
1255}
1256
1257/*
1258 * Shutdown hardware and free up resources. This can be called any
1259 * time after the mutex has been initialized. It is called in both
1260 * the error case in attach and the normal detach case so it needs
1261 * to be careful about only freeing resources that have actually been
1262 * allocated.
1263 */
1264static int
1265re_detach(dev)
1266	device_t		dev;
1267{
1268	struct rl_softc		*sc;
1269	struct ifnet		*ifp;
1270	int			i;
1271	int			attached;
1272
1273	sc = device_get_softc(dev);
1274	ifp = sc->rl_ifp;
1275	KASSERT(mtx_initialized(&sc->rl_mtx), ("re mutex not initialized"));
1276
1277	attached = device_is_attached(dev);
1278	/* These should only be active if attach succeeded */
1279	if (attached)
1280		ether_ifdetach(ifp);
1281	if (ifp == NULL)
1282		if_free(ifp);
1283
1284	RL_LOCK(sc);
1285#if 0
1286	sc->suspended = 1;
1287#endif
1288
1289	/* These should only be active if attach succeeded */
1290	if (attached) {
1291		re_stop(sc);
1292		/*
1293		 * Force off the IFF_UP flag here, in case someone
1294		 * still had a BPF descriptor attached to this
1295		 * interface. If they do, ether_ifdetach() will cause
1296		 * the BPF code to try and clear the promisc mode
1297		 * flag, which will bubble down to re_ioctl(),
1298		 * which will try to call re_init() again. This will
1299		 * turn the NIC back on and restart the MII ticker,
1300		 * which will panic the system when the kernel tries
1301		 * to invoke the re_tick() function that isn't there
1302		 * anymore.
1303		 */
1304		ifp->if_flags &= ~IFF_UP;
1305	}
1306	if (sc->rl_miibus)
1307		device_delete_child(dev, sc->rl_miibus);
1308	bus_generic_detach(dev);
1309
1310	/*
1311	 * The rest is resource deallocation, so we should already be
1312	 * stopped here.
1313	 */
1314	RL_UNLOCK(sc);
1315
1316	if (sc->rl_intrhand)
1317		bus_teardown_intr(dev, sc->rl_irq, sc->rl_intrhand);
1318	if (sc->rl_irq)
1319		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
1320	if (sc->rl_res)
1321		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1322
1323
1324	/* Unload and free the RX DMA ring memory and map */
1325
1326	if (sc->rl_ldata.rl_rx_list_tag) {
1327		bus_dmamap_unload(sc->rl_ldata.rl_rx_list_tag,
1328		    sc->rl_ldata.rl_rx_list_map);
1329		bus_dmamem_free(sc->rl_ldata.rl_rx_list_tag,
1330		    sc->rl_ldata.rl_rx_list,
1331		    sc->rl_ldata.rl_rx_list_map);
1332		bus_dma_tag_destroy(sc->rl_ldata.rl_rx_list_tag);
1333	}
1334
1335	/* Unload and free the TX DMA ring memory and map */
1336
1337	if (sc->rl_ldata.rl_tx_list_tag) {
1338		bus_dmamap_unload(sc->rl_ldata.rl_tx_list_tag,
1339		    sc->rl_ldata.rl_tx_list_map);
1340		bus_dmamem_free(sc->rl_ldata.rl_tx_list_tag,
1341		    sc->rl_ldata.rl_tx_list,
1342		    sc->rl_ldata.rl_tx_list_map);
1343		bus_dma_tag_destroy(sc->rl_ldata.rl_tx_list_tag);
1344	}
1345
1346	/* Destroy all the RX and TX buffer maps */
1347
1348	if (sc->rl_ldata.rl_mtag) {
1349		for (i = 0; i < RL_TX_DESC_CNT; i++)
1350			bus_dmamap_destroy(sc->rl_ldata.rl_mtag,
1351			    sc->rl_ldata.rl_tx_dmamap[i]);
1352		for (i = 0; i < RL_RX_DESC_CNT; i++)
1353			bus_dmamap_destroy(sc->rl_ldata.rl_mtag,
1354			    sc->rl_ldata.rl_rx_dmamap[i]);
1355		bus_dma_tag_destroy(sc->rl_ldata.rl_mtag);
1356	}
1357
1358	/* Unload and free the stats buffer and map */
1359
1360	if (sc->rl_ldata.rl_stag) {
1361		bus_dmamap_unload(sc->rl_ldata.rl_stag,
1362		    sc->rl_ldata.rl_rx_list_map);
1363		bus_dmamem_free(sc->rl_ldata.rl_stag,
1364		    sc->rl_ldata.rl_stats,
1365		    sc->rl_ldata.rl_smap);
1366		bus_dma_tag_destroy(sc->rl_ldata.rl_stag);
1367	}
1368
1369	if (sc->rl_parent_tag)
1370		bus_dma_tag_destroy(sc->rl_parent_tag);
1371
1372	mtx_destroy(&sc->rl_mtx);
1373
1374	return (0);
1375}
1376
1377static int
1378re_newbuf(sc, idx, m)
1379	struct rl_softc		*sc;
1380	int			idx;
1381	struct mbuf		*m;
1382{
1383	struct rl_dmaload_arg	arg;
1384	struct mbuf		*n = NULL;
1385	int			error;
1386
1387	if (m == NULL) {
1388		n = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1389		if (n == NULL)
1390			return (ENOBUFS);
1391		m = n;
1392	} else
1393		m->m_data = m->m_ext.ext_buf;
1394
1395	m->m_len = m->m_pkthdr.len = MCLBYTES;
1396#ifdef RE_FIXUP_RX
1397	/*
1398	 * This is part of an evil trick to deal with non-x86 platforms.
1399	 * The RealTek chip requires RX buffers to be aligned on 64-bit
1400	 * boundaries, but that will hose non-x86 machines. To get around
1401	 * this, we leave some empty space at the start of each buffer
1402	 * and for non-x86 hosts, we copy the buffer back six bytes
1403	 * to achieve word alignment. This is slightly more efficient
1404	 * than allocating a new buffer, copying the contents, and
1405	 * discarding the old buffer.
1406	 */
1407	m_adj(m, RE_ETHER_ALIGN);
1408#endif
1409	arg.sc = sc;
1410	arg.rl_idx = idx;
1411	arg.rl_maxsegs = 1;
1412	arg.rl_flags = 0;
1413	arg.rl_ring = sc->rl_ldata.rl_rx_list;
1414
1415	error = bus_dmamap_load_mbuf(sc->rl_ldata.rl_mtag,
1416	    sc->rl_ldata.rl_rx_dmamap[idx], m, re_dma_map_desc,
1417	    &arg, BUS_DMA_NOWAIT);
1418	if (error || arg.rl_maxsegs != 1) {
1419		if (n != NULL)
1420			m_freem(n);
1421		return (ENOMEM);
1422	}
1423
1424	sc->rl_ldata.rl_rx_list[idx].rl_cmdstat |= htole32(RL_RDESC_CMD_OWN);
1425	sc->rl_ldata.rl_rx_mbuf[idx] = m;
1426
1427	bus_dmamap_sync(sc->rl_ldata.rl_mtag,
1428	    sc->rl_ldata.rl_rx_dmamap[idx],
1429	    BUS_DMASYNC_PREREAD);
1430
1431	return (0);
1432}
1433
1434#ifdef RE_FIXUP_RX
1435static __inline void
1436re_fixup_rx(m)
1437	struct mbuf		*m;
1438{
1439	int                     i;
1440	uint16_t                *src, *dst;
1441
1442	src = mtod(m, uint16_t *);
1443	dst = src - (RE_ETHER_ALIGN - ETHER_ALIGN) / sizeof *src;
1444
1445	for (i = 0; i < (m->m_len / sizeof(uint16_t) + 1); i++)
1446		*dst++ = *src++;
1447
1448	m->m_data -= RE_ETHER_ALIGN - ETHER_ALIGN;
1449
1450	return;
1451}
1452#endif
1453
1454static int
1455re_tx_list_init(sc)
1456	struct rl_softc		*sc;
1457{
1458
1459	RL_LOCK_ASSERT(sc);
1460
1461	bzero ((char *)sc->rl_ldata.rl_tx_list, RL_TX_LIST_SZ);
1462	bzero ((char *)&sc->rl_ldata.rl_tx_mbuf,
1463	    (RL_TX_DESC_CNT * sizeof(struct mbuf *)));
1464
1465	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
1466	    sc->rl_ldata.rl_tx_list_map, BUS_DMASYNC_PREWRITE);
1467	sc->rl_ldata.rl_tx_prodidx = 0;
1468	sc->rl_ldata.rl_tx_considx = 0;
1469	sc->rl_ldata.rl_tx_free = RL_TX_DESC_CNT;
1470
1471	return (0);
1472}
1473
1474static int
1475re_rx_list_init(sc)
1476	struct rl_softc		*sc;
1477{
1478	int			i;
1479
1480	bzero ((char *)sc->rl_ldata.rl_rx_list, RL_RX_LIST_SZ);
1481	bzero ((char *)&sc->rl_ldata.rl_rx_mbuf,
1482	    (RL_RX_DESC_CNT * sizeof(struct mbuf *)));
1483
1484	for (i = 0; i < RL_RX_DESC_CNT; i++) {
1485		if (re_newbuf(sc, i, NULL) == ENOBUFS)
1486			return (ENOBUFS);
1487	}
1488
1489	/* Flush the RX descriptors */
1490
1491	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1492	    sc->rl_ldata.rl_rx_list_map,
1493	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1494
1495	sc->rl_ldata.rl_rx_prodidx = 0;
1496	sc->rl_head = sc->rl_tail = NULL;
1497
1498	return (0);
1499}
1500
1501/*
1502 * RX handler for C+ and 8169. For the gigE chips, we support
1503 * the reception of jumbo frames that have been fragmented
1504 * across multiple 2K mbuf cluster buffers.
1505 */
1506static void
1507re_rxeof(sc)
1508	struct rl_softc		*sc;
1509{
1510	struct mbuf		*m;
1511	struct ifnet		*ifp;
1512	int			i, total_len;
1513	struct rl_desc		*cur_rx;
1514	u_int32_t		rxstat, rxvlan;
1515
1516	RL_LOCK_ASSERT(sc);
1517
1518	ifp = sc->rl_ifp;
1519	i = sc->rl_ldata.rl_rx_prodidx;
1520
1521	/* Invalidate the descriptor memory */
1522
1523	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1524	    sc->rl_ldata.rl_rx_list_map,
1525	    BUS_DMASYNC_POSTREAD);
1526
1527	while (!RL_OWN(&sc->rl_ldata.rl_rx_list[i])) {
1528		cur_rx = &sc->rl_ldata.rl_rx_list[i];
1529		m = sc->rl_ldata.rl_rx_mbuf[i];
1530		total_len = RL_RXBYTES(cur_rx);
1531		rxstat = le32toh(cur_rx->rl_cmdstat);
1532		rxvlan = le32toh(cur_rx->rl_vlanctl);
1533
1534		/* Invalidate the RX mbuf and unload its map */
1535
1536		bus_dmamap_sync(sc->rl_ldata.rl_mtag,
1537		    sc->rl_ldata.rl_rx_dmamap[i],
1538		    BUS_DMASYNC_POSTWRITE);
1539		bus_dmamap_unload(sc->rl_ldata.rl_mtag,
1540		    sc->rl_ldata.rl_rx_dmamap[i]);
1541
1542		if (!(rxstat & RL_RDESC_STAT_EOF)) {
1543			m->m_len = RE_RX_DESC_BUFLEN;
1544			if (sc->rl_head == NULL)
1545				sc->rl_head = sc->rl_tail = m;
1546			else {
1547				m->m_flags &= ~M_PKTHDR;
1548				sc->rl_tail->m_next = m;
1549				sc->rl_tail = m;
1550			}
1551			re_newbuf(sc, i, NULL);
1552			RL_DESC_INC(i);
1553			continue;
1554		}
1555
1556		/*
1557		 * NOTE: for the 8139C+, the frame length field
1558		 * is always 12 bits in size, but for the gigE chips,
1559		 * it is 13 bits (since the max RX frame length is 16K).
1560		 * Unfortunately, all 32 bits in the status word
1561		 * were already used, so to make room for the extra
1562		 * length bit, RealTek took out the 'frame alignment
1563		 * error' bit and shifted the other status bits
1564		 * over one slot. The OWN, EOR, FS and LS bits are
1565		 * still in the same places. We have already extracted
1566		 * the frame length and checked the OWN bit, so rather
1567		 * than using an alternate bit mapping, we shift the
1568		 * status bits one space to the right so we can evaluate
1569		 * them using the 8169 status as though it was in the
1570		 * same format as that of the 8139C+.
1571		 */
1572		if (sc->rl_type == RL_8169)
1573			rxstat >>= 1;
1574
1575		/*
1576		 * if total_len > 2^13-1, both _RXERRSUM and _GIANT will be
1577		 * set, but if CRC is clear, it will still be a valid frame.
1578		 */
1579		if (rxstat & RL_RDESC_STAT_RXERRSUM && !(total_len > 8191 &&
1580		    (rxstat & RL_RDESC_STAT_ERRS) == RL_RDESC_STAT_GIANT)) {
1581			ifp->if_ierrors++;
1582			/*
1583			 * If this is part of a multi-fragment packet,
1584			 * discard all the pieces.
1585			 */
1586			if (sc->rl_head != NULL) {
1587				m_freem(sc->rl_head);
1588				sc->rl_head = sc->rl_tail = NULL;
1589			}
1590			re_newbuf(sc, i, m);
1591			RL_DESC_INC(i);
1592			continue;
1593		}
1594
1595		/*
1596		 * If allocating a replacement mbuf fails,
1597		 * reload the current one.
1598		 */
1599
1600		if (re_newbuf(sc, i, NULL)) {
1601			ifp->if_ierrors++;
1602			if (sc->rl_head != NULL) {
1603				m_freem(sc->rl_head);
1604				sc->rl_head = sc->rl_tail = NULL;
1605			}
1606			re_newbuf(sc, i, m);
1607			RL_DESC_INC(i);
1608			continue;
1609		}
1610
1611		RL_DESC_INC(i);
1612
1613		if (sc->rl_head != NULL) {
1614			m->m_len = total_len % RE_RX_DESC_BUFLEN;
1615			if (m->m_len == 0)
1616				m->m_len = RE_RX_DESC_BUFLEN;
1617			/*
1618			 * Special case: if there's 4 bytes or less
1619			 * in this buffer, the mbuf can be discarded:
1620			 * the last 4 bytes is the CRC, which we don't
1621			 * care about anyway.
1622			 */
1623			if (m->m_len <= ETHER_CRC_LEN) {
1624				sc->rl_tail->m_len -=
1625				    (ETHER_CRC_LEN - m->m_len);
1626				m_freem(m);
1627			} else {
1628				m->m_len -= ETHER_CRC_LEN;
1629				m->m_flags &= ~M_PKTHDR;
1630				sc->rl_tail->m_next = m;
1631			}
1632			m = sc->rl_head;
1633			sc->rl_head = sc->rl_tail = NULL;
1634			m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1635		} else
1636			m->m_pkthdr.len = m->m_len =
1637			    (total_len - ETHER_CRC_LEN);
1638
1639#ifdef RE_FIXUP_RX
1640		re_fixup_rx(m);
1641#endif
1642		ifp->if_ipackets++;
1643		m->m_pkthdr.rcvif = ifp;
1644
1645		/* Do RX checksumming if enabled */
1646
1647		if (ifp->if_capenable & IFCAP_RXCSUM) {
1648
1649			/* Check IP header checksum */
1650			if (rxstat & RL_RDESC_STAT_PROTOID)
1651				m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1652			if (!(rxstat & RL_RDESC_STAT_IPSUMBAD))
1653				m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1654
1655			/* Check TCP/UDP checksum */
1656			if ((RL_TCPPKT(rxstat) &&
1657			    !(rxstat & RL_RDESC_STAT_TCPSUMBAD)) ||
1658			    (RL_UDPPKT(rxstat) &&
1659			    !(rxstat & RL_RDESC_STAT_UDPSUMBAD))) {
1660				m->m_pkthdr.csum_flags |=
1661				    CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
1662				m->m_pkthdr.csum_data = 0xffff;
1663			}
1664		}
1665
1666		if (rxvlan & RL_RDESC_VLANCTL_TAG)
1667			VLAN_INPUT_TAG(ifp, m,
1668			    ntohs((rxvlan & RL_RDESC_VLANCTL_DATA)), continue);
1669		RL_UNLOCK(sc);
1670		(*ifp->if_input)(ifp, m);
1671		RL_LOCK(sc);
1672	}
1673
1674	/* Flush the RX DMA ring */
1675
1676	bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
1677	    sc->rl_ldata.rl_rx_list_map,
1678	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1679
1680	sc->rl_ldata.rl_rx_prodidx = i;
1681}
1682
1683static void
1684re_txeof(sc)
1685	struct rl_softc		*sc;
1686{
1687	struct ifnet		*ifp;
1688	u_int32_t		txstat;
1689	int			idx;
1690
1691	ifp = sc->rl_ifp;
1692	idx = sc->rl_ldata.rl_tx_considx;
1693
1694	/* Invalidate the TX descriptor list */
1695
1696	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
1697	    sc->rl_ldata.rl_tx_list_map,
1698	    BUS_DMASYNC_POSTREAD);
1699
1700	while (idx != sc->rl_ldata.rl_tx_prodidx) {
1701
1702		txstat = le32toh(sc->rl_ldata.rl_tx_list[idx].rl_cmdstat);
1703		if (txstat & RL_TDESC_CMD_OWN)
1704			break;
1705
1706		/*
1707		 * We only stash mbufs in the last descriptor
1708		 * in a fragment chain, which also happens to
1709		 * be the only place where the TX status bits
1710		 * are valid.
1711		 */
1712
1713		if (txstat & RL_TDESC_CMD_EOF) {
1714			m_freem(sc->rl_ldata.rl_tx_mbuf[idx]);
1715			sc->rl_ldata.rl_tx_mbuf[idx] = NULL;
1716			bus_dmamap_unload(sc->rl_ldata.rl_mtag,
1717			    sc->rl_ldata.rl_tx_dmamap[idx]);
1718			if (txstat & (RL_TDESC_STAT_EXCESSCOL|
1719			    RL_TDESC_STAT_COLCNT))
1720				ifp->if_collisions++;
1721			if (txstat & RL_TDESC_STAT_TXERRSUM)
1722				ifp->if_oerrors++;
1723			else
1724				ifp->if_opackets++;
1725		}
1726		sc->rl_ldata.rl_tx_free++;
1727		RL_DESC_INC(idx);
1728	}
1729
1730	/* No changes made to the TX ring, so no flush needed */
1731
1732	if (idx != sc->rl_ldata.rl_tx_considx) {
1733		sc->rl_ldata.rl_tx_considx = idx;
1734		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1735		ifp->if_timer = 0;
1736	}
1737
1738	/*
1739	 * If not all descriptors have been released reaped yet,
1740	 * reload the timer so that we will eventually get another
1741	 * interrupt that will cause us to re-enter this routine.
1742	 * This is done in case the transmitter has gone idle.
1743	 */
1744	if (sc->rl_ldata.rl_tx_free != RL_TX_DESC_CNT)
1745		CSR_WRITE_4(sc, RL_TIMERCNT, 1);
1746}
1747
1748static void
1749re_tick(xsc)
1750	void			*xsc;
1751{
1752	struct rl_softc		*sc;
1753
1754	sc = xsc;
1755	RL_LOCK(sc);
1756	re_tick_locked(sc);
1757	RL_UNLOCK(sc);
1758}
1759
1760static void
1761re_tick_locked(sc)
1762	struct rl_softc		*sc;
1763{
1764	struct mii_data		*mii;
1765
1766	RL_LOCK_ASSERT(sc);
1767
1768	mii = device_get_softc(sc->rl_miibus);
1769
1770	mii_tick(mii);
1771
1772	sc->rl_stat_ch = timeout(re_tick, sc, hz);
1773}
1774
1775#ifdef DEVICE_POLLING
1776static void
1777re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1778{
1779	struct rl_softc *sc = ifp->if_softc;
1780
1781	RL_LOCK(sc);
1782	re_poll_locked(ifp, cmd, count);
1783	RL_UNLOCK(sc);
1784}
1785
1786static void
1787re_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
1788{
1789	struct rl_softc *sc = ifp->if_softc;
1790
1791	RL_LOCK_ASSERT(sc);
1792
1793	if (!(ifp->if_capenable & IFCAP_POLLING)) {
1794		ether_poll_deregister(ifp);
1795		cmd = POLL_DEREGISTER;
1796	}
1797	if (cmd == POLL_DEREGISTER) { /* final call, enable interrupts */
1798		CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
1799		return;
1800	}
1801
1802	sc->rxcycles = count;
1803	re_rxeof(sc);
1804	re_txeof(sc);
1805
1806	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1807		re_start_locked(ifp);
1808
1809	if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1810		u_int16_t       status;
1811
1812		status = CSR_READ_2(sc, RL_ISR);
1813		if (status == 0xffff)
1814			return;
1815		if (status)
1816			CSR_WRITE_2(sc, RL_ISR, status);
1817
1818		/*
1819		 * XXX check behaviour on receiver stalls.
1820		 */
1821
1822		if (status & RL_ISR_SYSTEM_ERR) {
1823			re_reset(sc);
1824			re_init_locked(sc);
1825		}
1826	}
1827}
1828#endif /* DEVICE_POLLING */
1829
1830static void
1831re_intr(arg)
1832	void			*arg;
1833{
1834	struct rl_softc		*sc;
1835	struct ifnet		*ifp;
1836	u_int16_t		status;
1837
1838	sc = arg;
1839
1840	RL_LOCK(sc);
1841
1842	ifp = sc->rl_ifp;
1843
1844	if (sc->suspended || !(ifp->if_flags & IFF_UP))
1845		goto done_locked;
1846
1847#ifdef DEVICE_POLLING
1848	if  (ifp->if_flags & IFF_POLLING)
1849		goto done_locked;
1850	if ((ifp->if_capenable & IFCAP_POLLING) &&
1851	    ether_poll_register(re_poll, ifp)) { /* ok, disable interrupts */
1852		CSR_WRITE_2(sc, RL_IMR, 0x0000);
1853		re_poll_locked(ifp, 0, 1);
1854		goto done_locked;
1855	}
1856#endif /* DEVICE_POLLING */
1857
1858	for (;;) {
1859
1860		status = CSR_READ_2(sc, RL_ISR);
1861		/* If the card has gone away the read returns 0xffff. */
1862		if (status == 0xffff)
1863			break;
1864		if (status)
1865			CSR_WRITE_2(sc, RL_ISR, status);
1866
1867		if ((status & RL_INTRS_CPLUS) == 0)
1868			break;
1869
1870		if ((status & RL_ISR_RX_OK) ||
1871		    (status & RL_ISR_RX_ERR))
1872			re_rxeof(sc);
1873
1874		if ((status & RL_ISR_TIMEOUT_EXPIRED) ||
1875		    (status & RL_ISR_TX_ERR) ||
1876		    (status & RL_ISR_TX_DESC_UNAVAIL))
1877			re_txeof(sc);
1878
1879		if (status & RL_ISR_SYSTEM_ERR) {
1880			re_reset(sc);
1881			re_init_locked(sc);
1882		}
1883
1884		if (status & RL_ISR_LINKCHG) {
1885			untimeout(re_tick, sc, sc->rl_stat_ch);
1886			re_tick_locked(sc);
1887		}
1888	}
1889
1890	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1891		re_start_locked(ifp);
1892
1893done_locked:
1894	RL_UNLOCK(sc);
1895}
1896
1897static int
1898re_encap(sc, m_head, idx)
1899	struct rl_softc		*sc;
1900	struct mbuf		**m_head;
1901	int			*idx;
1902{
1903	struct mbuf		*m_new = NULL;
1904	struct rl_dmaload_arg	arg;
1905	bus_dmamap_t		map;
1906	int			error;
1907	struct m_tag		*mtag;
1908
1909	RL_LOCK_ASSERT(sc);
1910
1911	if (sc->rl_ldata.rl_tx_free <= 4)
1912		return (EFBIG);
1913
1914	/*
1915	 * Set up checksum offload. Note: checksum offload bits must
1916	 * appear in all descriptors of a multi-descriptor transmit
1917	 * attempt. This is according to testing done with an 8169
1918	 * chip. This is a requirement.
1919	 */
1920
1921	arg.rl_flags = 0;
1922
1923	if ((*m_head)->m_pkthdr.csum_flags & CSUM_IP)
1924		arg.rl_flags |= RL_TDESC_CMD_IPCSUM;
1925	if ((*m_head)->m_pkthdr.csum_flags & CSUM_TCP)
1926		arg.rl_flags |= RL_TDESC_CMD_TCPCSUM;
1927	if ((*m_head)->m_pkthdr.csum_flags & CSUM_UDP)
1928		arg.rl_flags |= RL_TDESC_CMD_UDPCSUM;
1929
1930	arg.sc = sc;
1931	arg.rl_idx = *idx;
1932	arg.rl_maxsegs = sc->rl_ldata.rl_tx_free;
1933	if (arg.rl_maxsegs > 4)
1934		arg.rl_maxsegs -= 4;
1935	arg.rl_ring = sc->rl_ldata.rl_tx_list;
1936
1937	map = sc->rl_ldata.rl_tx_dmamap[*idx];
1938	error = bus_dmamap_load_mbuf(sc->rl_ldata.rl_mtag, map,
1939	    *m_head, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1940
1941	if (error && error != EFBIG) {
1942		printf("re%d: can't map mbuf (error %d)\n", sc->rl_unit, error);
1943		return (ENOBUFS);
1944	}
1945
1946	/* Too many segments to map, coalesce into a single mbuf */
1947
1948	if (error || arg.rl_maxsegs == 0) {
1949		m_new = m_defrag(*m_head, M_DONTWAIT);
1950		if (m_new == NULL)
1951			return (ENOBUFS);
1952		else
1953			*m_head = m_new;
1954
1955		arg.sc = sc;
1956		arg.rl_idx = *idx;
1957		arg.rl_maxsegs = sc->rl_ldata.rl_tx_free;
1958		arg.rl_ring = sc->rl_ldata.rl_tx_list;
1959
1960		error = bus_dmamap_load_mbuf(sc->rl_ldata.rl_mtag, map,
1961		    *m_head, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1962		if (error) {
1963			printf("re%d: can't map mbuf (error %d)\n",
1964			    sc->rl_unit, error);
1965			return (EFBIG);
1966		}
1967	}
1968
1969	/*
1970	 * Insure that the map for this transmission
1971	 * is placed at the array index of the last descriptor
1972	 * in this chain.  (Swap last and first dmamaps.)
1973	 */
1974	sc->rl_ldata.rl_tx_dmamap[*idx] =
1975	    sc->rl_ldata.rl_tx_dmamap[arg.rl_idx];
1976	sc->rl_ldata.rl_tx_dmamap[arg.rl_idx] = map;
1977
1978	sc->rl_ldata.rl_tx_mbuf[arg.rl_idx] = *m_head;
1979	sc->rl_ldata.rl_tx_free -= arg.rl_maxsegs;
1980
1981	/*
1982	 * Set up hardware VLAN tagging. Note: vlan tag info must
1983	 * appear in the first descriptor of a multi-descriptor
1984	 * transmission attempt.
1985	 */
1986
1987	mtag = VLAN_OUTPUT_TAG(sc->rl_ifp, *m_head);
1988	if (mtag != NULL)
1989		sc->rl_ldata.rl_tx_list[*idx].rl_vlanctl =
1990		    htole32(htons(VLAN_TAG_VALUE(mtag)) | RL_TDESC_VLANCTL_TAG);
1991
1992	/* Transfer ownership of packet to the chip. */
1993
1994	sc->rl_ldata.rl_tx_list[arg.rl_idx].rl_cmdstat |=
1995	    htole32(RL_TDESC_CMD_OWN);
1996	if (*idx != arg.rl_idx)
1997		sc->rl_ldata.rl_tx_list[*idx].rl_cmdstat |=
1998		    htole32(RL_TDESC_CMD_OWN);
1999
2000	RL_DESC_INC(arg.rl_idx);
2001	*idx = arg.rl_idx;
2002
2003	return (0);
2004}
2005
2006static void
2007re_start(ifp)
2008	struct ifnet		*ifp;
2009{
2010	struct rl_softc		*sc;
2011
2012	sc = ifp->if_softc;
2013	RL_LOCK(sc);
2014	re_start_locked(ifp);
2015	RL_UNLOCK(sc);
2016}
2017
2018/*
2019 * Main transmit routine for C+ and gigE NICs.
2020 */
2021static void
2022re_start_locked(ifp)
2023	struct ifnet		*ifp;
2024{
2025	struct rl_softc		*sc;
2026	struct mbuf		*m_head = NULL;
2027	int			idx, queued = 0;
2028
2029	sc = ifp->if_softc;
2030
2031	RL_LOCK_ASSERT(sc);
2032
2033	idx = sc->rl_ldata.rl_tx_prodidx;
2034
2035	while (sc->rl_ldata.rl_tx_mbuf[idx] == NULL) {
2036		IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
2037		if (m_head == NULL)
2038			break;
2039
2040		if (re_encap(sc, &m_head, &idx)) {
2041			IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
2042			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2043			break;
2044		}
2045
2046		/*
2047		 * If there's a BPF listener, bounce a copy of this frame
2048		 * to him.
2049		 */
2050		BPF_MTAP(ifp, m_head);
2051
2052		queued++;
2053	}
2054
2055	if (queued == 0)
2056		return;
2057
2058	/* Flush the TX descriptors */
2059
2060	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
2061	    sc->rl_ldata.rl_tx_list_map,
2062	    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
2063
2064	sc->rl_ldata.rl_tx_prodidx = idx;
2065
2066	/*
2067	 * RealTek put the TX poll request register in a different
2068	 * location on the 8169 gigE chip. I don't know why.
2069	 */
2070
2071	if (sc->rl_type == RL_8169)
2072		CSR_WRITE_2(sc, RL_GTXSTART, RL_TXSTART_START);
2073	else
2074		CSR_WRITE_2(sc, RL_TXSTART, RL_TXSTART_START);
2075
2076	/*
2077	 * Use the countdown timer for interrupt moderation.
2078	 * 'TX done' interrupts are disabled. Instead, we reset the
2079	 * countdown timer, which will begin counting until it hits
2080	 * the value in the TIMERINT register, and then trigger an
2081	 * interrupt. Each time we write to the TIMERCNT register,
2082	 * the timer count is reset to 0.
2083	 */
2084	CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2085
2086	/*
2087	 * Set a timeout in case the chip goes out to lunch.
2088	 */
2089	ifp->if_timer = 5;
2090}
2091
2092static void
2093re_init(xsc)
2094	void			*xsc;
2095{
2096	struct rl_softc		*sc = xsc;
2097
2098	RL_LOCK(sc);
2099	re_init_locked(sc);
2100	RL_UNLOCK(sc);
2101}
2102
2103static void
2104re_init_locked(sc)
2105	struct rl_softc		*sc;
2106{
2107	struct ifnet		*ifp = sc->rl_ifp;
2108	struct mii_data		*mii;
2109	u_int32_t		rxcfg = 0;
2110
2111	RL_LOCK_ASSERT(sc);
2112
2113	mii = device_get_softc(sc->rl_miibus);
2114
2115	/*
2116	 * Cancel pending I/O and free all RX/TX buffers.
2117	 */
2118	re_stop(sc);
2119
2120	/*
2121	 * Enable C+ RX and TX mode, as well as VLAN stripping and
2122	 * RX checksum offload. We must configure the C+ register
2123	 * before all others.
2124	 */
2125	CSR_WRITE_2(sc, RL_CPLUS_CMD, RL_CPLUSCMD_RXENB|
2126	    RL_CPLUSCMD_TXENB|RL_CPLUSCMD_PCI_MRW|
2127	    RL_CPLUSCMD_VLANSTRIP|
2128	    (ifp->if_capenable & IFCAP_RXCSUM ?
2129	    RL_CPLUSCMD_RXCSUM_ENB : 0));
2130
2131	/*
2132	 * Init our MAC address.  Even though the chipset
2133	 * documentation doesn't mention it, we need to enter "Config
2134	 * register write enable" mode to modify the ID registers.
2135	 */
2136	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_WRITECFG);
2137	CSR_WRITE_STREAM_4(sc, RL_IDR0,
2138	    *(u_int32_t *)(&IFP2ENADDR(sc->rl_ifp)[0]));
2139	CSR_WRITE_STREAM_4(sc, RL_IDR4,
2140	    *(u_int32_t *)(&IFP2ENADDR(sc->rl_ifp)[4]));
2141	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
2142
2143	/*
2144	 * For C+ mode, initialize the RX descriptors and mbufs.
2145	 */
2146	re_rx_list_init(sc);
2147	re_tx_list_init(sc);
2148
2149	/*
2150	 * Enable transmit and receive.
2151	 */
2152	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
2153
2154	/*
2155	 * Set the initial TX and RX configuration.
2156	 */
2157	if (sc->rl_testmode) {
2158		if (sc->rl_type == RL_8169)
2159			CSR_WRITE_4(sc, RL_TXCFG,
2160			    RL_TXCFG_CONFIG|RL_LOOPTEST_ON);
2161		else
2162			CSR_WRITE_4(sc, RL_TXCFG,
2163			    RL_TXCFG_CONFIG|RL_LOOPTEST_ON_CPLUS);
2164	} else
2165		CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
2166	CSR_WRITE_4(sc, RL_RXCFG, RL_RXCFG_CONFIG);
2167
2168	/* Set the individual bit to receive frames for this host only. */
2169	rxcfg = CSR_READ_4(sc, RL_RXCFG);
2170	rxcfg |= RL_RXCFG_RX_INDIV;
2171
2172	/* If we want promiscuous mode, set the allframes bit. */
2173	if (ifp->if_flags & IFF_PROMISC)
2174		rxcfg |= RL_RXCFG_RX_ALLPHYS;
2175	else
2176		rxcfg &= ~RL_RXCFG_RX_ALLPHYS;
2177	CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
2178
2179	/*
2180	 * Set capture broadcast bit to capture broadcast frames.
2181	 */
2182	if (ifp->if_flags & IFF_BROADCAST)
2183		rxcfg |= RL_RXCFG_RX_BROAD;
2184	else
2185		rxcfg &= ~RL_RXCFG_RX_BROAD;
2186	CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
2187
2188	/*
2189	 * Program the multicast filter, if necessary.
2190	 */
2191	re_setmulti(sc);
2192
2193#ifdef DEVICE_POLLING
2194	/*
2195	 * Disable interrupts if we are polling.
2196	 */
2197	if (ifp->if_flags & IFF_POLLING)
2198		CSR_WRITE_2(sc, RL_IMR, 0);
2199	else	/* otherwise ... */
2200#endif /* DEVICE_POLLING */
2201	/*
2202	 * Enable interrupts.
2203	 */
2204	if (sc->rl_testmode)
2205		CSR_WRITE_2(sc, RL_IMR, 0);
2206	else
2207		CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
2208
2209	/* Set initial TX threshold */
2210	sc->rl_txthresh = RL_TX_THRESH_INIT;
2211
2212	/* Start RX/TX process. */
2213	CSR_WRITE_4(sc, RL_MISSEDPKT, 0);
2214#ifdef notdef
2215	/* Enable receiver and transmitter. */
2216	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
2217#endif
2218	/*
2219	 * Load the addresses of the RX and TX lists into the chip.
2220	 */
2221
2222	CSR_WRITE_4(sc, RL_RXLIST_ADDR_HI,
2223	    RL_ADDR_HI(sc->rl_ldata.rl_rx_list_addr));
2224	CSR_WRITE_4(sc, RL_RXLIST_ADDR_LO,
2225	    RL_ADDR_LO(sc->rl_ldata.rl_rx_list_addr));
2226
2227	CSR_WRITE_4(sc, RL_TXLIST_ADDR_HI,
2228	    RL_ADDR_HI(sc->rl_ldata.rl_tx_list_addr));
2229	CSR_WRITE_4(sc, RL_TXLIST_ADDR_LO,
2230	    RL_ADDR_LO(sc->rl_ldata.rl_tx_list_addr));
2231
2232	CSR_WRITE_1(sc, RL_EARLY_TX_THRESH, 16);
2233
2234	/*
2235	 * Initialize the timer interrupt register so that
2236	 * a timer interrupt will be generated once the timer
2237	 * reaches a certain number of ticks. The timer is
2238	 * reloaded on each transmit. This gives us TX interrupt
2239	 * moderation, which dramatically improves TX frame rate.
2240	 */
2241	if (sc->rl_type == RL_8169)
2242		CSR_WRITE_4(sc, RL_TIMERINT_8169, 0x800);
2243	else
2244		CSR_WRITE_4(sc, RL_TIMERINT, 0x400);
2245
2246	/*
2247	 * For 8169 gigE NICs, set the max allowed RX packet
2248	 * size so we can receive jumbo frames.
2249	 */
2250	if (sc->rl_type == RL_8169)
2251		CSR_WRITE_2(sc, RL_MAXRXPKTLEN, 16383);
2252
2253	if (sc->rl_testmode)
2254		return;
2255
2256	mii_mediachg(mii);
2257
2258	CSR_WRITE_1(sc, RL_CFG1, RL_CFG1_DRVLOAD|RL_CFG1_FULLDUPLEX);
2259
2260	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2261	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2262
2263	sc->rl_stat_ch = timeout(re_tick, sc, hz);
2264}
2265
2266/*
2267 * Set media options.
2268 */
2269static int
2270re_ifmedia_upd(ifp)
2271	struct ifnet		*ifp;
2272{
2273	struct rl_softc		*sc;
2274	struct mii_data		*mii;
2275
2276	sc = ifp->if_softc;
2277	mii = device_get_softc(sc->rl_miibus);
2278	mii_mediachg(mii);
2279
2280	return (0);
2281}
2282
2283/*
2284 * Report current media status.
2285 */
2286static void
2287re_ifmedia_sts(ifp, ifmr)
2288	struct ifnet		*ifp;
2289	struct ifmediareq	*ifmr;
2290{
2291	struct rl_softc		*sc;
2292	struct mii_data		*mii;
2293
2294	sc = ifp->if_softc;
2295	mii = device_get_softc(sc->rl_miibus);
2296
2297	mii_pollstat(mii);
2298	ifmr->ifm_active = mii->mii_media_active;
2299	ifmr->ifm_status = mii->mii_media_status;
2300}
2301
2302static int
2303re_ioctl(ifp, command, data)
2304	struct ifnet		*ifp;
2305	u_long			command;
2306	caddr_t			data;
2307{
2308	struct rl_softc		*sc = ifp->if_softc;
2309	struct ifreq		*ifr = (struct ifreq *) data;
2310	struct mii_data		*mii;
2311	int			error = 0;
2312
2313	switch (command) {
2314	case SIOCSIFMTU:
2315		if (ifr->ifr_mtu > RL_JUMBO_MTU)
2316			error = EINVAL;
2317		ifp->if_mtu = ifr->ifr_mtu;
2318		break;
2319	case SIOCSIFFLAGS:
2320		RL_LOCK(sc);
2321		if (ifp->if_flags & IFF_UP)
2322			re_init_locked(sc);
2323		else if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2324			re_stop(sc);
2325		RL_UNLOCK(sc);
2326		error = 0;
2327		break;
2328	case SIOCADDMULTI:
2329	case SIOCDELMULTI:
2330		RL_LOCK(sc);
2331		re_setmulti(sc);
2332		RL_UNLOCK(sc);
2333		error = 0;
2334		break;
2335	case SIOCGIFMEDIA:
2336	case SIOCSIFMEDIA:
2337		mii = device_get_softc(sc->rl_miibus);
2338		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2339		break;
2340	case SIOCSIFCAP:
2341		ifp->if_capenable &= ~(IFCAP_HWCSUM | IFCAP_POLLING);
2342		ifp->if_capenable |=
2343		    ifr->ifr_reqcap & (IFCAP_HWCSUM | IFCAP_POLLING);
2344		if (ifp->if_capenable & IFCAP_TXCSUM)
2345			ifp->if_hwassist = RE_CSUM_FEATURES;
2346		else
2347			ifp->if_hwassist = 0;
2348		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2349			re_init(sc);
2350		break;
2351	default:
2352		error = ether_ioctl(ifp, command, data);
2353		break;
2354	}
2355
2356	return (error);
2357}
2358
2359static void
2360re_watchdog(ifp)
2361	struct ifnet		*ifp;
2362{
2363	struct rl_softc		*sc;
2364
2365	sc = ifp->if_softc;
2366	RL_LOCK(sc);
2367	printf("re%d: watchdog timeout\n", sc->rl_unit);
2368	ifp->if_oerrors++;
2369
2370	re_txeof(sc);
2371	re_rxeof(sc);
2372	re_init_locked(sc);
2373
2374	RL_UNLOCK(sc);
2375}
2376
2377/*
2378 * Stop the adapter and free any mbufs allocated to the
2379 * RX and TX lists.
2380 */
2381static void
2382re_stop(sc)
2383	struct rl_softc		*sc;
2384{
2385	register int		i;
2386	struct ifnet		*ifp;
2387
2388	RL_LOCK_ASSERT(sc);
2389
2390	ifp = sc->rl_ifp;
2391	ifp->if_timer = 0;
2392
2393	untimeout(re_tick, sc, sc->rl_stat_ch);
2394	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2395#ifdef DEVICE_POLLING
2396	ether_poll_deregister(ifp);
2397#endif /* DEVICE_POLLING */
2398
2399	CSR_WRITE_1(sc, RL_COMMAND, 0x00);
2400	CSR_WRITE_2(sc, RL_IMR, 0x0000);
2401
2402	if (sc->rl_head != NULL) {
2403		m_freem(sc->rl_head);
2404		sc->rl_head = sc->rl_tail = NULL;
2405	}
2406
2407	/* Free the TX list buffers. */
2408
2409	for (i = 0; i < RL_TX_DESC_CNT; i++) {
2410		if (sc->rl_ldata.rl_tx_mbuf[i] != NULL) {
2411			bus_dmamap_unload(sc->rl_ldata.rl_mtag,
2412			    sc->rl_ldata.rl_tx_dmamap[i]);
2413			m_freem(sc->rl_ldata.rl_tx_mbuf[i]);
2414			sc->rl_ldata.rl_tx_mbuf[i] = NULL;
2415		}
2416	}
2417
2418	/* Free the RX list buffers. */
2419
2420	for (i = 0; i < RL_RX_DESC_CNT; i++) {
2421		if (sc->rl_ldata.rl_rx_mbuf[i] != NULL) {
2422			bus_dmamap_unload(sc->rl_ldata.rl_mtag,
2423			    sc->rl_ldata.rl_rx_dmamap[i]);
2424			m_freem(sc->rl_ldata.rl_rx_mbuf[i]);
2425			sc->rl_ldata.rl_rx_mbuf[i] = NULL;
2426		}
2427	}
2428}
2429
2430/*
2431 * Device suspend routine.  Stop the interface and save some PCI
2432 * settings in case the BIOS doesn't restore them properly on
2433 * resume.
2434 */
2435static int
2436re_suspend(dev)
2437	device_t		dev;
2438{
2439	struct rl_softc		*sc;
2440
2441	sc = device_get_softc(dev);
2442
2443	RL_LOCK(sc);
2444	re_stop(sc);
2445	sc->suspended = 1;
2446	RL_UNLOCK(sc);
2447
2448	return (0);
2449}
2450
2451/*
2452 * Device resume routine.  Restore some PCI settings in case the BIOS
2453 * doesn't, re-enable busmastering, and restart the interface if
2454 * appropriate.
2455 */
2456static int
2457re_resume(dev)
2458	device_t		dev;
2459{
2460	struct rl_softc		*sc;
2461	struct ifnet		*ifp;
2462
2463	sc = device_get_softc(dev);
2464
2465	RL_LOCK(sc);
2466
2467	ifp = sc->rl_ifp;
2468
2469	/* reinitialize interface if necessary */
2470	if (ifp->if_flags & IFF_UP)
2471		re_init_locked(sc);
2472
2473	sc->suspended = 0;
2474	RL_UNLOCK(sc);
2475
2476	return (0);
2477}
2478
2479/*
2480 * Stop all chip I/O so that the kernel's probe routines don't
2481 * get confused by errant DMAs when rebooting.
2482 */
2483static void
2484re_shutdown(dev)
2485	device_t		dev;
2486{
2487	struct rl_softc		*sc;
2488
2489	sc = device_get_softc(dev);
2490
2491	RL_LOCK(sc);
2492	re_stop(sc);
2493	RL_UNLOCK(sc);
2494}
2495