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