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