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