]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/pci/if_rl.c
MFC r210244:
[FreeBSD/stable/8.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 #ifdef HAVE_KERNEL_OPTION_HEADERS
87 #include "opt_device_polling.h"
88 #endif
89
90 #include <sys/param.h>
91 #include <sys/endian.h>
92 #include <sys/systm.h>
93 #include <sys/sockio.h>
94 #include <sys/mbuf.h>
95 #include <sys/malloc.h>
96 #include <sys/kernel.h>
97 #include <sys/module.h>
98 #include <sys/socket.h>
99 #include <sys/sysctl.h>
100
101 #include <net/if.h>
102 #include <net/if_arp.h>
103 #include <net/ethernet.h>
104 #include <net/if_dl.h>
105 #include <net/if_media.h>
106 #include <net/if_types.h>
107
108 #include <net/bpf.h>
109
110 #include <machine/bus.h>
111 #include <machine/resource.h>
112 #include <sys/bus.h>
113 #include <sys/rman.h>
114
115 #include <dev/mii/mii.h>
116 #include <dev/mii/miivar.h>
117
118 #include <dev/pci/pcireg.h>
119 #include <dev/pci/pcivar.h>
120
121 MODULE_DEPEND(rl, pci, 1, 1, 1);
122 MODULE_DEPEND(rl, ether, 1, 1, 1);
123 MODULE_DEPEND(rl, miibus, 1, 1, 1);
124
125 /* "device miibus" required.  See GENERIC if you get errors here. */
126 #include "miibus_if.h"
127
128 /*
129  * Default to using PIO access for this driver. On SMP systems,
130  * there appear to be problems with memory mapped mode: it looks like
131  * doing too many memory mapped access back to back in rapid succession
132  * can hang the bus. I'm inclined to blame this on crummy design/construction
133  * on the part of RealTek. Memory mapped mode does appear to work on
134  * uniprocessor systems though.
135  */
136 #define RL_USEIOSPACE
137
138 #include <pci/if_rlreg.h>
139
140 /*
141  * Various supported device vendors/types and their names.
142  */
143 static struct rl_type rl_devs[] = {
144         { RT_VENDORID, RT_DEVICEID_8129, RL_8129,
145                 "RealTek 8129 10/100BaseTX" },
146         { RT_VENDORID, RT_DEVICEID_8139, RL_8139,
147                 "RealTek 8139 10/100BaseTX" },
148         { RT_VENDORID, RT_DEVICEID_8139D, RL_8139,
149                 "RealTek 8139 10/100BaseTX" },
150         { RT_VENDORID, RT_DEVICEID_8138, RL_8139,
151                 "RealTek 8139 10/100BaseTX CardBus" },
152         { RT_VENDORID, RT_DEVICEID_8100, RL_8139,
153                 "RealTek 8100 10/100BaseTX" },
154         { ACCTON_VENDORID, ACCTON_DEVICEID_5030, RL_8139,
155                 "Accton MPX 5030/5038 10/100BaseTX" },
156         { DELTA_VENDORID, DELTA_DEVICEID_8139, RL_8139,
157                 "Delta Electronics 8139 10/100BaseTX" },
158         { ADDTRON_VENDORID, ADDTRON_DEVICEID_8139, RL_8139,
159                 "Addtron Technology 8139 10/100BaseTX" },
160         { DLINK_VENDORID, DLINK_DEVICEID_530TXPLUS, RL_8139,
161                 "D-Link DFE-530TX+ 10/100BaseTX" },
162         { DLINK_VENDORID, DLINK_DEVICEID_690TXD, RL_8139,
163                 "D-Link DFE-690TXD 10/100BaseTX" },
164         { NORTEL_VENDORID, ACCTON_DEVICEID_5030, RL_8139,
165                 "Nortel Networks 10/100BaseTX" },
166         { COREGA_VENDORID, COREGA_DEVICEID_FETHERCBTXD, RL_8139,
167                 "Corega FEther CB-TXD" },
168         { COREGA_VENDORID, COREGA_DEVICEID_FETHERIICBTXD, RL_8139,
169                 "Corega FEtherII CB-TXD" },
170         { PEPPERCON_VENDORID, PEPPERCON_DEVICEID_ROLF, RL_8139,
171                 "Peppercon AG ROL-F" },
172         { PLANEX_VENDORID, PLANEX_DEVICEID_FNW3603TX, RL_8139,
173                 "Planex FNW-3603-TX" },
174         { PLANEX_VENDORID, PLANEX_DEVICEID_FNW3800TX, RL_8139,
175                 "Planex FNW-3800-TX" },
176         { CP_VENDORID, RT_DEVICEID_8139, RL_8139,
177                 "Compaq HNE-300" },
178         { LEVEL1_VENDORID, LEVEL1_DEVICEID_FPC0106TX, RL_8139,
179                 "LevelOne FPC-0106TX" },
180         { EDIMAX_VENDORID, EDIMAX_DEVICEID_EP4103DL, RL_8139,
181                 "Edimax EP-4103DL CardBus" }
182 };
183
184 static int rl_attach(device_t);
185 static int rl_detach(device_t);
186 static void rl_dmamap_cb(void *, bus_dma_segment_t *, int, int);
187 static int rl_dma_alloc(struct rl_softc *);
188 static void rl_dma_free(struct rl_softc *);
189 static void rl_eeprom_putbyte(struct rl_softc *, int);
190 static void rl_eeprom_getword(struct rl_softc *, int, uint16_t *);
191 static int rl_encap(struct rl_softc *, struct mbuf **);
192 static int rl_list_tx_init(struct rl_softc *);
193 static int rl_list_rx_init(struct rl_softc *);
194 static int rl_ifmedia_upd(struct ifnet *);
195 static void rl_ifmedia_sts(struct ifnet *, struct ifmediareq *);
196 static int rl_ioctl(struct ifnet *, u_long, caddr_t);
197 static void rl_intr(void *);
198 static void rl_init(void *);
199 static void rl_init_locked(struct rl_softc *sc);
200 static void rl_mii_send(struct rl_softc *, uint32_t, int);
201 static void rl_mii_sync(struct rl_softc *);
202 static int rl_mii_readreg(struct rl_softc *, struct rl_mii_frame *);
203 static int rl_mii_writereg(struct rl_softc *, struct rl_mii_frame *);
204 static int rl_miibus_readreg(device_t, int, int);
205 static void rl_miibus_statchg(device_t);
206 static int rl_miibus_writereg(device_t, int, int, int);
207 #ifdef DEVICE_POLLING
208 static int rl_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
209 static int rl_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count);
210 #endif
211 static int rl_probe(device_t);
212 static void rl_read_eeprom(struct rl_softc *, uint8_t *, int, int, int);
213 static void rl_reset(struct rl_softc *);
214 static int rl_resume(device_t);
215 static int rl_rxeof(struct rl_softc *);
216 static void rl_setmulti(struct rl_softc *);
217 static int rl_shutdown(device_t);
218 static void rl_start(struct ifnet *);
219 static void rl_start_locked(struct ifnet *);
220 static void rl_stop(struct rl_softc *);
221 static int rl_suspend(device_t);
222 static void rl_tick(void *);
223 static void rl_txeof(struct rl_softc *);
224 static void rl_watchdog(struct rl_softc *);
225 static void rl_setwol(struct rl_softc *);
226 static void rl_clrwol(struct rl_softc *);
227
228 #ifdef RL_USEIOSPACE
229 #define RL_RES                  SYS_RES_IOPORT
230 #define RL_RID                  RL_PCI_LOIO
231 #else
232 #define RL_RES                  SYS_RES_MEMORY
233 #define RL_RID                  RL_PCI_LOMEM
234 #endif
235
236 static device_method_t rl_methods[] = {
237         /* Device interface */
238         DEVMETHOD(device_probe,         rl_probe),
239         DEVMETHOD(device_attach,        rl_attach),
240         DEVMETHOD(device_detach,        rl_detach),
241         DEVMETHOD(device_suspend,       rl_suspend),
242         DEVMETHOD(device_resume,        rl_resume),
243         DEVMETHOD(device_shutdown,      rl_shutdown),
244
245         /* bus interface */
246         DEVMETHOD(bus_print_child,      bus_generic_print_child),
247         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
248
249         /* MII interface */
250         DEVMETHOD(miibus_readreg,       rl_miibus_readreg),
251         DEVMETHOD(miibus_writereg,      rl_miibus_writereg),
252         DEVMETHOD(miibus_statchg,       rl_miibus_statchg),
253
254         { 0, 0 }
255 };
256
257 static driver_t rl_driver = {
258         "rl",
259         rl_methods,
260         sizeof(struct rl_softc)
261 };
262
263 static devclass_t rl_devclass;
264
265 DRIVER_MODULE(rl, pci, rl_driver, rl_devclass, 0, 0);
266 DRIVER_MODULE(rl, cardbus, rl_driver, rl_devclass, 0, 0);
267 DRIVER_MODULE(miibus, rl, miibus_driver, miibus_devclass, 0, 0);
268
269 #define EE_SET(x)                                       \
270         CSR_WRITE_1(sc, RL_EECMD,                       \
271                 CSR_READ_1(sc, RL_EECMD) | x)
272
273 #define EE_CLR(x)                                       \
274         CSR_WRITE_1(sc, RL_EECMD,                       \
275                 CSR_READ_1(sc, RL_EECMD) & ~x)
276
277 /*
278  * Send a read command and address to the EEPROM, check for ACK.
279  */
280 static void
281 rl_eeprom_putbyte(struct rl_softc *sc, int addr)
282 {
283         register int            d, i;
284
285         d = addr | sc->rl_eecmd_read;
286
287         /*
288          * Feed in each bit and strobe the clock.
289          */
290         for (i = 0x400; i; i >>= 1) {
291                 if (d & i) {
292                         EE_SET(RL_EE_DATAIN);
293                 } else {
294                         EE_CLR(RL_EE_DATAIN);
295                 }
296                 DELAY(100);
297                 EE_SET(RL_EE_CLK);
298                 DELAY(150);
299                 EE_CLR(RL_EE_CLK);
300                 DELAY(100);
301         }
302 }
303
304 /*
305  * Read a word of data stored in the EEPROM at address 'addr.'
306  */
307 static void
308 rl_eeprom_getword(struct rl_softc *sc, int addr, uint16_t *dest)
309 {
310         register int            i;
311         uint16_t                word = 0;
312
313         /* Enter EEPROM access mode. */
314         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
315
316         /*
317          * Send address of word we want to read.
318          */
319         rl_eeprom_putbyte(sc, addr);
320
321         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_PROGRAM|RL_EE_SEL);
322
323         /*
324          * Start reading bits from EEPROM.
325          */
326         for (i = 0x8000; i; i >>= 1) {
327                 EE_SET(RL_EE_CLK);
328                 DELAY(100);
329                 if (CSR_READ_1(sc, RL_EECMD) & RL_EE_DATAOUT)
330                         word |= i;
331                 EE_CLR(RL_EE_CLK);
332                 DELAY(100);
333         }
334
335         /* Turn off EEPROM access mode. */
336         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
337
338         *dest = word;
339 }
340
341 /*
342  * Read a sequence of words from the EEPROM.
343  */
344 static void
345 rl_read_eeprom(struct rl_softc *sc, uint8_t *dest, int off, int cnt, int swap)
346 {
347         int                     i;
348         uint16_t                word = 0, *ptr;
349
350         for (i = 0; i < cnt; i++) {
351                 rl_eeprom_getword(sc, off + i, &word);
352                 ptr = (uint16_t *)(dest + (i * 2));
353                 if (swap)
354                         *ptr = ntohs(word);
355                 else
356                         *ptr = word;
357         }
358 }
359
360 /*
361  * MII access routines are provided for the 8129, which
362  * doesn't have a built-in PHY. For the 8139, we fake things
363  * up by diverting rl_phy_readreg()/rl_phy_writereg() to the
364  * direct access PHY registers.
365  */
366 #define MII_SET(x)                                      \
367         CSR_WRITE_1(sc, RL_MII,                         \
368                 CSR_READ_1(sc, RL_MII) | (x))
369
370 #define MII_CLR(x)                                      \
371         CSR_WRITE_1(sc, RL_MII,                         \
372                 CSR_READ_1(sc, RL_MII) & ~(x))
373
374 /*
375  * Sync the PHYs by setting data bit and strobing the clock 32 times.
376  */
377 static void
378 rl_mii_sync(struct rl_softc *sc)
379 {
380         register int            i;
381
382         MII_SET(RL_MII_DIR|RL_MII_DATAOUT);
383
384         for (i = 0; i < 32; i++) {
385                 MII_SET(RL_MII_CLK);
386                 DELAY(1);
387                 MII_CLR(RL_MII_CLK);
388                 DELAY(1);
389         }
390 }
391
392 /*
393  * Clock a series of bits through the MII.
394  */
395 static void
396 rl_mii_send(struct rl_softc *sc, uint32_t bits, int cnt)
397 {
398         int                     i;
399
400         MII_CLR(RL_MII_CLK);
401
402         for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
403                 if (bits & i) {
404                         MII_SET(RL_MII_DATAOUT);
405                 } else {
406                         MII_CLR(RL_MII_DATAOUT);
407                 }
408                 DELAY(1);
409                 MII_CLR(RL_MII_CLK);
410                 DELAY(1);
411                 MII_SET(RL_MII_CLK);
412         }
413 }
414
415 /*
416  * Read an PHY register through the MII.
417  */
418 static int
419 rl_mii_readreg(struct rl_softc *sc, struct rl_mii_frame *frame)
420 {
421         int                     i, ack;
422
423         /* Set up frame for RX. */
424         frame->mii_stdelim = RL_MII_STARTDELIM;
425         frame->mii_opcode = RL_MII_READOP;
426         frame->mii_turnaround = 0;
427         frame->mii_data = 0;
428
429         CSR_WRITE_2(sc, RL_MII, 0);
430
431         /* Turn on data xmit. */
432         MII_SET(RL_MII_DIR);
433
434         rl_mii_sync(sc);
435
436         /* Send command/address info. */
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                 goto fail;
470         }
471
472         for (i = 0x8000; i; i >>= 1) {
473                 MII_CLR(RL_MII_CLK);
474                 DELAY(1);
475                 if (!ack) {
476                         if (CSR_READ_2(sc, RL_MII) & RL_MII_DATAIN)
477                                 frame->mii_data |= i;
478                         DELAY(1);
479                 }
480                 MII_SET(RL_MII_CLK);
481                 DELAY(1);
482         }
483
484 fail:
485         MII_CLR(RL_MII_CLK);
486         DELAY(1);
487         MII_SET(RL_MII_CLK);
488         DELAY(1);
489
490         return (ack ? 1 : 0);
491 }
492
493 /*
494  * Write to a PHY register through the MII.
495  */
496 static int
497 rl_mii_writereg(struct rl_softc *sc, struct rl_mii_frame *frame)
498 {
499
500         /* Set up frame for TX. */
501         frame->mii_stdelim = RL_MII_STARTDELIM;
502         frame->mii_opcode = RL_MII_WRITEOP;
503         frame->mii_turnaround = RL_MII_TURNAROUND;
504
505         /* Turn on data output. */
506         MII_SET(RL_MII_DIR);
507
508         rl_mii_sync(sc);
509
510         rl_mii_send(sc, frame->mii_stdelim, 2);
511         rl_mii_send(sc, frame->mii_opcode, 2);
512         rl_mii_send(sc, frame->mii_phyaddr, 5);
513         rl_mii_send(sc, frame->mii_regaddr, 5);
514         rl_mii_send(sc, frame->mii_turnaround, 2);
515         rl_mii_send(sc, frame->mii_data, 16);
516
517         /* Idle bit. */
518         MII_SET(RL_MII_CLK);
519         DELAY(1);
520         MII_CLR(RL_MII_CLK);
521         DELAY(1);
522
523         /* Turn off xmit. */
524         MII_CLR(RL_MII_DIR);
525
526         return (0);
527 }
528
529 static int
530 rl_miibus_readreg(device_t dev, int phy, int reg)
531 {
532         struct rl_softc         *sc;
533         struct rl_mii_frame     frame;
534         uint16_t                rval = 0;
535         uint16_t                rl8139_reg = 0;
536
537         sc = device_get_softc(dev);
538
539         if (sc->rl_type == RL_8139) {
540                 /* Pretend the internal PHY is only at address 0 */
541                 if (phy) {
542                         return (0);
543                 }
544                 switch (reg) {
545                 case MII_BMCR:
546                         rl8139_reg = RL_BMCR;
547                         break;
548                 case MII_BMSR:
549                         rl8139_reg = RL_BMSR;
550                         break;
551                 case MII_ANAR:
552                         rl8139_reg = RL_ANAR;
553                         break;
554                 case MII_ANER:
555                         rl8139_reg = RL_ANER;
556                         break;
557                 case MII_ANLPAR:
558                         rl8139_reg = RL_LPAR;
559                         break;
560                 case MII_PHYIDR1:
561                 case MII_PHYIDR2:
562                         return (0);
563                 /*
564                  * Allow the rlphy driver to read the media status
565                  * register. If we have a link partner which does not
566                  * support NWAY, this is the register which will tell
567                  * us the results of parallel detection.
568                  */
569                 case RL_MEDIASTAT:
570                         rval = CSR_READ_1(sc, RL_MEDIASTAT);
571                         return (rval);
572                 default:
573                         device_printf(sc->rl_dev, "bad phy register\n");
574                         return (0);
575                 }
576                 rval = CSR_READ_2(sc, rl8139_reg);
577                 return (rval);
578         }
579
580         bzero((char *)&frame, sizeof(frame));
581         frame.mii_phyaddr = phy;
582         frame.mii_regaddr = reg;
583         rl_mii_readreg(sc, &frame);
584
585         return (frame.mii_data);
586 }
587
588 static int
589 rl_miibus_writereg(device_t dev, int phy, int reg, int data)
590 {
591         struct rl_softc         *sc;
592         struct rl_mii_frame     frame;
593         uint16_t                rl8139_reg = 0;
594
595         sc = device_get_softc(dev);
596
597         if (sc->rl_type == RL_8139) {
598                 /* Pretend the internal PHY is only at address 0 */
599                 if (phy) {
600                         return (0);
601                 }
602                 switch (reg) {
603                 case MII_BMCR:
604                         rl8139_reg = RL_BMCR;
605                         break;
606                 case MII_BMSR:
607                         rl8139_reg = RL_BMSR;
608                         break;
609                 case MII_ANAR:
610                         rl8139_reg = RL_ANAR;
611                         break;
612                 case MII_ANER:
613                         rl8139_reg = RL_ANER;
614                         break;
615                 case MII_ANLPAR:
616                         rl8139_reg = RL_LPAR;
617                         break;
618                 case MII_PHYIDR1:
619                 case MII_PHYIDR2:
620                         return (0);
621                         break;
622                 default:
623                         device_printf(sc->rl_dev, "bad phy register\n");
624                         return (0);
625                 }
626                 CSR_WRITE_2(sc, rl8139_reg, data);
627                 return (0);
628         }
629
630         bzero((char *)&frame, sizeof(frame));
631         frame.mii_phyaddr = phy;
632         frame.mii_regaddr = reg;
633         frame.mii_data = data;
634         rl_mii_writereg(sc, &frame);
635
636         return (0);
637 }
638
639 static void
640 rl_miibus_statchg(device_t dev)
641 {
642         struct rl_softc         *sc;
643         struct ifnet            *ifp;
644         struct mii_data         *mii;
645
646         sc = device_get_softc(dev);
647         mii = device_get_softc(sc->rl_miibus);
648         ifp = sc->rl_ifp;
649         if (mii == NULL || ifp == NULL ||
650             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
651                 return;
652
653         sc->rl_flags &= ~RL_FLAG_LINK;
654         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
655             (IFM_ACTIVE | IFM_AVALID)) {
656                 switch (IFM_SUBTYPE(mii->mii_media_active)) {
657                 case IFM_10_T:
658                 case IFM_100_TX:
659                         sc->rl_flags |= RL_FLAG_LINK;
660                         break;
661                 default:
662                         break;
663                 }
664         }
665         /*
666          * RealTek controllers do not provide any interface to
667          * Tx/Rx MACs for resolved speed, duplex and flow-control
668          * parameters.
669          */
670 }
671
672 /*
673  * Program the 64-bit multicast hash filter.
674  */
675 static void
676 rl_setmulti(struct rl_softc *sc)
677 {
678         struct ifnet            *ifp = sc->rl_ifp;
679         int                     h = 0;
680         uint32_t                hashes[2] = { 0, 0 };
681         struct ifmultiaddr      *ifma;
682         uint32_t                rxfilt;
683         int                     mcnt = 0;
684
685         RL_LOCK_ASSERT(sc);
686
687         rxfilt = CSR_READ_4(sc, RL_RXCFG);
688
689         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
690                 rxfilt |= RL_RXCFG_RX_MULTI;
691                 CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
692                 CSR_WRITE_4(sc, RL_MAR0, 0xFFFFFFFF);
693                 CSR_WRITE_4(sc, RL_MAR4, 0xFFFFFFFF);
694                 return;
695         }
696
697         /* first, zot all the existing hash bits */
698         CSR_WRITE_4(sc, RL_MAR0, 0);
699         CSR_WRITE_4(sc, RL_MAR4, 0);
700
701         /* now program new ones */
702         if_maddr_rlock(ifp);
703         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
704                 if (ifma->ifma_addr->sa_family != AF_LINK)
705                         continue;
706                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
707                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
708                 if (h < 32)
709                         hashes[0] |= (1 << h);
710                 else
711                         hashes[1] |= (1 << (h - 32));
712                 mcnt++;
713         }
714         if_maddr_runlock(ifp);
715
716         if (mcnt)
717                 rxfilt |= RL_RXCFG_RX_MULTI;
718         else
719                 rxfilt &= ~RL_RXCFG_RX_MULTI;
720
721         CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
722         CSR_WRITE_4(sc, RL_MAR0, hashes[0]);
723         CSR_WRITE_4(sc, RL_MAR4, hashes[1]);
724 }
725
726 static void
727 rl_reset(struct rl_softc *sc)
728 {
729         register int            i;
730
731         RL_LOCK_ASSERT(sc);
732
733         CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RESET);
734
735         for (i = 0; i < RL_TIMEOUT; i++) {
736                 DELAY(10);
737                 if (!(CSR_READ_1(sc, RL_COMMAND) & RL_CMD_RESET))
738                         break;
739         }
740         if (i == RL_TIMEOUT)
741                 device_printf(sc->rl_dev, "reset never completed!\n");
742 }
743
744 /*
745  * Probe for a RealTek 8129/8139 chip. Check the PCI vendor and device
746  * IDs against our list and return a device name if we find a match.
747  */
748 static int
749 rl_probe(device_t dev)
750 {
751         struct rl_type          *t;
752         uint16_t                devid, revid, vendor;
753         int                     i;
754         
755         vendor = pci_get_vendor(dev);
756         devid = pci_get_device(dev);
757         revid = pci_get_revid(dev);
758
759         if (vendor == RT_VENDORID && devid == RT_DEVICEID_8139) {
760                 if (revid == 0x20) {
761                         /* 8139C+, let re(4) take care of this device. */
762                         return (ENXIO);
763                 }
764         }
765         t = rl_devs;
766         for (i = 0; i < sizeof(rl_devs) / sizeof(rl_devs[0]); i++, t++) {
767                 if (vendor == t->rl_vid && devid == t->rl_did) {
768                         device_set_desc(dev, t->rl_name);
769                         return (BUS_PROBE_DEFAULT);
770                 }
771         }
772
773         return (ENXIO);
774 }
775
776 struct rl_dmamap_arg {
777         bus_addr_t      rl_busaddr;
778 };
779
780 static void
781 rl_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
782 {
783         struct rl_dmamap_arg    *ctx;
784
785         if (error != 0)
786                 return;
787
788         KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
789
790         ctx = (struct rl_dmamap_arg *)arg;
791         ctx->rl_busaddr = segs[0].ds_addr;
792 }
793
794 /*
795  * Attach the interface. Allocate softc structures, do ifmedia
796  * setup and ethernet/BPF attach.
797  */
798 static int
799 rl_attach(device_t dev)
800 {
801         uint8_t                 eaddr[ETHER_ADDR_LEN];
802         uint16_t                as[3];
803         struct ifnet            *ifp;
804         struct rl_softc         *sc;
805         struct rl_type          *t;
806         struct sysctl_ctx_list  *ctx;
807         struct sysctl_oid_list  *children;
808         int                     error = 0, hwrev, i, pmc, rid;
809         int                     unit;
810         uint16_t                rl_did = 0;
811         char                    tn[32];
812
813         sc = device_get_softc(dev);
814         unit = device_get_unit(dev);
815         sc->rl_dev = dev;
816
817         sc->rl_twister_enable = 0;
818         snprintf(tn, sizeof(tn), "dev.rl.%d.twister_enable", unit);
819         TUNABLE_INT_FETCH(tn, &sc->rl_twister_enable);
820         ctx = device_get_sysctl_ctx(sc->rl_dev);
821         children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->rl_dev));
822         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "twister_enable", CTLFLAG_RD,
823            &sc->rl_twister_enable, 0, "");
824
825         mtx_init(&sc->rl_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
826             MTX_DEF);
827         callout_init_mtx(&sc->rl_stat_callout, &sc->rl_mtx, 0);
828
829         pci_enable_busmaster(dev);
830
831         /* Map control/status registers. */
832         rid = RL_RID;
833         sc->rl_res = bus_alloc_resource_any(dev, RL_RES, &rid, RF_ACTIVE);
834
835         if (sc->rl_res == NULL) {
836                 device_printf(dev, "couldn't map ports/memory\n");
837                 error = ENXIO;
838                 goto fail;
839         }
840
841 #ifdef notdef
842         /*
843          * Detect the Realtek 8139B. For some reason, this chip is very
844          * unstable when left to autoselect the media
845          * The best workaround is to set the device to the required
846          * media type or to set it to the 10 Meg speed.
847          */
848         if ((rman_get_end(sc->rl_res) - rman_get_start(sc->rl_res)) == 0xFF)
849                 device_printf(dev,
850 "Realtek 8139B detected. Warning, this may be unstable in autoselect mode\n");
851 #endif
852
853         sc->rl_btag = rman_get_bustag(sc->rl_res);
854         sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
855
856         /* Allocate interrupt */
857         rid = 0;
858         sc->rl_irq[0] = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
859             RF_SHAREABLE | RF_ACTIVE);
860
861         if (sc->rl_irq[0] == NULL) {
862                 device_printf(dev, "couldn't map interrupt\n");
863                 error = ENXIO;
864                 goto fail;
865         }
866
867         /*
868          * Reset the adapter. Only take the lock here as it's needed in
869          * order to call rl_reset().
870          */
871         RL_LOCK(sc);
872         rl_reset(sc);
873         RL_UNLOCK(sc);
874
875         sc->rl_eecmd_read = RL_EECMD_READ_6BIT;
876         rl_read_eeprom(sc, (uint8_t *)&rl_did, 0, 1, 0);
877         if (rl_did != 0x8129)
878                 sc->rl_eecmd_read = RL_EECMD_READ_8BIT;
879
880         /*
881          * Get station address from the EEPROM.
882          */
883         rl_read_eeprom(sc, (uint8_t *)as, RL_EE_EADDR, 3, 0);
884         for (i = 0; i < 3; i++) {
885                 eaddr[(i * 2) + 0] = as[i] & 0xff;
886                 eaddr[(i * 2) + 1] = as[i] >> 8;
887         }
888
889         /*
890          * Now read the exact device type from the EEPROM to find
891          * out if it's an 8129 or 8139.
892          */
893         rl_read_eeprom(sc, (uint8_t *)&rl_did, RL_EE_PCI_DID, 1, 0);
894
895         t = rl_devs;
896         sc->rl_type = 0;
897         while(t->rl_name != NULL) {
898                 if (rl_did == t->rl_did) {
899                         sc->rl_type = t->rl_basetype;
900                         break;
901                 }
902                 t++;
903         }
904
905         if (sc->rl_type == 0) {
906                 device_printf(dev, "unknown device ID: %x assuming 8139\n",
907                     rl_did);
908                 sc->rl_type = RL_8139;
909                 /*
910                  * Read RL_IDR register to get ethernet address as accessing
911                  * EEPROM may not extract correct address.
912                  */
913                 for (i = 0; i < ETHER_ADDR_LEN; i++)
914                         eaddr[i] = CSR_READ_1(sc, RL_IDR0 + i);
915         }
916
917         if ((error = rl_dma_alloc(sc)) != 0)
918                 goto fail;
919
920         ifp = sc->rl_ifp = if_alloc(IFT_ETHER);
921         if (ifp == NULL) {
922                 device_printf(dev, "can not if_alloc()\n");
923                 error = ENOSPC;
924                 goto fail;
925         }
926
927         /* Do MII setup */
928         if (mii_phy_probe(dev, &sc->rl_miibus,
929             rl_ifmedia_upd, rl_ifmedia_sts)) {
930                 device_printf(dev, "MII without any phy!\n");
931                 error = ENXIO;
932                 goto fail;
933         }
934
935         ifp->if_softc = sc;
936         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
937         ifp->if_mtu = ETHERMTU;
938         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
939         ifp->if_ioctl = rl_ioctl;
940         ifp->if_start = rl_start;
941         ifp->if_init = rl_init;
942         ifp->if_capabilities = IFCAP_VLAN_MTU;
943         /* Check WOL for RTL8139B or newer controllers. */
944         if (sc->rl_type == RL_8139 &&
945             pci_find_extcap(sc->rl_dev, PCIY_PMG, &pmc) == 0) {
946                 hwrev = CSR_READ_4(sc, RL_TXCFG) & RL_TXCFG_HWREV;
947                 switch (hwrev) {
948                 case RL_HWREV_8139B:
949                 case RL_HWREV_8130:
950                 case RL_HWREV_8139C:
951                 case RL_HWREV_8139D:
952                 case RL_HWREV_8101:
953                 case RL_HWREV_8100:
954                         ifp->if_capabilities |= IFCAP_WOL;
955                         /* Disable WOL. */
956                         rl_clrwol(sc);
957                         break;
958                 default:
959                         break;
960                 }
961         }
962         ifp->if_capenable = ifp->if_capabilities;
963 #ifdef DEVICE_POLLING
964         ifp->if_capabilities |= IFCAP_POLLING;
965 #endif
966         IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
967         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
968         IFQ_SET_READY(&ifp->if_snd);
969
970         /*
971          * Call MI attach routine.
972          */
973         ether_ifattach(ifp, eaddr);
974
975         /* Hook interrupt last to avoid having to lock softc */
976         error = bus_setup_intr(dev, sc->rl_irq[0], INTR_TYPE_NET | INTR_MPSAFE,
977             NULL, rl_intr, sc, &sc->rl_intrhand[0]);
978         if (error) {
979                 device_printf(sc->rl_dev, "couldn't set up irq\n");
980                 ether_ifdetach(ifp);
981         }
982
983 fail:
984         if (error)
985                 rl_detach(dev);
986
987         return (error);
988 }
989
990 /*
991  * Shutdown hardware and free up resources. This can be called any
992  * time after the mutex has been initialized. It is called in both
993  * the error case in attach and the normal detach case so it needs
994  * to be careful about only freeing resources that have actually been
995  * allocated.
996  */
997 static int
998 rl_detach(device_t dev)
999 {
1000         struct rl_softc         *sc;
1001         struct ifnet            *ifp;
1002
1003         sc = device_get_softc(dev);
1004         ifp = sc->rl_ifp;
1005
1006         KASSERT(mtx_initialized(&sc->rl_mtx), ("rl mutex not initialized"));
1007
1008 #ifdef DEVICE_POLLING
1009         if (ifp->if_capenable & IFCAP_POLLING)
1010                 ether_poll_deregister(ifp);
1011 #endif
1012         /* These should only be active if attach succeeded */
1013         if (device_is_attached(dev)) {
1014                 RL_LOCK(sc);
1015                 rl_stop(sc);
1016                 RL_UNLOCK(sc);
1017                 callout_drain(&sc->rl_stat_callout);
1018                 ether_ifdetach(ifp);
1019         }
1020 #if 0
1021         sc->suspended = 1;
1022 #endif
1023         if (sc->rl_miibus)
1024                 device_delete_child(dev, sc->rl_miibus);
1025         bus_generic_detach(dev);
1026
1027         if (sc->rl_intrhand[0])
1028                 bus_teardown_intr(dev, sc->rl_irq[0], sc->rl_intrhand[0]);
1029         if (sc->rl_irq[0])
1030                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq[0]);
1031         if (sc->rl_res)
1032                 bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
1033
1034         if (ifp)
1035                 if_free(ifp);
1036
1037         rl_dma_free(sc);
1038
1039         mtx_destroy(&sc->rl_mtx);
1040
1041         return (0);
1042 }
1043
1044 static int
1045 rl_dma_alloc(struct rl_softc *sc)
1046 {
1047         struct rl_dmamap_arg    ctx;
1048         int                     error, i;
1049
1050         /*
1051          * Allocate the parent bus DMA tag appropriate for PCI.
1052          */
1053         error = bus_dma_tag_create(bus_get_dma_tag(sc->rl_dev), /* parent */
1054             1, 0,                       /* alignment, boundary */
1055             BUS_SPACE_MAXADDR_32BIT,    /* lowaddr */
1056             BUS_SPACE_MAXADDR,          /* highaddr */
1057             NULL, NULL,                 /* filter, filterarg */
1058             BUS_SPACE_MAXSIZE_32BIT, 0, /* maxsize, nsegments */
1059             BUS_SPACE_MAXSIZE_32BIT,    /* maxsegsize */
1060             0,                          /* flags */
1061             NULL, NULL,                 /* lockfunc, lockarg */
1062             &sc->rl_parent_tag);
1063         if (error) {
1064                 device_printf(sc->rl_dev,
1065                     "failed to create parent DMA tag.\n");
1066                 goto fail;
1067         }
1068         /* Create DMA tag for Rx memory block. */
1069         error = bus_dma_tag_create(sc->rl_parent_tag,   /* parent */
1070             RL_RX_8139_BUF_ALIGN, 0,    /* alignment, boundary */
1071             BUS_SPACE_MAXADDR,          /* lowaddr */
1072             BUS_SPACE_MAXADDR,          /* highaddr */
1073             NULL, NULL,                 /* filter, filterarg */
1074             RL_RXBUFLEN + RL_RX_8139_BUF_GUARD_SZ, 1,   /* maxsize,nsegments */
1075             RL_RXBUFLEN + RL_RX_8139_BUF_GUARD_SZ,      /* maxsegsize */
1076             0,                          /* flags */
1077             NULL, NULL,                 /* lockfunc, lockarg */
1078             &sc->rl_cdata.rl_rx_tag);
1079         if (error) {
1080                 device_printf(sc->rl_dev,
1081                     "failed to create Rx memory block DMA tag.\n");
1082                 goto fail;
1083         }
1084         /* Create DMA tag for Tx buffer. */
1085         error = bus_dma_tag_create(sc->rl_parent_tag,   /* parent */
1086             RL_TX_8139_BUF_ALIGN, 0,    /* alignment, boundary */
1087             BUS_SPACE_MAXADDR,          /* lowaddr */
1088             BUS_SPACE_MAXADDR,          /* highaddr */
1089             NULL, NULL,                 /* filter, filterarg */
1090             MCLBYTES, 1,                /* maxsize, nsegments */
1091             MCLBYTES,                   /* maxsegsize */
1092             0,                          /* flags */
1093             NULL, NULL,                 /* lockfunc, lockarg */
1094             &sc->rl_cdata.rl_tx_tag);
1095         if (error) {
1096                 device_printf(sc->rl_dev, "failed to create Tx DMA tag.\n");
1097                 goto fail;
1098         }
1099
1100         /*
1101          * Allocate DMA'able memory and load DMA map for Rx memory block.
1102          */
1103         error = bus_dmamem_alloc(sc->rl_cdata.rl_rx_tag,
1104             (void **)&sc->rl_cdata.rl_rx_buf, BUS_DMA_WAITOK |
1105             BUS_DMA_COHERENT | BUS_DMA_ZERO, &sc->rl_cdata.rl_rx_dmamap);
1106         if (error != 0) {
1107                 device_printf(sc->rl_dev,
1108                     "failed to allocate Rx DMA memory block.\n");
1109                 goto fail;
1110         }
1111         ctx.rl_busaddr = 0;
1112         error = bus_dmamap_load(sc->rl_cdata.rl_rx_tag,
1113             sc->rl_cdata.rl_rx_dmamap, sc->rl_cdata.rl_rx_buf,
1114             RL_RXBUFLEN + RL_RX_8139_BUF_GUARD_SZ, rl_dmamap_cb, &ctx,
1115             BUS_DMA_NOWAIT);
1116         if (error != 0 || ctx.rl_busaddr == 0) {
1117                 device_printf(sc->rl_dev,
1118                     "could not load Rx DMA memory block.\n");
1119                 goto fail;
1120         }
1121         sc->rl_cdata.rl_rx_buf_paddr = ctx.rl_busaddr;
1122
1123         /* Create DMA maps for Tx buffers. */
1124         for (i = 0; i < RL_TX_LIST_CNT; i++) {
1125                 sc->rl_cdata.rl_tx_chain[i] = NULL;
1126                 sc->rl_cdata.rl_tx_dmamap[i] = NULL;
1127                 error = bus_dmamap_create(sc->rl_cdata.rl_tx_tag, 0,
1128                     &sc->rl_cdata.rl_tx_dmamap[i]);
1129                 if (error != 0) {
1130                         device_printf(sc->rl_dev,
1131                             "could not create Tx dmamap.\n");
1132                         goto fail;
1133                 }
1134         }
1135
1136         /* Leave a few bytes before the start of the RX ring buffer. */
1137         sc->rl_cdata.rl_rx_buf_ptr = sc->rl_cdata.rl_rx_buf;
1138         sc->rl_cdata.rl_rx_buf += RL_RX_8139_BUF_RESERVE;
1139
1140 fail:
1141         return (error);
1142 }
1143
1144 static void
1145 rl_dma_free(struct rl_softc *sc)
1146 {
1147         int                     i;
1148
1149         /* Rx memory block. */
1150         if (sc->rl_cdata.rl_rx_tag != NULL) {
1151                 if (sc->rl_cdata.rl_rx_dmamap != NULL)
1152                         bus_dmamap_unload(sc->rl_cdata.rl_rx_tag,
1153                             sc->rl_cdata.rl_rx_dmamap);
1154                 if (sc->rl_cdata.rl_rx_dmamap != NULL &&
1155                     sc->rl_cdata.rl_rx_buf_ptr != NULL)
1156                         bus_dmamem_free(sc->rl_cdata.rl_rx_tag,
1157                             sc->rl_cdata.rl_rx_buf_ptr,
1158                             sc->rl_cdata.rl_rx_dmamap);
1159                 sc->rl_cdata.rl_rx_buf_ptr = NULL;
1160                 sc->rl_cdata.rl_rx_buf = NULL;
1161                 sc->rl_cdata.rl_rx_dmamap = NULL;
1162                 bus_dma_tag_destroy(sc->rl_cdata.rl_rx_tag);
1163                 sc->rl_cdata.rl_tx_tag = NULL;
1164         }
1165
1166         /* Tx buffers. */
1167         if (sc->rl_cdata.rl_tx_tag != NULL) {
1168                 for (i = 0; i < RL_TX_LIST_CNT; i++) {
1169                         if (sc->rl_cdata.rl_tx_dmamap[i] != NULL) {
1170                                 bus_dmamap_destroy(
1171                                     sc->rl_cdata.rl_tx_tag,
1172                                     sc->rl_cdata.rl_tx_dmamap[i]);
1173                                 sc->rl_cdata.rl_tx_dmamap[i] = NULL;
1174                         }
1175                 }
1176                 bus_dma_tag_destroy(sc->rl_cdata.rl_tx_tag);
1177                 sc->rl_cdata.rl_tx_tag = NULL;
1178         }
1179
1180         if (sc->rl_parent_tag != NULL) {
1181                 bus_dma_tag_destroy(sc->rl_parent_tag);
1182                 sc->rl_parent_tag = NULL;
1183         }
1184 }
1185
1186 /*
1187  * Initialize the transmit descriptors.
1188  */
1189 static int
1190 rl_list_tx_init(struct rl_softc *sc)
1191 {
1192         struct rl_chain_data    *cd;
1193         int                     i;
1194
1195         RL_LOCK_ASSERT(sc);
1196
1197         cd = &sc->rl_cdata;
1198         for (i = 0; i < RL_TX_LIST_CNT; i++) {
1199                 cd->rl_tx_chain[i] = NULL;
1200                 CSR_WRITE_4(sc,
1201                     RL_TXADDR0 + (i * sizeof(uint32_t)), 0x0000000);
1202         }
1203
1204         sc->rl_cdata.cur_tx = 0;
1205         sc->rl_cdata.last_tx = 0;
1206
1207         return (0);
1208 }
1209
1210 static int
1211 rl_list_rx_init(struct rl_softc *sc)
1212 {
1213
1214         RL_LOCK_ASSERT(sc);
1215
1216         bzero(sc->rl_cdata.rl_rx_buf_ptr,
1217             RL_RXBUFLEN + RL_RX_8139_BUF_GUARD_SZ);
1218         bus_dmamap_sync(sc->rl_cdata.rl_tx_tag, sc->rl_cdata.rl_rx_dmamap,
1219             BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1220
1221         return (0);
1222 }
1223
1224 /*
1225  * A frame has been uploaded: pass the resulting mbuf chain up to
1226  * the higher level protocols.
1227  *
1228  * You know there's something wrong with a PCI bus-master chip design
1229  * when you have to use m_devget().
1230  *
1231  * The receive operation is badly documented in the datasheet, so I'll
1232  * attempt to document it here. The driver provides a buffer area and
1233  * places its base address in the RX buffer start address register.
1234  * The chip then begins copying frames into the RX buffer. Each frame
1235  * is preceded by a 32-bit RX status word which specifies the length
1236  * of the frame and certain other status bits. Each frame (starting with
1237  * the status word) is also 32-bit aligned. The frame length is in the
1238  * first 16 bits of the status word; the lower 15 bits correspond with
1239  * the 'rx status register' mentioned in the datasheet.
1240  *
1241  * Note: to make the Alpha happy, the frame payload needs to be aligned
1242  * on a 32-bit boundary. To achieve this, we pass RL_ETHER_ALIGN (2 bytes)
1243  * as the offset argument to m_devget().
1244  */
1245 static int
1246 rl_rxeof(struct rl_softc *sc)
1247 {
1248         struct mbuf             *m;
1249         struct ifnet            *ifp = sc->rl_ifp;
1250         uint8_t                 *rxbufpos;
1251         int                     total_len = 0;
1252         int                     wrap = 0;
1253         int                     rx_npkts = 0;
1254         uint32_t                rxstat;
1255         uint16_t                cur_rx;
1256         uint16_t                limit;
1257         uint16_t                max_bytes, rx_bytes = 0;
1258
1259         RL_LOCK_ASSERT(sc);
1260
1261         bus_dmamap_sync(sc->rl_cdata.rl_rx_tag, sc->rl_cdata.rl_rx_dmamap,
1262             BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1263
1264         cur_rx = (CSR_READ_2(sc, RL_CURRXADDR) + 16) % RL_RXBUFLEN;
1265
1266         /* Do not try to read past this point. */
1267         limit = CSR_READ_2(sc, RL_CURRXBUF) % RL_RXBUFLEN;
1268
1269         if (limit < cur_rx)
1270                 max_bytes = (RL_RXBUFLEN - cur_rx) + limit;
1271         else
1272                 max_bytes = limit - cur_rx;
1273
1274         while((CSR_READ_1(sc, RL_COMMAND) & RL_CMD_EMPTY_RXBUF) == 0) {
1275 #ifdef DEVICE_POLLING
1276                 if (ifp->if_capenable & IFCAP_POLLING) {
1277                         if (sc->rxcycles <= 0)
1278                                 break;
1279                         sc->rxcycles--;
1280                 }
1281 #endif
1282                 rxbufpos = sc->rl_cdata.rl_rx_buf + cur_rx;
1283                 rxstat = le32toh(*(uint32_t *)rxbufpos);
1284
1285                 /*
1286                  * Here's a totally undocumented fact for you. When the
1287                  * RealTek chip is in the process of copying a packet into
1288                  * RAM for you, the length will be 0xfff0. If you spot a
1289                  * packet header with this value, you need to stop. The
1290                  * datasheet makes absolutely no mention of this and
1291                  * RealTek should be shot for this.
1292                  */
1293                 total_len = rxstat >> 16;
1294                 if (total_len == RL_RXSTAT_UNFINISHED)
1295                         break;
1296
1297                 if (!(rxstat & RL_RXSTAT_RXOK) ||
1298                     total_len < ETHER_MIN_LEN ||
1299                     total_len > ETHER_MAX_LEN + ETHER_VLAN_ENCAP_LEN) {
1300                         ifp->if_ierrors++;
1301                         rl_init_locked(sc);
1302                         return (rx_npkts);
1303                 }
1304
1305                 /* No errors; receive the packet. */
1306                 rx_bytes += total_len + 4;
1307
1308                 /*
1309                  * XXX The RealTek chip includes the CRC with every
1310                  * received frame, and there's no way to turn this
1311                  * behavior off (at least, I can't find anything in
1312                  * the manual that explains how to do it) so we have
1313                  * to trim off the CRC manually.
1314                  */
1315                 total_len -= ETHER_CRC_LEN;
1316
1317                 /*
1318                  * Avoid trying to read more bytes than we know
1319                  * the chip has prepared for us.
1320                  */
1321                 if (rx_bytes > max_bytes)
1322                         break;
1323
1324                 rxbufpos = sc->rl_cdata.rl_rx_buf +
1325                         ((cur_rx + sizeof(uint32_t)) % RL_RXBUFLEN);
1326                 if (rxbufpos == (sc->rl_cdata.rl_rx_buf + RL_RXBUFLEN))
1327                         rxbufpos = sc->rl_cdata.rl_rx_buf;
1328
1329                 wrap = (sc->rl_cdata.rl_rx_buf + RL_RXBUFLEN) - rxbufpos;
1330                 if (total_len > wrap) {
1331                         m = m_devget(rxbufpos, total_len, RL_ETHER_ALIGN, ifp,
1332                             NULL);
1333                         if (m != NULL)
1334                                 m_copyback(m, wrap, total_len - wrap,
1335                                         sc->rl_cdata.rl_rx_buf);
1336                         cur_rx = (total_len - wrap + ETHER_CRC_LEN);
1337                 } else {
1338                         m = m_devget(rxbufpos, total_len, RL_ETHER_ALIGN, ifp,
1339                             NULL);
1340                         cur_rx += total_len + 4 + ETHER_CRC_LEN;
1341                 }
1342
1343                 /* Round up to 32-bit boundary. */
1344                 cur_rx = (cur_rx + 3) & ~3;
1345                 CSR_WRITE_2(sc, RL_CURRXADDR, cur_rx - 16);
1346
1347                 if (m == NULL) {
1348                         ifp->if_iqdrops++;
1349                         continue;
1350                 }
1351
1352                 ifp->if_ipackets++;
1353                 RL_UNLOCK(sc);
1354                 (*ifp->if_input)(ifp, m);
1355                 RL_LOCK(sc);
1356                 rx_npkts++;
1357         }
1358
1359         /* No need to sync Rx memory block as we didn't modify it. */
1360         return (rx_npkts);
1361 }
1362
1363 /*
1364  * A frame was downloaded to the chip. It's safe for us to clean up
1365  * the list buffers.
1366  */
1367 static void
1368 rl_txeof(struct rl_softc *sc)
1369 {
1370         struct ifnet            *ifp = sc->rl_ifp;
1371         uint32_t                txstat;
1372
1373         RL_LOCK_ASSERT(sc);
1374
1375         /*
1376          * Go through our tx list and free mbufs for those
1377          * frames that have been uploaded.
1378          */
1379         do {
1380                 if (RL_LAST_TXMBUF(sc) == NULL)
1381                         break;
1382                 txstat = CSR_READ_4(sc, RL_LAST_TXSTAT(sc));
1383                 if (!(txstat & (RL_TXSTAT_TX_OK|
1384                     RL_TXSTAT_TX_UNDERRUN|RL_TXSTAT_TXABRT)))
1385                         break;
1386
1387                 ifp->if_collisions += (txstat & RL_TXSTAT_COLLCNT) >> 24;
1388
1389                 bus_dmamap_sync(sc->rl_cdata.rl_tx_tag, RL_LAST_DMAMAP(sc),
1390                     BUS_DMASYNC_POSTWRITE);
1391                 bus_dmamap_unload(sc->rl_cdata.rl_tx_tag, RL_LAST_DMAMAP(sc));
1392                 m_freem(RL_LAST_TXMBUF(sc));
1393                 RL_LAST_TXMBUF(sc) = NULL;
1394                 /*
1395                  * If there was a transmit underrun, bump the TX threshold.
1396                  * Make sure not to overflow the 63 * 32byte we can address
1397                  * with the 6 available bit.
1398                  */
1399                 if ((txstat & RL_TXSTAT_TX_UNDERRUN) &&
1400                     (sc->rl_txthresh < 2016))
1401                         sc->rl_txthresh += 32;
1402                 if (txstat & RL_TXSTAT_TX_OK)
1403                         ifp->if_opackets++;
1404                 else {
1405                         int                     oldthresh;
1406                         ifp->if_oerrors++;
1407                         if ((txstat & RL_TXSTAT_TXABRT) ||
1408                             (txstat & RL_TXSTAT_OUTOFWIN))
1409                                 CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
1410                         oldthresh = sc->rl_txthresh;
1411                         /* error recovery */
1412                         rl_init_locked(sc);
1413                         /* restore original threshold */
1414                         sc->rl_txthresh = oldthresh;
1415                         return;
1416                 }
1417                 RL_INC(sc->rl_cdata.last_tx);
1418                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1419         } while (sc->rl_cdata.last_tx != sc->rl_cdata.cur_tx);
1420
1421         if (RL_LAST_TXMBUF(sc) == NULL)
1422                 sc->rl_watchdog_timer = 0;
1423 }
1424
1425 static void
1426 rl_twister_update(struct rl_softc *sc)
1427 {
1428         uint16_t linktest;
1429         /*
1430          * Table provided by RealTek (Kinston <shangh@realtek.com.tw>) for
1431          * Linux driver.  Values undocumented otherwise.
1432          */
1433         static const uint32_t param[4][4] = {
1434                 {0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
1435                 {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
1436                 {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
1437                 {0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
1438         };
1439
1440         /*
1441          * Tune the so-called twister registers of the RTL8139.  These
1442          * are used to compensate for impedance mismatches.  The
1443          * method for tuning these registers is undocumented and the
1444          * following procedure is collected from public sources.
1445          */
1446         switch (sc->rl_twister)
1447         {
1448         case CHK_LINK:
1449                 /*
1450                  * If we have a sufficient link, then we can proceed in
1451                  * the state machine to the next stage.  If not, then
1452                  * disable further tuning after writing sane defaults.
1453                  */
1454                 if (CSR_READ_2(sc, RL_CSCFG) & RL_CSCFG_LINK_OK) {
1455                         CSR_WRITE_2(sc, RL_CSCFG, RL_CSCFG_LINK_DOWN_OFF_CMD);
1456                         sc->rl_twister = FIND_ROW;
1457                 } else {
1458                         CSR_WRITE_2(sc, RL_CSCFG, RL_CSCFG_LINK_DOWN_CMD);
1459                         CSR_WRITE_4(sc, RL_NWAYTST, RL_NWAYTST_CBL_TEST);
1460                         CSR_WRITE_4(sc, RL_PARA78, RL_PARA78_DEF);
1461                         CSR_WRITE_4(sc, RL_PARA7C, RL_PARA7C_DEF);
1462                         sc->rl_twister = DONE;
1463                 }
1464                 break;
1465         case FIND_ROW:
1466                 /*
1467                  * Read how long it took to see the echo to find the tuning
1468                  * row to use.
1469                  */
1470                 linktest = CSR_READ_2(sc, RL_CSCFG) & RL_CSCFG_STATUS;
1471                 if (linktest == RL_CSCFG_ROW3)
1472                         sc->rl_twist_row = 3;
1473                 else if (linktest == RL_CSCFG_ROW2)
1474                         sc->rl_twist_row = 2;
1475                 else if (linktest == RL_CSCFG_ROW1)
1476                         sc->rl_twist_row = 1;
1477                 else
1478                         sc->rl_twist_row = 0;
1479                 sc->rl_twist_col = 0;
1480                 sc->rl_twister = SET_PARAM;
1481                 break;
1482         case SET_PARAM:
1483                 if (sc->rl_twist_col == 0)
1484                         CSR_WRITE_4(sc, RL_NWAYTST, RL_NWAYTST_RESET);
1485                 CSR_WRITE_4(sc, RL_PARA7C,
1486                     param[sc->rl_twist_row][sc->rl_twist_col]);
1487                 if (++sc->rl_twist_col == 4) {
1488                         if (sc->rl_twist_row == 3)
1489                                 sc->rl_twister = RECHK_LONG;
1490                         else
1491                                 sc->rl_twister = DONE;
1492                 }
1493                 break;
1494         case RECHK_LONG:
1495                 /*
1496                  * For long cables, we have to double check to make sure we
1497                  * don't mistune.
1498                  */
1499                 linktest = CSR_READ_2(sc, RL_CSCFG) & RL_CSCFG_STATUS;
1500                 if (linktest == RL_CSCFG_ROW3)
1501                         sc->rl_twister = DONE;
1502                 else {
1503                         CSR_WRITE_4(sc, RL_PARA7C, RL_PARA7C_RETUNE);
1504                         sc->rl_twister = RETUNE;
1505                 }
1506                 break;
1507         case RETUNE:
1508                 /* Retune for a shorter cable (try column 2) */
1509                 CSR_WRITE_4(sc, RL_NWAYTST, RL_NWAYTST_CBL_TEST);
1510                 CSR_WRITE_4(sc, RL_PARA78, RL_PARA78_DEF);
1511                 CSR_WRITE_4(sc, RL_PARA7C, RL_PARA7C_DEF);
1512                 CSR_WRITE_4(sc, RL_NWAYTST, RL_NWAYTST_RESET);
1513                 sc->rl_twist_row--;
1514                 sc->rl_twist_col = 0;
1515                 sc->rl_twister = SET_PARAM;
1516                 break;
1517
1518         case DONE:
1519                 break;
1520         }
1521         
1522 }
1523
1524 static void
1525 rl_tick(void *xsc)
1526 {
1527         struct rl_softc         *sc = xsc;
1528         struct mii_data         *mii;
1529         int ticks;
1530
1531         RL_LOCK_ASSERT(sc);
1532         /*
1533          * If we're doing the twister cable calibration, then we need to defer
1534          * watchdog timeouts.  This is a no-op in normal operations, but
1535          * can falsely trigger when the cable calibration takes a while and
1536          * there was traffic ready to go when rl was started.
1537          *
1538          * We don't defer mii_tick since that updates the mii status, which
1539          * helps the twister process, at least according to similar patches
1540          * for the Linux driver I found online while doing the fixes.  Worst
1541          * case is a few extra mii reads during calibration.
1542          */
1543         mii = device_get_softc(sc->rl_miibus);
1544         mii_tick(mii);
1545         if ((sc->rl_flags & RL_FLAG_LINK) == 0)
1546                 rl_miibus_statchg(sc->rl_dev);
1547         if (sc->rl_twister_enable) {
1548                 if (sc->rl_twister == DONE)
1549                         rl_watchdog(sc);
1550                 else
1551                         rl_twister_update(sc);
1552                 if (sc->rl_twister == DONE)
1553                         ticks = hz;
1554                 else
1555                         ticks = hz / 10;
1556         } else {
1557                 rl_watchdog(sc);
1558                 ticks = hz;
1559         }
1560
1561         callout_reset(&sc->rl_stat_callout, ticks, rl_tick, sc);
1562 }
1563
1564 #ifdef DEVICE_POLLING
1565 static int
1566 rl_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1567 {
1568         struct rl_softc *sc = ifp->if_softc;
1569         int rx_npkts = 0;
1570
1571         RL_LOCK(sc);
1572         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1573                 rx_npkts = rl_poll_locked(ifp, cmd, count);
1574         RL_UNLOCK(sc);
1575         return (rx_npkts);
1576 }
1577
1578 static int
1579 rl_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
1580 {
1581         struct rl_softc *sc = ifp->if_softc;
1582         int rx_npkts;
1583
1584         RL_LOCK_ASSERT(sc);
1585
1586         sc->rxcycles = count;
1587         rx_npkts = rl_rxeof(sc);
1588         rl_txeof(sc);
1589
1590         if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1591                 rl_start_locked(ifp);
1592
1593         if (cmd == POLL_AND_CHECK_STATUS) {
1594                 uint16_t        status;
1595
1596                 /* We should also check the status register. */
1597                 status = CSR_READ_2(sc, RL_ISR);
1598                 if (status == 0xffff)
1599                         return (rx_npkts);
1600                 if (status != 0)
1601                         CSR_WRITE_2(sc, RL_ISR, status);
1602
1603                 /* XXX We should check behaviour on receiver stalls. */
1604
1605                 if (status & RL_ISR_SYSTEM_ERR)
1606                         rl_init_locked(sc);
1607         }
1608         return (rx_npkts);
1609 }
1610 #endif /* DEVICE_POLLING */
1611
1612 static void
1613 rl_intr(void *arg)
1614 {
1615         struct rl_softc         *sc = arg;
1616         struct ifnet            *ifp = sc->rl_ifp;
1617         uint16_t                status;
1618
1619         RL_LOCK(sc);
1620
1621         if (sc->suspended)
1622                 goto done_locked;
1623
1624 #ifdef DEVICE_POLLING
1625         if  (ifp->if_capenable & IFCAP_POLLING)
1626                 goto done_locked;
1627 #endif
1628
1629         for (;;) {
1630                 status = CSR_READ_2(sc, RL_ISR);
1631                 /* If the card has gone away, the read returns 0xffff. */
1632                 if (status == 0xffff)
1633                         break;
1634                 if (status != 0)
1635                         CSR_WRITE_2(sc, RL_ISR, status);
1636                 if ((status & RL_INTRS) == 0)
1637                         break;
1638                 if (status & RL_ISR_RX_OK)
1639                         rl_rxeof(sc);
1640                 if (status & RL_ISR_RX_ERR)
1641                         rl_rxeof(sc);
1642                 if ((status & RL_ISR_TX_OK) || (status & RL_ISR_TX_ERR))
1643                         rl_txeof(sc);
1644                 if (status & RL_ISR_SYSTEM_ERR)
1645                         rl_init_locked(sc);
1646         }
1647
1648         if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1649                 rl_start_locked(ifp);
1650
1651 done_locked:
1652         RL_UNLOCK(sc);
1653 }
1654
1655 /*
1656  * Encapsulate an mbuf chain in a descriptor by coupling the mbuf data
1657  * pointers to the fragment pointers.
1658  */
1659 static int
1660 rl_encap(struct rl_softc *sc, struct mbuf **m_head)
1661 {
1662         struct mbuf             *m;
1663         bus_dma_segment_t       txsegs[1];
1664         int                     error, nsegs, padlen;
1665
1666         RL_LOCK_ASSERT(sc);
1667
1668         m = *m_head;
1669         padlen = 0;
1670         /*
1671          * Hardware doesn't auto-pad, so we have to make sure
1672          * pad short frames out to the minimum frame length.
1673          */
1674         if (m->m_pkthdr.len < RL_MIN_FRAMELEN)
1675                 padlen = RL_MIN_FRAMELEN - m->m_pkthdr.len;
1676         /*
1677          * The RealTek is brain damaged and wants longword-aligned
1678          * TX buffers, plus we can only have one fragment buffer
1679          * per packet. We have to copy pretty much all the time.
1680          */
1681         if (m->m_next != NULL || (mtod(m, uintptr_t) & 3) != 0 ||
1682             (padlen > 0 && M_TRAILINGSPACE(m) < padlen)) {
1683                 m = m_defrag(*m_head, M_DONTWAIT);
1684                 if (m == NULL) {
1685                         m_freem(*m_head);
1686                         *m_head = NULL;
1687                         return (ENOMEM);
1688                 }
1689         }
1690         *m_head = m;
1691
1692         if (padlen > 0) {
1693                 /*
1694                  * Make security-conscious people happy: zero out the
1695                  * bytes in the pad area, since we don't know what
1696                  * this mbuf cluster buffer's previous user might
1697                  * have left in it.
1698                  */
1699                 bzero(mtod(m, char *) + m->m_pkthdr.len, padlen);
1700                 m->m_pkthdr.len += padlen;
1701                 m->m_len = m->m_pkthdr.len;
1702         }
1703
1704         error = bus_dmamap_load_mbuf_sg(sc->rl_cdata.rl_tx_tag,
1705             RL_CUR_DMAMAP(sc), m, txsegs, &nsegs, 0);
1706         if (error != 0)
1707                 return (error);
1708         if (nsegs == 0) {
1709                 m_freem(*m_head);
1710                 *m_head = NULL;
1711                 return (EIO);
1712         }
1713
1714         RL_CUR_TXMBUF(sc) = m;
1715         bus_dmamap_sync(sc->rl_cdata.rl_tx_tag, RL_CUR_DMAMAP(sc),
1716             BUS_DMASYNC_PREWRITE);
1717         CSR_WRITE_4(sc, RL_CUR_TXADDR(sc), RL_ADDR_LO(txsegs[0].ds_addr));
1718
1719         return (0);
1720 }
1721
1722 /*
1723  * Main transmit routine.
1724  */
1725 static void
1726 rl_start(struct ifnet *ifp)
1727 {
1728         struct rl_softc         *sc = ifp->if_softc;
1729
1730         RL_LOCK(sc);
1731         rl_start_locked(ifp);
1732         RL_UNLOCK(sc);
1733 }
1734
1735 static void
1736 rl_start_locked(struct ifnet *ifp)
1737 {
1738         struct rl_softc         *sc = ifp->if_softc;
1739         struct mbuf             *m_head = NULL;
1740
1741         RL_LOCK_ASSERT(sc);
1742
1743         if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
1744             IFF_DRV_RUNNING || (sc->rl_flags & RL_FLAG_LINK) == 0)
1745                 return;
1746
1747         while (RL_CUR_TXMBUF(sc) == NULL) {
1748
1749                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
1750
1751                 if (m_head == NULL)
1752                         break;
1753
1754                 if (rl_encap(sc, &m_head)) {
1755                         if (m_head == NULL)
1756                                 break;
1757                         IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
1758                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1759                         break;
1760                 }
1761
1762                 /* Pass a copy of this mbuf chain to the bpf subsystem. */
1763                 BPF_MTAP(ifp, RL_CUR_TXMBUF(sc));
1764
1765                 /* Transmit the frame. */
1766                 CSR_WRITE_4(sc, RL_CUR_TXSTAT(sc),
1767                     RL_TXTHRESH(sc->rl_txthresh) |
1768                     RL_CUR_TXMBUF(sc)->m_pkthdr.len);
1769
1770                 RL_INC(sc->rl_cdata.cur_tx);
1771
1772                 /* Set a timeout in case the chip goes out to lunch. */
1773                 sc->rl_watchdog_timer = 5;
1774         }
1775
1776         /*
1777          * We broke out of the loop because all our TX slots are
1778          * full. Mark the NIC as busy until it drains some of the
1779          * packets from the queue.
1780          */
1781         if (RL_CUR_TXMBUF(sc) != NULL)
1782                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1783 }
1784
1785 static void
1786 rl_init(void *xsc)
1787 {
1788         struct rl_softc         *sc = xsc;
1789
1790         RL_LOCK(sc);
1791         rl_init_locked(sc);
1792         RL_UNLOCK(sc);
1793 }
1794
1795 static void
1796 rl_init_locked(struct rl_softc *sc)
1797 {
1798         struct ifnet            *ifp = sc->rl_ifp;
1799         struct mii_data         *mii;
1800         uint32_t                rxcfg = 0;
1801         uint32_t                eaddr[2];
1802
1803         RL_LOCK_ASSERT(sc);
1804
1805         mii = device_get_softc(sc->rl_miibus);
1806
1807         /*
1808          * Cancel pending I/O and free all RX/TX buffers.
1809          */
1810         rl_stop(sc);
1811
1812         rl_reset(sc);
1813         if (sc->rl_twister_enable) {
1814                 /*
1815                  * Reset twister register tuning state.  The twister
1816                  * registers and their tuning are undocumented, but
1817                  * are necessary to cope with bad links.  rl_twister =
1818                  * DONE here will disable this entirely.
1819                  */
1820                 sc->rl_twister = CHK_LINK;
1821         }
1822
1823         /*
1824          * Init our MAC address.  Even though the chipset
1825          * documentation doesn't mention it, we need to enter "Config
1826          * register write enable" mode to modify the ID registers.
1827          */
1828         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_WRITECFG);
1829         bzero(eaddr, sizeof(eaddr));
1830         bcopy(IF_LLADDR(sc->rl_ifp), eaddr, ETHER_ADDR_LEN);
1831         CSR_WRITE_STREAM_4(sc, RL_IDR0, eaddr[0]);
1832         CSR_WRITE_STREAM_4(sc, RL_IDR4, eaddr[1]);
1833         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1834
1835         /* Init the RX memory block pointer register. */
1836         CSR_WRITE_4(sc, RL_RXADDR, sc->rl_cdata.rl_rx_buf_paddr +
1837             RL_RX_8139_BUF_RESERVE);
1838         /* Init TX descriptors. */
1839         rl_list_tx_init(sc);
1840         /* Init Rx memory block. */
1841         rl_list_rx_init(sc);
1842
1843         /*
1844          * Enable transmit and receive.
1845          */
1846         CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
1847
1848         /*
1849          * Set the initial TX and RX configuration.
1850          */
1851         CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
1852         CSR_WRITE_4(sc, RL_RXCFG, RL_RXCFG_CONFIG);
1853
1854         /* Set the individual bit to receive frames for this host only. */
1855         rxcfg = CSR_READ_4(sc, RL_RXCFG);
1856         rxcfg |= RL_RXCFG_RX_INDIV;
1857
1858         /* If we want promiscuous mode, set the allframes bit. */
1859         if (ifp->if_flags & IFF_PROMISC) {
1860                 rxcfg |= RL_RXCFG_RX_ALLPHYS;
1861                 CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1862         } else {
1863                 rxcfg &= ~RL_RXCFG_RX_ALLPHYS;
1864                 CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1865         }
1866
1867         /* Set capture broadcast bit to capture broadcast frames. */
1868         if (ifp->if_flags & IFF_BROADCAST) {
1869                 rxcfg |= RL_RXCFG_RX_BROAD;
1870                 CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1871         } else {
1872                 rxcfg &= ~RL_RXCFG_RX_BROAD;
1873                 CSR_WRITE_4(sc, RL_RXCFG, rxcfg);
1874         }
1875
1876         /* Program the multicast filter, if necessary. */
1877         rl_setmulti(sc);
1878
1879 #ifdef DEVICE_POLLING
1880         /* Disable interrupts if we are polling. */
1881         if (ifp->if_capenable & IFCAP_POLLING)
1882                 CSR_WRITE_2(sc, RL_IMR, 0);
1883         else
1884 #endif
1885         /* Enable interrupts. */
1886         CSR_WRITE_2(sc, RL_IMR, RL_INTRS);
1887
1888         /* Set initial TX threshold */
1889         sc->rl_txthresh = RL_TX_THRESH_INIT;
1890
1891         /* Start RX/TX process. */
1892         CSR_WRITE_4(sc, RL_MISSEDPKT, 0);
1893
1894         /* Enable receiver and transmitter. */
1895         CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB|RL_CMD_RX_ENB);
1896
1897         sc->rl_flags &= ~RL_FLAG_LINK;
1898         mii_mediachg(mii);
1899
1900         CSR_WRITE_1(sc, RL_CFG1, RL_CFG1_DRVLOAD|RL_CFG1_FULLDUPLEX);
1901
1902         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1903         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1904
1905         callout_reset(&sc->rl_stat_callout, hz, rl_tick, sc);
1906 }
1907
1908 /*
1909  * Set media options.
1910  */
1911 static int
1912 rl_ifmedia_upd(struct ifnet *ifp)
1913 {
1914         struct rl_softc         *sc = ifp->if_softc;
1915         struct mii_data         *mii;
1916
1917         mii = device_get_softc(sc->rl_miibus);
1918
1919         RL_LOCK(sc);
1920         mii_mediachg(mii);
1921         RL_UNLOCK(sc);
1922
1923         return (0);
1924 }
1925
1926 /*
1927  * Report current media status.
1928  */
1929 static void
1930 rl_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
1931 {
1932         struct rl_softc         *sc = ifp->if_softc;
1933         struct mii_data         *mii;
1934
1935         mii = device_get_softc(sc->rl_miibus);
1936
1937         RL_LOCK(sc);
1938         mii_pollstat(mii);
1939         RL_UNLOCK(sc);
1940         ifmr->ifm_active = mii->mii_media_active;
1941         ifmr->ifm_status = mii->mii_media_status;
1942 }
1943
1944 static int
1945 rl_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
1946 {
1947         struct ifreq            *ifr = (struct ifreq *)data;
1948         struct mii_data         *mii;
1949         struct rl_softc         *sc = ifp->if_softc;
1950         int                     error = 0, mask;
1951
1952         switch (command) {
1953         case SIOCSIFFLAGS:
1954                 RL_LOCK(sc);
1955                 if (ifp->if_flags & IFF_UP) {
1956                         rl_init_locked(sc);
1957                 } else {
1958                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1959                                 rl_stop(sc);
1960                 }
1961                 RL_UNLOCK(sc);
1962                 error = 0;
1963                 break;
1964         case SIOCADDMULTI:
1965         case SIOCDELMULTI:
1966                 RL_LOCK(sc);
1967                 rl_setmulti(sc);
1968                 RL_UNLOCK(sc);
1969                 error = 0;
1970                 break;
1971         case SIOCGIFMEDIA:
1972         case SIOCSIFMEDIA:
1973                 mii = device_get_softc(sc->rl_miibus);
1974                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
1975                 break;
1976         case SIOCSIFCAP:
1977                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1978 #ifdef DEVICE_POLLING
1979                 if (ifr->ifr_reqcap & IFCAP_POLLING &&
1980                     !(ifp->if_capenable & IFCAP_POLLING)) {
1981                         error = ether_poll_register(rl_poll, ifp);
1982                         if (error)
1983                                 return(error);
1984                         RL_LOCK(sc);
1985                         /* Disable interrupts */
1986                         CSR_WRITE_2(sc, RL_IMR, 0x0000);
1987                         ifp->if_capenable |= IFCAP_POLLING;
1988                         RL_UNLOCK(sc);
1989                         return (error);
1990                         
1991                 }
1992                 if (!(ifr->ifr_reqcap & IFCAP_POLLING) &&
1993                     ifp->if_capenable & IFCAP_POLLING) {
1994                         error = ether_poll_deregister(ifp);
1995                         /* Enable interrupts. */
1996                         RL_LOCK(sc);
1997                         CSR_WRITE_2(sc, RL_IMR, RL_INTRS);
1998                         ifp->if_capenable &= ~IFCAP_POLLING;
1999                         RL_UNLOCK(sc);
2000                         return (error);
2001                 }
2002 #endif /* DEVICE_POLLING */
2003                 if ((mask & IFCAP_WOL) != 0 &&
2004                     (ifp->if_capabilities & IFCAP_WOL) != 0) {
2005                         if ((mask & IFCAP_WOL_UCAST) != 0)
2006                                 ifp->if_capenable ^= IFCAP_WOL_UCAST;
2007                         if ((mask & IFCAP_WOL_MCAST) != 0)
2008                                 ifp->if_capenable ^= IFCAP_WOL_MCAST;
2009                         if ((mask & IFCAP_WOL_MAGIC) != 0)
2010                                 ifp->if_capenable ^= IFCAP_WOL_MAGIC;
2011                 }
2012                 break;
2013         default:
2014                 error = ether_ioctl(ifp, command, data);
2015                 break;
2016         }
2017
2018         return (error);
2019 }
2020
2021 static void
2022 rl_watchdog(struct rl_softc *sc)
2023 {
2024
2025         RL_LOCK_ASSERT(sc);
2026
2027         if (sc->rl_watchdog_timer == 0 || --sc->rl_watchdog_timer >0)
2028                 return;
2029
2030         device_printf(sc->rl_dev, "watchdog timeout\n");
2031         sc->rl_ifp->if_oerrors++;
2032
2033         rl_txeof(sc);
2034         rl_rxeof(sc);
2035         rl_init_locked(sc);
2036 }
2037
2038 /*
2039  * Stop the adapter and free any mbufs allocated to the
2040  * RX and TX lists.
2041  */
2042 static void
2043 rl_stop(struct rl_softc *sc)
2044 {
2045         register int            i;
2046         struct ifnet            *ifp = sc->rl_ifp;
2047
2048         RL_LOCK_ASSERT(sc);
2049
2050         sc->rl_watchdog_timer = 0;
2051         callout_stop(&sc->rl_stat_callout);
2052         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2053         sc->rl_flags &= ~RL_FLAG_LINK;
2054
2055         CSR_WRITE_1(sc, RL_COMMAND, 0x00);
2056         CSR_WRITE_2(sc, RL_IMR, 0x0000);
2057         for (i = 0; i < RL_TIMEOUT; i++) {
2058                 DELAY(10);
2059                 if ((CSR_READ_1(sc, RL_COMMAND) &
2060                     (RL_CMD_RX_ENB | RL_CMD_TX_ENB)) == 0)
2061                         break;
2062         }
2063         if (i == RL_TIMEOUT)
2064                 device_printf(sc->rl_dev, "Unable to stop Tx/Rx MAC\n");
2065
2066         /*
2067          * Free the TX list buffers.
2068          */
2069         for (i = 0; i < RL_TX_LIST_CNT; i++) {
2070                 if (sc->rl_cdata.rl_tx_chain[i] != NULL) {
2071                         if (sc->rl_cdata.rl_tx_chain[i] != NULL) {
2072                                 bus_dmamap_sync(sc->rl_cdata.rl_tx_tag,
2073                                     sc->rl_cdata.rl_tx_dmamap[i],
2074                                     BUS_DMASYNC_POSTWRITE);
2075                                 bus_dmamap_unload(sc->rl_cdata.rl_tx_tag,
2076                                     sc->rl_cdata.rl_tx_dmamap[i]);
2077                                 m_freem(sc->rl_cdata.rl_tx_chain[i]);
2078                                 sc->rl_cdata.rl_tx_chain[i] = NULL;
2079                         }
2080                         CSR_WRITE_4(sc, RL_TXADDR0 + (i * sizeof(uint32_t)),
2081                             0x0000000);
2082                 }
2083         }
2084 }
2085
2086 /*
2087  * Device suspend routine.  Stop the interface and save some PCI
2088  * settings in case the BIOS doesn't restore them properly on
2089  * resume.
2090  */
2091 static int
2092 rl_suspend(device_t dev)
2093 {
2094         struct rl_softc         *sc;
2095
2096         sc = device_get_softc(dev);
2097
2098         RL_LOCK(sc);
2099         rl_stop(sc);
2100         rl_setwol(sc);
2101         sc->suspended = 1;
2102         RL_UNLOCK(sc);
2103
2104         return (0);
2105 }
2106
2107 /*
2108  * Device resume routine.  Restore some PCI settings in case the BIOS
2109  * doesn't, re-enable busmastering, and restart the interface if
2110  * appropriate.
2111  */
2112 static int
2113 rl_resume(device_t dev)
2114 {
2115         struct rl_softc         *sc;
2116         struct ifnet            *ifp;
2117         int                     pmc;
2118         uint16_t                pmstat;
2119
2120         sc = device_get_softc(dev);
2121         ifp = sc->rl_ifp;
2122
2123         RL_LOCK(sc);
2124
2125         if ((ifp->if_capabilities & IFCAP_WOL) != 0 &&
2126             pci_find_extcap(sc->rl_dev, PCIY_PMG, &pmc) == 0) {
2127                 /* Disable PME and clear PME status. */
2128                 pmstat = pci_read_config(sc->rl_dev,
2129                     pmc + PCIR_POWER_STATUS, 2);
2130                 if ((pmstat & PCIM_PSTAT_PMEENABLE) != 0) {
2131                         pmstat &= ~PCIM_PSTAT_PMEENABLE;
2132                         pci_write_config(sc->rl_dev,
2133                             pmc + PCIR_POWER_STATUS, pmstat, 2);
2134                 }
2135                 /*
2136                  * Clear WOL matching such that normal Rx filtering
2137                  * wouldn't interfere with WOL patterns.
2138                  */
2139                 rl_clrwol(sc);
2140         }
2141
2142         /* reinitialize interface if necessary */
2143         if (ifp->if_flags & IFF_UP)
2144                 rl_init_locked(sc);
2145
2146         sc->suspended = 0;
2147
2148         RL_UNLOCK(sc);
2149
2150         return (0);
2151 }
2152
2153 /*
2154  * Stop all chip I/O so that the kernel's probe routines don't
2155  * get confused by errant DMAs when rebooting.
2156  */
2157 static int
2158 rl_shutdown(device_t dev)
2159 {
2160         struct rl_softc         *sc;
2161
2162         sc = device_get_softc(dev);
2163
2164         RL_LOCK(sc);
2165         rl_stop(sc);
2166         /*
2167          * Mark interface as down since otherwise we will panic if
2168          * interrupt comes in later on, which can happen in some
2169          * cases.
2170          */
2171         sc->rl_ifp->if_flags &= ~IFF_UP;
2172         rl_setwol(sc);
2173         RL_UNLOCK(sc);
2174
2175         return (0);
2176 }
2177
2178 static void
2179 rl_setwol(struct rl_softc *sc)
2180 {
2181         struct ifnet            *ifp;
2182         int                     pmc;
2183         uint16_t                pmstat;
2184         uint8_t                 v;
2185
2186         RL_LOCK_ASSERT(sc);
2187
2188         ifp = sc->rl_ifp;
2189         if ((ifp->if_capabilities & IFCAP_WOL) == 0)
2190                 return;
2191         if (pci_find_extcap(sc->rl_dev, PCIY_PMG, &pmc) != 0)
2192                 return;
2193
2194         /* Enable config register write. */
2195         CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
2196
2197         /* Enable PME. */
2198         v = CSR_READ_1(sc, RL_CFG1);
2199         v &= ~RL_CFG1_PME;
2200         if ((ifp->if_capenable & IFCAP_WOL) != 0)
2201                 v |= RL_CFG1_PME;
2202         CSR_WRITE_1(sc, RL_CFG1, v);
2203
2204         v = CSR_READ_1(sc, RL_CFG3);
2205         v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
2206         if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
2207                 v |= RL_CFG3_WOL_MAGIC;
2208         CSR_WRITE_1(sc, RL_CFG3, v);
2209
2210         /* Config register write done. */
2211         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
2212
2213         v = CSR_READ_1(sc, RL_CFG5);
2214         v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST);
2215         v &= ~RL_CFG5_WOL_LANWAKE;
2216         if ((ifp->if_capenable & IFCAP_WOL_UCAST) != 0)
2217                 v |= RL_CFG5_WOL_UCAST;
2218         if ((ifp->if_capenable & IFCAP_WOL_MCAST) != 0)
2219                 v |= RL_CFG5_WOL_MCAST | RL_CFG5_WOL_BCAST;
2220         if ((ifp->if_capenable & IFCAP_WOL) != 0)
2221                 v |= RL_CFG5_WOL_LANWAKE;
2222         CSR_WRITE_1(sc, RL_CFG5, v);
2223         /* Request PME if WOL is requested. */
2224         pmstat = pci_read_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, 2);
2225         pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
2226         if ((ifp->if_capenable & IFCAP_WOL) != 0)
2227                 pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
2228         pci_write_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, pmstat, 2);
2229 }
2230
2231 static void
2232 rl_clrwol(struct rl_softc *sc)
2233 {
2234         struct ifnet            *ifp;
2235         uint8_t                 v;
2236
2237         ifp = sc->rl_ifp;
2238         if ((ifp->if_capabilities & IFCAP_WOL) == 0)
2239                 return;
2240
2241         /* Enable config register write. */
2242         CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
2243
2244         v = CSR_READ_1(sc, RL_CFG3);
2245         v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
2246         CSR_WRITE_1(sc, RL_CFG3, v);
2247
2248         /* Config register write done. */
2249         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
2250
2251         v = CSR_READ_1(sc, RL_CFG5);
2252         v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST);
2253         v &= ~RL_CFG5_WOL_LANWAKE;
2254         CSR_WRITE_1(sc, RL_CFG5, v);
2255 }