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