setup enviroment for compilation
[linux-2.4.21-pre4.git] / drivers / net / 8139too.c
1 /*
2
3         8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
4
5         Maintained by Jeff Garzik <jgarzik@pobox.com>
6         Copyright 2000-2002 Jeff Garzik
7
8         Much code comes from Donald Becker's rtl8139.c driver,
9         versions 1.13 and older.  This driver was originally based
10         on rtl8139.c version 1.07.  Header of rtl8139.c version 1.13:
11
12         -----<snip>-----
13
14                 Written 1997-2001 by Donald Becker.
15                 This software may be used and distributed according to the
16                 terms of the GNU General Public License (GPL), incorporated
17                 herein by reference.  Drivers based on or derived from this
18                 code fall under the GPL and must retain the authorship,
19                 copyright and license notice.  This file is not a complete
20                 program and may only be used when the entire operating
21                 system is licensed under the GPL.
22
23                 This driver is for boards based on the RTL8129 and RTL8139
24                 PCI ethernet chips.
25
26                 The author may be reached as becker@scyld.com, or C/O Scyld
27                 Computing Corporation 410 Severn Ave., Suite 210 Annapolis
28                 MD 21403
29
30                 Support and updates available at
31                 http://www.scyld.com/network/rtl8139.html
32
33                 Twister-tuning table provided by Kinston
34                 <shangh@realtek.com.tw>.
35
36         -----<snip>-----
37
38         This software may be used and distributed according to the terms
39         of the GNU General Public License, incorporated herein by reference.
40
41         Contributors:
42
43                 Donald Becker - he wrote the original driver, kudos to him!
44                 (but please don't e-mail him for support, this isn't his driver)
45
46                 Tigran Aivazian - bug fixes, skbuff free cleanup
47
48                 Martin Mares - suggestions for PCI cleanup
49
50                 David S. Miller - PCI DMA and softnet updates
51
52                 Ernst Gill - fixes ported from BSD driver
53
54                 Daniel Kobras - identified specific locations of
55                         posted MMIO write bugginess
56
57                 Gerard Sharp - bug fix, testing and feedback
58
59                 David Ford - Rx ring wrap fix
60
61                 Dan DeMaggio - swapped RTL8139 cards with me, and allowed me
62                 to find and fix a crucial bug on older chipsets.
63
64                 Donald Becker/Chris Butterworth/Marcus Westergren -
65                 Noticed various Rx packet size-related buglets.
66
67                 Santiago Garcia Mantinan - testing and feedback
68
69                 Jens David - 2.2.x kernel backports
70
71                 Martin Dennett - incredibly helpful insight on undocumented
72                 features of the 8139 chips
73
74                 Jean-Jacques Michel - bug fix
75
76                 Tobias Ringström - Rx interrupt status checking suggestion
77
78                 Andrew Morton - Clear blocked signals, avoid
79                 buffer overrun setting current->comm.
80
81                 Kalle Olavi Niemitalo - Wake-on-LAN ioctls
82
83                 Robert Kuebel - Save kernel thread from dying on any signal.
84
85         Submitting bug reports:
86
87                 "rtl8139-diag -mmmaaavvveefN" output
88                 enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log
89
90                 See 8139too.txt for more details.
91
92 */
93
94 #define DRV_NAME        "8139too"
95 #define DRV_VERSION     "0.9.26"
96
97
98 #include <linux/config.h>
99 #include <linux/module.h>
100 #include <linux/kernel.h>
101 #include <linux/compiler.h>
102 #include <linux/pci.h>
103 #include <linux/init.h>
104 #include <linux/ioport.h>
105 #include <linux/netdevice.h>
106 #include <linux/etherdevice.h>
107 #include <linux/rtnetlink.h>
108 #include <linux/delay.h>
109 #include <linux/ethtool.h>
110 #include <linux/mii.h>
111 #include <linux/completion.h>
112 #include <linux/crc32.h>
113 #include <asm/io.h>
114 #include <asm/uaccess.h>
115
116 #define RTL8139_DRIVER_NAME   DRV_NAME " Fast Ethernet driver " DRV_VERSION
117 #define PFX DRV_NAME ": "
118
119
120 /* enable PIO instead of MMIO, if CONFIG_8139TOO_PIO is selected */
121 #ifdef CONFIG_8139TOO_PIO
122 #define USE_IO_OPS 1
123 #endif
124
125 /* define to 1 to enable copious debugging info */
126 #undef RTL8139_DEBUG
127
128 /* define to 1 to disable lightweight runtime debugging checks */
129 #undef RTL8139_NDEBUG
130
131
132 #ifdef RTL8139_DEBUG
133 /* note: prints function name for you */
134 #  define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt, __FUNCTION__ , ## args)
135 #else
136 #  define DPRINTK(fmt, args...)
137 #endif
138
139 #ifdef RTL8139_NDEBUG
140 #  define assert(expr) do {} while (0)
141 #else
142 #  define assert(expr) \
143         if(!(expr)) {                                   \
144         printk( "Assertion failed! %s,%s,%s,line=%d\n", \
145         #expr,__FILE__,__FUNCTION__,__LINE__);          \
146         }
147 #endif
148
149
150 /* A few user-configurable values. */
151 /* media options */
152 #define MAX_UNITS 8
153 static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
154 static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
155
156 /* Maximum events (Rx packets, etc.) to handle at each interrupt. */
157 static int max_interrupt_work = 20;
158
159 /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
160    The RTL chips use a 64 element hash table based on the Ethernet CRC.  */
161 static int multicast_filter_limit = 32;
162
163 /* bitmapped message enable number */
164 static int debug = -1;
165
166 /* Size of the in-memory receive ring. */
167 #define RX_BUF_LEN_IDX  2       /* 0==8K, 1==16K, 2==32K, 3==64K */
168 #define RX_BUF_LEN      (8192 << RX_BUF_LEN_IDX)
169 #define RX_BUF_PAD      16
170 #define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */
171 #define RX_BUF_TOT_LEN  (RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD)
172
173 /* Number of Tx descriptor registers. */
174 #define NUM_TX_DESC     4
175
176 /* max supported ethernet frame size -- must be at least (dev->mtu+14+4).*/
177 #define MAX_ETH_FRAME_SIZE      1536
178
179 /* Size of the Tx bounce buffers -- must be at least (dev->mtu+14+4). */
180 #define TX_BUF_SIZE     MAX_ETH_FRAME_SIZE
181 #define TX_BUF_TOT_LEN  (TX_BUF_SIZE * NUM_TX_DESC)
182
183 /* PCI Tuning Parameters
184    Threshold is bytes transferred to chip before transmission starts. */
185 #define TX_FIFO_THRESH 256      /* In bytes, rounded down to 32 byte units. */
186
187 /* The following settings are log_2(bytes)-4:  0 == 16 bytes .. 6==1024, 7==end of packet. */
188 #define RX_FIFO_THRESH  7       /* Rx buffer level before first PCI xfer.  */
189 #define RX_DMA_BURST    7       /* Maximum PCI burst, '6' is 1024 */
190 #define TX_DMA_BURST    6       /* Maximum PCI burst, '6' is 1024 */
191 #define TX_RETRY        8       /* 0-15.  retries = 16 + (TX_RETRY * 16) */
192
193 /* Operational parameters that usually are not changed. */
194 /* Time in jiffies before concluding the transmitter is hung. */
195 #define TX_TIMEOUT  (6*HZ)
196
197
198 enum {
199         HAS_MII_XCVR = 0x010000,
200         HAS_CHIP_XCVR = 0x020000,
201         HAS_LNK_CHNG = 0x040000,
202 };
203
204 #define RTL_NUM_STATS 4         /* number of ETHTOOL_GSTATS u64's */
205 #define RTL_REGS_VER 1          /* version of reg. data in ETHTOOL_GREGS */
206 #define RTL_MIN_IO_SIZE 0x80
207 #define RTL8139B_IO_SIZE 256
208
209 #define RTL8129_CAPS    HAS_MII_XCVR
210 #define RTL8139_CAPS    HAS_CHIP_XCVR|HAS_LNK_CHNG
211
212 typedef enum {
213         RTL8139 = 0,
214         RTL8139_CB,
215         SMC1211TX,
216         /*MPX5030,*/
217         DELTA8139,
218         ADDTRON8139,
219         DFE538TX,
220         DFE690TXD,
221         FE2000VX,
222         ALLIED8139,
223         RTL8129,
224         FNW3603TX,
225         FNW3800TX,
226 } board_t;
227
228
229 /* indexed by board_t, above */
230 static struct {
231         const char *name;
232         u32 hw_flags;
233 } board_info[] __devinitdata = {
234         { "RealTek RTL8139 Fast Ethernet", RTL8139_CAPS },
235         { "RealTek RTL8139B PCI/CardBus", RTL8139_CAPS },
236         { "SMC1211TX EZCard 10/100 (RealTek RTL8139)", RTL8139_CAPS },
237 /*      { MPX5030, "Accton MPX5030 (RealTek RTL8139)", RTL8139_CAPS },*/
238         { "Delta Electronics 8139 10/100BaseTX", RTL8139_CAPS },
239         { "Addtron Technolgy 8139 10/100BaseTX", RTL8139_CAPS },
240         { "D-Link DFE-538TX (RealTek RTL8139)", RTL8139_CAPS },
241         { "D-Link DFE-690TXD (RealTek RTL8139)", RTL8139_CAPS },
242         { "AboCom FE2000VX (RealTek RTL8139)", RTL8139_CAPS },
243         { "Allied Telesyn 8139 CardBus", RTL8139_CAPS },
244         { "RealTek RTL8129", RTL8129_CAPS },
245         { "Planex FNW-3603-TX 10/100 CardBus", RTL8139_CAPS },
246         { "Planex FNW-3800-TX 10/100 CardBus", RTL8139_CAPS },
247 };
248
249
250 static struct pci_device_id rtl8139_pci_tbl[] __devinitdata = {
251         {0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
252         {0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139_CB },
253         {0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, SMC1211TX },
254 /*      {0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MPX5030 },*/
255         {0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DELTA8139 },
256         {0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ADDTRON8139 },
257         {0x1186, 0x1300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DFE538TX },
258         {0x1186, 0x1340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DFE690TXD },
259         {0x13d1, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, FE2000VX },
260         {0x1259, 0xa117, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ALLIED8139 },
261         {0x14ea, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, FNW3603TX },
262         {0x14ea, 0xab07, PCI_ANY_ID, PCI_ANY_ID, 0, 0, FNW3800TX },
263
264 #ifdef CONFIG_8139TOO_8129
265         {0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8129 },
266 #endif
267
268         /* some crazy cards report invalid vendor ids like
269          * 0x0001 here.  The other ids are valid and constant,
270          * so we simply don't match on the main vendor id.
271          */
272         {PCI_ANY_ID, 0x8139, 0x10ec, 0x8139, 0, 0, RTL8139 },
273         {PCI_ANY_ID, 0x8139, 0x1186, 0x1300, 0, 0, DFE538TX },
274         {PCI_ANY_ID, 0x8139, 0x13d1, 0xab06, 0, 0, FE2000VX },
275
276         {0,}
277 };
278 MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
279
280 static struct {
281         const char str[ETH_GSTRING_LEN];
282 } ethtool_stats_keys[] = {
283         { "early_rx" },
284         { "tx_buf_mapped" },
285         { "tx_timeouts" },
286         { "rx_lost_in_ring" },
287 };
288
289 /* The rest of these values should never change. */
290
291 /* Symbolic offsets to registers. */
292 enum RTL8139_registers {
293         MAC0 = 0,               /* Ethernet hardware address. */
294         MAR0 = 8,               /* Multicast filter. */
295         TxStatus0 = 0x10,       /* Transmit status (Four 32bit registers). */
296         TxAddr0 = 0x20,         /* Tx descriptors (also four 32bit). */
297         RxBuf = 0x30,
298         ChipCmd = 0x37,
299         RxBufPtr = 0x38,
300         RxBufAddr = 0x3A,
301         IntrMask = 0x3C,
302         IntrStatus = 0x3E,
303         TxConfig = 0x40,
304         ChipVersion = 0x43,
305         RxConfig = 0x44,
306         Timer = 0x48,           /* A general-purpose counter. */
307         RxMissed = 0x4C,        /* 24 bits valid, write clears. */
308         Cfg9346 = 0x50,
309         Config0 = 0x51,
310         Config1 = 0x52,
311         FlashReg = 0x54,
312         MediaStatus = 0x58,
313         Config3 = 0x59,
314         Config4 = 0x5A,         /* absent on RTL-8139A */
315         HltClk = 0x5B,
316         MultiIntr = 0x5C,
317         TxSummary = 0x60,
318         BasicModeCtrl = 0x62,
319         BasicModeStatus = 0x64,
320         NWayAdvert = 0x66,
321         NWayLPAR = 0x68,
322         NWayExpansion = 0x6A,
323         /* Undocumented registers, but required for proper operation. */
324         FIFOTMS = 0x70,         /* FIFO Control and test. */
325         CSCR = 0x74,            /* Chip Status and Configuration Register. */
326         PARA78 = 0x78,
327         PARA7c = 0x7c,          /* Magic transceiver parameter register. */
328         Config5 = 0xD8,         /* absent on RTL-8139A */
329 };
330
331 enum ClearBitMasks {
332         MultiIntrClear = 0xF000,
333         ChipCmdClear = 0xE2,
334         Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
335 };
336
337 enum ChipCmdBits {
338         CmdReset = 0x10,
339         CmdRxEnb = 0x08,
340         CmdTxEnb = 0x04,
341         RxBufEmpty = 0x01,
342 };
343
344 /* Interrupt register bits, using my own meaningful names. */
345 enum IntrStatusBits {
346         PCIErr = 0x8000,
347         PCSTimeout = 0x4000,
348         RxFIFOOver = 0x40,
349         RxUnderrun = 0x20,
350         RxOverflow = 0x10,
351         TxErr = 0x08,
352         TxOK = 0x04,
353         RxErr = 0x02,
354         RxOK = 0x01,
355
356         RxAckBits = RxFIFOOver | RxOverflow | RxOK,
357 };
358
359 enum TxStatusBits {
360         TxHostOwns = 0x2000,
361         TxUnderrun = 0x4000,
362         TxStatOK = 0x8000,
363         TxOutOfWindow = 0x20000000,
364         TxAborted = 0x40000000,
365         TxCarrierLost = 0x80000000,
366 };
367 enum RxStatusBits {
368         RxMulticast = 0x8000,
369         RxPhysical = 0x4000,
370         RxBroadcast = 0x2000,
371         RxBadSymbol = 0x0020,
372         RxRunt = 0x0010,
373         RxTooLong = 0x0008,
374         RxCRCErr = 0x0004,
375         RxBadAlign = 0x0002,
376         RxStatusOK = 0x0001,
377 };
378
379 /* Bits in RxConfig. */
380 enum rx_mode_bits {
381         AcceptErr = 0x20,
382         AcceptRunt = 0x10,
383         AcceptBroadcast = 0x08,
384         AcceptMulticast = 0x04,
385         AcceptMyPhys = 0x02,
386         AcceptAllPhys = 0x01,
387 };
388
389 /* Bits in TxConfig. */
390 enum tx_config_bits {
391         TxIFG1 = (1 << 25),     /* Interframe Gap Time */
392         TxIFG0 = (1 << 24),     /* Enabling these bits violates IEEE 802.3 */
393         TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */
394         TxCRC = (1 << 16),      /* DISABLE appending CRC to end of Tx packets */
395         TxClearAbt = (1 << 0),  /* Clear abort (WO) */
396         TxDMAShift = 8,         /* DMA burst value (0-7) is shifted this many bits */
397         TxRetryShift = 4,       /* TXRR value (0-15) is shifted this many bits */
398
399         TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */
400 };
401
402 /* Bits in Config1 */
403 enum Config1Bits {
404         Cfg1_PM_Enable = 0x01,
405         Cfg1_VPD_Enable = 0x02,
406         Cfg1_PIO = 0x04,
407         Cfg1_MMIO = 0x08,
408         LWAKE = 0x10,           /* not on 8139, 8139A */
409         Cfg1_Driver_Load = 0x20,
410         Cfg1_LED0 = 0x40,
411         Cfg1_LED1 = 0x80,
412         SLEEP = (1 << 1),       /* only on 8139, 8139A */
413         PWRDN = (1 << 0),       /* only on 8139, 8139A */
414 };
415
416 /* Bits in Config3 */
417 enum Config3Bits {
418         Cfg3_FBtBEn    = (1 << 0), /* 1 = Fast Back to Back */
419         Cfg3_FuncRegEn = (1 << 1), /* 1 = enable CardBus Function registers */
420         Cfg3_CLKRUN_En = (1 << 2), /* 1 = enable CLKRUN */
421         Cfg3_CardB_En  = (1 << 3), /* 1 = enable CardBus registers */
422         Cfg3_LinkUp    = (1 << 4), /* 1 = wake up on link up */
423         Cfg3_Magic     = (1 << 5), /* 1 = wake up on Magic Packet (tm) */
424         Cfg3_PARM_En   = (1 << 6), /* 0 = software can set twister parameters */
425         Cfg3_GNTSel    = (1 << 7), /* 1 = delay 1 clock from PCI GNT signal */
426 };
427
428 /* Bits in Config4 */
429 enum Config4Bits {
430         LWPTN = (1 << 2),       /* not on 8139, 8139A */
431 };
432
433 /* Bits in Config5 */
434 enum Config5Bits {
435         Cfg5_PME_STS     = (1 << 0), /* 1 = PCI reset resets PME_Status */
436         Cfg5_LANWake     = (1 << 1), /* 1 = enable LANWake signal */
437         Cfg5_LDPS        = (1 << 2), /* 0 = save power when link is down */
438         Cfg5_FIFOAddrPtr = (1 << 3), /* Realtek internal SRAM testing */
439         Cfg5_UWF         = (1 << 4), /* 1 = accept unicast wakeup frame */
440         Cfg5_MWF         = (1 << 5), /* 1 = accept multicast wakeup frame */
441         Cfg5_BWF         = (1 << 6), /* 1 = accept broadcast wakeup frame */
442 };
443
444 enum RxConfigBits {
445         /* rx fifo threshold */
446         RxCfgFIFOShift = 13,
447         RxCfgFIFONone = (7 << RxCfgFIFOShift),
448
449         /* Max DMA burst */
450         RxCfgDMAShift = 8,
451         RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
452
453         /* rx ring buffer length */
454         RxCfgRcv8K = 0,
455         RxCfgRcv16K = (1 << 11),
456         RxCfgRcv32K = (1 << 12),
457         RxCfgRcv64K = (1 << 11) | (1 << 12),
458
459         /* Disable packet wrap at end of Rx buffer */
460         RxNoWrap = (1 << 7),
461 };
462
463
464 /* Twister tuning parameters from RealTek.
465    Completely undocumented, but required to tune bad links on some boards. */
466 enum CSCRBits {
467         CSCR_LinkOKBit = 0x0400,
468         CSCR_LinkChangeBit = 0x0800,
469         CSCR_LinkStatusBits = 0x0f000,
470         CSCR_LinkDownOffCmd = 0x003c0,
471         CSCR_LinkDownCmd = 0x0f3c0,
472 };
473
474
475 enum Cfg9346Bits {
476         Cfg9346_Lock = 0x00,
477         Cfg9346_Unlock = 0xC0,
478 };
479
480 #ifdef CONFIG_8139TOO_TUNE_TWISTER
481
482 enum TwisterParamVals {
483         PARA78_default  = 0x78fa8388,
484         PARA7c_default  = 0xcb38de43,   /* param[0][3] */
485         PARA7c_xxx      = 0xcb38de43,
486 };
487
488 static const unsigned long param[4][4] = {
489         {0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
490         {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
491         {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
492         {0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
493 };
494
495 #endif /* CONFIG_8139TOO_TUNE_TWISTER */
496
497 typedef enum {
498         CH_8139 = 0,
499         CH_8139_K,
500         CH_8139A,
501         CH_8139B,
502         CH_8130,
503         CH_8139C,
504 } chip_t;
505
506 enum chip_flags {
507         HasHltClk = (1 << 0),
508         HasLWake = (1 << 1),
509 };
510
511
512 /* directly indexed by chip_t, above */
513 const static struct {
514         const char *name;
515         u8 version; /* from RTL8139C docs */
516         u32 RxConfigMask; /* should clear the bits supported by this chip */
517         u32 flags;
518 } rtl_chip_info[] = {
519         { "RTL-8139",
520           0x40,
521           0xf0fe0040, /* XXX copied from RTL8139A, verify */
522           HasHltClk,
523         },
524
525         { "RTL-8139 rev K",
526           0x60,
527           0xf0fe0040,
528           HasHltClk,
529         },
530
531         { "RTL-8139A",
532           0x70,
533           0xf0fe0040,
534           HasHltClk, /* XXX undocumented? */
535         },
536
537         { "RTL-8139B",
538           0x78,
539           0xf0fc0040,
540           HasLWake,
541         },
542
543         { "RTL-8130",
544           0x7C,
545           0xf0fe0040, /* XXX copied from RTL8139A, verify */
546           HasLWake,
547         },
548
549         { "RTL-8139C",
550           0x74,
551           0xf0fc0040, /* XXX copied from RTL8139B, verify */
552           HasLWake,
553         },
554
555 };
556
557 struct rtl_extra_stats {
558         unsigned long early_rx;
559         unsigned long tx_buf_mapped;
560         unsigned long tx_timeouts;
561         unsigned long rx_lost_in_ring;
562 };
563
564 struct rtl8139_private {
565         void *mmio_addr;
566         int drv_flags;
567         struct pci_dev *pci_dev;
568         struct net_device_stats stats;
569         unsigned char *rx_ring;
570         unsigned int cur_rx;    /* Index into the Rx buffer of next Rx pkt. */
571         unsigned int tx_flag;
572         unsigned long cur_tx;
573         unsigned long dirty_tx;
574         unsigned char *tx_buf[NUM_TX_DESC];     /* Tx bounce buffers */
575         unsigned char *tx_bufs; /* Tx bounce buffer region. */
576         dma_addr_t rx_ring_dma;
577         dma_addr_t tx_bufs_dma;
578         signed char phys[4];            /* MII device addresses. */
579         char twistie, twist_row, twist_col;     /* Twister tune state. */
580         unsigned int default_port:4;    /* Last dev->if_port value. */
581         spinlock_t lock;
582         chip_t chipset;
583         pid_t thr_pid;
584         wait_queue_head_t thr_wait;
585         struct completion thr_exited;
586         u32 rx_config;
587         struct rtl_extra_stats xstats;
588         int time_to_die;
589         struct mii_if_info mii;
590         unsigned int regs_len;
591 };
592
593 MODULE_AUTHOR ("Jeff Garzik <jgarzik@pobox.com>");
594 MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver");
595 MODULE_LICENSE("GPL");
596
597 MODULE_PARM (multicast_filter_limit, "i");
598 MODULE_PARM (max_interrupt_work, "i");
599 MODULE_PARM (media, "1-" __MODULE_STRING(MAX_UNITS) "i");
600 MODULE_PARM (full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
601 MODULE_PARM (debug, "i");
602 MODULE_PARM_DESC (debug, "8139too bitmapped message enable number");
603 MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses");
604 MODULE_PARM_DESC (max_interrupt_work, "8139too maximum events handled per interrupt");
605 MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps");
606 MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)");
607
608 static int read_eeprom (void *ioaddr, int location, int addr_len);
609 static int rtl8139_open (struct net_device *dev);
610 static int mdio_read (struct net_device *dev, int phy_id, int location);
611 static void mdio_write (struct net_device *dev, int phy_id, int location,
612                         int val);
613 static int rtl8139_thread (void *data);
614 static void rtl8139_tx_timeout (struct net_device *dev);
615 static void rtl8139_init_ring (struct net_device *dev);
616 static int rtl8139_start_xmit (struct sk_buff *skb,
617                                struct net_device *dev);
618 static void rtl8139_interrupt (int irq, void *dev_instance,
619                                struct pt_regs *regs);
620 static int rtl8139_close (struct net_device *dev);
621 static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
622 static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
623 static void rtl8139_set_rx_mode (struct net_device *dev);
624 static void __set_rx_mode (struct net_device *dev);
625 static void rtl8139_hw_start (struct net_device *dev);
626
627 #ifdef USE_IO_OPS
628
629 #define RTL_R8(reg)             inb (((unsigned long)ioaddr) + (reg))
630 #define RTL_R16(reg)            inw (((unsigned long)ioaddr) + (reg))
631 #define RTL_R32(reg)            ((unsigned long) inl (((unsigned long)ioaddr) + (reg)))
632 #define RTL_W8(reg, val8)       outb ((val8), ((unsigned long)ioaddr) + (reg))
633 #define RTL_W16(reg, val16)     outw ((val16), ((unsigned long)ioaddr) + (reg))
634 #define RTL_W32(reg, val32)     outl ((val32), ((unsigned long)ioaddr) + (reg))
635 #define RTL_W8_F                RTL_W8
636 #define RTL_W16_F               RTL_W16
637 #define RTL_W32_F               RTL_W32
638 #undef readb
639 #undef readw
640 #undef readl
641 #undef writeb
642 #undef writew
643 #undef writel
644 #define readb(addr) inb((unsigned long)(addr))
645 #define readw(addr) inw((unsigned long)(addr))
646 #define readl(addr) inl((unsigned long)(addr))
647 #define writeb(val,addr) outb((val),(unsigned long)(addr))
648 #define writew(val,addr) outw((val),(unsigned long)(addr))
649 #define writel(val,addr) outl((val),(unsigned long)(addr))
650
651 #else
652
653 /* write MMIO register, with flush */
654 /* Flush avoids rtl8139 bug w/ posted MMIO writes */
655 #define RTL_W8_F(reg, val8)     do { writeb ((val8), ioaddr + (reg)); readb (ioaddr + (reg)); } while (0)
656 #define RTL_W16_F(reg, val16)   do { writew ((val16), ioaddr + (reg)); readw (ioaddr + (reg)); } while (0)
657 #define RTL_W32_F(reg, val32)   do { writel ((val32), ioaddr + (reg)); readl (ioaddr + (reg)); } while (0)
658
659
660 #define MMIO_FLUSH_AUDIT_COMPLETE 1
661 #if MMIO_FLUSH_AUDIT_COMPLETE
662
663 /* write MMIO register */
664 #define RTL_W8(reg, val8)       writeb ((val8), ioaddr + (reg))
665 #define RTL_W16(reg, val16)     writew ((val16), ioaddr + (reg))
666 #define RTL_W32(reg, val32)     writel ((val32), ioaddr + (reg))
667
668 #else
669
670 /* write MMIO register, then flush */
671 #define RTL_W8          RTL_W8_F
672 #define RTL_W16         RTL_W16_F
673 #define RTL_W32         RTL_W32_F
674
675 #endif /* MMIO_FLUSH_AUDIT_COMPLETE */
676
677 /* read MMIO register */
678 #define RTL_R8(reg)             readb (ioaddr + (reg))
679 #define RTL_R16(reg)            readw (ioaddr + (reg))
680 #define RTL_R32(reg)            ((unsigned long) readl (ioaddr + (reg)))
681
682 #endif /* USE_IO_OPS */
683
684
685 static const u16 rtl8139_intr_mask =
686         PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
687         TxErr | TxOK | RxErr | RxOK;
688
689 static const unsigned int rtl8139_rx_config =
690         RxCfgRcv32K | RxNoWrap |
691         (RX_FIFO_THRESH << RxCfgFIFOShift) |
692         (RX_DMA_BURST << RxCfgDMAShift);
693
694 static const unsigned int rtl8139_tx_config =
695         (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift);
696
697 static void __rtl8139_cleanup_dev (struct net_device *dev)
698 {
699         struct rtl8139_private *tp;
700         struct pci_dev *pdev;
701
702         assert (dev != NULL);
703         assert (dev->priv != NULL);
704
705         tp = dev->priv;
706         assert (tp->pci_dev != NULL);
707         pdev = tp->pci_dev;
708
709 #ifndef USE_IO_OPS
710         if (tp->mmio_addr)
711                 iounmap (tp->mmio_addr);
712 #endif /* !USE_IO_OPS */
713
714         /* it's ok to call this even if we have no regions to free */
715         pci_release_regions (pdev);
716
717 #ifndef RTL8139_NDEBUG
718         /* poison memory before freeing */
719         memset (dev, 0xBC,
720                 sizeof (struct net_device) +
721                 sizeof (struct rtl8139_private));
722 #endif /* RTL8139_NDEBUG */
723
724         kfree (dev);
725
726         pci_set_drvdata (pdev, NULL);
727 }
728
729
730 static void rtl8139_chip_reset (void *ioaddr)
731 {
732         int i;
733
734         /* Soft reset the chip. */
735         RTL_W8 (ChipCmd, CmdReset);
736
737         /* Check that the chip has finished the reset. */
738         for (i = 1000; i > 0; i--) {
739                 barrier();
740                 if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
741                         break;
742                 udelay (10);
743         }
744 }
745
746
747 static int __devinit rtl8139_init_board (struct pci_dev *pdev,
748                                          struct net_device **dev_out)
749 {
750         void *ioaddr;
751         struct net_device *dev;
752         struct rtl8139_private *tp;
753         u8 tmp8;
754         int rc;
755         unsigned int i;
756         u32 pio_start, pio_end, pio_flags, pio_len;
757         unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
758         u32 tmp;
759
760         assert (pdev != NULL);
761
762         *dev_out = NULL;
763
764         /* dev and dev->priv zeroed in alloc_etherdev */
765         dev = alloc_etherdev (sizeof (*tp));
766         if (dev == NULL) {
767                 printk (KERN_ERR PFX "%s: Unable to alloc new net device\n", pdev->slot_name);
768                 return -ENOMEM;
769         }
770         SET_MODULE_OWNER(dev);
771         tp = dev->priv;
772         tp->pci_dev = pdev;
773
774         /* enable device (incl. PCI PM wakeup and hotplug setup) */
775         rc = pci_enable_device (pdev);
776         if (rc)
777                 goto err_out;
778
779         pio_start = pci_resource_start (pdev, 0);
780         pio_end = pci_resource_end (pdev, 0);
781         pio_flags = pci_resource_flags (pdev, 0);
782         pio_len = pci_resource_len (pdev, 0);
783
784         mmio_start = pci_resource_start (pdev, 1);
785         mmio_end = pci_resource_end (pdev, 1);
786         mmio_flags = pci_resource_flags (pdev, 1);
787         mmio_len = pci_resource_len (pdev, 1);
788
789         /* set this immediately, we need to know before
790          * we talk to the chip directly */
791         DPRINTK("PIO region size == 0x%02X\n", pio_len);
792         DPRINTK("MMIO region size == 0x%02lX\n", mmio_len);
793
794 #ifdef USE_IO_OPS
795         /* make sure PCI base addr 0 is PIO */
796         if (!(pio_flags & IORESOURCE_IO)) {
797                 printk (KERN_ERR PFX "%s: region #0 not a PIO resource, aborting\n", pdev->slot_name);
798                 rc = -ENODEV;
799                 goto err_out;
800         }
801         /* check for weird/broken PCI region reporting */
802         if (pio_len < RTL_MIN_IO_SIZE) {
803                 printk (KERN_ERR PFX "%s: Invalid PCI I/O region size(s), aborting\n", pdev->slot_name);
804                 rc = -ENODEV;
805                 goto err_out;
806         }
807 #else
808         /* make sure PCI base addr 1 is MMIO */
809         if (!(mmio_flags & IORESOURCE_MEM)) {
810                 printk (KERN_ERR PFX "%s: region #1 not an MMIO resource, aborting\n", pdev->slot_name);
811                 rc = -ENODEV;
812                 goto err_out;
813         }
814         if (mmio_len < RTL_MIN_IO_SIZE) {
815                 printk (KERN_ERR PFX "%s: Invalid PCI mem region size(s), aborting\n", pdev->slot_name);
816                 rc = -ENODEV;
817                 goto err_out;
818         }
819 #endif
820
821         rc = pci_request_regions (pdev, "8139too");
822         if (rc)
823                 goto err_out;
824
825         /* enable PCI bus-mastering */
826         pci_set_master (pdev);
827
828 #ifdef USE_IO_OPS
829         ioaddr = (void *) pio_start;
830         dev->base_addr = pio_start;
831         tp->mmio_addr = ioaddr;
832         tp->regs_len = pio_len;
833 #else
834         /* ioremap MMIO region */
835         ioaddr = ioremap (mmio_start, mmio_len);
836         if (ioaddr == NULL) {
837                 printk (KERN_ERR PFX "%s: cannot remap MMIO, aborting\n", pdev->slot_name);
838                 rc = -EIO;
839                 goto err_out;
840         }
841         dev->base_addr = (long) ioaddr;
842         tp->mmio_addr = ioaddr;
843         tp->regs_len = mmio_len;
844 #endif /* USE_IO_OPS */
845
846         /* Bring old chips out of low-power mode. */
847         RTL_W8 (HltClk, 'R');
848
849         /* check for missing/broken hardware */
850         if (RTL_R32 (TxConfig) == 0xFFFFFFFF) {
851                 printk (KERN_ERR PFX "%s: Chip not responding, ignoring board\n",
852                         pdev->slot_name);
853                 rc = -EIO;
854                 goto err_out;
855         }
856
857         /* identify chip attached to board */
858         tmp = RTL_R8 (ChipVersion);
859         for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++)
860                 if (tmp == rtl_chip_info[i].version) {
861                         tp->chipset = i;
862                         goto match;
863                 }
864
865         /* if unknown chip, assume array element #0, original RTL-8139 in this case */
866         printk (KERN_DEBUG PFX "%s: unknown chip version, assuming RTL-8139\n",
867                 pdev->slot_name);
868         printk (KERN_DEBUG PFX "%s: TxConfig = 0x%lx\n", pdev->slot_name, RTL_R32 (TxConfig));
869         tp->chipset = 0;
870
871 match:
872         DPRINTK ("chipset id (%d) == index %d, '%s'\n",
873                 tmp,
874                 tp->chipset,
875                 rtl_chip_info[tp->chipset].name);
876
877         if (tp->chipset >= CH_8139B) {
878                 u8 new_tmp8 = tmp8 = RTL_R8 (Config1);
879                 DPRINTK("PCI PM wakeup\n");
880                 if ((rtl_chip_info[tp->chipset].flags & HasLWake) &&
881                     (tmp8 & LWAKE))
882                         new_tmp8 &= ~LWAKE;
883                 new_tmp8 |= Cfg1_PM_Enable;
884                 if (new_tmp8 != tmp8) {
885                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
886                         RTL_W8 (Config1, tmp8);
887                         RTL_W8 (Cfg9346, Cfg9346_Lock);
888                 }
889                 if (rtl_chip_info[tp->chipset].flags & HasLWake) {
890                         tmp8 = RTL_R8 (Config4);
891                         if (tmp8 & LWPTN)
892                                 RTL_W8 (Config4, tmp8 & ~LWPTN);
893                 }
894         } else {
895                 DPRINTK("Old chip wakeup\n");
896                 tmp8 = RTL_R8 (Config1);
897                 tmp8 &= ~(SLEEP | PWRDN);
898                 RTL_W8 (Config1, tmp8);
899         }
900
901         rtl8139_chip_reset (ioaddr);
902
903         *dev_out = dev;
904         return 0;
905
906 err_out:
907         __rtl8139_cleanup_dev (dev);
908         return rc;
909 }
910
911
912 static int __devinit rtl8139_init_one (struct pci_dev *pdev,
913                                        const struct pci_device_id *ent)
914 {
915         struct net_device *dev = NULL;
916         struct rtl8139_private *tp;
917         int i, addr_len, option;
918         void *ioaddr;
919         static int board_idx = -1;
920         u8 pci_rev;
921
922         assert (pdev != NULL);
923         assert (ent != NULL);
924
925         board_idx++;
926
927         /* when we're built into the kernel, the driver version message
928          * is only printed if at least one 8139 board has been found
929          */
930 #ifndef MODULE
931         {
932                 static int printed_version;
933                 if (!printed_version++)
934                         printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
935         }
936 #endif
937
938         pci_read_config_byte(pdev, PCI_REVISION_ID, &pci_rev);
939
940         if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
941             pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pci_rev >= 0x20) {
942                 printk(KERN_INFO PFX "pci dev %s (id %04x:%04x rev %02x) is an enhanced 8139C+ chip\n",
943                        pdev->slot_name, pdev->vendor, pdev->device, pci_rev);
944                 printk(KERN_INFO PFX "Use the \"8139cp\" driver for improved performance and stability.\n");
945         }
946
947         i = rtl8139_init_board (pdev, &dev);
948         if (i < 0)
949                 return i;
950
951         tp = dev->priv;
952         ioaddr = tp->mmio_addr;
953
954         assert (ioaddr != NULL);
955         assert (dev != NULL);
956         assert (tp != NULL);
957
958         addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
959         for (i = 0; i < 3; i++)
960                 ((u16 *) (dev->dev_addr))[i] =
961                     le16_to_cpu (read_eeprom (ioaddr, i + 7, addr_len));
962
963         /* The Rtl8139-specific entries in the device structure. */
964         dev->open = rtl8139_open;
965         dev->hard_start_xmit = rtl8139_start_xmit;
966         dev->stop = rtl8139_close;
967         dev->get_stats = rtl8139_get_stats;
968         dev->set_multicast_list = rtl8139_set_rx_mode;
969         dev->do_ioctl = netdev_ioctl;
970         dev->tx_timeout = rtl8139_tx_timeout;
971         dev->watchdog_timeo = TX_TIMEOUT;
972
973         /* note: the hardware is not capable of sg/csum/highdma, however
974          * through the use of skb_copy_and_csum_dev we enable these
975          * features
976          */
977         dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HIGHDMA;
978
979         dev->irq = pdev->irq;
980
981         /* dev->priv/tp zeroed and aligned in init_etherdev */
982         tp = dev->priv;
983
984         /* note: tp->chipset set in rtl8139_init_board */
985         tp->drv_flags = board_info[ent->driver_data].hw_flags;
986         tp->mmio_addr = ioaddr;
987         spin_lock_init (&tp->lock);
988         init_waitqueue_head (&tp->thr_wait);
989         init_completion (&tp->thr_exited);
990         tp->mii.dev = dev;
991         tp->mii.mdio_read = mdio_read;
992         tp->mii.mdio_write = mdio_write;
993         tp->mii.phy_id_mask = 0x3f;
994         tp->mii.reg_num_mask = 0x1f;
995
996         /* dev is fully set up and ready to use now */
997         DPRINTK("about to register device named %s (%p)...\n", dev->name, dev);
998         i = register_netdev (dev);
999         if (i) goto err_out;
1000
1001         pci_set_drvdata (pdev, dev);
1002
1003         printk (KERN_INFO "%s: %s at 0x%lx, "
1004                 "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x, "
1005                 "IRQ %d\n",
1006                 dev->name,
1007                 board_info[ent->driver_data].name,
1008                 dev->base_addr,
1009                 dev->dev_addr[0], dev->dev_addr[1],
1010                 dev->dev_addr[2], dev->dev_addr[3],
1011                 dev->dev_addr[4], dev->dev_addr[5],
1012                 dev->irq);
1013
1014         printk (KERN_DEBUG "%s:  Identified 8139 chip type '%s'\n",
1015                 dev->name, rtl_chip_info[tp->chipset].name);
1016
1017         /* Find the connected MII xcvrs.
1018            Doing this in open() would allow detecting external xcvrs later, but
1019            takes too much time. */
1020 #ifdef CONFIG_8139TOO_8129
1021         if (tp->drv_flags & HAS_MII_XCVR) {
1022                 int phy, phy_idx = 0;
1023                 for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) {
1024                         int mii_status = mdio_read(dev, phy, 1);
1025                         if (mii_status != 0xffff  &&  mii_status != 0x0000) {
1026                                 u16 advertising = mdio_read(dev, phy, 4);
1027                                 tp->phys[phy_idx++] = phy;
1028                                 printk(KERN_INFO "%s: MII transceiver %d status 0x%4.4x "
1029                                            "advertising %4.4x.\n",
1030                                            dev->name, phy, mii_status, advertising);
1031                         }
1032                 }
1033                 if (phy_idx == 0) {
1034                         printk(KERN_INFO "%s: No MII transceivers found!  Assuming SYM "
1035                                    "transceiver.\n",
1036                                    dev->name);
1037                         tp->phys[0] = 32;
1038                 }
1039         } else
1040 #endif
1041                 tp->phys[0] = 32;
1042         tp->mii.phy_id = tp->phys[0];
1043
1044         /* The lower four bits are the media type. */
1045         option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
1046         if (option > 0) {
1047                 tp->mii.full_duplex = (option & 0x210) ? 1 : 0;
1048                 tp->default_port = option & 0xFF;
1049                 if (tp->default_port)
1050                         tp->mii.force_media = 1;
1051         }
1052         if (board_idx < MAX_UNITS  &&  full_duplex[board_idx] > 0)
1053                 tp->mii.full_duplex = full_duplex[board_idx];
1054         if (tp->mii.full_duplex) {
1055                 printk(KERN_INFO "%s: Media type forced to Full Duplex.\n", dev->name);
1056                 /* Changing the MII-advertised media because might prevent
1057                    re-connection. */
1058                 tp->mii.force_media = 1;
1059         }
1060         if (tp->default_port) {
1061                 printk(KERN_INFO "  Forcing %dMbps %s-duplex operation.\n",
1062                            (option & 0x20 ? 100 : 10),
1063                            (option & 0x10 ? "full" : "half"));
1064                 mdio_write(dev, tp->phys[0], 0,
1065                                    ((option & 0x20) ? 0x2000 : 0) |     /* 100Mbps? */
1066                                    ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
1067         }
1068
1069         /* Put the chip into low-power mode. */
1070         if (rtl_chip_info[tp->chipset].flags & HasHltClk)
1071                 RTL_W8 (HltClk, 'H');   /* 'R' would leave the clock running. */
1072
1073         return 0;
1074
1075 err_out:
1076         __rtl8139_cleanup_dev (dev);
1077         return i;
1078 }
1079
1080
1081 static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
1082 {
1083         struct net_device *dev = pci_get_drvdata (pdev);
1084         struct rtl8139_private *np;
1085
1086         assert (dev != NULL);
1087         np = dev->priv;
1088         assert (np != NULL);
1089
1090         unregister_netdev (dev);
1091
1092         __rtl8139_cleanup_dev (dev);
1093 }
1094
1095
1096 /* Serial EEPROM section. */
1097
1098 /*  EEPROM_Ctrl bits. */
1099 #define EE_SHIFT_CLK    0x04    /* EEPROM shift clock. */
1100 #define EE_CS                   0x08    /* EEPROM chip select. */
1101 #define EE_DATA_WRITE   0x02    /* EEPROM chip data in. */
1102 #define EE_WRITE_0              0x00
1103 #define EE_WRITE_1              0x02
1104 #define EE_DATA_READ    0x01    /* EEPROM chip data out. */
1105 #define EE_ENB                  (0x80 | EE_CS)
1106
1107 /* Delay between EEPROM clock transitions.
1108    No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
1109  */
1110
1111 #define eeprom_delay()  readl(ee_addr)
1112
1113 /* The EEPROM commands include the alway-set leading bit. */
1114 #define EE_WRITE_CMD    (5)
1115 #define EE_READ_CMD             (6)
1116 #define EE_ERASE_CMD    (7)
1117
1118 static int __devinit read_eeprom (void *ioaddr, int location, int addr_len)
1119 {
1120         int i;
1121         unsigned retval = 0;
1122         void *ee_addr = ioaddr + Cfg9346;
1123         int read_cmd = location | (EE_READ_CMD << addr_len);
1124
1125         writeb (EE_ENB & ~EE_CS, ee_addr);
1126         writeb (EE_ENB, ee_addr);
1127         eeprom_delay ();
1128
1129         /* Shift the read command bits out. */
1130         for (i = 4 + addr_len; i >= 0; i--) {
1131                 int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
1132                 writeb (EE_ENB | dataval, ee_addr);
1133                 eeprom_delay ();
1134                 writeb (EE_ENB | dataval | EE_SHIFT_CLK, ee_addr);
1135                 eeprom_delay ();
1136         }
1137         writeb (EE_ENB, ee_addr);
1138         eeprom_delay ();
1139
1140         for (i = 16; i > 0; i--) {
1141                 writeb (EE_ENB | EE_SHIFT_CLK, ee_addr);
1142                 eeprom_delay ();
1143                 retval =
1144                     (retval << 1) | ((readb (ee_addr) & EE_DATA_READ) ? 1 :
1145                                      0);
1146                 writeb (EE_ENB, ee_addr);
1147                 eeprom_delay ();
1148         }
1149
1150         /* Terminate the EEPROM access. */
1151         writeb (~EE_CS, ee_addr);
1152         eeprom_delay ();
1153
1154         return retval;
1155 }
1156
1157 /* MII serial management: mostly bogus for now. */
1158 /* Read and write the MII management registers using software-generated
1159    serial MDIO protocol.
1160    The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
1161    met by back-to-back PCI I/O cycles, but we insert a delay to avoid
1162    "overclocking" issues. */
1163 #define MDIO_DIR                0x80
1164 #define MDIO_DATA_OUT   0x04
1165 #define MDIO_DATA_IN    0x02
1166 #define MDIO_CLK                0x01
1167 #define MDIO_WRITE0 (MDIO_DIR)
1168 #define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
1169
1170 #define mdio_delay(mdio_addr)   readb(mdio_addr)
1171
1172
1173 static char mii_2_8139_map[8] = {
1174         BasicModeCtrl,
1175         BasicModeStatus,
1176         0,
1177         0,
1178         NWayAdvert,
1179         NWayLPAR,
1180         NWayExpansion,
1181         0
1182 };
1183
1184
1185 #ifdef CONFIG_8139TOO_8129
1186 /* Syncronize the MII management interface by shifting 32 one bits out. */
1187 static void mdio_sync (void *mdio_addr)
1188 {
1189         int i;
1190
1191         for (i = 32; i >= 0; i--) {
1192                 writeb (MDIO_WRITE1, mdio_addr);
1193                 mdio_delay (mdio_addr);
1194                 writeb (MDIO_WRITE1 | MDIO_CLK, mdio_addr);
1195                 mdio_delay (mdio_addr);
1196         }
1197 }
1198 #endif
1199
1200 static int mdio_read (struct net_device *dev, int phy_id, int location)
1201 {
1202         struct rtl8139_private *tp = dev->priv;
1203         int retval = 0;
1204 #ifdef CONFIG_8139TOO_8129
1205         void *mdio_addr = tp->mmio_addr + Config4;
1206         int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
1207         int i;
1208 #endif
1209
1210         if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1211                 return location < 8 && mii_2_8139_map[location] ?
1212                     readw (tp->mmio_addr + mii_2_8139_map[location]) : 0;
1213         }
1214
1215 #ifdef CONFIG_8139TOO_8129
1216         mdio_sync (mdio_addr);
1217         /* Shift the read command bits out. */
1218         for (i = 15; i >= 0; i--) {
1219                 int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
1220
1221                 writeb (MDIO_DIR | dataval, mdio_addr);
1222                 mdio_delay (mdio_addr);
1223                 writeb (MDIO_DIR | dataval | MDIO_CLK, mdio_addr);
1224                 mdio_delay (mdio_addr);
1225         }
1226
1227         /* Read the two transition, 16 data, and wire-idle bits. */
1228         for (i = 19; i > 0; i--) {
1229                 writeb (0, mdio_addr);
1230                 mdio_delay (mdio_addr);
1231                 retval = (retval << 1) | ((readb (mdio_addr) & MDIO_DATA_IN) ? 1 : 0);
1232                 writeb (MDIO_CLK, mdio_addr);
1233                 mdio_delay (mdio_addr);
1234         }
1235 #endif
1236
1237         return (retval >> 1) & 0xffff;
1238 }
1239
1240
1241 static void mdio_write (struct net_device *dev, int phy_id, int location,
1242                         int value)
1243 {
1244         struct rtl8139_private *tp = dev->priv;
1245 #ifdef CONFIG_8139TOO_8129
1246         void *mdio_addr = tp->mmio_addr + Config4;
1247         int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
1248         int i;
1249 #endif
1250
1251         if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1252                 void *ioaddr = tp->mmio_addr;
1253                 if (location == 0) {
1254                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
1255                         RTL_W16 (BasicModeCtrl, value);
1256                         RTL_W8 (Cfg9346, Cfg9346_Lock);
1257                 } else if (location < 8 && mii_2_8139_map[location])
1258                         RTL_W16 (mii_2_8139_map[location], value);
1259                 return;
1260         }
1261
1262 #ifdef CONFIG_8139TOO_8129
1263         mdio_sync (mdio_addr);
1264
1265         /* Shift the command bits out. */
1266         for (i = 31; i >= 0; i--) {
1267                 int dataval =
1268                     (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
1269                 writeb (dataval, mdio_addr);
1270                 mdio_delay (mdio_addr);
1271                 writeb (dataval | MDIO_CLK, mdio_addr);
1272                 mdio_delay (mdio_addr);
1273         }
1274         /* Clear out extra bits. */
1275         for (i = 2; i > 0; i--) {
1276                 writeb (0, mdio_addr);
1277                 mdio_delay (mdio_addr);
1278                 writeb (MDIO_CLK, mdio_addr);
1279                 mdio_delay (mdio_addr);
1280         }
1281 #endif
1282 }
1283
1284
1285 static int rtl8139_open (struct net_device *dev)
1286 {
1287         struct rtl8139_private *tp = dev->priv;
1288         int retval;
1289 #ifdef RTL8139_DEBUG
1290         void *ioaddr = tp->mmio_addr;
1291 #endif
1292
1293         retval = request_irq (dev->irq, rtl8139_interrupt, SA_SHIRQ, dev->name, dev);
1294         if (retval)
1295                 return retval;
1296
1297         tp->tx_bufs = pci_alloc_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1298                                            &tp->tx_bufs_dma);
1299         tp->rx_ring = pci_alloc_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1300                                            &tp->rx_ring_dma);
1301         if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
1302                 free_irq(dev->irq, dev);
1303
1304                 if (tp->tx_bufs)
1305                         pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1306                                             tp->tx_bufs, tp->tx_bufs_dma);
1307                 if (tp->rx_ring)
1308                         pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1309                                             tp->rx_ring, tp->rx_ring_dma);
1310
1311                 return -ENOMEM;
1312
1313         }
1314
1315         tp->mii.full_duplex = tp->mii.force_media;
1316         tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
1317         tp->twistie = (tp->chipset == CH_8139_K) ? 1 : 0;
1318         tp->time_to_die = 0;
1319
1320         rtl8139_init_ring (dev);
1321         rtl8139_hw_start (dev);
1322
1323         DPRINTK ("%s: rtl8139_open() ioaddr %#lx IRQ %d"
1324                         " GP Pins %2.2x %s-duplex.\n",
1325                         dev->name, pci_resource_start (tp->pci_dev, 1),
1326                         dev->irq, RTL_R8 (MediaStatus),
1327                         tp->mii.full_duplex ? "full" : "half");
1328
1329         tp->thr_pid = kernel_thread (rtl8139_thread, dev, CLONE_FS | CLONE_FILES);
1330         if (tp->thr_pid < 0)
1331                 printk (KERN_WARNING "%s: unable to start kernel thread\n",
1332                         dev->name);
1333
1334         return 0;
1335 }
1336
1337
1338 static void rtl_check_media (struct net_device *dev)
1339 {
1340         struct rtl8139_private *tp = dev->priv;
1341
1342         if (tp->phys[0] >= 0) {
1343                 u16 mii_lpa = mdio_read(dev, tp->phys[0], MII_LPA);
1344                 if (mii_lpa == 0xffff)
1345                         ;                                       /* Not there */
1346                 else if ((mii_lpa & LPA_100FULL) == LPA_100FULL
1347                                  || (mii_lpa & 0x00C0) == LPA_10FULL)
1348                         tp->mii.full_duplex = 1;
1349
1350                 printk (KERN_INFO"%s: Setting %s%s-duplex based on"
1351                                 " auto-negotiated partner ability %4.4x.\n",
1352                         dev->name, mii_lpa == 0 ? "" :
1353                                 (mii_lpa & 0x0180) ? "100mbps " : "10mbps ",
1354                         tp->mii.full_duplex ? "full" : "half", mii_lpa);
1355         }
1356 }
1357
1358 /* Start the hardware at open or resume. */
1359 static void rtl8139_hw_start (struct net_device *dev)
1360 {
1361         struct rtl8139_private *tp = dev->priv;
1362         void *ioaddr = tp->mmio_addr;
1363         u32 i;
1364         u8 tmp;
1365
1366         /* Bring old chips out of low-power mode. */
1367         if (rtl_chip_info[tp->chipset].flags & HasHltClk)
1368                 RTL_W8 (HltClk, 'R');
1369
1370         rtl8139_chip_reset (ioaddr);
1371
1372         /* unlock Config[01234] and BMCR register writes */
1373         RTL_W8_F (Cfg9346, Cfg9346_Unlock);
1374         /* Restore our idea of the MAC address. */
1375         RTL_W32_F (MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
1376         RTL_W32_F (MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
1377
1378         /* Must enable Tx/Rx before setting transfer thresholds! */
1379         RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1380
1381         tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
1382         RTL_W32 (RxConfig, tp->rx_config);
1383
1384         /* Check this value: the documentation for IFG contradicts ifself. */
1385         RTL_W32 (TxConfig, rtl8139_tx_config);
1386
1387         tp->cur_rx = 0;
1388
1389         rtl_check_media (dev);
1390
1391         if (tp->chipset >= CH_8139B) {
1392                 /* Disable magic packet scanning, which is enabled
1393                  * when PM is enabled in Config1.  It can be reenabled
1394                  * via ETHTOOL_SWOL if desired.  */
1395                 RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic);
1396         }
1397
1398         DPRINTK("init buffer addresses\n");
1399
1400         /* Lock Config[01234] and BMCR register writes */
1401         RTL_W8 (Cfg9346, Cfg9346_Lock);
1402
1403         /* init Rx ring buffer DMA address */
1404         RTL_W32_F (RxBuf, tp->rx_ring_dma);
1405
1406         /* init Tx buffer DMA addresses */
1407         for (i = 0; i < NUM_TX_DESC; i++)
1408                 RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
1409
1410         RTL_W32 (RxMissed, 0);
1411
1412         rtl8139_set_rx_mode (dev);
1413
1414         /* no early-rx interrupts */
1415         RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
1416
1417         /* make sure RxTx has started */
1418         tmp = RTL_R8 (ChipCmd);
1419         if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb)))
1420                 RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1421
1422         /* Enable all known interrupts by setting the interrupt mask. */
1423         RTL_W16 (IntrMask, rtl8139_intr_mask);
1424
1425         netif_start_queue (dev);
1426 }
1427
1428
1429 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1430 static void rtl8139_init_ring (struct net_device *dev)
1431 {
1432         struct rtl8139_private *tp = dev->priv;
1433         int i;
1434
1435         tp->cur_rx = 0;
1436         tp->cur_tx = 0;
1437         tp->dirty_tx = 0;
1438
1439         for (i = 0; i < NUM_TX_DESC; i++)
1440                 tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
1441 }
1442
1443
1444 /* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
1445 static int next_tick = 3 * HZ;
1446
1447 #ifndef CONFIG_8139TOO_TUNE_TWISTER
1448 static inline void rtl8139_tune_twister (struct net_device *dev,
1449                                   struct rtl8139_private *tp) {}
1450 #else
1451 static void rtl8139_tune_twister (struct net_device *dev,
1452                                   struct rtl8139_private *tp)
1453 {
1454         int linkcase;
1455         void *ioaddr = tp->mmio_addr;
1456
1457         /* This is a complicated state machine to configure the "twister" for
1458            impedance/echos based on the cable length.
1459            All of this is magic and undocumented.
1460          */
1461         switch (tp->twistie) {
1462         case 1:
1463                 if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
1464                         /* We have link beat, let us tune the twister. */
1465                         RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
1466                         tp->twistie = 2;        /* Change to state 2. */
1467                         next_tick = HZ / 10;
1468                 } else {
1469                         /* Just put in some reasonable defaults for when beat returns. */
1470                         RTL_W16 (CSCR, CSCR_LinkDownCmd);
1471                         RTL_W32 (FIFOTMS, 0x20);        /* Turn on cable test mode. */
1472                         RTL_W32 (PARA78, PARA78_default);
1473                         RTL_W32 (PARA7c, PARA7c_default);
1474                         tp->twistie = 0;        /* Bail from future actions. */
1475                 }
1476                 break;
1477         case 2:
1478                 /* Read how long it took to hear the echo. */
1479                 linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
1480                 if (linkcase == 0x7000)
1481                         tp->twist_row = 3;
1482                 else if (linkcase == 0x3000)
1483                         tp->twist_row = 2;
1484                 else if (linkcase == 0x1000)
1485                         tp->twist_row = 1;
1486                 else
1487                         tp->twist_row = 0;
1488                 tp->twist_col = 0;
1489                 tp->twistie = 3;        /* Change to state 2. */
1490                 next_tick = HZ / 10;
1491                 break;
1492         case 3:
1493                 /* Put out four tuning parameters, one per 100msec. */
1494                 if (tp->twist_col == 0)
1495                         RTL_W16 (FIFOTMS, 0);
1496                 RTL_W32 (PARA7c, param[(int) tp->twist_row]
1497                          [(int) tp->twist_col]);
1498                 next_tick = HZ / 10;
1499                 if (++tp->twist_col >= 4) {
1500                         /* For short cables we are done.
1501                            For long cables (row == 3) check for mistune. */
1502                         tp->twistie =
1503                             (tp->twist_row == 3) ? 4 : 0;
1504                 }
1505                 break;
1506         case 4:
1507                 /* Special case for long cables: check for mistune. */
1508                 if ((RTL_R16 (CSCR) &
1509                      CSCR_LinkStatusBits) == 0x7000) {
1510                         tp->twistie = 0;
1511                         break;
1512                 } else {
1513                         RTL_W32 (PARA7c, 0xfb38de03);
1514                         tp->twistie = 5;
1515                         next_tick = HZ / 10;
1516                 }
1517                 break;
1518         case 5:
1519                 /* Retune for shorter cable (column 2). */
1520                 RTL_W32 (FIFOTMS, 0x20);
1521                 RTL_W32 (PARA78, PARA78_default);
1522                 RTL_W32 (PARA7c, PARA7c_default);
1523                 RTL_W32 (FIFOTMS, 0x00);
1524                 tp->twist_row = 2;
1525                 tp->twist_col = 0;
1526                 tp->twistie = 3;
1527                 next_tick = HZ / 10;
1528                 break;
1529
1530         default:
1531                 /* do nothing */
1532                 break;
1533         }
1534 }
1535 #endif /* CONFIG_8139TOO_TUNE_TWISTER */
1536
1537
1538 static inline void rtl8139_thread_iter (struct net_device *dev,
1539                                  struct rtl8139_private *tp,
1540                                  void *ioaddr)
1541 {
1542         int mii_lpa;
1543
1544         mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA);
1545
1546         if (!tp->mii.force_media && mii_lpa != 0xffff) {
1547                 int duplex = (mii_lpa & LPA_100FULL)
1548                     || (mii_lpa & 0x01C0) == 0x0040;
1549                 if (tp->mii.full_duplex != duplex) {
1550                         tp->mii.full_duplex = duplex;
1551
1552                         if (mii_lpa) {
1553                                 printk (KERN_INFO
1554                                         "%s: Setting %s-duplex based on MII #%d link"
1555                                         " partner ability of %4.4x.\n",
1556                                         dev->name,
1557                                         tp->mii.full_duplex ? "full" : "half",
1558                                         tp->phys[0], mii_lpa);
1559                         } else {
1560                                 printk(KERN_INFO"%s: media is unconnected, link down, or incompatible connection\n",
1561                                        dev->name);
1562                         }
1563 #if 0
1564                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
1565                         RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
1566                         RTL_W8 (Cfg9346, Cfg9346_Lock);
1567 #endif
1568                 }
1569         }
1570
1571         next_tick = HZ * 60;
1572
1573         rtl8139_tune_twister (dev, tp);
1574
1575         DPRINTK ("%s: Media selection tick, Link partner %4.4x.\n",
1576                  dev->name, RTL_R16 (NWayLPAR));
1577         DPRINTK ("%s:  Other registers are IntMask %4.4x IntStatus %4.4x\n",
1578                  dev->name, RTL_R16 (IntrMask), RTL_R16 (IntrStatus));
1579         DPRINTK ("%s:  Chip config %2.2x %2.2x.\n",
1580                  dev->name, RTL_R8 (Config0),
1581                  RTL_R8 (Config1));
1582 }
1583
1584
1585 static int rtl8139_thread (void *data)
1586 {
1587         struct net_device *dev = data;
1588         struct rtl8139_private *tp = dev->priv;
1589         unsigned long timeout;
1590
1591         daemonize ();
1592         reparent_to_init();
1593         spin_lock_irq(&current->sigmask_lock);
1594         sigemptyset(&current->blocked);
1595         recalc_sigpending(current);
1596         spin_unlock_irq(&current->sigmask_lock);
1597
1598         strncpy (current->comm, dev->name, sizeof(current->comm) - 1);
1599         current->comm[sizeof(current->comm) - 1] = '\0';
1600
1601         while (1) {
1602                 timeout = next_tick;
1603                 do {
1604                         timeout = interruptible_sleep_on_timeout (&tp->thr_wait, timeout);
1605                 } while (!signal_pending (current) && (timeout > 0));
1606
1607                 if (signal_pending (current)) {
1608                         spin_lock_irq(&current->sigmask_lock);
1609                         flush_signals(current);
1610                         spin_unlock_irq(&current->sigmask_lock);
1611                 }
1612
1613                 if (tp->time_to_die)
1614                         break;
1615
1616                 rtnl_lock ();
1617                 rtl8139_thread_iter (dev, tp, tp->mmio_addr);
1618                 rtnl_unlock ();
1619         }
1620
1621         complete_and_exit (&tp->thr_exited, 0);
1622 }
1623
1624
1625 static void rtl8139_tx_clear (struct rtl8139_private *tp)
1626 {
1627         tp->cur_tx = 0;
1628         tp->dirty_tx = 0;
1629
1630         /* XXX account for unsent Tx packets in tp->stats.tx_dropped */
1631 }
1632
1633
1634 static void rtl8139_tx_timeout (struct net_device *dev)
1635 {
1636         struct rtl8139_private *tp = dev->priv;
1637         void *ioaddr = tp->mmio_addr;
1638         int i;
1639         u8 tmp8;
1640         unsigned long flags;
1641
1642         DPRINTK ("%s: Transmit timeout, status %2.2x %4.4x "
1643                  "media %2.2x.\n", dev->name,
1644                  RTL_R8 (ChipCmd),
1645                  RTL_R16 (IntrStatus),
1646                  RTL_R8 (MediaStatus));
1647
1648         tp->xstats.tx_timeouts++;
1649
1650         /* disable Tx ASAP, if not already */
1651         tmp8 = RTL_R8 (ChipCmd);
1652         if (tmp8 & CmdTxEnb)
1653                 RTL_W8 (ChipCmd, CmdRxEnb);
1654
1655         /* Disable interrupts by clearing the interrupt mask. */
1656         RTL_W16 (IntrMask, 0x0000);
1657
1658         /* Emit info to figure out what went wrong. */
1659         printk (KERN_DEBUG "%s: Tx queue start entry %ld  dirty entry %ld.\n",
1660                 dev->name, tp->cur_tx, tp->dirty_tx);
1661         for (i = 0; i < NUM_TX_DESC; i++)
1662                 printk (KERN_DEBUG "%s:  Tx descriptor %d is %8.8lx.%s\n",
1663                         dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
1664                         i == tp->dirty_tx % NUM_TX_DESC ?
1665                                 " (queue head)" : "");
1666
1667         /* Stop a shared interrupt from scavenging while we are. */
1668         spin_lock_irqsave (&tp->lock, flags);
1669         rtl8139_tx_clear (tp);
1670         spin_unlock_irqrestore (&tp->lock, flags);
1671
1672         /* ...and finally, reset everything */
1673         rtl8139_hw_start (dev);
1674
1675         netif_wake_queue (dev);
1676 }
1677
1678
1679 static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
1680 {
1681         struct rtl8139_private *tp = dev->priv;
1682         void *ioaddr = tp->mmio_addr;
1683         unsigned int entry;
1684         unsigned int len = skb->len;
1685
1686         /* Calculate the next Tx descriptor entry. */
1687         entry = tp->cur_tx % NUM_TX_DESC;
1688
1689         if (likely(len < TX_BUF_SIZE)) {
1690                 if(len < ETH_ZLEN)
1691                         memset(tp->tx_buf[entry], 0, ETH_ZLEN);
1692                 skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
1693                 dev_kfree_skb(skb);
1694         } else {
1695                 dev_kfree_skb(skb);
1696                 tp->stats.tx_dropped++;
1697                 return 0;
1698         }
1699
1700         /* Note: the chip doesn't have auto-pad! */
1701         spin_lock_irq(&tp->lock);
1702         RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
1703                    tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
1704
1705         dev->trans_start = jiffies;
1706
1707         tp->cur_tx++;
1708         wmb();
1709
1710         if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
1711                 netif_stop_queue (dev);
1712         spin_unlock_irq(&tp->lock);
1713
1714         DPRINTK ("%s: Queued Tx packet size %u to slot %d.\n",
1715                  dev->name, len, entry);
1716
1717         return 0;
1718 }
1719
1720
1721 static void rtl8139_tx_interrupt (struct net_device *dev,
1722                                   struct rtl8139_private *tp,
1723                                   void *ioaddr)
1724 {
1725         unsigned long dirty_tx, tx_left;
1726
1727         assert (dev != NULL);
1728         assert (tp != NULL);
1729         assert (ioaddr != NULL);
1730
1731         dirty_tx = tp->dirty_tx;
1732         tx_left = tp->cur_tx - dirty_tx;
1733         while (tx_left > 0) {
1734                 int entry = dirty_tx % NUM_TX_DESC;
1735                 int txstatus;
1736
1737                 txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
1738
1739                 if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
1740                         break;  /* It still hasn't been Txed */
1741
1742                 /* Note: TxCarrierLost is always asserted at 100mbps. */
1743                 if (txstatus & (TxOutOfWindow | TxAborted)) {
1744                         /* There was an major error, log it. */
1745                         DPRINTK ("%s: Transmit error, Tx status %8.8x.\n",
1746                                  dev->name, txstatus);
1747                         tp->stats.tx_errors++;
1748                         if (txstatus & TxAborted) {
1749                                 tp->stats.tx_aborted_errors++;
1750                                 RTL_W32 (TxConfig, TxClearAbt);
1751                                 RTL_W16 (IntrStatus, TxErr);
1752                                 wmb();
1753                         }
1754                         if (txstatus & TxCarrierLost)
1755                                 tp->stats.tx_carrier_errors++;
1756                         if (txstatus & TxOutOfWindow)
1757                                 tp->stats.tx_window_errors++;
1758                 } else {
1759                         if (txstatus & TxUnderrun) {
1760                                 /* Add 64 to the Tx FIFO threshold. */
1761                                 if (tp->tx_flag < 0x00300000)
1762                                         tp->tx_flag += 0x00020000;
1763                                 tp->stats.tx_fifo_errors++;
1764                         }
1765                         tp->stats.collisions += (txstatus >> 24) & 15;
1766                         tp->stats.tx_bytes += txstatus & 0x7ff;
1767                         tp->stats.tx_packets++;
1768                 }
1769
1770                 dirty_tx++;
1771                 tx_left--;
1772         }
1773
1774 #ifndef RTL8139_NDEBUG
1775         if (tp->cur_tx - dirty_tx > NUM_TX_DESC) {
1776                 printk (KERN_ERR "%s: Out-of-sync dirty pointer, %ld vs. %ld.\n",
1777                         dev->name, dirty_tx, tp->cur_tx);
1778                 dirty_tx += NUM_TX_DESC;
1779         }
1780 #endif /* RTL8139_NDEBUG */
1781
1782         /* only wake the queue if we did work, and the queue is stopped */
1783         if (tp->dirty_tx != dirty_tx) {
1784                 tp->dirty_tx = dirty_tx;
1785                 mb();
1786                 if (netif_queue_stopped (dev))
1787                         netif_wake_queue (dev);
1788         }
1789 }
1790
1791
1792 /* TODO: clean this up!  Rx reset need not be this intensive */
1793 static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
1794                             struct rtl8139_private *tp, void *ioaddr)
1795 {
1796         u8 tmp8;
1797 #ifdef CONFIG_8139_OLD_RX_RESET
1798         int tmp_work;
1799 #endif
1800
1801         DPRINTK ("%s: Ethernet frame had errors, status %8.8x.\n",
1802                  dev->name, rx_status);
1803         tp->stats.rx_errors++;
1804         if (!(rx_status & RxStatusOK)) {
1805                 if (rx_status & RxTooLong) {
1806                         DPRINTK ("%s: Oversized Ethernet frame, status %4.4x!\n",
1807                                 dev->name, rx_status);
1808                         /* A.C.: The chip hangs here. */
1809                 }
1810                 if (rx_status & (RxBadSymbol | RxBadAlign))
1811                         tp->stats.rx_frame_errors++;
1812                 if (rx_status & (RxRunt | RxTooLong))
1813                         tp->stats.rx_length_errors++;
1814                 if (rx_status & RxCRCErr)
1815                         tp->stats.rx_crc_errors++;
1816         } else {
1817                 tp->xstats.rx_lost_in_ring++;
1818         }
1819
1820 #ifndef CONFIG_8139_OLD_RX_RESET
1821         tmp8 = RTL_R8 (ChipCmd);
1822         RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb);
1823         RTL_W8 (ChipCmd, tmp8);
1824         RTL_W32 (RxConfig, tp->rx_config);
1825         tp->cur_rx = 0;
1826 #else
1827         /* Reset the receiver, based on RealTek recommendation. (Bug?) */
1828
1829         /* disable receive */
1830         RTL_W8_F (ChipCmd, CmdTxEnb);
1831         tmp_work = 200;
1832         while (--tmp_work > 0) {
1833                 udelay(1);
1834                 tmp8 = RTL_R8 (ChipCmd);
1835                 if (!(tmp8 & CmdRxEnb))
1836                         break;
1837         }
1838         if (tmp_work <= 0)
1839                 printk (KERN_WARNING PFX "rx stop wait too long\n");
1840         /* restart receive */
1841         tmp_work = 200;
1842         while (--tmp_work > 0) {
1843                 RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb);
1844                 udelay(1);
1845                 tmp8 = RTL_R8 (ChipCmd);
1846                 if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
1847                         break;
1848         }
1849         if (tmp_work <= 0)
1850                 printk (KERN_WARNING PFX "tx/rx enable wait too long\n");
1851
1852         /* and reinitialize all rx related registers */
1853         RTL_W8_F (Cfg9346, Cfg9346_Unlock);
1854         /* Must enable Tx/Rx before setting transfer thresholds! */
1855         RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1856
1857         tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
1858         RTL_W32 (RxConfig, tp->rx_config);
1859         tp->cur_rx = 0;
1860
1861         DPRINTK("init buffer addresses\n");
1862
1863         /* Lock Config[01234] and BMCR register writes */
1864         RTL_W8 (Cfg9346, Cfg9346_Lock);
1865
1866         /* init Rx ring buffer DMA address */
1867         RTL_W32_F (RxBuf, tp->rx_ring_dma);
1868
1869         /* A.C.: Reset the multicast list. */
1870         __set_rx_mode (dev);
1871 #endif
1872 }
1873
1874 static void rtl8139_rx_interrupt (struct net_device *dev,
1875                                   struct rtl8139_private *tp, void *ioaddr)
1876 {
1877         unsigned char *rx_ring;
1878         u16 cur_rx;
1879
1880         assert (dev != NULL);
1881         assert (tp != NULL);
1882         assert (ioaddr != NULL);
1883
1884         rx_ring = tp->rx_ring;
1885         cur_rx = tp->cur_rx;
1886
1887         DPRINTK ("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1888                  " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1889                  RTL_R16 (RxBufAddr),
1890                  RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1891
1892         while ((RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
1893                 int ring_offset = cur_rx % RX_BUF_LEN;
1894                 u32 rx_status;
1895                 unsigned int rx_size;
1896                 unsigned int pkt_size;
1897                 struct sk_buff *skb;
1898
1899                 rmb();
1900
1901                 /* read size+status of next frame from DMA ring buffer */
1902                 rx_status = le32_to_cpu (*(u32 *) (rx_ring + ring_offset));
1903                 rx_size = rx_status >> 16;
1904                 pkt_size = rx_size - 4;
1905
1906                 DPRINTK ("%s:  rtl8139_rx() status %4.4x, size %4.4x,"
1907                          " cur %4.4x.\n", dev->name, rx_status,
1908                          rx_size, cur_rx);
1909 #if RTL8139_DEBUG > 2
1910                 {
1911                         int i;
1912                         DPRINTK ("%s: Frame contents ", dev->name);
1913                         for (i = 0; i < 70; i++)
1914                                 printk (" %2.2x",
1915                                         rx_ring[ring_offset + i]);
1916                         printk (".\n");
1917                 }
1918 #endif
1919
1920                 /* Packet copy from FIFO still in progress.
1921                  * Theoretically, this should never happen
1922                  * since EarlyRx is disabled.
1923                  */
1924                 if (rx_size == 0xfff0) {
1925                         tp->xstats.early_rx++;
1926                         break;
1927                 }
1928
1929                 /* If Rx err or invalid rx_size/rx_status received
1930                  * (which happens if we get lost in the ring),
1931                  * Rx process gets reset, so we abort any further
1932                  * Rx processing.
1933                  */
1934                 if ((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
1935                     (rx_size < 8) ||
1936                     (!(rx_status & RxStatusOK))) {
1937                         rtl8139_rx_err (rx_status, dev, tp, ioaddr);
1938                         return;
1939                 }
1940
1941                 /* Malloc up new buffer, compatible with net-2e. */
1942                 /* Omit the four octet CRC from the length. */
1943
1944                 /* TODO: consider allocating skb's outside of
1945                  * interrupt context, both to speed interrupt processing,
1946                  * and also to reduce the chances of having to
1947                  * drop packets here under memory pressure.
1948                  */
1949
1950                 skb = dev_alloc_skb (pkt_size + 2);
1951                 if (skb) {
1952                         skb->dev = dev;
1953                         skb_reserve (skb, 2);   /* 16 byte align the IP fields. */
1954
1955                         eth_copy_and_sum (skb, &rx_ring[ring_offset + 4], pkt_size, 0);
1956                         skb_put (skb, pkt_size);
1957
1958                         skb->protocol = eth_type_trans (skb, dev);
1959                         netif_rx (skb);
1960                         dev->last_rx = jiffies;
1961                         tp->stats.rx_bytes += pkt_size;
1962                         tp->stats.rx_packets++;
1963                 } else {
1964                         printk (KERN_WARNING
1965                                 "%s: Memory squeeze, dropping packet.\n",
1966                                 dev->name);
1967                         tp->stats.rx_dropped++;
1968                 }
1969
1970                 cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
1971                 RTL_W16 (RxBufPtr, cur_rx - 16);
1972
1973                 if (RTL_R16 (IntrStatus) & RxAckBits)
1974                         RTL_W16_F (IntrStatus, RxAckBits);
1975         }
1976
1977         DPRINTK ("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1978                  " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1979                  RTL_R16 (RxBufAddr),
1980                  RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1981
1982         tp->cur_rx = cur_rx;
1983 }
1984
1985
1986 static void rtl8139_weird_interrupt (struct net_device *dev,
1987                                      struct rtl8139_private *tp,
1988                                      void *ioaddr,
1989                                      int status, int link_changed)
1990 {
1991         DPRINTK ("%s: Abnormal interrupt, status %8.8x.\n",
1992                  dev->name, status);
1993
1994         assert (dev != NULL);
1995         assert (tp != NULL);
1996         assert (ioaddr != NULL);
1997
1998         /* Update the error count. */
1999         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2000         RTL_W32 (RxMissed, 0);
2001
2002         if ((status & RxUnderrun) && link_changed &&
2003             (tp->drv_flags & HAS_LNK_CHNG)) {
2004                 /* Really link-change on new chips. */
2005                 int lpar = RTL_R16 (NWayLPAR);
2006                 int duplex = (lpar & LPA_100FULL) || (lpar & 0x01C0) == 0x0040
2007                                 || tp->mii.force_media;
2008                 if (tp->mii.full_duplex != duplex) {
2009                         tp->mii.full_duplex = duplex;
2010 #if 0
2011                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
2012                         RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
2013                         RTL_W8 (Cfg9346, Cfg9346_Lock);
2014 #endif
2015                 }
2016                 status &= ~RxUnderrun;
2017         }
2018
2019         /* XXX along with rtl8139_rx_err, are we double-counting errors? */
2020         if (status &
2021             (RxUnderrun | RxOverflow | RxErr | RxFIFOOver))
2022                 tp->stats.rx_errors++;
2023
2024         if (status & PCSTimeout)
2025                 tp->stats.rx_length_errors++;
2026         if (status & (RxUnderrun | RxFIFOOver))
2027                 tp->stats.rx_fifo_errors++;
2028         if (status & PCIErr) {
2029                 u16 pci_cmd_status;
2030                 pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
2031                 pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status);
2032
2033                 printk (KERN_ERR "%s: PCI Bus error %4.4x.\n",
2034                         dev->name, pci_cmd_status);
2035         }
2036 }
2037
2038
2039 /* The interrupt handler does all of the Rx thread work and cleans up
2040    after the Tx thread. */
2041 static void rtl8139_interrupt (int irq, void *dev_instance,
2042                                struct pt_regs *regs)
2043 {
2044         struct net_device *dev = (struct net_device *) dev_instance;
2045         struct rtl8139_private *tp = dev->priv;
2046         int boguscnt = max_interrupt_work;
2047         void *ioaddr = tp->mmio_addr;
2048         int ackstat, status;
2049         int link_changed = 0; /* avoid bogus "uninit" warning */
2050
2051         spin_lock (&tp->lock);
2052
2053         do {
2054                 status = RTL_R16 (IntrStatus);
2055
2056                 /* h/w no longer present (hotplug?) or major error, bail */
2057                 if (status == 0xFFFF)
2058                         break;
2059
2060                 if ((status &
2061                      (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
2062                       RxFIFOOver | TxErr | TxOK | RxErr | RxOK)) == 0)
2063                         break;
2064
2065                 /* Acknowledge all of the current interrupt sources ASAP, but
2066                    an first get an additional status bit from CSCR. */
2067                 if (status & RxUnderrun)
2068                         link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
2069
2070                 /* The chip takes special action when we clear RxAckBits,
2071                  * so we clear them later in rtl8139_rx_interrupt
2072                  */
2073                 ackstat = status & ~(RxAckBits | TxErr);
2074                 RTL_W16 (IntrStatus, ackstat);
2075
2076                 DPRINTK ("%s: interrupt  status=%#4.4x ackstat=%#4.4x new intstat=%#4.4x.\n",
2077                          dev->name, ackstat, status, RTL_R16 (IntrStatus));
2078
2079                 if (netif_running (dev) && (status & RxAckBits))
2080                         rtl8139_rx_interrupt (dev, tp, ioaddr);
2081
2082                 /* Check uncommon events with one test. */
2083                 if (status & (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
2084                               RxFIFOOver | RxErr))
2085                         rtl8139_weird_interrupt (dev, tp, ioaddr,
2086                                                  status, link_changed);
2087
2088                 if (netif_running (dev) && (status & (TxOK | TxErr))) {
2089                         rtl8139_tx_interrupt (dev, tp, ioaddr);
2090                         if (status & TxErr)
2091                                 RTL_W16 (IntrStatus, TxErr);
2092                 }
2093
2094                 boguscnt--;
2095         } while (boguscnt > 0);
2096
2097         if (boguscnt <= 0) {
2098                 printk (KERN_WARNING "%s: Too much work at interrupt, "
2099                         "IntrStatus=0x%4.4x.\n", dev->name, status);
2100
2101                 /* Clear all interrupt sources. */
2102                 RTL_W16 (IntrStatus, 0xffff);
2103         }
2104
2105         spin_unlock (&tp->lock);
2106
2107         DPRINTK ("%s: exiting interrupt, intr_status=%#4.4x.\n",
2108                  dev->name, RTL_R16 (IntrStatus));
2109 }
2110
2111
2112 static int rtl8139_close (struct net_device *dev)
2113 {
2114         struct rtl8139_private *tp = dev->priv;
2115         void *ioaddr = tp->mmio_addr;
2116         int ret = 0;
2117         unsigned long flags;
2118
2119         netif_stop_queue (dev);
2120
2121         if (tp->thr_pid >= 0) {
2122                 tp->time_to_die = 1;
2123                 wmb();
2124                 ret = kill_proc (tp->thr_pid, SIGTERM, 1);
2125                 if (ret) {
2126                         printk (KERN_ERR "%s: unable to signal thread\n", dev->name);
2127                         return ret;
2128                 }
2129                 wait_for_completion (&tp->thr_exited);
2130         }
2131
2132         DPRINTK ("%s: Shutting down ethercard, status was 0x%4.4x.\n",
2133                         dev->name, RTL_R16 (IntrStatus));
2134
2135         spin_lock_irqsave (&tp->lock, flags);
2136
2137         /* Stop the chip's Tx and Rx DMA processes. */
2138         RTL_W8 (ChipCmd, 0);
2139
2140         /* Disable interrupts by clearing the interrupt mask. */
2141         RTL_W16 (IntrMask, 0);
2142
2143         /* Update the error counts. */
2144         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2145         RTL_W32 (RxMissed, 0);
2146
2147         spin_unlock_irqrestore (&tp->lock, flags);
2148
2149         synchronize_irq ();
2150         free_irq (dev->irq, dev);
2151
2152         rtl8139_tx_clear (tp);
2153
2154         pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
2155                             tp->rx_ring, tp->rx_ring_dma);
2156         pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
2157                             tp->tx_bufs, tp->tx_bufs_dma);
2158         tp->rx_ring = NULL;
2159         tp->tx_bufs = NULL;
2160
2161         /* Green! Put the chip in low-power mode. */
2162         RTL_W8 (Cfg9346, Cfg9346_Unlock);
2163
2164         if (rtl_chip_info[tp->chipset].flags & HasHltClk)
2165                 RTL_W8 (HltClk, 'H');   /* 'R' would leave the clock running. */
2166
2167         return 0;
2168 }
2169
2170
2171 /* Get the ethtool Wake-on-LAN settings.  Assumes that wol points to
2172    kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and
2173    other threads or interrupts aren't messing with the 8139.  */
2174 static void netdev_get_wol (struct net_device *dev, struct ethtool_wolinfo *wol)
2175 {
2176         struct rtl8139_private *np = dev->priv;
2177         void *ioaddr = np->mmio_addr;
2178
2179         if (rtl_chip_info[np->chipset].flags & HasLWake) {
2180                 u8 cfg3 = RTL_R8 (Config3);
2181                 u8 cfg5 = RTL_R8 (Config5);
2182
2183                 wol->supported = WAKE_PHY | WAKE_MAGIC
2184                         | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST;
2185
2186                 wol->wolopts = 0;
2187                 if (cfg3 & Cfg3_LinkUp)
2188                         wol->wolopts |= WAKE_PHY;
2189                 if (cfg3 & Cfg3_Magic)
2190                         wol->wolopts |= WAKE_MAGIC;
2191                 /* (KON)FIXME: See how netdev_set_wol() handles the
2192                    following constants.  */
2193                 if (cfg5 & Cfg5_UWF)
2194                         wol->wolopts |= WAKE_UCAST;
2195                 if (cfg5 & Cfg5_MWF)
2196                         wol->wolopts |= WAKE_MCAST;
2197                 if (cfg5 & Cfg5_BWF)
2198                         wol->wolopts |= WAKE_BCAST;
2199         }
2200 }
2201
2202
2203 /* Set the ethtool Wake-on-LAN settings.  Return 0 or -errno.  Assumes
2204    that wol points to kernel memory and other threads or interrupts
2205    aren't messing with the 8139.  */
2206 static int netdev_set_wol (struct net_device *dev,
2207                            const struct ethtool_wolinfo *wol)
2208 {
2209         struct rtl8139_private *np = dev->priv;
2210         void *ioaddr = np->mmio_addr;
2211         u32 support;
2212         u8 cfg3, cfg5;
2213
2214         support = ((rtl_chip_info[np->chipset].flags & HasLWake)
2215                    ? (WAKE_PHY | WAKE_MAGIC
2216                       | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)
2217                    : 0);
2218         if (wol->wolopts & ~support)
2219                 return -EINVAL;
2220
2221         cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic);
2222         if (wol->wolopts & WAKE_PHY)
2223                 cfg3 |= Cfg3_LinkUp;
2224         if (wol->wolopts & WAKE_MAGIC)
2225                 cfg3 |= Cfg3_Magic;
2226         RTL_W8 (Cfg9346, Cfg9346_Unlock);
2227         RTL_W8 (Config3, cfg3);
2228         RTL_W8 (Cfg9346, Cfg9346_Lock);
2229
2230         cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF);
2231         /* (KON)FIXME: These are untested.  We may have to set the
2232            CRC0, Wakeup0 and LSBCRC0 registers too, but I have no
2233            documentation.  */
2234         if (wol->wolopts & WAKE_UCAST)
2235                 cfg5 |= Cfg5_UWF;
2236         if (wol->wolopts & WAKE_MCAST)
2237                 cfg5 |= Cfg5_MWF;
2238         if (wol->wolopts & WAKE_BCAST)
2239                 cfg5 |= Cfg5_BWF;
2240         RTL_W8 (Config5, cfg5); /* need not unlock via Cfg9346 */
2241
2242         return 0;
2243 }
2244
2245 static int netdev_ethtool_ioctl (struct net_device *dev, void *useraddr)
2246 {
2247         struct rtl8139_private *np = dev->priv;
2248         u32 ethcmd;
2249
2250         /* dev_ioctl() in ../../net/core/dev.c has already checked
2251            capable(CAP_NET_ADMIN), so don't bother with that here.  */
2252
2253         if (get_user(ethcmd, (u32 *)useraddr))
2254                 return -EFAULT;
2255
2256         switch (ethcmd) {
2257
2258         case ETHTOOL_GDRVINFO: {
2259                 struct ethtool_drvinfo info = { ETHTOOL_GDRVINFO };
2260                 strcpy (info.driver, DRV_NAME);
2261                 strcpy (info.version, DRV_VERSION);
2262                 strcpy (info.bus_info, np->pci_dev->slot_name);
2263                 info.regdump_len = np->regs_len;
2264                 if (copy_to_user (useraddr, &info, sizeof (info)))
2265                         return -EFAULT;
2266                 return 0;
2267         }
2268
2269         /* get settings */
2270         case ETHTOOL_GSET: {
2271                 struct ethtool_cmd ecmd = { ETHTOOL_GSET };
2272                 spin_lock_irq(&np->lock);
2273                 mii_ethtool_gset(&np->mii, &ecmd);
2274                 spin_unlock_irq(&np->lock);
2275                 if (copy_to_user(useraddr, &ecmd, sizeof(ecmd)))
2276                         return -EFAULT;
2277                 return 0;
2278         }
2279         /* set settings */
2280         case ETHTOOL_SSET: {
2281                 int r;
2282                 struct ethtool_cmd ecmd;
2283                 if (copy_from_user(&ecmd, useraddr, sizeof(ecmd)))
2284                         return -EFAULT;
2285                 spin_lock_irq(&np->lock);
2286                 r = mii_ethtool_sset(&np->mii, &ecmd);
2287                 spin_unlock_irq(&np->lock);
2288                 return r;
2289         }
2290         /* restart autonegotiation */
2291         case ETHTOOL_NWAY_RST: {
2292                 return mii_nway_restart(&np->mii);
2293         }
2294         /* get link status */
2295         case ETHTOOL_GLINK: {
2296                 struct ethtool_value edata = {ETHTOOL_GLINK};
2297                 edata.data = mii_link_ok(&np->mii);
2298                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2299                         return -EFAULT;
2300                 return 0;
2301         }
2302
2303         /* get message-level */
2304         case ETHTOOL_GMSGLVL: {
2305                 struct ethtool_value edata = {ETHTOOL_GMSGLVL};
2306                 edata.data = debug;
2307                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2308                         return -EFAULT;
2309                 return 0;
2310         }
2311         /* set message-level */
2312         case ETHTOOL_SMSGLVL: {
2313                 struct ethtool_value edata;
2314                 if (copy_from_user(&edata, useraddr, sizeof(edata)))
2315                         return -EFAULT;
2316                 debug = edata.data;
2317                 return 0;
2318         }
2319
2320         case ETHTOOL_GWOL:
2321                 {
2322                         struct ethtool_wolinfo wol = { ETHTOOL_GWOL };
2323                         spin_lock_irq (&np->lock);
2324                         netdev_get_wol (dev, &wol);
2325                         spin_unlock_irq (&np->lock);
2326                         if (copy_to_user (useraddr, &wol, sizeof (wol)))
2327                                 return -EFAULT;
2328                         return 0;
2329                 }
2330
2331         case ETHTOOL_SWOL:
2332                 {
2333                         struct ethtool_wolinfo wol;
2334                         int rc;
2335                         if (copy_from_user (&wol, useraddr, sizeof (wol)))
2336                                 return -EFAULT;
2337                         spin_lock_irq (&np->lock);
2338                         rc = netdev_set_wol (dev, &wol);
2339                         spin_unlock_irq (&np->lock);
2340                         return rc;
2341                 }
2342
2343 /* TODO: we are too slack to do reg dumping for pio, for now */
2344 #ifndef CONFIG_8139TOO_PIO
2345         /* NIC register dump */
2346         case ETHTOOL_GREGS: {
2347                 struct ethtool_regs regs;
2348                 unsigned int regs_len = np->regs_len;
2349                 u8 *regbuf = kmalloc(regs_len, GFP_KERNEL);
2350                 int rc;
2351
2352                 if (!regbuf)
2353                         return -ENOMEM;
2354                 memset(regbuf, 0, regs_len);
2355
2356                 rc = copy_from_user(&regs, useraddr, sizeof(regs));
2357                 if (rc) {
2358                         rc = -EFAULT;
2359                         goto err_out_gregs;
2360                 }
2361                 
2362                 if (regs.len > regs_len)
2363                         regs.len = regs_len;
2364                 if (regs.len < regs_len) {
2365                         rc = -EINVAL;
2366                         goto err_out_gregs;
2367                 }
2368
2369                 regs.version = RTL_REGS_VER;
2370                 rc = copy_to_user(useraddr, &regs, sizeof(regs));
2371                 if (rc) {
2372                         rc = -EFAULT;
2373                         goto err_out_gregs;
2374                 }
2375
2376                 useraddr += offsetof(struct ethtool_regs, data);
2377
2378                 spin_lock_irq(&np->lock);
2379                 memcpy_fromio(regbuf, np->mmio_addr, regs_len);
2380                 spin_unlock_irq(&np->lock);
2381
2382                 if (copy_to_user(useraddr, regbuf, regs_len))
2383                         rc = -EFAULT;
2384
2385 err_out_gregs:
2386                 kfree(regbuf);
2387                 return rc;
2388         }
2389 #endif /* CONFIG_8139TOO_PIO */
2390
2391         /* get string list(s) */
2392         case ETHTOOL_GSTRINGS: {
2393                 struct ethtool_gstrings estr = { ETHTOOL_GSTRINGS };
2394
2395                 if (copy_from_user(&estr, useraddr, sizeof(estr)))
2396                         return -EFAULT;
2397                 if (estr.string_set != ETH_SS_STATS)
2398                         return -EINVAL;
2399
2400                 estr.len = RTL_NUM_STATS;
2401                 if (copy_to_user(useraddr, &estr, sizeof(estr)))
2402                         return -EFAULT;
2403                 if (copy_to_user(useraddr + sizeof(estr),
2404                                  &ethtool_stats_keys,
2405                                  sizeof(ethtool_stats_keys)))
2406                         return -EFAULT;
2407                 return 0;
2408         }
2409
2410         /* get NIC-specific statistics */
2411         case ETHTOOL_GSTATS: {
2412                 struct ethtool_stats estats = { ETHTOOL_GSTATS };
2413                 u64 *tmp_stats;
2414                 const unsigned int sz = sizeof(u64) * RTL_NUM_STATS;
2415                 int i;
2416
2417                 estats.n_stats = RTL_NUM_STATS;
2418                 if (copy_to_user(useraddr, &estats, sizeof(estats)))
2419                         return -EFAULT;
2420
2421                 tmp_stats = kmalloc(sz, GFP_KERNEL);
2422                 if (!tmp_stats)
2423                         return -ENOMEM;
2424                 memset(tmp_stats, 0, sz);
2425
2426                 i = 0;
2427                 tmp_stats[i++] = np->xstats.early_rx;
2428                 tmp_stats[i++] = np->xstats.tx_buf_mapped;
2429                 tmp_stats[i++] = np->xstats.tx_timeouts;
2430                 tmp_stats[i++] = np->xstats.rx_lost_in_ring;
2431                 if (i != RTL_NUM_STATS)
2432                         BUG();
2433
2434                 i = copy_to_user(useraddr + sizeof(estats), tmp_stats, sz);
2435                 kfree(tmp_stats);
2436
2437                 if (i)
2438                         return -EFAULT;
2439                 return 0;
2440         }
2441         default:
2442                 break;
2443         }
2444
2445         return -EOPNOTSUPP;
2446 }
2447
2448
2449 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2450 {
2451         struct rtl8139_private *np = dev->priv;
2452         struct mii_ioctl_data *data = (struct mii_ioctl_data *) & rq->ifr_data;
2453         int rc;
2454
2455         if (!netif_running(dev))
2456                 return -EINVAL;
2457
2458         if (cmd == SIOCETHTOOL)
2459                 rc = netdev_ethtool_ioctl(dev, (void *) rq->ifr_data);
2460
2461         else {
2462                 spin_lock_irq(&np->lock);
2463                 rc = generic_mii_ioctl(&np->mii, data, cmd, NULL);
2464                 spin_unlock_irq(&np->lock);
2465         }
2466
2467         return rc;
2468 }
2469
2470
2471 static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
2472 {
2473         struct rtl8139_private *tp = dev->priv;
2474         void *ioaddr = tp->mmio_addr;
2475         unsigned long flags;
2476
2477         if (netif_running(dev)) {
2478                 spin_lock_irqsave (&tp->lock, flags);
2479                 tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2480                 RTL_W32 (RxMissed, 0);
2481                 spin_unlock_irqrestore (&tp->lock, flags);
2482         }
2483
2484         return &tp->stats;
2485 }
2486
2487 /* Set or clear the multicast filter for this adaptor.
2488    This routine is not state sensitive and need not be SMP locked. */
2489
2490 static void __set_rx_mode (struct net_device *dev)
2491 {
2492         struct rtl8139_private *tp = dev->priv;
2493         void *ioaddr = tp->mmio_addr;
2494         u32 mc_filter[2];       /* Multicast hash filter */
2495         int i, rx_mode;
2496         u32 tmp;
2497
2498         DPRINTK ("%s:   rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
2499                         dev->name, dev->flags, RTL_R32 (RxConfig));
2500
2501         /* Note: do not reorder, GCC is clever about common statements. */
2502         if (dev->flags & IFF_PROMISC) {
2503                 /* Unconditionally log net taps. */
2504                 printk (KERN_NOTICE "%s: Promiscuous mode enabled.\n",
2505                         dev->name);
2506                 rx_mode =
2507                     AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
2508                     AcceptAllPhys;
2509                 mc_filter[1] = mc_filter[0] = 0xffffffff;
2510         } else if ((dev->mc_count > multicast_filter_limit)
2511                    || (dev->flags & IFF_ALLMULTI)) {
2512                 /* Too many to filter perfectly -- accept all multicasts. */
2513                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
2514                 mc_filter[1] = mc_filter[0] = 0xffffffff;
2515         } else {
2516                 struct dev_mc_list *mclist;
2517                 rx_mode = AcceptBroadcast | AcceptMyPhys;
2518                 mc_filter[1] = mc_filter[0] = 0;
2519                 for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
2520                      i++, mclist = mclist->next) {
2521                         int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
2522
2523                         mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
2524                         rx_mode |= AcceptMulticast;
2525                 }
2526         }
2527
2528         /* We can safely update without stopping the chip. */
2529         tmp = rtl8139_rx_config | rx_mode;
2530         if (tp->rx_config != tmp) {
2531                 RTL_W32_F (RxConfig, tmp);
2532                 tp->rx_config = tmp;
2533         }
2534         RTL_W32_F (MAR0 + 0, mc_filter[0]);
2535         RTL_W32_F (MAR0 + 4, mc_filter[1]);
2536 }
2537
2538 static void rtl8139_set_rx_mode (struct net_device *dev)
2539 {
2540         unsigned long flags;
2541         struct rtl8139_private *tp = dev->priv;
2542
2543         spin_lock_irqsave (&tp->lock, flags);
2544         __set_rx_mode(dev);
2545         spin_unlock_irqrestore (&tp->lock, flags);
2546 }
2547
2548 #ifdef CONFIG_PM
2549
2550 static int rtl8139_suspend (struct pci_dev *pdev, u32 state)
2551 {
2552         struct net_device *dev = pci_get_drvdata (pdev);
2553         struct rtl8139_private *tp = dev->priv;
2554         void *ioaddr = tp->mmio_addr;
2555         unsigned long flags;
2556
2557         if (!netif_running (dev))
2558                 return 0;
2559
2560         netif_device_detach (dev);
2561
2562         spin_lock_irqsave (&tp->lock, flags);
2563
2564         /* Disable interrupts, stop Tx and Rx. */
2565         RTL_W16 (IntrMask, 0);
2566         RTL_W8 (ChipCmd, 0);
2567
2568         /* Update the error counts. */
2569         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2570         RTL_W32 (RxMissed, 0);
2571
2572         spin_unlock_irqrestore (&tp->lock, flags);
2573         return 0;
2574 }
2575
2576
2577 static int rtl8139_resume (struct pci_dev *pdev)
2578 {
2579         struct net_device *dev = pci_get_drvdata (pdev);
2580
2581         if (!netif_running (dev))
2582                 return 0;
2583         netif_device_attach (dev);
2584         rtl8139_hw_start (dev);
2585         return 0;
2586 }
2587
2588 #endif /* CONFIG_PM */
2589
2590
2591 static struct pci_driver rtl8139_pci_driver = {
2592         .name           = DRV_NAME,
2593         .id_table       = rtl8139_pci_tbl,
2594         .probe          = rtl8139_init_one,
2595         .remove         = __devexit_p(rtl8139_remove_one),
2596 #ifdef CONFIG_PM
2597         .suspend        = rtl8139_suspend,
2598         .resume         = rtl8139_resume,
2599 #endif /* CONFIG_PM */
2600 };
2601
2602
2603 static int __init rtl8139_init_module (void)
2604 {
2605         /* when we're a module, we always print a version message,
2606          * even if no 8139 board is found.
2607          */
2608 #ifdef MODULE
2609         printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
2610 #endif
2611
2612         return pci_module_init (&rtl8139_pci_driver);
2613 }
2614
2615
2616 static void __exit rtl8139_cleanup_module (void)
2617 {
2618         pci_unregister_driver (&rtl8139_pci_driver);
2619 }
2620
2621
2622 module_init(rtl8139_init_module);
2623 module_exit(rtl8139_cleanup_module);