if_rl.c revision 105221
1/*
2 * Copyright (c) 1997, 1998
3 *	Bill Paul <wpaul@ctr.columbia.edu>.  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 * $FreeBSD: head/sys/pci/if_rl.c 105221 2002-10-16 09:14:59Z phk $
33 */
34
35/*
36 * RealTek 8129/8139 PCI NIC driver
37 *
38 * Supports several extremely cheap PCI 10/100 adapters based on
39 * the RealTek chipset. Datasheets can be obtained from
40 * www.realtek.com.tw.
41 *
42 * Written by Bill Paul <wpaul@ctr.columbia.edu>
43 * Electrical Engineering Department
44 * Columbia University, New York City
45 */
46
47/*
48 * The RealTek 8139 PCI NIC redefines the meaning of 'low end.' This is
49 * probably the worst PCI ethernet controller ever made, with the possible
50 * exception of the FEAST chip made by SMC. The 8139 supports bus-master
51 * DMA, but it has a terrible interface that nullifies any performance
52 * gains that bus-master DMA usually offers.
53 *
54 * For transmission, the chip offers a series of four TX descriptor
55 * registers. Each transmit frame must be in a contiguous buffer, aligned
56 * on a longword (32-bit) boundary. This means we almost always have to
57 * do mbuf copies in order to transmit a frame, except in the unlikely
58 * case where a) the packet fits into a single mbuf, and b) the packet
59 * is 32-bit aligned within the mbuf's data area. The presence of only
60 * four descriptor registers means that we can never have more than four
61 * packets queued for transmission at any one time.
62 *
63 * Reception is not much better. The driver has to allocate a single large
64 * buffer area (up to 64K in size) into which the chip will DMA received
65 * frames. Because we don't know where within this region received packets
66 * will begin or end, we have no choice but to copy data from the buffer
67 * area into mbufs in order to pass the packets up to the higher protocol
68 * levels.
69 *
70 * It's impossible given this rotten design to really achieve decent
71 * performance at 100Mbps, unless you happen to have a 400Mhz PII or
72 * some equally overmuscled CPU to drive it.
73 *
74 * On the bright side, the 8139 does have a built-in PHY, although
75 * rather than using an MDIO serial interface like most other NICs, the
76 * PHY registers are directly accessible through the 8139's register
77 * space. The 8139 supports autonegotiation, as well as a 64-bit multicast
78 * filter.
79 *
80 * The 8129 chip is an older version of the 8139 that uses an external PHY
81 * chip. The 8129 has a serial MDIO interface for accessing the MII where
82 * the 8139 lets you directly access the on-board PHY registers. We need
83 * to select which interface to use depending on the chip type.
84 */
85
86#include <sys/param.h>
87#include <sys/systm.h>
88#include <sys/sockio.h>
89#include <sys/mbuf.h>
90#include <sys/malloc.h>
91#include <sys/kernel.h>
92#include <sys/socket.h>
93
94#include <net/if.h>
95#include <net/if_arp.h>
96#include <net/ethernet.h>
97#include <net/if_dl.h>
98#include <net/if_media.h>
99
100#include <net/bpf.h>
101
102#include <machine/bus_pio.h>
103#include <machine/bus_memio.h>
104#include <machine/bus.h>
105#include <machine/resource.h>
106#include <sys/bus.h>
107#include <sys/rman.h>
108
109#include <dev/mii/mii.h>
110#include <dev/mii/miivar.h>
111
112#include <pci/pcireg.h>
113#include <pci/pcivar.h>
114
115MODULE_DEPEND(rl, miibus, 1, 1, 1);
116
117/* "controller miibus0" required.  See GENERIC if you get errors here. */
118#include "miibus_if.h"
119
120/*
121 * Default to using PIO access for this driver. On SMP systems,
122 * there appear to be problems with memory mapped mode: it looks like
123 * doing too many memory mapped access back to back in rapid succession
124 * can hang the bus. I'm inclined to blame this on crummy design/construction
125 * on the part of RealTek. Memory mapped mode does appear to work on
126 * uniprocessor systems though.
127 */
128#define RL_USEIOSPACE
129
130#include <pci/if_rlreg.h>
131
132#ifndef lint
133static const char rcsid[] =
134  "$FreeBSD: head/sys/pci/if_rl.c 105221 2002-10-16 09:14:59Z phk $";
135#endif
136
137/*
138 * Various supported device vendors/types and their names.
139 */
140static struct rl_type rl_devs[] = {
141	{ RT_VENDORID, RT_DEVICEID_8129,
142		"RealTek 8129 10/100BaseTX" },
143	{ RT_VENDORID, RT_DEVICEID_8139,
144		"RealTek 8139 10/100BaseTX" },
145	{ RT_VENDORID, RT_DEVICEID_8138,
146		"RealTek 8139 10/100BaseTX CardBus" },
147	{ ACCTON_VENDORID, ACCTON_DEVICEID_5030,
148		"Accton MPX 5030/5038 10/100BaseTX" },
149	{ DELTA_VENDORID, DELTA_DEVICEID_8139,
150		"Delta Electronics 8139 10/100BaseTX" },
151	{ ADDTRON_VENDORID, ADDTRON_DEVICEID_8139,
152		"Addtron Technolgy 8139 10/100BaseTX" },
153	{ DLINK_VENDORID, DLINK_DEVICEID_530TXPLUS,
154		"D-Link DFE-530TX+ 10/100BaseTX" },
155	{ DLINK_VENDORID, DLINK_DEVICEID_690TXD,
156		"D-Link DFE-690TXD 10/100BaseTX" },
157	{ NORTEL_VENDORID, ACCTON_DEVICEID_5030,
158		"Nortel Networks 10/100BaseTX" },
159	{ COREGA_VENDORID, COREGA_DEVICEID_CBTXD,
160		"Corega FEther CB-TXD" },
161	{ 0, 0, NULL }
162};
163
164static int rl_probe		(device_t);
165static int rl_attach		(device_t);
166static int rl_detach		(device_t);
167
168static int rl_encap		(struct rl_softc *, struct mbuf * );
169
170static void rl_rxeof		(struct rl_softc *);
171static void rl_txeof		(struct rl_softc *);
172static void rl_intr		(void *);
173static void rl_tick		(void *);
174static void rl_start		(struct ifnet *);
175static int rl_ioctl		(struct ifnet *, u_long, caddr_t);
176static void rl_init		(void *);
177static void rl_stop		(struct rl_softc *);
178static void rl_watchdog		(struct ifnet *);
179static int rl_suspend		(device_t);
180static int rl_resume		(device_t);
181static void rl_shutdown		(device_t);
182static int rl_ifmedia_upd	(struct ifnet *);
183static void rl_ifmedia_sts	(struct ifnet *, struct ifmediareq *);
184
185static void rl_eeprom_putbyte	(struct rl_softc *, int);
186static void rl_eeprom_getword	(struct rl_softc *, int, u_int16_t *);
187static void rl_read_eeprom	(struct rl_softc *, caddr_t, int, int, int);
188static void rl_mii_sync		(struct rl_softc *);
189static void rl_mii_send		(struct rl_softc *, u_int32_t, int);
190static int rl_mii_readreg	(struct rl_softc *, struct rl_mii_frame *);
191static int rl_mii_writereg	(struct rl_softc *, struct rl_mii_frame *);
192
193static int rl_miibus_readreg	(device_t, int, int);
194static int rl_miibus_writereg	(device_t, int, int, int);
195static void rl_miibus_statchg	(device_t);
196
197static u_int8_t rl_calchash	(caddr_t);
198static void rl_setmulti		(struct rl_softc *);
199static void rl_reset		(struct rl_softc *);
200static int rl_list_tx_init	(struct rl_softc *);
201
202static void rl_dma_map_rxbuf	(void *, bus_dma_segment_t *, int, int);
203static void rl_dma_map_txbuf	(void *, bus_dma_segment_t *, int, int);
204
205#ifdef RL_USEIOSPACE
206#define RL_RES			SYS_RES_IOPORT
207#define RL_RID			RL_PCI_LOIO
208#else
209#define RL_RES			SYS_RES_MEMORY
210#define RL_RID			RL_PCI_LOMEM
211#endif
212
213static device_method_t rl_methods[] = {
214	/* Device interface */
215	DEVMETHOD(device_probe,		rl_probe),
216	DEVMETHOD(device_attach,	rl_attach),
217	DEVMETHOD(device_detach,	rl_detach),
218	DEVMETHOD(device_suspend,	rl_suspend),
219	DEVMETHOD(device_resume,	rl_resume),
220	DEVMETHOD(device_shutdown,	rl_shutdown),
221
222	/* bus interface */
223	DEVMETHOD(bus_print_child,	bus_generic_print_child),
224	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
225
226	/* MII interface */
227	DEVMETHOD(miibus_readreg,	rl_miibus_readreg),
228	DEVMETHOD(miibus_writereg,	rl_miibus_writereg),
229	DEVMETHOD(miibus_statchg,	rl_miibus_statchg),
230
231	{ 0, 0 }
232};
233
234static driver_t rl_driver = {
235	"rl",
236	rl_methods,
237	sizeof(struct rl_softc)
238};
239
240static devclass_t rl_devclass;
241
242DRIVER_MODULE(if_rl, pci, rl_driver, rl_devclass, 0, 0);
243DRIVER_MODULE(if_rl, cardbus, rl_driver, rl_devclass, 0, 0);
244DRIVER_MODULE(miibus, rl, miibus_driver, miibus_devclass, 0, 0);
245
246#define EE_SET(x)					\
247	CSR_WRITE_1(sc, RL_EECMD,			\
248		CSR_READ_1(sc, RL_EECMD) | x)
249
250#define EE_CLR(x)					\
251	CSR_WRITE_1(sc, RL_EECMD,			\
252		CSR_READ_1(sc, RL_EECMD) & ~x)
253
254static void
255rl_dma_map_rxbuf(arg, segs, nseg, error)
256	void *arg;
257	bus_dma_segment_t *segs;
258	int nseg, error;
259{
260	struct rl_softc *sc;
261
262	sc = arg;
263	CSR_WRITE_4(sc, RL_RXADDR, segs->ds_addr & 0xFFFFFFFF);
264
265	return;
266}
267
268static void
269rl_dma_map_txbuf(arg, segs, nseg, error)
270	void *arg;
271	bus_dma_segment_t *segs;
272	int nseg, error;
273{
274	struct rl_softc *sc;
275
276	sc = arg;
277	CSR_WRITE_4(sc, RL_CUR_TXADDR(sc), segs->ds_addr & 0xFFFFFFFF);
278
279	return;
280}
281
282/*
283 * Send a read command and address to the EEPROM, check for ACK.
284 */
285static void
286rl_eeprom_putbyte(sc, addr)
287	struct rl_softc		*sc;
288	int			addr;
289{
290	register int		d, i;
291
292	d = addr | sc->rl_eecmd_read;
293
294	/*
295	 * Feed in each bit and strobe the clock.
296	 */
297	for (i = 0x400; i; i >>= 1) {
298		if (d & i) {
299			EE_SET(RL_EE_DATAIN);
300		} else {
301			EE_CLR(RL_EE_DATAIN);
302		}
303		DELAY(100);
304		EE_SET(RL_EE_CLK);
305		DELAY(150);
306		EE_CLR(RL_EE_CLK);
307		DELAY(100);
308	}
309
310	return;
311}
312
313/*
314 * Read a word of data stored in the EEPROM at address 'addr.'
315 */
316static void
317rl_eeprom_getword(sc, addr, dest)
318	struct rl_softc		*sc;
319	int			addr;
320	u_int16_t		*dest;
321{
322	register int		i;
323	u_int16_t		word = 0;
324
325	/* Enter EEPROM access mode. */
326	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
327
328	/*
329	 * Send address of word we want to read.
330	 */
331	rl_eeprom_putbyte(sc, addr);
332
333	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
334
335	/*
336	 * Start reading bits from EEPROM.
337	 */
338	for (i = 0x8000; i; i >>= 1) {
339		EE_SET(RL_EE_CLK);
340		DELAY(100);
341		if (CSR_READ_1(sc, RL_EECMD) & RL_EE_DATAOUT)
342			word |= i;
343		EE_CLR(RL_EE_CLK);
344		DELAY(100);
345	}
346
347	/* Turn off EEPROM access mode. */
348	CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
349
350	*dest = word;
351
352	return;
353}
354
355/*
356 * Read a sequence of words from the EEPROM.
357 */
358static void
359rl_read_eeprom(sc, dest, off, cnt, swap)
360	struct rl_softc		*sc;
361	caddr_t			dest;
362	int			off;
363	int			cnt;
364	int			swap;
365{
366	int			i;
367	u_int16_t		word = 0, *ptr;
368
369	for (i = 0; i < cnt; i++) {
370		rl_eeprom_getword(sc, off + i, &word);
371		ptr = (u_int16_t *)(dest + (i * 2));
372		if (swap)
373			*ptr = ntohs(word);
374		else
375			*ptr = word;
376	}
377
378	return;
379}
380
381
382/*
383 * MII access routines are provided for the 8129, which
384 * doesn't have a built-in PHY. For the 8139, we fake things
385 * up by diverting rl_phy_readreg()/rl_phy_writereg() to the
386 * direct access PHY registers.
387 */
388#define MII_SET(x)					\
389	CSR_WRITE_1(sc, RL_MII,				\
390		CSR_READ_1(sc, RL_MII) | (x))
391
392#define MII_CLR(x)					\
393	CSR_WRITE_1(sc, RL_MII,				\
394		CSR_READ_1(sc, RL_MII) & ~(x))
395
396/*
397 * Sync the PHYs by setting data bit and strobing the clock 32 times.
398 */
399static void
400rl_mii_sync(sc)
401	struct rl_softc		*sc;
402{
403	register int		i;
404
405	MII_SET(RL_MII_DIR|RL_MII_DATAOUT);
406
407	for (i = 0; i < 32; i++) {
408		MII_SET(RL_MII_CLK);
409		DELAY(1);
410		MII_CLR(RL_MII_CLK);
411		DELAY(1);
412	}
413
414	return;
415}
416
417/*
418 * Clock a series of bits through the MII.
419 */
420static void
421rl_mii_send(sc, bits, cnt)
422	struct rl_softc		*sc;
423	u_int32_t		bits;
424	int			cnt;
425{
426	int			i;
427
428	MII_CLR(RL_MII_CLK);
429
430	for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
431                if (bits & i) {
432			MII_SET(RL_MII_DATAOUT);
433                } else {
434			MII_CLR(RL_MII_DATAOUT);
435                }
436		DELAY(1);
437		MII_CLR(RL_MII_CLK);
438		DELAY(1);
439		MII_SET(RL_MII_CLK);
440	}
441}
442
443/*
444 * Read an PHY register through the MII.
445 */
446static int
447rl_mii_readreg(sc, frame)
448	struct rl_softc		*sc;
449	struct rl_mii_frame	*frame;
450
451{
452	int			i, ack;
453
454	RL_LOCK(sc);
455
456	/*
457	 * Set up frame for RX.
458	 */
459	frame->mii_stdelim = RL_MII_STARTDELIM;
460	frame->mii_opcode = RL_MII_READOP;
461	frame->mii_turnaround = 0;
462	frame->mii_data = 0;
463
464	CSR_WRITE_2(sc, RL_MII, 0);
465
466	/*
467 	 * Turn on data xmit.
468	 */
469	MII_SET(RL_MII_DIR);
470
471	rl_mii_sync(sc);
472
473	/*
474	 * Send command/address info.
475	 */
476	rl_mii_send(sc, frame->mii_stdelim, 2);
477	rl_mii_send(sc, frame->mii_opcode, 2);
478	rl_mii_send(sc, frame->mii_phyaddr, 5);
479	rl_mii_send(sc, frame->mii_regaddr, 5);
480
481	/* Idle bit */
482	MII_CLR((RL_MII_CLK|RL_MII_DATAOUT));
483	DELAY(1);
484	MII_SET(RL_MII_CLK);
485	DELAY(1);
486
487	/* Turn off xmit. */
488	MII_CLR(RL_MII_DIR);
489
490	/* Check for ack */
491	MII_CLR(RL_MII_CLK);
492	DELAY(1);
493	MII_SET(RL_MII_CLK);
494	DELAY(1);
495	ack = CSR_READ_2(sc, RL_MII) & RL_MII_DATAIN;
496
497	/*
498	 * Now try reading data bits. If the ack failed, we still
499	 * need to clock through 16 cycles to keep the PHY(s) in sync.
500	 */
501	if (ack) {
502		for(i = 0; i < 16; i++) {
503			MII_CLR(RL_MII_CLK);
504			DELAY(1);
505			MII_SET(RL_MII_CLK);
506			DELAY(1);
507		}
508		goto fail;
509	}
510
511	for (i = 0x8000; i; i >>= 1) {
512		MII_CLR(RL_MII_CLK);
513		DELAY(1);
514		if (!ack) {
515			if (CSR_READ_2(sc, RL_MII) & RL_MII_DATAIN)
516				frame->mii_data |= i;
517			DELAY(1);
518		}
519		MII_SET(RL_MII_CLK);
520		DELAY(1);
521	}
522
523fail:
524
525	MII_CLR(RL_MII_CLK);
526	DELAY(1);
527	MII_SET(RL_MII_CLK);
528	DELAY(1);
529
530	RL_UNLOCK(sc);
531
532	if (ack)
533		return(1);
534	return(0);
535}
536
537/*
538 * Write to a PHY register through the MII.
539 */
540static int
541rl_mii_writereg(sc, frame)
542	struct rl_softc		*sc;
543	struct rl_mii_frame	*frame;
544
545{
546	RL_LOCK(sc);
547
548	/*
549	 * Set up frame for TX.
550	 */
551
552	frame->mii_stdelim = RL_MII_STARTDELIM;
553	frame->mii_opcode = RL_MII_WRITEOP;
554	frame->mii_turnaround = RL_MII_TURNAROUND;
555
556	/*
557 	 * Turn on data output.
558	 */
559	MII_SET(RL_MII_DIR);
560
561	rl_mii_sync(sc);
562
563	rl_mii_send(sc, frame->mii_stdelim, 2);
564	rl_mii_send(sc, frame->mii_opcode, 2);
565	rl_mii_send(sc, frame->mii_phyaddr, 5);
566	rl_mii_send(sc, frame->mii_regaddr, 5);
567	rl_mii_send(sc, frame->mii_turnaround, 2);
568	rl_mii_send(sc, frame->mii_data, 16);
569
570	/* Idle bit. */
571	MII_SET(RL_MII_CLK);
572	DELAY(1);
573	MII_CLR(RL_MII_CLK);
574	DELAY(1);
575
576	/*
577	 * Turn off xmit.
578	 */
579	MII_CLR(RL_MII_DIR);
580
581	RL_UNLOCK(sc);
582
583	return(0);
584}
585
586static int
587rl_miibus_readreg(dev, phy, reg)
588	device_t		dev;
589	int			phy, reg;
590{
591	struct rl_softc		*sc;
592	struct rl_mii_frame	frame;
593	u_int16_t		rval = 0;
594	u_int16_t		rl8139_reg = 0;
595
596	sc = device_get_softc(dev);
597	RL_LOCK(sc);
598
599	if (sc->rl_type == RL_8139) {
600		/* Pretend the internal PHY is only at address 0 */
601		if (phy) {
602			RL_UNLOCK(sc);
603			return(0);
604		}
605		switch(reg) {
606		case MII_BMCR:
607			rl8139_reg = RL_BMCR;
608			break;
609		case MII_BMSR:
610			rl8139_reg = RL_BMSR;
611			break;
612		case MII_ANAR:
613			rl8139_reg = RL_ANAR;
614			break;
615		case MII_ANER:
616			rl8139_reg = RL_ANER;
617			break;
618		case MII_ANLPAR:
619			rl8139_reg = RL_LPAR;
620			break;
621		case MII_PHYIDR1:
622		case MII_PHYIDR2:
623			RL_UNLOCK(sc);
624			return(0);
625			break;
626		/*
627		 * Allow the rlphy driver to read the media status
628		 * register. If we have a link partner which does not
629		 * support NWAY, this is the register which will tell
630		 * us the results of parallel detection.
631		 */
632		case RL_MEDIASTAT:
633			rval = CSR_READ_1(sc, RL_MEDIASTAT);
634			RL_UNLOCK(sc);
635			return(rval);
636			break;
637		default:
638			printf("rl%d: bad phy register\n", sc->rl_unit);
639			RL_UNLOCK(sc);
640			return(0);
641		}
642		rval = CSR_READ_2(sc, rl8139_reg);
643		RL_UNLOCK(sc);
644		return(rval);
645	}
646
647	bzero((char *)&frame, sizeof(frame));
648
649	frame.mii_phyaddr = phy;
650	frame.mii_regaddr = reg;
651	rl_mii_readreg(sc, &frame);
652	RL_UNLOCK(sc);
653
654	return(frame.mii_data);
655}
656
657static int
658rl_miibus_writereg(dev, phy, reg, data)
659	device_t		dev;
660	int			phy, reg, data;
661{
662	struct rl_softc		*sc;
663	struct rl_mii_frame	frame;
664	u_int16_t		rl8139_reg = 0;
665
666	sc = device_get_softc(dev);
667	RL_LOCK(sc);
668
669	if (sc->rl_type == RL_8139) {
670		/* Pretend the internal PHY is only at address 0 */
671		if (phy) {
672			RL_UNLOCK(sc);
673			return(0);
674		}
675		switch(reg) {
676		case MII_BMCR:
677			rl8139_reg = RL_BMCR;
678			break;
679		case MII_BMSR:
680			rl8139_reg = RL_BMSR;
681			break;
682		case MII_ANAR:
683			rl8139_reg = RL_ANAR;
684			break;
685		case MII_ANER:
686			rl8139_reg = RL_ANER;
687			break;
688		case MII_ANLPAR:
689			rl8139_reg = RL_LPAR;
690			break;
691		case MII_PHYIDR1:
692		case MII_PHYIDR2:
693			RL_UNLOCK(sc);
694			return(0);
695			break;
696		default:
697			printf("rl%d: bad phy register\n", sc->rl_unit);
698			RL_UNLOCK(sc);
699			return(0);
700		}
701		CSR_WRITE_2(sc, rl8139_reg, data);
702		RL_UNLOCK(sc);
703		return(0);
704	}
705
706	bzero((char *)&frame, sizeof(frame));
707
708	frame.mii_phyaddr = phy;
709	frame.mii_regaddr = reg;
710	frame.mii_data = data;
711
712	rl_mii_writereg(sc, &frame);
713
714	RL_UNLOCK(sc);
715	return(0);
716}
717
718static void
719rl_miibus_statchg(dev)
720	device_t		dev;
721{
722	return;
723}
724
725/*
726 * Calculate CRC of a multicast group address, return the upper 6 bits.
727 */
728static u_int8_t
729rl_calchash(addr)
730	caddr_t			addr;
731{
732	u_int32_t		crc, carry;
733	int			i, j;
734	u_int8_t		c;
735
736	/* Compute CRC for the address value. */
737	crc = 0xFFFFFFFF; /* initial value */
738
739	for (i = 0; i < 6; i++) {
740		c = *(addr + i);
741		for (j = 0; j < 8; j++) {
742			carry = ((crc & 0x80000000) ? 1 : 0) ^ (c & 0x01);
743			crc <<= 1;
744			c >>= 1;
745			if (carry)
746				crc = (crc ^ 0x04c11db6) | carry;
747		}
748	}
749
750	/* return the filter bit position */
751	return(crc >> 26);
752}
753
754/*
755 * Program the 64-bit multicast hash filter.
756 */
757static void
758rl_setmulti(sc)
759	struct rl_softc		*sc;
760{
761	struct ifnet		*ifp;
762	int			h = 0;
763	u_int32_t		hashes[2] = { 0, 0 };
764	struct ifmultiaddr	*ifma;
765	u_int32_t		rxfilt;
766	int			mcnt = 0;
767
768	ifp = &sc->arpcom.ac_if;
769
770	rxfilt = CSR_READ_4(sc, RL_RXCFG);
771
772	if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
773		rxfilt |= RL_RXCFG_RX_MULTI;
774		CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
775		CSR_WRITE_4(sc, RL_MAR0, 0xFFFFFFFF);
776		CSR_WRITE_4(sc, RL_MAR4, 0xFFFFFFFF);
777		return;
778	}
779
780	/* first, zot all the existing hash bits */
781	CSR_WRITE_4(sc, RL_MAR0, 0);
782	CSR_WRITE_4(sc, RL_MAR4, 0);
783
784	/* now program new ones */
785	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
786		if (ifma->ifma_addr->sa_family != AF_LINK)
787			continue;
788		h = rl_calchash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
789		if (h < 32)
790			hashes[0] |= (1 << h);
791		else
792			hashes[1] |= (1 << (h - 32));
793		mcnt++;
794	}
795
796	if (mcnt)
797		rxfilt |= RL_RXCFG_RX_MULTI;
798	else
799		rxfilt &= ~RL_RXCFG_RX_MULTI;
800
801	CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
802	CSR_WRITE_4(sc, RL_MAR0, hashes[0]);
803	CSR_WRITE_4(sc, RL_MAR4, hashes[1]);
804
805	return;
806}
807
808static void
809rl_reset(sc)
810	struct rl_softc		*sc;
811{
812	register int		i;
813
814	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RESET);
815
816	for (i = 0; i < RL_TIMEOUT; i++) {
817		DELAY(10);
818		if (!(CSR_READ_1(sc, RL_COMMAND) & RL_CMD_RESET))
819			break;
820	}
821	if (i == RL_TIMEOUT)
822		printf("rl%d: reset never completed!\n", sc->rl_unit);
823
824        return;
825}
826
827/*
828 * Probe for a RealTek 8129/8139 chip. Check the PCI vendor and device
829 * IDs against our list and return a device name if we find a match.
830 */
831static int
832rl_probe(dev)
833	device_t		dev;
834{
835	struct rl_type		*t;
836
837	t = rl_devs;
838
839	while(t->rl_name != NULL) {
840		if ((pci_get_vendor(dev) == t->rl_vid) &&
841		    (pci_get_device(dev) == t->rl_did)) {
842			device_set_desc(dev, t->rl_name);
843			return(0);
844		}
845		t++;
846	}
847
848	return(ENXIO);
849}
850
851/*
852 * Attach the interface. Allocate softc structures, do ifmedia
853 * setup and ethernet/BPF attach.
854 */
855static int
856rl_attach(dev)
857	device_t		dev;
858{
859	u_char			eaddr[ETHER_ADDR_LEN];
860	u_int32_t		command;
861	struct rl_softc		*sc;
862	struct ifnet		*ifp;
863	u_int16_t		rl_did = 0;
864	int			unit, error = 0, rid;
865
866	sc = device_get_softc(dev);
867	unit = device_get_unit(dev);
868	bzero(sc, sizeof(struct rl_softc));
869
870	mtx_init(&sc->rl_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
871	    MTX_DEF | MTX_RECURSE);
872	RL_LOCK(sc);
873
874	/*
875	 * Handle power management nonsense.
876	 */
877
878	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
879		u_int32_t		iobase, membase, irq;
880
881		/* Save important PCI config data. */
882		iobase = pci_read_config(dev, RL_PCI_LOIO, 4);
883		membase = pci_read_config(dev, RL_PCI_LOMEM, 4);
884		irq = pci_read_config(dev, RL_PCI_INTLINE, 4);
885
886		/* Reset the power state. */
887		printf("rl%d: chip is is in D%d power mode "
888		    "-- setting to D0\n", unit,
889		    pci_get_powerstate(dev));
890
891		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
892
893		/* Restore PCI config data. */
894		pci_write_config(dev, RL_PCI_LOIO, iobase, 4);
895		pci_write_config(dev, RL_PCI_LOMEM, membase, 4);
896		pci_write_config(dev, RL_PCI_INTLINE, irq, 4);
897	}
898
899	/*
900	 * Map control/status registers.
901	 */
902	pci_enable_busmaster(dev);
903	pci_enable_io(dev, SYS_RES_IOPORT);
904	pci_enable_io(dev, SYS_RES_MEMORY);
905	command = pci_read_config(dev, PCIR_COMMAND, 4);
906
907#ifdef RL_USEIOSPACE
908	if (!(command & PCIM_CMD_PORTEN)) {
909		printf("rl%d: failed to enable I/O ports!\n", unit);
910		error = ENXIO;
911		goto fail;
912	}
913#else
914	if (!(command & PCIM_CMD_MEMEN)) {
915		printf("rl%d: failed to enable memory mapping!\n", unit);
916		error = ENXIO;
917		goto fail;
918	}
919#endif
920
921	rid = RL_RID;
922	sc->rl_res = bus_alloc_resource(dev, RL_RES, &rid,
923	    0, ~0, 1, RF_ACTIVE);
924
925	if (sc->rl_res == NULL) {
926		printf ("rl%d: couldn't map ports/memory\n", unit);
927		error = ENXIO;
928		goto fail;
929	}
930
931	/* Detect the Realtek 8139B. For some reason, this chip is very
932	 * unstable when left to autoselect the media
933	 * The best workaround is to set the device to the required
934	 * media type or to set it to the 10 Meg speed.
935	 */
936
937	if ((rman_get_end(sc->rl_res)-rman_get_start(sc->rl_res))==0xff) {
938		printf("rl%d: Realtek 8139B detected. Warning, this may be unstable in autoselect mode\n", unit);
939	}
940
941	sc->rl_btag = rman_get_bustag(sc->rl_res);
942	sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
943
944	rid = 0;
945	sc->rl_irq = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
946	    RF_SHAREABLE | RF_ACTIVE);
947
948	if (sc->rl_irq == NULL) {
949		printf("rl%d: couldn't map interrupt\n", unit);
950		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
951		error = ENXIO;
952		goto fail;
953	}
954
955	error = bus_setup_intr(dev, sc->rl_irq, INTR_TYPE_NET,
956	    rl_intr, sc, &sc->rl_intrhand);
957
958	if (error) {
959		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
960		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
961		printf("rl%d: couldn't set up irq\n", unit);
962		goto fail;
963	}
964
965	callout_handle_init(&sc->rl_stat_ch);
966
967	/* Reset the adapter. */
968	rl_reset(sc);
969	sc->rl_eecmd_read = RL_EECMD_READ_6BIT;
970	rl_read_eeprom(sc, (caddr_t)&rl_did, 0, 1, 0);
971	if (rl_did != 0x8129)
972		sc->rl_eecmd_read = RL_EECMD_READ_8BIT;
973
974	/*
975	 * Get station address from the EEPROM.
976	 */
977	rl_read_eeprom(sc, (caddr_t)&eaddr, RL_EE_EADDR, 3, 0);
978
979	/*
980	 * A RealTek chip was detected. Inform the world.
981	 */
982	printf("rl%d: Ethernet address: %6D\n", unit, eaddr, ":");
983
984	sc->rl_unit = unit;
985	bcopy(eaddr, (char *)&sc->arpcom.ac_enaddr, ETHER_ADDR_LEN);
986
987	/*
988	 * Now read the exact device type from the EEPROM to find
989	 * out if it's an 8129 or 8139.
990	 */
991	rl_read_eeprom(sc, (caddr_t)&rl_did, RL_EE_PCI_DID, 1, 0);
992
993	if (rl_did == RT_DEVICEID_8139 || rl_did == ACCTON_DEVICEID_5030 ||
994	    rl_did == DELTA_DEVICEID_8139 || rl_did == ADDTRON_DEVICEID_8139 ||
995	    rl_did == RT_DEVICEID_8138 || rl_did == DLINK_DEVICEID_530TXPLUS ||
996	    rl_did == DLINK_DEVICEID_690TXD || rl_did == COREGA_DEVICEID_CBTXD)
997		sc->rl_type = RL_8139;
998	else if (rl_did == RT_DEVICEID_8129)
999		sc->rl_type = RL_8129;
1000	else {
1001		printf("rl%d: unknown device ID: %x\n", unit, rl_did);
1002		bus_teardown_intr(dev, sc->rl_irq, sc->rl_intrhand);
1003		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
1004		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1005		error = ENXIO;
1006		goto fail;
1007	}
1008
1009	/*
1010	 * Allocate the parent bus DMA tag appropriate for PCI.
1011	 */
1012#define RL_NSEG_NEW 32
1013	error = bus_dma_tag_create(NULL,	/* parent */
1014			1, 0,			/* alignment, boundary */
1015			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1016			BUS_SPACE_MAXADDR,	/* highaddr */
1017			NULL, NULL,		/* filter, filterarg */
1018			MAXBSIZE, RL_NSEG_NEW,	/* maxsize, nsegments */
1019			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1020			BUS_DMA_ALLOCNOW,	/* flags */
1021			&sc->rl_parent_tag);
1022
1023	/*
1024	 * Now allocate a tag for the DMA descriptor lists.
1025	 * All of our lists are allocated as a contiguous block
1026	 * of memory.
1027	 */
1028	error = bus_dma_tag_create(sc->rl_parent_tag,	/* parent */
1029			1, 0,			/* alignment, boundary */
1030			BUS_SPACE_MAXADDR,	/* lowaddr */
1031			BUS_SPACE_MAXADDR,	/* highaddr */
1032			NULL, NULL,		/* filter, filterarg */
1033			RL_RXBUFLEN + 1518, 1,	/* maxsize,nsegments */
1034			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1035			0,			/* flags */
1036			&sc->rl_tag);
1037
1038	/*
1039	 * Now allocate a chunk of DMA-able memory based on the
1040	 * tag we just created.
1041	 */
1042	error = bus_dmamem_alloc(sc->rl_tag,
1043	    (void **)&sc->rl_cdata.rl_rx_buf, BUS_DMA_NOWAIT,
1044	    &sc->rl_cdata.rl_rx_dmamap);
1045
1046	if (sc->rl_cdata.rl_rx_buf == NULL) {
1047		printf("rl%d: no memory for list buffers!\n", unit);
1048		bus_teardown_intr(dev, sc->rl_irq, sc->rl_intrhand);
1049		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
1050		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1051		bus_dma_tag_destroy(sc->rl_tag);
1052		error = ENXIO;
1053		goto fail;
1054	}
1055
1056	/* Leave a few bytes before the start of the RX ring buffer. */
1057	sc->rl_cdata.rl_rx_buf_ptr = sc->rl_cdata.rl_rx_buf;
1058	sc->rl_cdata.rl_rx_buf += sizeof(u_int64_t);
1059
1060	/* Do MII setup */
1061	if (mii_phy_probe(dev, &sc->rl_miibus,
1062	    rl_ifmedia_upd, rl_ifmedia_sts)) {
1063		printf("rl%d: MII without any phy!\n", sc->rl_unit);
1064		bus_teardown_intr(dev, sc->rl_irq, sc->rl_intrhand);
1065		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
1066		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1067		bus_dmamem_free(sc->rl_tag,
1068		    sc->rl_cdata.rl_rx_buf, sc->rl_cdata.rl_rx_dmamap);
1069		bus_dma_tag_destroy(sc->rl_tag);
1070		error = ENXIO;
1071		goto fail;
1072	}
1073
1074	ifp = &sc->arpcom.ac_if;
1075	ifp->if_softc = sc;
1076	ifp->if_unit = unit;
1077	ifp->if_name = "rl";
1078	ifp->if_mtu = ETHERMTU;
1079	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1080	ifp->if_ioctl = rl_ioctl;
1081	ifp->if_output = ether_output;
1082	ifp->if_start = rl_start;
1083	ifp->if_watchdog = rl_watchdog;
1084	ifp->if_init = rl_init;
1085	ifp->if_baudrate = 10000000;
1086	ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
1087
1088	/*
1089	 * Call MI attach routine.
1090	 */
1091	ether_ifattach(ifp, ETHER_BPF_SUPPORTED);
1092	RL_UNLOCK(sc);
1093	return(0);
1094
1095fail:
1096	RL_UNLOCK(sc);
1097	mtx_destroy(&sc->rl_mtx);
1098	return(error);
1099}
1100
1101static int
1102rl_detach(dev)
1103	device_t		dev;
1104{
1105	struct rl_softc		*sc;
1106	struct ifnet		*ifp;
1107
1108	sc = device_get_softc(dev);
1109	RL_LOCK(sc);
1110	ifp = &sc->arpcom.ac_if;
1111
1112	ether_ifdetach(ifp, ETHER_BPF_SUPPORTED);
1113	rl_stop(sc);
1114
1115	bus_generic_detach(dev);
1116	device_delete_child(dev, sc->rl_miibus);
1117
1118	bus_teardown_intr(dev, sc->rl_irq, sc->rl_intrhand);
1119	bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq);
1120	bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1121
1122	bus_dmamap_unload(sc->rl_tag, sc->rl_cdata.rl_rx_dmamap);
1123	bus_dmamem_free(sc->rl_tag, sc->rl_cdata.rl_rx_buf,
1124	    sc->rl_cdata.rl_rx_dmamap);
1125	bus_dma_tag_destroy(sc->rl_tag);
1126	bus_dma_tag_destroy(sc->rl_parent_tag);
1127
1128	RL_UNLOCK(sc);
1129	mtx_destroy(&sc->rl_mtx);
1130
1131	return(0);
1132}
1133
1134/*
1135 * Initialize the transmit descriptors.
1136 */
1137static int
1138rl_list_tx_init(sc)
1139	struct rl_softc		*sc;
1140{
1141	struct rl_chain_data	*cd;
1142	int			i;
1143
1144	cd = &sc->rl_cdata;
1145	for (i = 0; i < RL_TX_LIST_CNT; i++) {
1146		cd->rl_tx_chain[i] = NULL;
1147		CSR_WRITE_4(sc,
1148		    RL_TXADDR0 + (i * sizeof(u_int32_t)), 0x0000000);
1149	}
1150
1151	sc->rl_cdata.cur_tx = 0;
1152	sc->rl_cdata.last_tx = 0;
1153
1154	return(0);
1155}
1156
1157/*
1158 * A frame has been uploaded: pass the resulting mbuf chain up to
1159 * the higher level protocols.
1160 *
1161 * You know there's something wrong with a PCI bus-master chip design
1162 * when you have to use m_devget().
1163 *
1164 * The receive operation is badly documented in the datasheet, so I'll
1165 * attempt to document it here. The driver provides a buffer area and
1166 * places its base address in the RX buffer start address register.
1167 * The chip then begins copying frames into the RX buffer. Each frame
1168 * is preceded by a 32-bit RX status word which specifies the length
1169 * of the frame and certain other status bits. Each frame (starting with
1170 * the status word) is also 32-bit aligned. The frame length is in the
1171 * first 16 bits of the status word; the lower 15 bits correspond with
1172 * the 'rx status register' mentioned in the datasheet.
1173 *
1174 * Note: to make the Alpha happy, the frame payload needs to be aligned
1175 * on a 32-bit boundary. To achieve this, we pass RL_ETHER_ALIGN (2 bytes)
1176 * as the offset argument to m_devget().
1177 */
1178static void
1179rl_rxeof(sc)
1180	struct rl_softc		*sc;
1181{
1182        struct ether_header	*eh;
1183        struct mbuf		*m;
1184        struct ifnet		*ifp;
1185	int			total_len = 0;
1186	u_int32_t		rxstat;
1187	caddr_t			rxbufpos;
1188	int			wrap = 0;
1189	u_int16_t		cur_rx;
1190	u_int16_t		limit;
1191	u_int16_t		rx_bytes = 0, max_bytes;
1192
1193	ifp = &sc->arpcom.ac_if;
1194
1195	bus_dmamap_sync(sc->rl_tag, sc->rl_cdata.rl_rx_dmamap,
1196	    BUS_DMASYNC_POSTWRITE);
1197
1198	cur_rx = (CSR_READ_2(sc, RL_CURRXADDR) + 16) % RL_RXBUFLEN;
1199
1200	/* Do not try to read past this point. */
1201	limit = CSR_READ_2(sc, RL_CURRXBUF) % RL_RXBUFLEN;
1202
1203	if (limit < cur_rx)
1204		max_bytes = (RL_RXBUFLEN - cur_rx) + limit;
1205	else
1206		max_bytes = limit - cur_rx;
1207
1208	while((CSR_READ_1(sc, RL_COMMAND) & RL_CMD_EMPTY_RXBUF) == 0) {
1209#ifdef DEVICE_POLLING
1210		if (ifp->if_flags & IFF_POLLING) {
1211			if (sc->rxcycles <= 0)
1212				break;
1213			sc->rxcycles--;
1214		}
1215#endif /* DEVICE_POLLING */
1216		rxbufpos = sc->rl_cdata.rl_rx_buf + cur_rx;
1217		rxstat = *(u_int32_t *)rxbufpos;
1218
1219		/*
1220		 * Here's a totally undocumented fact for you. When the
1221		 * RealTek chip is in the process of copying a packet into
1222		 * RAM for you, the length will be 0xfff0. If you spot a
1223		 * packet header with this value, you need to stop. The
1224		 * datasheet makes absolutely no mention of this and
1225		 * RealTek should be shot for this.
1226		 */
1227		if ((u_int16_t)(rxstat >> 16) == RL_RXSTAT_UNFINISHED)
1228			break;
1229
1230		if (!(rxstat & RL_RXSTAT_RXOK)) {
1231			ifp->if_ierrors++;
1232			rl_init(sc);
1233			return;
1234		}
1235
1236		/* No errors; receive the packet. */
1237		total_len = rxstat >> 16;
1238		rx_bytes += total_len + 4;
1239
1240		/*
1241		 * XXX The RealTek chip includes the CRC with every
1242		 * received frame, and there's no way to turn this
1243		 * behavior off (at least, I can't find anything in
1244	 	 * the manual that explains how to do it) so we have
1245		 * to trim off the CRC manually.
1246		 */
1247		total_len -= ETHER_CRC_LEN;
1248
1249		/*
1250		 * Avoid trying to read more bytes than we know
1251		 * the chip has prepared for us.
1252		 */
1253		if (rx_bytes > max_bytes)
1254			break;
1255
1256		rxbufpos = sc->rl_cdata.rl_rx_buf +
1257			((cur_rx + sizeof(u_int32_t)) % RL_RXBUFLEN);
1258
1259		if (rxbufpos == (sc->rl_cdata.rl_rx_buf + RL_RXBUFLEN))
1260			rxbufpos = sc->rl_cdata.rl_rx_buf;
1261
1262		wrap = (sc->rl_cdata.rl_rx_buf + RL_RXBUFLEN) - rxbufpos;
1263
1264		if (total_len > wrap) {
1265			m = m_devget(rxbufpos, total_len, RL_ETHER_ALIGN, ifp,
1266			    NULL);
1267			if (m == NULL) {
1268				ifp->if_ierrors++;
1269			} else {
1270				m_copyback(m, wrap, total_len - wrap,
1271					sc->rl_cdata.rl_rx_buf);
1272			}
1273			cur_rx = (total_len - wrap + ETHER_CRC_LEN);
1274		} else {
1275			m = m_devget(rxbufpos, total_len, RL_ETHER_ALIGN, ifp,
1276			    NULL);
1277			if (m == NULL) {
1278				ifp->if_ierrors++;
1279			}
1280			cur_rx += total_len + 4 + ETHER_CRC_LEN;
1281		}
1282
1283		/*
1284		 * Round up to 32-bit boundary.
1285		 */
1286		cur_rx = (cur_rx + 3) & ~3;
1287		CSR_WRITE_2(sc, RL_CURRXADDR, cur_rx - 16);
1288
1289		if (m == NULL)
1290			continue;
1291
1292		eh = mtod(m, struct ether_header *);
1293		ifp->if_ipackets++;
1294
1295		/* Remove header from mbuf and pass it on. */
1296		m_adj(m, sizeof(struct ether_header));
1297		ether_input(ifp, eh, m);
1298	}
1299
1300	return;
1301}
1302
1303/*
1304 * A frame was downloaded to the chip. It's safe for us to clean up
1305 * the list buffers.
1306 */
1307static void
1308rl_txeof(sc)
1309	struct rl_softc		*sc;
1310{
1311	struct ifnet		*ifp;
1312	u_int32_t		txstat;
1313
1314	ifp = &sc->arpcom.ac_if;
1315
1316	/*
1317	 * Go through our tx list and free mbufs for those
1318	 * frames that have been uploaded.
1319	 */
1320	do {
1321		txstat = CSR_READ_4(sc, RL_LAST_TXSTAT(sc));
1322		if (!(txstat & (RL_TXSTAT_TX_OK|
1323		    RL_TXSTAT_TX_UNDERRUN|RL_TXSTAT_TXABRT)))
1324			break;
1325
1326		ifp->if_collisions += (txstat & RL_TXSTAT_COLLCNT) >> 24;
1327
1328		if (RL_LAST_TXMBUF(sc) != NULL) {
1329			bus_dmamap_unload(sc->rl_tag, RL_LAST_DMAMAP(sc));
1330			bus_dmamap_destroy(sc->rl_tag, RL_LAST_DMAMAP(sc));
1331			m_freem(RL_LAST_TXMBUF(sc));
1332			RL_LAST_TXMBUF(sc) = NULL;
1333		}
1334		if (txstat & RL_TXSTAT_TX_OK)
1335			ifp->if_opackets++;
1336		else {
1337			int			oldthresh;
1338			ifp->if_oerrors++;
1339			if ((txstat & RL_TXSTAT_TXABRT) ||
1340			    (txstat & RL_TXSTAT_OUTOFWIN))
1341				CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
1342			oldthresh = sc->rl_txthresh;
1343			/* error recovery */
1344			rl_reset(sc);
1345			rl_init(sc);
1346			/*
1347			 * If there was a transmit underrun,
1348			 * bump the TX threshold.
1349			 */
1350			if (txstat & RL_TXSTAT_TX_UNDERRUN)
1351				sc->rl_txthresh = oldthresh + 32;
1352			return;
1353		}
1354		RL_INC(sc->rl_cdata.last_tx);
1355		ifp->if_flags &= ~IFF_OACTIVE;
1356	} while (sc->rl_cdata.last_tx != sc->rl_cdata.cur_tx);
1357
1358	ifp->if_timer =
1359	    (sc->rl_cdata.last_tx == sc->rl_cdata.cur_tx) ? 0 : 5;
1360
1361	return;
1362}
1363
1364static void
1365rl_tick(xsc)
1366	void			*xsc;
1367{
1368	struct rl_softc		*sc;
1369	struct mii_data		*mii;
1370
1371	sc = xsc;
1372	RL_LOCK(sc);
1373	mii = device_get_softc(sc->rl_miibus);
1374
1375	mii_tick(mii);
1376
1377	sc->rl_stat_ch = timeout(rl_tick, sc, hz);
1378	RL_UNLOCK(sc);
1379
1380	return;
1381}
1382
1383#ifdef DEVICE_POLLING
1384static void
1385rl_poll (struct ifnet *ifp, enum poll_cmd cmd, int count)
1386{
1387	struct rl_softc *sc = ifp->if_softc;
1388
1389	RL_LOCK(sc);
1390	if (cmd == POLL_DEREGISTER) { /* final call, enable interrupts */
1391		CSR_WRITE_2(sc, RL_IMR, RL_INTRS);
1392		goto done;
1393	}
1394
1395	sc->rxcycles = count;
1396	rl_rxeof(sc);
1397	rl_txeof(sc);
1398	if (ifp->if_snd.ifq_head != NULL)
1399		rl_start(ifp);
1400
1401	if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1402		u_int16_t       status;
1403
1404		status = CSR_READ_2(sc, RL_ISR);
1405		if (status == 0xffff)
1406			goto done;
1407		if (status)
1408			CSR_WRITE_2(sc, RL_ISR, status);
1409
1410		/*
1411		 * XXX check behaviour on receiver stalls.
1412		 */
1413
1414		if (status & RL_ISR_SYSTEM_ERR) {
1415			rl_reset(sc);
1416			rl_init(sc);
1417		}
1418	}
1419done:
1420	RL_UNLOCK(sc);
1421}
1422#endif /* DEVICE_POLLING */
1423
1424static void
1425rl_intr(arg)
1426	void			*arg;
1427{
1428	struct rl_softc		*sc;
1429	struct ifnet		*ifp;
1430	u_int16_t		status;
1431
1432	sc = arg;
1433
1434	if (sc->suspended) {
1435		return;
1436	}
1437
1438	RL_LOCK(sc);
1439	ifp = &sc->arpcom.ac_if;
1440
1441#ifdef DEVICE_POLLING
1442	if  (ifp->if_flags & IFF_POLLING)
1443		goto done;
1444	if (ether_poll_register(rl_poll, ifp)) { /* ok, disable interrupts */
1445		CSR_WRITE_2(sc, RL_IMR, 0x0000);
1446		rl_poll(ifp, 0, 1);
1447		goto done;
1448	}
1449#endif /* DEVICE_POLLING */
1450
1451	for (;;) {
1452
1453		status = CSR_READ_2(sc, RL_ISR);
1454		/* If the card has gone away the read returns 0xffff. */
1455		if (status == 0xffff)
1456			break;
1457		if (status)
1458			CSR_WRITE_2(sc, RL_ISR, status);
1459
1460		if ((status & RL_INTRS) == 0)
1461			break;
1462
1463		if (status & RL_ISR_RX_OK)
1464			rl_rxeof(sc);
1465
1466		if (status & RL_ISR_RX_ERR)
1467			rl_rxeof(sc);
1468
1469		if ((status & RL_ISR_TX_OK) || (status & RL_ISR_TX_ERR))
1470			rl_txeof(sc);
1471
1472		if (status & RL_ISR_SYSTEM_ERR) {
1473			rl_reset(sc);
1474			rl_init(sc);
1475		}
1476
1477	}
1478
1479	if (ifp->if_snd.ifq_head != NULL)
1480		rl_start(ifp);
1481
1482#ifdef DEVICE_POLLING
1483done:
1484#endif
1485	RL_UNLOCK(sc);
1486
1487	return;
1488}
1489
1490/*
1491 * Encapsulate an mbuf chain in a descriptor by coupling the mbuf data
1492 * pointers to the fragment pointers.
1493 */
1494static int
1495rl_encap(sc, m_head)
1496	struct rl_softc		*sc;
1497	struct mbuf		*m_head;
1498{
1499	struct mbuf		*m_new = NULL;
1500
1501	/*
1502	 * The RealTek is brain damaged and wants longword-aligned
1503	 * TX buffers, plus we can only have one fragment buffer
1504	 * per packet. We have to copy pretty much all the time.
1505	 */
1506
1507	MGETHDR(m_new, M_DONTWAIT, MT_DATA);
1508	if (m_new == NULL)
1509		return(1);
1510	if (m_head->m_pkthdr.len > MHLEN) {
1511		MCLGET(m_new, M_DONTWAIT);
1512		if (!(m_new->m_flags & M_EXT)) {
1513			m_freem(m_new);
1514			return(1);
1515		}
1516	}
1517	m_copydata(m_head, 0, m_head->m_pkthdr.len, mtod(m_new, caddr_t));
1518	m_new->m_pkthdr.len = m_new->m_len = m_head->m_pkthdr.len;
1519	m_freem(m_head);
1520	m_head = m_new;
1521
1522	/* Pad frames to at least 60 bytes. */
1523	if (m_head->m_pkthdr.len < RL_MIN_FRAMELEN) {
1524		/*
1525		 * Make security concious people happy: zero out the
1526		 * bytes in the pad area, since we don't know what
1527		 * this mbuf cluster buffer's previous user might
1528		 * have left in it.
1529	 	 */
1530		bzero(mtod(m_head, char *) + m_head->m_pkthdr.len,
1531		     RL_MIN_FRAMELEN - m_head->m_pkthdr.len);
1532		m_head->m_pkthdr.len +=
1533		    (RL_MIN_FRAMELEN - m_head->m_pkthdr.len);
1534		m_head->m_len = m_head->m_pkthdr.len;
1535	}
1536
1537	RL_CUR_TXMBUF(sc) = m_head;
1538
1539	return(0);
1540}
1541
1542/*
1543 * Main transmit routine.
1544 */
1545
1546static void
1547rl_start(ifp)
1548	struct ifnet		*ifp;
1549{
1550	struct rl_softc		*sc;
1551	struct mbuf		*m_head = NULL;
1552
1553	sc = ifp->if_softc;
1554	RL_LOCK(sc);
1555
1556	while(RL_CUR_TXMBUF(sc) == NULL) {
1557		IF_DEQUEUE(&ifp->if_snd, m_head);
1558		if (m_head == NULL)
1559			break;
1560
1561		if (rl_encap(sc, m_head)) {
1562			IF_PREPEND(&ifp->if_snd, m_head);
1563			ifp->if_flags |= IFF_OACTIVE;
1564			break;
1565		}
1566
1567		/*
1568		 * If there's a BPF listener, bounce a copy of this frame
1569		 * to him.
1570		 */
1571		if (ifp->if_bpf)
1572			bpf_mtap(ifp, RL_CUR_TXMBUF(sc));
1573
1574		/*
1575		 * Transmit the frame.
1576	 	 */
1577		bus_dmamap_create(sc->rl_tag, 0, &RL_CUR_DMAMAP(sc));
1578		bus_dmamap_load(sc->rl_tag, RL_CUR_DMAMAP(sc),
1579		    mtod(RL_CUR_TXMBUF(sc), void *),
1580		    RL_CUR_TXMBUF(sc)->m_pkthdr.len, rl_dma_map_txbuf, sc, 0);
1581		bus_dmamap_sync(sc->rl_tag, RL_CUR_DMAMAP(sc),
1582		    BUS_DMASYNC_PREREAD);
1583		CSR_WRITE_4(sc, RL_CUR_TXSTAT(sc),
1584		    RL_TXTHRESH(sc->rl_txthresh) |
1585		    RL_CUR_TXMBUF(sc)->m_pkthdr.len);
1586
1587		RL_INC(sc->rl_cdata.cur_tx);
1588	}
1589
1590	/*
1591	 * We broke out of the loop because all our TX slots are
1592	 * full. Mark the NIC as busy until it drains some of the
1593	 * packets from the queue.
1594	 */
1595	if (RL_CUR_TXMBUF(sc) != NULL)
1596		ifp->if_flags |= IFF_OACTIVE;
1597
1598	/*
1599	 * Set a timeout in case the chip goes out to lunch.
1600	 */
1601	ifp->if_timer = 5;
1602	RL_UNLOCK(sc);
1603
1604	return;
1605}
1606
1607static void
1608rl_init(xsc)
1609	void			*xsc;
1610{
1611	struct rl_softc		*sc = xsc;
1612	struct ifnet		*ifp = &sc->arpcom.ac_if;
1613	struct mii_data		*mii;
1614	int			i;
1615	u_int32_t		rxcfg = 0;
1616
1617	RL_LOCK(sc);
1618	mii = device_get_softc(sc->rl_miibus);
1619
1620	/*
1621	 * Cancel pending I/O and free all RX/TX buffers.
1622	 */
1623	rl_stop(sc);
1624
1625	/* Init our MAC address */
1626	for (i = 0; i < ETHER_ADDR_LEN; i++) {
1627		CSR_WRITE_1(sc, RL_IDR0 + i, sc->arpcom.ac_enaddr[i]);
1628	}
1629
1630	/* Init the RX buffer pointer register. */
1631	bus_dmamap_load(sc->rl_tag, sc->rl_cdata.rl_rx_dmamap,
1632	    sc->rl_cdata.rl_rx_buf, RL_RXBUFLEN, rl_dma_map_rxbuf, sc, 0);
1633	bus_dmamap_sync(sc->rl_tag, sc->rl_cdata.rl_rx_dmamap,
1634	    BUS_DMASYNC_PREWRITE);
1635
1636	/* Init TX descriptors. */
1637	rl_list_tx_init(sc);
1638
1639	/*
1640	 * Enable transmit and receive.
1641	 */
1642	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
1643
1644	/*
1645	 * Set the initial TX and RX configuration.
1646	 */
1647	CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
1648	CSR_WRITE_4(sc, RL_RXCFG, RL_RXCFG_CONFIG);
1649
1650	/* Set the individual bit to receive frames for this host only. */
1651	rxcfg = CSR_READ_4(sc, RL_RXCFG);
1652	rxcfg |= RL_RXCFG_RX_INDIV;
1653
1654	/* If we want promiscuous mode, set the allframes bit. */
1655	if (ifp->if_flags & IFF_PROMISC) {
1656		rxcfg |= RL_RXCFG_RX_ALLPHYS;
1657		CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1658	} else {
1659		rxcfg &= ~RL_RXCFG_RX_ALLPHYS;
1660		CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1661	}
1662
1663	/*
1664	 * Set capture broadcast bit to capture broadcast frames.
1665	 */
1666	if (ifp->if_flags & IFF_BROADCAST) {
1667		rxcfg |= RL_RXCFG_RX_BROAD;
1668		CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1669	} else {
1670		rxcfg &= ~RL_RXCFG_RX_BROAD;
1671		CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1672	}
1673
1674	/*
1675	 * Program the multicast filter, if necessary.
1676	 */
1677	rl_setmulti(sc);
1678
1679#ifdef DEVICE_POLLING
1680	/*
1681	 * Disable interrupts if we are polling.
1682	 */
1683	if (ifp->if_flags & IFF_POLLING)
1684		CSR_WRITE_2(sc, RL_IMR, 0);
1685	else	/* otherwise ... */
1686#endif /* DEVICE_POLLING */
1687	/*
1688	 * Enable interrupts.
1689	 */
1690	CSR_WRITE_2(sc, RL_IMR, RL_INTRS);
1691
1692	/* Set initial TX threshold */
1693	sc->rl_txthresh = RL_TX_THRESH_INIT;
1694
1695	/* Start RX/TX process. */
1696	CSR_WRITE_4(sc, RL_MISSEDPKT, 0);
1697
1698	/* Enable receiver and transmitter. */
1699	CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
1700
1701	mii_mediachg(mii);
1702
1703	CSR_WRITE_1(sc, RL_CFG1, RL_CFG1_DRVLOAD|RL_CFG1_FULLDUPLEX);
1704
1705	ifp->if_flags |= IFF_RUNNING;
1706	ifp->if_flags &= ~IFF_OACTIVE;
1707
1708	sc->rl_stat_ch = timeout(rl_tick, sc, hz);
1709	RL_UNLOCK(sc);
1710
1711	return;
1712}
1713
1714/*
1715 * Set media options.
1716 */
1717static int
1718rl_ifmedia_upd(ifp)
1719	struct ifnet		*ifp;
1720{
1721	struct rl_softc		*sc;
1722	struct mii_data		*mii;
1723
1724	sc = ifp->if_softc;
1725	mii = device_get_softc(sc->rl_miibus);
1726	mii_mediachg(mii);
1727
1728	return(0);
1729}
1730
1731/*
1732 * Report current media status.
1733 */
1734static void
1735rl_ifmedia_sts(ifp, ifmr)
1736	struct ifnet		*ifp;
1737	struct ifmediareq	*ifmr;
1738{
1739	struct rl_softc		*sc;
1740	struct mii_data		*mii;
1741
1742	sc = ifp->if_softc;
1743	mii = device_get_softc(sc->rl_miibus);
1744
1745	mii_pollstat(mii);
1746	ifmr->ifm_active = mii->mii_media_active;
1747	ifmr->ifm_status = mii->mii_media_status;
1748
1749	return;
1750}
1751
1752static int
1753rl_ioctl(ifp, command, data)
1754	struct ifnet		*ifp;
1755	u_long			command;
1756	caddr_t			data;
1757{
1758	struct rl_softc		*sc = ifp->if_softc;
1759	struct ifreq		*ifr = (struct ifreq *) data;
1760	struct mii_data		*mii;
1761	int			error = 0;
1762
1763	RL_LOCK(sc);
1764
1765	switch(command) {
1766	case SIOCSIFADDR:
1767	case SIOCGIFADDR:
1768	case SIOCSIFMTU:
1769		error = ether_ioctl(ifp, command, data);
1770		break;
1771	case SIOCSIFFLAGS:
1772		if (ifp->if_flags & IFF_UP) {
1773			rl_init(sc);
1774		} else {
1775			if (ifp->if_flags & IFF_RUNNING)
1776				rl_stop(sc);
1777		}
1778		error = 0;
1779		break;
1780	case SIOCADDMULTI:
1781	case SIOCDELMULTI:
1782		rl_setmulti(sc);
1783		error = 0;
1784		break;
1785	case SIOCGIFMEDIA:
1786	case SIOCSIFMEDIA:
1787		mii = device_get_softc(sc->rl_miibus);
1788		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
1789		break;
1790	default:
1791		error = EINVAL;
1792		break;
1793	}
1794
1795	RL_UNLOCK(sc);
1796
1797	return(error);
1798}
1799
1800static void
1801rl_watchdog(ifp)
1802	struct ifnet		*ifp;
1803{
1804	struct rl_softc		*sc;
1805
1806	sc = ifp->if_softc;
1807	RL_LOCK(sc);
1808	printf("rl%d: watchdog timeout\n", sc->rl_unit);
1809	ifp->if_oerrors++;
1810
1811	rl_txeof(sc);
1812	rl_rxeof(sc);
1813	rl_init(sc);
1814	RL_UNLOCK(sc);
1815
1816	return;
1817}
1818
1819/*
1820 * Stop the adapter and free any mbufs allocated to the
1821 * RX and TX lists.
1822 */
1823static void
1824rl_stop(sc)
1825	struct rl_softc		*sc;
1826{
1827	register int		i;
1828	struct ifnet		*ifp;
1829
1830	RL_LOCK(sc);
1831	ifp = &sc->arpcom.ac_if;
1832	ifp->if_timer = 0;
1833
1834	untimeout(rl_tick, sc, sc->rl_stat_ch);
1835	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1836#ifdef DEVICE_POLLING
1837	ether_poll_deregister(ifp);
1838#endif /* DEVICE_POLLING */
1839
1840	CSR_WRITE_1(sc, RL_COMMAND, 0x00);
1841	CSR_WRITE_2(sc, RL_IMR, 0x0000);
1842	bus_dmamap_unload(sc->rl_tag, sc->rl_cdata.rl_rx_dmamap);
1843
1844	/*
1845	 * Free the TX list buffers.
1846	 */
1847	for (i = 0; i < RL_TX_LIST_CNT; i++) {
1848		if (sc->rl_cdata.rl_tx_chain[i] != NULL) {
1849			bus_dmamap_unload(sc->rl_tag,
1850			    sc->rl_cdata.rl_tx_dmamap[i]);
1851			bus_dmamap_destroy(sc->rl_tag,
1852			    sc->rl_cdata.rl_tx_dmamap[i]);
1853			m_freem(sc->rl_cdata.rl_tx_chain[i]);
1854			sc->rl_cdata.rl_tx_chain[i] = NULL;
1855			CSR_WRITE_4(sc, RL_TXADDR0 + i, 0x0000000);
1856		}
1857	}
1858
1859	RL_UNLOCK(sc);
1860	return;
1861}
1862
1863/*
1864 * Device suspend routine.  Stop the interface and save some PCI
1865 * settings in case the BIOS doesn't restore them properly on
1866 * resume.
1867 */
1868static int
1869rl_suspend(dev)
1870	device_t		dev;
1871{
1872	register int		i;
1873	struct rl_softc		*sc;
1874
1875	sc = device_get_softc(dev);
1876
1877	rl_stop(sc);
1878
1879	for (i = 0; i < 5; i++)
1880		sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
1881	sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
1882	sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
1883	sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
1884	sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
1885
1886	sc->suspended = 1;
1887
1888	return (0);
1889}
1890
1891/*
1892 * Device resume routine.  Restore some PCI settings in case the BIOS
1893 * doesn't, re-enable busmastering, and restart the interface if
1894 * appropriate.
1895 */
1896static int
1897rl_resume(dev)
1898	device_t		dev;
1899{
1900	register int		i;
1901	struct rl_softc		*sc;
1902	struct ifnet		*ifp;
1903
1904	sc = device_get_softc(dev);
1905	ifp = &sc->arpcom.ac_if;
1906
1907	/* better way to do this? */
1908	for (i = 0; i < 5; i++)
1909		pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
1910	pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
1911	pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
1912	pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
1913	pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
1914
1915	/* reenable busmastering */
1916	pci_enable_busmaster(dev);
1917	pci_enable_io(dev, RL_RES);
1918
1919        /* reinitialize interface if necessary */
1920        if (ifp->if_flags & IFF_UP)
1921                rl_init(sc);
1922
1923	sc->suspended = 0;
1924
1925	return (0);
1926}
1927
1928/*
1929 * Stop all chip I/O so that the kernel's probe routines don't
1930 * get confused by errant DMAs when rebooting.
1931 */
1932static void
1933rl_shutdown(dev)
1934	device_t		dev;
1935{
1936	struct rl_softc		*sc;
1937
1938	sc = device_get_softc(dev);
1939
1940	rl_stop(sc);
1941
1942	return;
1943}
1944