~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Linux Cross Reference
Linux/drivers/net/8139too.c

Version: ~ [ 2.2.5 ] ~ [ 2.4.1 ] ~ [ 2.4.9 ] ~ [ 2.6.17.10 ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2 
  3         8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
  4 
  5         Maintained by Jeff Garzik <jgarzik@mandrakesoft.com>
  6 
  7         Much code comes from Donald Becker's rtl8139.c driver,
  8         versions 1.11 and older.  This driver was originally based
  9         on rtl8139.c version 1.07.  Header of rtl8139.c version 1.11:
 10 
 11         -----<snip>-----
 12 
 13                 Written 1997-2000 by Donald Becker.
 14                 This software may be used and distributed according to the
 15                 terms of the GNU General Public License (GPL), incorporated
 16                 herein by reference.  Drivers based on or derived from this
 17                 code fall under the GPL and must retain the authorship,
 18                 copyright and license notice.  This file is not a complete
 19                 program and may only be used when the entire operating
 20                 system is licensed under the GPL.
 21 
 22                 This driver is for boards based on the RTL8129 and RTL8139
 23                 PCI ethernet chips.
 24 
 25                 The author may be reached as becker@scyld.com, or C/O Scyld
 26                 Computing Corporation 410 Severn Ave., Suite 210 Annapolis
 27                 MD 21403
 28 
 29                 Support and updates available at
 30                 http://www.scyld.com/network/rtl8139.html
 31 
 32                 Twister-tuning table provided by Kinston
 33                 <shangh@realtek.com.tw>.
 34 
 35         -----<snip>-----
 36 
 37         This software may be used and distributed according to the terms
 38         of the GNU Public License, incorporated herein by reference.
 39 
 40         Contributors:
 41 
 42                 Donald Becker - he wrote the original driver, kudos to him!
 43                 (but please don't e-mail him for support, this isn't his driver)
 44 
 45                 Tigran Aivazian - bug fixes, skbuff free cleanup
 46 
 47                 Martin Mares - suggestions for PCI cleanup
 48 
 49                 David S. Miller - PCI DMA and softnet updates
 50 
 51                 Ernst Gill - fixes ported from BSD driver
 52 
 53                 Daniel Kobras - identified specific locations of
 54                         posted MMIO write bugginess
 55 
 56                 Gerard Sharp - bug fix, testing and feedback
 57 
 58                 David Ford - Rx ring wrap fix
 59 
 60                 Dan DeMaggio - swapped RTL8139 cards with me, and allowed me
 61                 to find and fix a crucial bug on older chipsets.
 62 
 63                 Donald Becker/Chris Butterworth/Marcus Westergren -
 64                 Noticed various Rx packet size-related buglets.
 65 
 66                 Santiago Garcia Mantinan - testing and feedback
 67 
 68                 Jens David - 2.2.x kernel backports
 69 
 70                 Martin Dennett - incredibly helpful insight on undocumented
 71                 features of the 8139 chips
 72 
 73                 Jean-Jacques Michel - bug fix
 74                 
 75                 Tobias Ringström - Rx interrupt status checking suggestion
 76 
 77                 Andrew Morton - (v0.9.13): clear blocked signals, avoid
 78                 buffer overrun setting current->comm.
 79 
 80         Submitting bug reports:
 81 
 82                 "rtl8139-diag -mmmaaavvveefN" output
 83                 enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log
 84 
 85                 See 8139too.txt for more details.
 86 
 87 -----------------------------------------------------------------------------
 88 
 89                                 Theory of Operation
 90 
 91 I. Board Compatibility
 92 
 93 This device driver is designed for the RealTek RTL8139 series, the RealTek
 94 Fast Ethernet controllers for PCI and CardBus.  This chip is used on many
 95 low-end boards, sometimes with its markings changed.
 96 
 97 
 98 II. Board-specific settings
 99 
100 PCI bus devices are configured by the system at boot time, so no jumpers
101 need to be set on the board.  The system BIOS will assign the
102 PCI INTA signal to a (preferably otherwise unused) system IRQ line.
103 
104 III. Driver operation
105 
106 IIIa. Rx Ring buffers
107 
108 The receive unit uses a single linear ring buffer rather than the more
109 common (and more efficient) descriptor-based architecture.  Incoming frames
110 are sequentially stored into the Rx region, and the host copies them into
111 skbuffs.
112 
113 Comment: While it is theoretically possible to process many frames in place,
114 any delay in Rx processing would cause us to drop frames.  More importantly,
115 the Linux protocol stack is not designed to operate in this manner.
116 
117 IIIb. Tx operation
118 
119 The RTL8139 uses a fixed set of four Tx descriptors in register space.
120 In a stunningly bad design choice, Tx frames must be 32 bit aligned.  Linux
121 aligns the IP header on word boundaries, and 14 byte ethernet header means
122 that almost all frames will need to be copied to an alignment buffer.
123 
124 IVb. References
125 
126 http://www.realtek.com.tw/cn/cn.html
127 http://www.scyld.com/expert/NWay.html
128 
129 IVc. Errata
130 
131 1) The RTL-8139 has a serious problem with motherboards which do
132 posted MMIO writes to PCI space.  This driver works around the
133 problem by having an MMIO  register write be immediately followed by
134 an MMIO register read.
135 
136 2) The RTL-8129 is only supported in Donald Becker's rtl8139 driver.
137 
138 */
139 
140 #include <linux/config.h>
141 #include <linux/module.h>
142 #include <linux/kernel.h>
143 #include <linux/pci.h>
144 #include <linux/init.h>
145 #include <linux/ioport.h>
146 #include <linux/netdevice.h>
147 #include <linux/etherdevice.h>
148 #include <linux/rtnetlink.h>
149 #include <linux/delay.h>
150 #include <asm/io.h>
151 
152 
153 #define RTL8139_VERSION "0.9.13"
154 #define MODNAME "8139too"
155 #define RTL8139_DRIVER_NAME   MODNAME " Fast Ethernet driver " RTL8139_VERSION
156 #define PFX MODNAME ": "
157 
158 
159 /* enable PIO instead of MMIO, if CONFIG_8139TOO_PIO is selected */
160 #ifdef CONFIG_8139TOO_PIO
161 #define USE_IO_OPS 1
162 #endif
163 
164 /* define to 1 to enable copious debugging info */
165 #undef RTL8139_DEBUG
166 
167 /* define to 1 to disable lightweight runtime debugging checks */
168 #undef RTL8139_NDEBUG
169 
170 
171 #ifdef RTL8139_DEBUG
172 /* note: prints function name for you */
173 #  define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt, __FUNCTION__ , ## args)
174 #else
175 #  define DPRINTK(fmt, args...)
176 #endif
177 
178 #ifdef RTL8139_NDEBUG
179 #  define assert(expr) do {} while (0)
180 #else
181 #  define assert(expr) \
182         if(!(expr)) {                                   \
183         printk( "Assertion failed! %s,%s,%s,line=%d\n", \
184         #expr,__FILE__,__FUNCTION__,__LINE__);          \
185         }
186 #endif
187 
188 
189 /* A few user-configurable values. */
190 /* media options */
191 static int media[] = {-1, -1, -1, -1, -1, -1, -1, -1};
192 
193 /* Maximum events (Rx packets, etc.) to handle at each interrupt. */
194 static int max_interrupt_work = 20;
195 
196 /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
197    The RTL chips use a 64 element hash table based on the Ethernet CRC.  */
198 static int multicast_filter_limit = 32;
199 
200 /* Size of the in-memory receive ring. */
201 #define RX_BUF_LEN_IDX  2       /* 0==8K, 1==16K, 2==32K, 3==64K */
202 #define RX_BUF_LEN (8192 << RX_BUF_LEN_IDX)
203 #define RX_BUF_PAD 16
204 #define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */
205 #define RX_BUF_TOT_LEN (RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD)
206 
207 /* Number of Tx descriptor registers. */
208 #define NUM_TX_DESC     4
209 
210 /* max supported ethernet frame size -- must be at least (dev->mtu+14+4).*/
211 #define MAX_ETH_FRAME_SIZE      1536
212 
213 /* Size of the Tx bounce buffers -- must be at least (dev->mtu+14+4). */
214 #define TX_BUF_SIZE     MAX_ETH_FRAME_SIZE
215 #define TX_BUF_TOT_LEN  (TX_BUF_SIZE * NUM_TX_DESC)
216 
217 /* PCI Tuning Parameters
218    Threshold is bytes transferred to chip before transmission starts. */
219 #define TX_FIFO_THRESH 256      /* In bytes, rounded down to 32 byte units. */
220 
221 /* The following settings are log_2(bytes)-4:  0 == 16 bytes .. 6==1024, 7==end of packet. */
222 #define RX_FIFO_THRESH  6       /* Rx buffer level before first PCI xfer.  */
223 #define RX_DMA_BURST    6       /* Maximum PCI burst, '6' is 1024 */
224 #define TX_DMA_BURST    6       /* Maximum PCI burst, '6' is 1024 */
225 
226 
227 /* Operational parameters that usually are not changed. */
228 /* Time in jiffies before concluding the transmitter is hung. */
229 #define TX_TIMEOUT  (6*HZ)
230 
231 
232 enum {
233         HAS_CHIP_XCVR = 0x020000,
234         HAS_LNK_CHNG = 0x040000,
235 };
236 
237 #define RTL_MIN_IO_SIZE 0x80
238 #define RTL8139B_IO_SIZE 256
239 
240 #define RTL8139_CAPS    HAS_CHIP_XCVR|HAS_LNK_CHNG
241 
242 typedef enum {
243         RTL8139 = 0,
244         RTL8139_CB,
245         SMC1211TX,
246         /*MPX5030,*/
247         DELTA8139,
248         ADDTRON8139,
249 } board_t;
250 
251 
252 /* indexed by board_t, above */
253 static struct {
254         const char *name;
255 } board_info[] __devinitdata = {
256         { "RealTek RTL8139 Fast Ethernet" },
257         { "RealTek RTL8139B PCI/CardBus" },
258         { "SMC1211TX EZCard 10/100 (RealTek RTL8139)" },
259 /*      { MPX5030, "Accton MPX5030 (RealTek RTL8139)" },*/
260         { "Delta Electronics 8139 10/100BaseTX" },
261         { "Addtron Technolgy 8139 10/100BaseTX" },
262 };
263 
264 
265 static struct pci_device_id rtl8139_pci_tbl[] __devinitdata = {
266         {0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
267         {0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139_CB },
268         {0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, SMC1211TX },
269 /*      {0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MPX5030 },*/
270         {0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DELTA8139 },
271         {0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ADDTRON8139 },
272         {0,}
273 };
274 MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
275 
276 
277 /* The rest of these values should never change. */
278 
279 /* Symbolic offsets to registers. */
280 enum RTL8139_registers {
281         MAC0 = 0,               /* Ethernet hardware address. */
282         MAR0 = 8,               /* Multicast filter. */
283         TxStatus0 = 0x10,       /* Transmit status (Four 32bit registers). */
284         TxAddr0 = 0x20,         /* Tx descriptors (also four 32bit). */
285         RxBuf = 0x30,
286         RxEarlyCnt = 0x34,
287         RxEarlyStatus = 0x36,
288         ChipCmd = 0x37,
289         RxBufPtr = 0x38,
290         RxBufAddr = 0x3A,
291         IntrMask = 0x3C,
292         IntrStatus = 0x3E,
293         TxConfig = 0x40,
294         ChipVersion = 0x43,
295         RxConfig = 0x44,
296         Timer = 0x48,           /* A general-purpose counter. */
297         RxMissed = 0x4C,        /* 24 bits valid, write clears. */
298         Cfg9346 = 0x50,
299         Config0 = 0x51,
300         Config1 = 0x52,
301         FlashReg = 0x54,
302         MediaStatus = 0x58,
303         Config3 = 0x59,
304         Config4 = 0x5A,         /* absent on RTL-8139A */
305         HltClk = 0x5B,
306         MultiIntr = 0x5C,
307         TxSummary = 0x60,
308         BasicModeCtrl = 0x62,
309         BasicModeStatus = 0x64,
310         NWayAdvert = 0x66,
311         NWayLPAR = 0x68,
312         NWayExpansion = 0x6A,
313         /* Undocumented registers, but required for proper operation. */
314         FIFOTMS = 0x70,         /* FIFO Control and test. */
315         CSCR = 0x74,            /* Chip Status and Configuration Register. */
316         PARA78 = 0x78,
317         PARA7c = 0x7c,          /* Magic transceiver parameter register. */
318         Config5 = 0xD8,         /* absent on RTL-8139A */
319 };
320 
321 enum ClearBitMasks {
322         MultiIntrClear = 0xF000,
323         ChipCmdClear = 0xE2,
324         Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
325 };
326 
327 enum ChipCmdBits {
328         CmdReset = 0x10,
329         CmdRxEnb = 0x08,
330         CmdTxEnb = 0x04,
331         RxBufEmpty = 0x01,
332 };
333 
334 /* Interrupt register bits, using my own meaningful names. */
335 enum IntrStatusBits {
336         PCIErr = 0x8000,
337         PCSTimeout = 0x4000,
338         RxFIFOOver = 0x40,
339         RxUnderrun = 0x20,
340         RxOverflow = 0x10,
341         TxErr = 0x08,
342         TxOK = 0x04,
343         RxErr = 0x02,
344         RxOK = 0x01,
345 };
346 enum TxStatusBits {
347         TxHostOwns = 0x2000,
348         TxUnderrun = 0x4000,
349         TxStatOK = 0x8000,
350         TxOutOfWindow = 0x20000000,
351         TxAborted = 0x40000000,
352         TxCarrierLost = 0x80000000,
353 };
354 enum RxStatusBits {
355         RxMulticast = 0x8000,
356         RxPhysical = 0x4000,
357         RxBroadcast = 0x2000,
358         RxBadSymbol = 0x0020,
359         RxRunt = 0x0010,
360         RxTooLong = 0x0008,
361         RxCRCErr = 0x0004,
362         RxBadAlign = 0x0002,
363         RxStatusOK = 0x0001,
364 };
365 
366 /* Bits in RxConfig. */
367 enum rx_mode_bits {
368         AcceptErr = 0x20,
369         AcceptRunt = 0x10,
370         AcceptBroadcast = 0x08,
371         AcceptMulticast = 0x04,
372         AcceptMyPhys = 0x02,
373         AcceptAllPhys = 0x01,
374 };
375 
376 /* Bits in TxConfig. */
377 enum tx_config_bits {
378         TxIFG1 = (1 << 25),     /* Interframe Gap Time */
379         TxIFG0 = (1 << 24),     /* Enabling these bits violates IEEE 802.3 */
380         TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */
381         TxCRC = (1 << 16),      /* DISABLE appending CRC to end of Tx packets */
382         TxClearAbt = (1 << 0),  /* Clear abort (WO) */
383         TxDMAShift = 8,         /* DMA burst value (0-7) is shift this many bits */
384 
385         TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */
386 };
387 
388 /* Bits in Config1 */
389 enum Config1Bits {
390         Cfg1_PM_Enable = 0x01,
391         Cfg1_VPD_Enable = 0x02,
392         Cfg1_PIO = 0x04,
393         Cfg1_MMIO = 0x08,
394         Cfg1_LWAKE = 0x10,
395         Cfg1_Driver_Load = 0x20,
396         Cfg1_LED0 = 0x40,
397         Cfg1_LED1 = 0x80,
398 };
399 
400 enum RxConfigBits {
401         /* Early Rx threshold, none or X/16 */
402         RxCfgEarlyRxNone = 0,
403         RxCfgEarlyRxShift = 24,
404 
405         /* rx fifo threshold */
406         RxCfgFIFOShift = 13,
407         RxCfgFIFONone = (7 << RxCfgFIFOShift),
408 
409         /* Max DMA burst */
410         RxCfgDMAShift = 8,
411         RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
412 
413         /* rx ring buffer length */
414         RxCfgRcv8K = 0,
415         RxCfgRcv16K = (1 << 11),
416         RxCfgRcv32K = (1 << 12),
417         RxCfgRcv64K = (1 << 11) | (1 << 12),
418 
419         /* Disable packet wrap at end of Rx buffer */
420         RxNoWrap = (1 << 7),
421 };
422 
423 
424 /* Twister tuning parameters from RealTek.
425    Completely undocumented, but required to tune bad links. */
426 enum CSCRBits {
427         CSCR_LinkOKBit = 0x0400,
428         CSCR_LinkChangeBit = 0x0800,
429         CSCR_LinkStatusBits = 0x0f000,
430         CSCR_LinkDownOffCmd = 0x003c0,
431         CSCR_LinkDownCmd = 0x0f3c0,
432 };
433 
434 
435 enum Cfg9346Bits {
436         Cfg9346_Lock = 0x00,
437         Cfg9346_Unlock = 0xC0,
438 };
439 
440 
441 #define PARA78_default  0x78fa8388
442 #define PARA7c_default  0xcb38de43      /* param[0][3] */
443 #define PARA7c_xxx              0xcb38de43
444 static const unsigned long param[4][4] = {
445         {0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
446         {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
447         {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
448         {0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
449 };
450 
451 struct ring_info {
452         struct sk_buff *skb;
453         dma_addr_t mapping;
454 };
455 
456 
457 typedef enum {
458         CH_8139 = 0,
459         CH_8139_K,
460         CH_8139A,
461         CH_8139B,
462         CH_8130,
463         CH_8139C,
464 } chip_t;
465 
466 
467 /* directly indexed by chip_t, above */
468 const static struct {
469         const char *name;
470         u8 version; /* from RTL8139C docs */
471         u32 RxConfigMask; /* should clear the bits supported by this chip */
472 } rtl_chip_info[] = {
473         { "RTL-8139",
474           0x40,
475           0xf0fe0040, /* XXX copied from RTL8139A, verify */
476         },
477 
478         { "RTL-8139 rev K",
479           0x60,
480           0xf0fe0040,
481         },
482 
483         { "RTL-8139A",
484           0x70,
485           0xf0fe0040,
486         },
487 
488         { "RTL-8139B",
489           0x78,
490           0xf0fc0040
491         },
492 
493         { "RTL-8130",
494           0x7C,
495           0xf0fe0040, /* XXX copied from RTL8139A, verify */
496         },
497 
498         { "RTL-8139C",
499           0x74,
500           0xf0fc0040, /* XXX copied from RTL8139B, verify */
501         },
502 
503 };
504 
505 
506 struct rtl8139_private {
507         board_t board;
508         void *mmio_addr;
509         int drv_flags;
510         struct pci_dev *pci_dev;
511         struct net_device_stats stats;
512         unsigned char *rx_ring;
513         unsigned int cur_rx;    /* Index into the Rx buffer of next Rx pkt. */
514         unsigned int tx_flag;
515         unsigned int cur_tx;
516         unsigned int dirty_tx;
517         /* The saved address of a sent-in-place packet/buffer, for skfree(). */
518         struct ring_info tx_info[NUM_TX_DESC];
519         unsigned char *tx_buf[NUM_TX_DESC];     /* Tx bounce buffers */
520         unsigned char *tx_bufs; /* Tx bounce buffer region. */
521         dma_addr_t rx_ring_dma;
522         dma_addr_t tx_bufs_dma;
523         char phys[4];           /* MII device addresses. */
524         char twistie, twist_row, twist_col;     /* Twister tune state. */
525         unsigned int full_duplex:1;     /* Full-duplex operation requested. */
526         unsigned int duplex_lock:1;
527         unsigned int default_port:4;    /* Last dev->if_port value. */
528         unsigned int media2:4;  /* Secondary monitored media port. */
529         unsigned int medialock:1;       /* Don't sense media type. */
530         unsigned int mediasense:1;      /* Media sensing in progress. */
531         spinlock_t lock;
532         chip_t chipset;
533         pid_t thr_pid;
534         wait_queue_head_t thr_wait;
535         struct semaphore thr_exited;
536 };
537 
538 MODULE_AUTHOR ("Jeff Garzik <jgarzik@mandrakesoft.com>");
539 MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver");
540 MODULE_PARM (multicast_filter_limit, "i");
541 MODULE_PARM (max_interrupt_work, "i");
542 MODULE_PARM (media, "1-" __MODULE_STRING(8) "i");
543 
544 static int read_eeprom (void *ioaddr, int location, int addr_len);
545 static int rtl8139_open (struct net_device *dev);
546 static int mdio_read (struct net_device *dev, int phy_id, int location);
547 static void mdio_write (struct net_device *dev, int phy_id, int location,
548                         int val);
549 static int rtl8139_thread (void *data);
550 static void rtl8139_tx_timeout (struct net_device *dev);
551 static void rtl8139_init_ring (struct net_device *dev);
552 static int rtl8139_start_xmit (struct sk_buff *skb,
553                                struct net_device *dev);
554 static void rtl8139_interrupt (int irq, void *dev_instance,
555                                struct pt_regs *regs);
556 static int rtl8139_close (struct net_device *dev);
557 static int mii_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
558 static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
559 static inline u32 ether_crc (int length, unsigned char *data);
560 static void rtl8139_set_rx_mode (struct net_device *dev);
561 static void rtl8139_hw_start (struct net_device *dev);
562 
563 #ifdef USE_IO_OPS
564 
565 #define RTL_R8(reg)             inb (((unsigned long)ioaddr) + (reg))
566 #define RTL_R16(reg)            inw (((unsigned long)ioaddr) + (reg))
567 #define RTL_R32(reg)            ((unsigned long) inl (((unsigned long)ioaddr) + (reg)))
568 #define RTL_W8(reg, val8)       outb ((val8), ((unsigned long)ioaddr) + (reg))
569 #define RTL_W16(reg, val16)     outw ((val16), ((unsigned long)ioaddr) + (reg))
570 #define RTL_W32(reg, val32)     outl ((val32), ((unsigned long)ioaddr) + (reg))
571 #define RTL_W8_F                RTL_W8
572 #define RTL_W16_F               RTL_W16
573 #define RTL_W32_F               RTL_W32
574 #undef readb
575 #undef readw
576 #undef readl
577 #undef writeb
578 #undef writew
579 #undef writel
580 #define readb(addr) inb((unsigned long)(addr))
581 #define readw(addr) inw((unsigned long)(addr))
582 #define readl(addr) inl((unsigned long)(addr))
583 #define writeb(val,addr) outb((val),(unsigned long)(addr))
584 #define writew(val,addr) outw((val),(unsigned long)(addr))
585 #define writel(val,addr) outl((val),(unsigned long)(addr))
586 
587 #else
588 
589 /* write MMIO register, with flush */
590 /* Flush avoids rtl8139 bug w/ posted MMIO writes */
591 #define RTL_W8_F(reg, val8)     do { writeb ((val8), ioaddr + (reg)); readb (ioaddr + (reg)); } while (0)
592 #define RTL_W16_F(reg, val16)   do { writew ((val16), ioaddr + (reg)); readw (ioaddr + (reg)); } while (0)
593 #define RTL_W32_F(reg, val32)   do { writel ((val32), ioaddr + (reg)); readl (ioaddr + (reg)); } while (0)
594 
595 
596 #if MMIO_FLUSH_AUDIT_COMPLETE
597 
598 /* write MMIO register */
599 #define RTL_W8(reg, val8)       writeb ((val8), ioaddr + (reg))
600 #define RTL_W16(reg, val16)     writew ((val16), ioaddr + (reg))
601 #define RTL_W32(reg, val32)     writel ((val32), ioaddr + (reg))
602 
603 #else
604 
605 /* write MMIO register, then flush */
606 #define RTL_W8          RTL_W8_F
607 #define RTL_W16         RTL_W16_F
608 #define RTL_W32         RTL_W32_F
609 
610 #endif /* MMIO_FLUSH_AUDIT_COMPLETE */
611 
612 /* read MMIO register */
613 #define RTL_R8(reg)             readb (ioaddr + (reg))
614 #define RTL_R16(reg)            readw (ioaddr + (reg))
615 #define RTL_R32(reg)            ((unsigned long) readl (ioaddr + (reg)))
616 
617 #endif /* USE_IO_OPS */
618 
619 
620 static const u16 rtl8139_intr_mask =
621         PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
622         TxErr | TxOK | RxErr | RxOK;
623 
624 static const unsigned int rtl8139_rx_config =
625           RxCfgEarlyRxNone | RxCfgRcv32K | RxNoWrap |
626           (RX_FIFO_THRESH << RxCfgFIFOShift) |
627           (RX_DMA_BURST << RxCfgDMAShift);
628 
629 
630 static int __devinit rtl8139_init_board (struct pci_dev *pdev,
631                                          struct net_device **dev_out,
632                                          void **ioaddr_out)
633 {
634         void *ioaddr = NULL;
635         struct net_device *dev;
636         struct rtl8139_private *tp;
637         u8 tmp8;
638         int rc, i;
639         u32 pio_start, pio_end, pio_flags, pio_len;
640         unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
641         u32 tmp;
642 
643         DPRINTK ("ENTER\n");
644 
645         assert (pdev != NULL);
646         assert (ioaddr_out != NULL);
647 
648         *ioaddr_out = NULL;
649         *dev_out = NULL;
650 
651         /* dev zeroed in init_etherdev */
652         dev = init_etherdev (NULL, sizeof (*tp));
653         if (dev == NULL) {
654                 printk (KERN_ERR PFX "unable to alloc new ethernet\n");
655                 DPRINTK ("EXIT, returning -ENOMEM\n");
656                 return -ENOMEM;
657         }
658         SET_MODULE_OWNER(dev);
659         tp = dev->priv;
660 
661         pio_start = pci_resource_start (pdev, 0);
662         pio_end = pci_resource_end (pdev, 0);
663         pio_flags = pci_resource_flags (pdev, 0);
664         pio_len = pci_resource_len (pdev, 0);
665 
666         mmio_start = pci_resource_start (pdev, 1);
667         mmio_end = pci_resource_end (pdev, 1);
668         mmio_flags = pci_resource_flags (pdev, 1);
669         mmio_len = pci_resource_len (pdev, 1);
670 
671         /* set this immediately, we need to know before
672          * we talk to the chip directly */
673         DPRINTK("PIO region size == 0x%02X\n", pio_len);
674         DPRINTK("MMIO region size == 0x%02lX\n", mmio_len);
675         if (pio_len == RTL8139B_IO_SIZE)
676                 tp->chipset = CH_8139B;
677 
678         /* make sure PCI base addr 0 is PIO */
679         if (!(pio_flags & IORESOURCE_IO)) {
680                 printk (KERN_ERR PFX "region #0 not a PIO resource, aborting\n");
681                 rc = -ENODEV;
682                 goto err_out;
683         }
684 
685         /* make sure PCI base addr 1 is MMIO */
686         if (!(mmio_flags & IORESOURCE_MEM)) {
687                 printk (KERN_ERR PFX "region #1 not an MMIO resource, aborting\n");
688                 rc = -ENODEV;
689                 goto err_out;
690         }
691 
692         /* check for weird/broken PCI region reporting */
693         if ((pio_len < RTL_MIN_IO_SIZE) ||
694             (mmio_len < RTL_MIN_IO_SIZE)) {
695                 printk (KERN_ERR PFX "Invalid PCI region size(s), aborting\n");
696                 rc = -ENODEV;
697                 goto err_out;
698         }
699 
700         /* make sure our PIO region in PCI space is available */
701         if (!request_region (pio_start, pio_len, dev->name)) {
702                 printk (KERN_ERR PFX "no I/O resource available, aborting\n");
703                 rc = -EBUSY;
704                 goto err_out;
705         }
706 
707         /* make sure our MMIO region in PCI space is available */
708         if (!request_mem_region (mmio_start, mmio_len, dev->name)) {
709                 printk (KERN_ERR PFX "no mem resource available, aborting\n");
710                 rc = -EBUSY;
711                 goto err_out_free_pio;
712         }
713 
714         /* enable device (incl. PCI PM wakeup), and bus-mastering */
715         rc = pci_enable_device (pdev);
716         if (rc)
717                 goto err_out_free_mmio;
718 
719         pci_set_master (pdev);
720 
721 #ifdef USE_IO_OPS
722         ioaddr = (void *) pio_start;
723 #else
724         /* ioremap MMIO region */
725         ioaddr = ioremap (mmio_start, mmio_len);
726         if (ioaddr == NULL) {
727                 printk (KERN_ERR PFX "cannot remap MMIO, aborting\n");
728                 rc = -EIO;
729                 goto err_out_free_mmio;
730         }
731 #endif /* USE_IO_OPS */
732 
733         /* Soft reset the chip. */
734         RTL_W8 (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear) | CmdReset);
735 
736         /* Check that the chip has finished the reset. */
737         for (i = 1000; i > 0; i--)
738                 if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
739                         break;
740                 else
741                         udelay (10);
742 
743         /* Bring the chip out of low-power mode. */
744         if (tp->chipset == CH_8139B) {
745                 RTL_W8 (Config1, RTL_R8 (Config1) & ~(1<<4));
746                 RTL_W8 (Config4, RTL_R8 (Config4) & ~(1<<2));
747         } else {
748                 /* handle RTL8139A and RTL8139 cases */
749                 /* XXX from becker driver. is this right?? */
750                 RTL_W8 (Config1, 0);
751         }
752 
753         /* make sure chip thinks PIO and MMIO are enabled */
754         tmp8 = RTL_R8 (Config1);
755         if ((tmp8 & Cfg1_PIO) == 0) {
756                 printk (KERN_ERR PFX "PIO not enabled, Cfg1=%02X, aborting\n", tmp8);
757                 rc = -EIO;
758                 goto err_out_iounmap;
759         }
760         if ((tmp8 & Cfg1_MMIO) == 0) {
761                 printk (KERN_ERR PFX "MMIO not enabled, Cfg1=%02X, aborting\n", tmp8);
762                 rc = -EIO;
763                 goto err_out_iounmap;
764         }
765 
766         /* identify chip attached to board */
767         tmp = RTL_R8 (ChipVersion);
768         for (i = ARRAY_SIZE (rtl_chip_info) - 1; i >= 0; i--)
769                 if (tmp == rtl_chip_info[i].version) {
770                         tp->chipset = i;
771                         goto match;
772                 }
773 
774         /* if unknown chip, assume array element #0, original RTL-8139 in this case */
775         printk (KERN_DEBUG PFX "PCI device %s: unknown chip version, assuming RTL-8139\n",
776                 pdev->slot_name);
777         printk (KERN_DEBUG PFX "PCI device %s: TxConfig = 0x%lx\n", pdev->slot_name, RTL_R32 (TxConfig));
778         tp->chipset = 0;
779 
780 match:
781         DPRINTK ("chipset id (%d) == index %d, '%s'\n",
782                 tmp,
783                 tp->chipset,
784                 rtl_chip_info[tp->chipset].name);
785 
786         DPRINTK ("EXIT, returning 0\n");
787         *ioaddr_out = ioaddr;
788         *dev_out = dev;
789         return 0;
790 
791 err_out_iounmap:
792         assert (ioaddr > 0);
793 #ifndef USE_IO_OPS
794         iounmap (ioaddr);
795 #endif /* !USE_IO_OPS */
796 err_out_free_mmio:
797         release_mem_region (mmio_start, mmio_len);
798 err_out_free_pio:
799         release_region (pio_start, pio_len);
800 err_out:
801         unregister_netdev (dev);
802         kfree (dev);
803         DPRINTK ("EXIT, returning %d\n", rc);
804         return rc;
805 }
806 
807 
808 static int __devinit rtl8139_init_one (struct pci_dev *pdev,
809                                        const struct pci_device_id *ent)
810 {
811         struct net_device *dev = NULL;
812         struct rtl8139_private *tp;
813         int i, addr_len, option;
814         void *ioaddr = NULL;
815         static int board_idx = -1;
816         static int printed_version = 0;
817         u8 tmp;
818 
819         DPRINTK ("ENTER\n");
820 
821         assert (pdev != NULL);
822         assert (ent != NULL);
823 
824         board_idx++;
825 
826         if (!printed_version) {
827                 printk (KERN_INFO RTL8139_DRIVER_NAME " loaded\n");
828                 printed_version = 1;
829         }
830 
831         i = rtl8139_init_board (pdev, &dev, &ioaddr);
832         if (i < 0) {
833                 DPRINTK ("EXIT, returning %d\n", i);
834                 return i;
835         }
836 
837         tp = dev->priv;
838 
839         assert (ioaddr != NULL);
840         assert (dev != NULL);
841         assert (tp != NULL);
842 
843         addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
844         for (i = 0; i < 3; i++)
845                 ((u16 *) (dev->dev_addr))[i] =
846                     le16_to_cpu (read_eeprom (ioaddr, i + 7, addr_len));
847 
848         /* The Rtl8139-specific entries in the device structure. */
849         dev->open = rtl8139_open;
850         dev->hard_start_xmit = rtl8139_start_xmit;
851         dev->stop = rtl8139_close;
852         dev->get_stats = rtl8139_get_stats;
853         dev->set_multicast_list = rtl8139_set_rx_mode;
854         dev->do_ioctl = mii_ioctl;
855         dev->tx_timeout = rtl8139_tx_timeout;
856         dev->watchdog_timeo = TX_TIMEOUT;
857 
858         dev->irq = pdev->irq;
859         dev->base_addr = (unsigned long) ioaddr;
860 
861         /* dev->priv/tp zeroed and aligned in init_etherdev */
862         tp = dev->priv;
863 
864         /* note: tp->chipset set in rtl8139_init_board */
865         tp->drv_flags = PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
866                         PCI_COMMAND_MASTER | RTL8139_CAPS;
867         tp->pci_dev = pdev;
868         tp->board = ent->driver_data;
869         tp->mmio_addr = ioaddr;
870         spin_lock_init (&tp->lock);
871         init_waitqueue_head (&tp->thr_wait);
872         init_MUTEX_LOCKED (&tp->thr_exited);
873 
874         pdev->driver_data = dev;
875 
876         tp->phys[0] = 32;
877 
878         printk (KERN_INFO "%s: %s at 0x%lx, "
879                 "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x, "
880                 "IRQ %d\n",
881                 dev->name,
882                 board_info[ent->driver_data].name,
883                 dev->base_addr,
884                 dev->dev_addr[0], dev->dev_addr[1],
885                 dev->dev_addr[2], dev->dev_addr[3],
886                 dev->dev_addr[4], dev->dev_addr[5],
887                 dev->irq);
888 
889         printk (KERN_DEBUG "%s:  Identified 8139 chip type '%s'\n",
890                 dev->name, rtl_chip_info[tp->chipset].name);
891 
892         /* Put the chip into low-power mode. */
893         RTL_W8_F (Cfg9346, Cfg9346_Unlock);
894 
895         tmp = RTL_R8 (Config1) & Config1Clear;
896         tmp |= (tp->chipset == CH_8139B) ? 3 : 1; /* Enable PM/VPD */
897         RTL_W8_F (Config1, tmp);
898 
899         RTL_W8_F (HltClk, 'H'); /* 'R' would leave the clock running. */
900 
901         /* The lower four bits are the media type. */
902         option = (board_idx >= ARRAY_SIZE(media)) ? 0 : media[board_idx];
903         if (option > 0) {
904                 tp->full_duplex = (option & 0x200) ? 1 : 0;
905                 tp->default_port = option & 15;
906                 if (tp->default_port)
907                         tp->medialock = 1;
908         }
909 
910         if (tp->full_duplex) {
911                 printk (KERN_INFO
912                         "%s: Media type forced to Full Duplex.\n",
913                         dev->name);
914                 mdio_write (dev, tp->phys[0], 4, 0x141);
915                 tp->duplex_lock = 1;
916         }
917 
918         DPRINTK ("EXIT - returning 0\n");
919         return 0;
920 }
921 
922 
923 static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
924 {
925         struct net_device *dev = pdev->driver_data;
926         struct rtl8139_private *np;
927 
928         DPRINTK ("ENTER\n");
929 
930         assert (dev != NULL);
931 
932         np = (struct rtl8139_private *) (dev->priv);
933         assert (np != NULL);
934 
935         unregister_netdev (dev);
936 
937 #ifndef USE_IO_OPS
938         iounmap (np->mmio_addr);
939 #endif /* !USE_IO_OPS */
940 
941         release_region (pci_resource_start (pdev, 0),
942                         pci_resource_len (pdev, 0));
943         release_mem_region (pci_resource_start (pdev, 1),
944                             pci_resource_len (pdev, 1));
945 
946 #ifndef RTL8139_NDEBUG
947         /* poison memory before freeing */
948         memset (dev, 0xBC,
949                 sizeof (struct net_device) +
950                 sizeof (struct rtl8139_private));
951 #endif /* RTL8139_NDEBUG */
952 
953         kfree (dev);
954 
955         pdev->driver_data = NULL;
956 
957         DPRINTK ("EXIT\n");
958 }
959 
960 
961 /* Serial EEPROM section. */
962 
963 /*  EEPROM_Ctrl bits. */
964 #define EE_SHIFT_CLK    0x04    /* EEPROM shift clock. */
965 #define EE_CS                   0x08    /* EEPROM chip select. */
966 #define EE_DATA_WRITE   0x02    /* EEPROM chip data in. */
967 #define EE_WRITE_0              0x00
968 #define EE_WRITE_1              0x02
969 #define EE_DATA_READ    0x01    /* EEPROM chip data out. */
970 #define EE_ENB                  (0x80 | EE_CS)
971 
972 /* Delay between EEPROM clock transitions.
973    No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
974  */
975 
976 #define eeprom_delay()  readl(ee_addr)
977 
978 /* The EEPROM commands include the alway-set leading bit. */
979 #define EE_WRITE_CMD    (5)
980 #define EE_READ_CMD             (6)
981 #define EE_ERASE_CMD    (7)
982 
983 static int __devinit read_eeprom (void *ioaddr, int location, int addr_len)
984 {
985         int i;
986         unsigned retval = 0;
987         void *ee_addr = ioaddr + Cfg9346;
988         int read_cmd = location | (EE_READ_CMD << addr_len);
989 
990         DPRINTK ("ENTER\n");
991 
992         writeb (EE_ENB & ~EE_CS, ee_addr);
993         writeb (EE_ENB, ee_addr);
994         eeprom_delay ();
995 
996         /* Shift the read command bits out. */
997         for (i = 4 + addr_len; i >= 0; i--) {
998                 int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
999                 writeb (EE_ENB | dataval, ee_addr);
1000                 eeprom_delay ();
1001                 writeb (EE_ENB | dataval | EE_SHIFT_CLK, ee_addr);
1002                 eeprom_delay ();
1003         }
1004         writeb (EE_ENB, ee_addr);
1005         eeprom_delay ();
1006 
1007         for (i = 16; i > 0; i--) {
1008                 writeb (EE_ENB | EE_SHIFT_CLK, ee_addr);
1009                 eeprom_delay ();
1010                 retval =
1011                     (retval << 1) | ((readb (ee_addr) & EE_DATA_READ) ? 1 :
1012                                      0);
1013                 writeb (EE_ENB, ee_addr);
1014                 eeprom_delay ();
1015         }
1016 
1017         /* Terminate the EEPROM access. */
1018         writeb (~EE_CS, ee_addr);
1019         eeprom_delay ();
1020 
1021         DPRINTK ("EXIT - returning %d\n", retval);
1022         return retval;
1023 }
1024 
1025 /* MII serial management: mostly bogus for now. */
1026 /* Read and write the MII management registers using software-generated
1027    serial MDIO protocol.
1028    The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
1029    met by back-to-back PCI I/O cycles, but we insert a delay to avoid
1030    "overclocking" issues. */
1031 #define MDIO_DIR                0x80
1032 #define MDIO_DATA_OUT   0x04
1033 #define MDIO_DATA_IN    0x02
1034 #define MDIO_CLK                0x01
1035 #define MDIO_WRITE0 (MDIO_DIR)
1036 #define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
1037 
1038 #define mdio_delay()    readb(mdio_addr)
1039 
1040 
1041 static char mii_2_8139_map[8] = {
1042         BasicModeCtrl,
1043         BasicModeStatus,
1044         0,
1045         0,
1046         NWayAdvert,
1047         NWayLPAR,
1048         NWayExpansion,
1049         0
1050 };
1051 
1052 
1053 /* Syncronize the MII management interface by shifting 32 one bits out. */
1054 static void mdio_sync (void *mdio_addr)
1055 {
1056         int i;
1057 
1058         DPRINTK ("ENTER\n");
1059 
1060         for (i = 32; i >= 0; i--) {
1061                 writeb (MDIO_WRITE1, mdio_addr);
1062                 mdio_delay ();
1063                 writeb (MDIO_WRITE1 | MDIO_CLK, mdio_addr);
1064                 mdio_delay ();
1065         }
1066 
1067         DPRINTK ("EXIT\n");
1068 }
1069 
1070 
1071 static int mdio_read (struct net_device *dev, int phy_id, int location)
1072 {
1073         struct rtl8139_private *tp = dev->priv;
1074         void *mdio_addr = tp->mmio_addr + Config4;
1075         int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
1076         int retval = 0;
1077         int i;
1078 
1079         DPRINTK ("ENTER\n");
1080 
1081         if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1082                 DPRINTK ("EXIT after directly using 8139 internal regs\n");
1083                 return location < 8 && mii_2_8139_map[location] ?
1084                     readw (tp->mmio_addr + mii_2_8139_map[location]) : 0;
1085         }
1086         mdio_sync (mdio_addr);
1087         /* Shift the read command bits out. */
1088         for (i = 15; i >= 0; i--) {
1089                 int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
1090 
1091                 writeb (MDIO_DIR | dataval, mdio_addr);
1092                 mdio_delay ();
1093                 writeb (MDIO_DIR | dataval | MDIO_CLK, mdio_addr);
1094                 mdio_delay ();
1095         }
1096 
1097         /* Read the two transition, 16 data, and wire-idle bits. */
1098         for (i = 19; i > 0; i--) {
1099                 writeb (0, mdio_addr);
1100                 mdio_delay ();
1101                 retval =
1102                     (retval << 1) | ((readb (mdio_addr) & MDIO_DATA_IN) ? 1
1103                                      : 0);
1104                 writeb (MDIO_CLK, mdio_addr);
1105                 mdio_delay ();
1106         }
1107 
1108         DPRINTK ("EXIT, returning %d\n", (retval >> 1) & 0xffff);
1109         return (retval >> 1) & 0xffff;
1110 }
1111 
1112 
1113 static void mdio_write (struct net_device *dev, int phy_id, int location,
1114                         int value)
1115 {
1116         struct rtl8139_private *tp = dev->priv;
1117         void *mdio_addr = tp->mmio_addr + Config4;
1118         int mii_cmd =
1119             (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
1120         int i;
1121 
1122         DPRINTK ("ENTER\n");
1123 
1124         if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1125                 if (location < 8 && mii_2_8139_map[location]) {
1126                         writew (value,
1127                                 tp->mmio_addr + mii_2_8139_map[location]);
1128                         readw (tp->mmio_addr + mii_2_8139_map[location]);
1129                 }
1130                 DPRINTK ("EXIT after directly using 8139 internal regs\n");
1131                 return;
1132         }
1133         mdio_sync (mdio_addr);
1134 
1135         /* Shift the command bits out. */
1136         for (i = 31; i >= 0; i--) {
1137                 int dataval =
1138                     (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
1139                 writeb (dataval, mdio_addr);
1140                 mdio_delay ();
1141                 writeb (dataval | MDIO_CLK, mdio_addr);
1142                 mdio_delay ();
1143         }
1144 
1145         /* Clear out extra bits. */
1146         for (i = 2; i > 0; i--) {
1147                 writeb (0, mdio_addr);
1148                 mdio_delay ();
1149                 writeb (MDIO_CLK, mdio_addr);
1150                 mdio_delay ();
1151         }
1152 
1153         DPRINTK ("EXIT\n");
1154 }
1155 
1156 
1157 static int rtl8139_open (struct net_device *dev)
1158 {
1159         struct rtl8139_private *tp = dev->priv;
1160         int retval;
1161 #ifdef RTL8139_DEBUG
1162         void *ioaddr = tp->mmio_addr;
1163 #endif
1164 
1165         DPRINTK ("ENTER\n");
1166 
1167         retval = request_irq (dev->irq, rtl8139_interrupt, SA_SHIRQ, dev->name, dev);
1168         if (retval) {
1169                 DPRINTK ("EXIT, returning %d\n", retval);
1170                 return retval;
1171         }
1172 
1173         tp->tx_bufs = pci_alloc_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1174                                            &tp->tx_bufs_dma);
1175         tp->rx_ring = pci_alloc_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1176                                            &tp->rx_ring_dma);
1177         if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
1178                 free_irq(dev->irq, dev);
1179 
1180                 if (tp->tx_bufs)
1181                         pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1182                                             tp->tx_bufs, tp->tx_bufs_dma);
1183                 if (tp->rx_ring)
1184                         pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1185                                             tp->rx_ring, tp->rx_ring_dma);
1186 
1187                 DPRINTK ("EXIT, returning -ENOMEM\n");
1188                 return -ENOMEM;
1189 
1190         }
1191 
1192         tp->full_duplex = tp->duplex_lock;
1193         tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
1194         tp->twistie = 1;
1195 
1196         rtl8139_init_ring (dev);
1197         rtl8139_hw_start (dev);
1198 
1199         DPRINTK ("%s: rtl8139_open() ioaddr %#lx IRQ %d"
1200                         " GP Pins %2.2x %s-duplex.\n",
1201                         dev->name, pci_resource_start (tp->pci_dev, 1),
1202                         dev->irq, RTL_R8 (MediaStatus),
1203                         tp->full_duplex ? "full" : "half");
1204 
1205         tp->thr_pid = kernel_thread (rtl8139_thread, dev, CLONE_FS | CLONE_FILES);
1206         if (tp->thr_pid < 0)
1207                 printk (KERN_WARNING "%s: unable to start kernel thread\n",
1208                         dev->name);
1209 
1210         DPRINTK ("EXIT, returning 0\n");
1211         return 0;
1212 }
1213 
1214 
1215 /* Start the hardware at open or resume. */
1216 static void rtl8139_hw_start (struct net_device *dev)
1217 {
1218         struct rtl8139_private *tp = dev->priv;
1219         void *ioaddr = tp->mmio_addr;
1220         u32 i;
1221         u8 tmp;
1222 
1223         DPRINTK ("ENTER\n");
1224 
1225         /* Soft reset the chip. */
1226         RTL_W8 (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear) | CmdReset);
1227         udelay (100);
1228 
1229         /* Check that the chip has finished the reset. */
1230         for (i = 1000; i > 0; i--)
1231                 if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
1232                         break;
1233 
1234         /* Restore our idea of the MAC address. */
1235         RTL_W32_F (MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
1236         RTL_W32_F (MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
1237 
1238         /* Must enable Tx/Rx before setting transfer thresholds! */
1239         RTL_W8_F (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear) |
1240                            CmdRxEnb | CmdTxEnb);
1241 
1242         i = rtl8139_rx_config |
1243             (RTL_R32 (RxConfig) & rtl_chip_info[tp->chipset].RxConfigMask);
1244         RTL_W32_F (RxConfig, i);
1245 
1246         /* Check this value: the documentation for IFG contradicts ifself. */
1247         RTL_W32 (TxConfig, (TX_DMA_BURST << TxDMAShift));
1248 
1249         /* unlock Config[01234] and BMCR register writes */
1250         RTL_W8_F (Cfg9346, Cfg9346_Unlock);
1251         udelay (10);
1252 
1253         tp->cur_rx = 0;
1254 
1255         if (tp->chipset >= CH_8139A) {
1256                 tmp = RTL_R8 (Config1) & Config1Clear;
1257                 tmp |= Cfg1_Driver_Load;
1258                 tmp |= (tp->chipset == CH_8139B) ? 3 : 1; /* Enable PM/VPD */
1259                 RTL_W8_F (Config1, tmp);
1260         } else {
1261                 u8 foo = RTL_R8 (Config1) & Config1Clear;
1262                 RTL_W8 (Config1, tp->full_duplex ? (foo|0x60) : (foo|0x20));
1263         }
1264 
1265         if (tp->chipset >= CH_8139B) {
1266                 tmp = RTL_R8 (Config4) & ~(1<<2);
1267                 /* chip will clear Rx FIFO overflow automatically */
1268                 tmp |= (1<<7);
1269                 RTL_W8 (Config4, tmp);
1270 
1271                 /* disable magic packet scanning, which is enabled
1272                  * when PM is enabled above (Config1) */
1273                 RTL_W8 (Config3, RTL_R8 (Config3) & ~(1<<5));
1274         }
1275 
1276         /* Lock Config[01234] and BMCR register writes */
1277         RTL_W8_F (Cfg9346, Cfg9346_Lock);
1278         udelay (10);
1279 
1280         /* init Rx ring buffer DMA address */
1281         RTL_W32_F (RxBuf, tp->rx_ring_dma);
1282 
1283         /* init Tx buffer DMA addresses */
1284         for (i = 0; i < NUM_TX_DESC; i++)
1285                 RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
1286 
1287         RTL_W32_F (RxMissed, 0);
1288 
1289         rtl8139_set_rx_mode (dev);
1290 
1291         /* no early-rx interrupts */
1292         RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
1293 
1294         /* make sure RxTx has started */
1295         RTL_W8_F (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear) |
1296                            CmdRxEnb | CmdTxEnb);
1297 
1298         /* Enable all known interrupts by setting the interrupt mask. */
1299         RTL_W16_F (IntrMask, rtl8139_intr_mask);
1300 
1301         netif_start_queue (dev);
1302 
1303         DPRINTK ("EXIT\n");
1304 }
1305 
1306 
1307 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1308 static void rtl8139_init_ring (struct net_device *dev)
1309 {
1310         struct rtl8139_private *tp = dev->priv;
1311         int i;
1312 
1313         DPRINTK ("ENTER\n");
1314 
1315         tp->cur_rx = 0;
1316         tp->cur_tx = 0;
1317         tp->dirty_tx = 0;
1318 
1319         for (i = 0; i < NUM_TX_DESC; i++) {
1320                 tp->tx_info[i].skb = NULL;
1321                 tp->tx_info[i].mapping = 0;
1322                 tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
1323         }
1324 
1325         DPRINTK ("EXIT\n");
1326 }
1327 
1328 
1329 /* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
1330 static int next_tick = 3 * HZ;
1331 
1332 #ifndef CONFIG_8139TOO_TUNE_TWISTER
1333 static inline void rtl8139_tune_twister (struct net_device *dev,
1334                                   struct rtl8139_private *tp) {}
1335 #else
1336 static void rtl8139_tune_twister (struct net_device *dev,
1337                                   struct rtl8139_private *tp)
1338 {
1339         int linkcase;
1340         void *ioaddr = tp->mmio_addr;
1341 
1342         DPRINTK ("ENTER\n");
1343 
1344         /* This is a complicated state machine to configure the "twister" for
1345            impedance/echos based on the cable length.
1346            All of this is magic and undocumented.
1347          */
1348         switch (tp->twistie) {
1349         case 1:
1350                 if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
1351                         /* We have link beat, let us tune the twister. */
1352                         RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
1353                         tp->twistie = 2;        /* Change to state 2. */
1354                         next_tick = HZ / 10;
1355                 } else {
1356                         /* Just put in some reasonable defaults for when beat returns. */
1357                         RTL_W16 (CSCR, CSCR_LinkDownCmd);
1358                         RTL_W32 (FIFOTMS, 0x20);        /* Turn on cable test mode. */
1359                         RTL_W32 (PARA78, PARA78_default);
1360                         RTL_W32 (PARA7c, PARA7c_default);
1361                         tp->twistie = 0;        /* Bail from future actions. */
1362                 }
1363                 break;
1364         case 2:
1365                 /* Read how long it took to hear the echo. */
1366                 linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
1367                 if (linkcase == 0x7000)
1368                         tp->twist_row = 3;
1369                 else if (linkcase == 0x3000)
1370                         tp->twist_row = 2;
1371                 else if (linkcase == 0x1000)
1372                         tp->twist_row = 1;
1373                 else
1374                         tp->twist_row = 0;
1375                 tp->twist_col = 0;
1376                 tp->twistie = 3;        /* Change to state 2. */
1377                 next_tick = HZ / 10;
1378                 break;
1379         case 3:
1380                 /* Put out four tuning parameters, one per 100msec. */
1381                 if (tp->twist_col == 0)
1382                         RTL_W16 (FIFOTMS, 0);
1383                 RTL_W32 (PARA7c, param[(int) tp->twist_row]
1384                          [(int) tp->twist_col]);
1385                 next_tick = HZ / 10;
1386                 if (++tp->twist_col >= 4) {
1387                         /* For short cables we are done.
1388                            For long cables (row == 3) check for mistune. */
1389                         tp->twistie =
1390                             (tp->twist_row == 3) ? 4 : 0;
1391                 }
1392                 break;
1393         case 4:
1394                 /* Special case for long cables: check for mistune. */
1395                 if ((RTL_R16 (CSCR) &
1396                      CSCR_LinkStatusBits) == 0x7000) {
1397                         tp->twistie = 0;
1398                         break;
1399                 } else {
1400                         RTL_W32 (PARA7c, 0xfb38de03);
1401                         tp->twistie = 5;
1402                         next_tick = HZ / 10;
1403                 }
1404                 break;
1405         case 5:
1406                 /* Retune for shorter cable (column 2). */
1407                 RTL_W32 (FIFOTMS, 0x20);
1408                 RTL_W32 (PARA78, PARA78_default);
1409                 RTL_W32 (PARA7c, PARA7c_default);
1410                 RTL_W32 (FIFOTMS, 0x00);
1411                 tp->twist_row = 2;
1412                 tp->twist_col = 0;
1413                 tp->twistie = 3;
1414                 next_tick = HZ / 10;
1415                 break;
1416 
1417         default:
1418                 /* do nothing */
1419                 break;
1420         }
1421 
1422         DPRINTK ("EXIT\n");
1423 }
1424 #endif /* CONFIG_8139TOO_TUNE_TWISTER */
1425 
1426 
1427 static inline void rtl8139_thread_iter (struct net_device *dev,
1428                                  struct rtl8139_private *tp,
1429                                  void *ioaddr)
1430 {
1431         int mii_reg5;
1432 
1433         mii_reg5 = mdio_read (dev, tp->phys[0], 5);
1434 
1435         if (!tp->duplex_lock && mii_reg5 != 0xffff) {
1436                 int duplex = (mii_reg5 & 0x0100)
1437                     || (mii_reg5 & 0x01C0) == 0x0040;
1438                 if (tp->full_duplex != duplex) {
1439                         tp->full_duplex = duplex;
1440                         printk (KERN_INFO
1441                                 "%s: Setting %s-duplex based on MII #%d link"
1442                                 " partner ability of %4.4x.\n", dev->name,
1443                                 tp->full_duplex ? "full" : "half",
1444                                 tp->phys[0], mii_reg5);
1445                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
1446                         RTL_W8 (Config1, tp->full_duplex ? 0x60 : 0x20);
1447                         RTL_W8 (Cfg9346, Cfg9346_Lock);
1448                 }
1449         }
1450 
1451         next_tick = HZ * 60;
1452 
1453         rtl8139_tune_twister (dev, tp);
1454 
1455         DPRINTK ("%s: Media selection tick, Link partner %4.4x.\n",
1456                  dev->name, RTL_R16 (NWayLPAR));
1457         DPRINTK ("%s:  Other registers are IntMask %4.4x IntStatus %4.4x"
1458                  " RxStatus %4.4lx.\n", dev->name,
1459                  RTL_R16 (IntrMask),
1460                  RTL_R16 (IntrStatus),
1461                  RTL_R32 (RxEarlyStatus));
1462         DPRINTK ("%s:  Chip config %2.2x %2.2x.\n",
1463                  dev->name, RTL_R8 (Config0),
1464                  RTL_R8 (Config1));
1465 }
1466 
1467 
1468 static int rtl8139_thread (void *data)
1469 {
1470         struct net_device *dev = data;
1471         struct rtl8139_private *tp = dev->priv;
1472         unsigned long timeout;
1473 
1474         daemonize ();
1475         spin_lock_irq(&current->sigmask_lock);
1476         sigemptyset(&current->blocked);
1477         recalc_sigpending(current);
1478         spin_unlock_irq(&current->sigmask_lock);
1479 
1480         strncpy (current->comm, dev->name, sizeof(current->comm) - 1);
1481         current->comm[sizeof(current->comm) - 1] = '\0';
1482 
1483         while (1) {
1484                 timeout = next_tick;
1485                 do {
1486                         timeout = interruptible_sleep_on_timeout (&tp->thr_wait, timeout);
1487                 } while (!signal_pending (current) && (timeout > 0));
1488 
1489                 if (signal_pending (current))
1490                         break;
1491 
1492                 rtnl_lock ();
1493                 rtl8139_thread_iter (dev, tp, tp->mmio_addr);
1494                 rtnl_unlock ();
1495         }
1496 
1497         up_and_exit (&tp->thr_exited, 0);
1498 }
1499 
1500 
1501 static void rtl8139_tx_clear (struct rtl8139_private *tp)
1502 {
1503         int i;
1504 
1505         tp->cur_tx = 0;
1506         tp->dirty_tx = 0;
1507 
1508         /* Dump the unsent Tx packets. */
1509         for (i = 0; i < NUM_TX_DESC; i++) {
1510                 struct ring_info *rp = &tp->tx_info[i];
1511                 if (rp->mapping != 0) {
1512                         pci_unmap_single (tp->pci_dev, rp->mapping,
1513                                           rp->skb->len, PCI_DMA_TODEVICE);
1514                         rp->mapping = 0;
1515                 }
1516                 if (rp->skb) {
1517                         dev_kfree_skb (rp->skb);
1518                         rp->skb = NULL;
1519                         tp->stats.tx_dropped++;
1520                 }
1521         }
1522 }
1523 
1524 
1525 static void rtl8139_tx_timeout (struct net_device *dev)
1526 {
1527         struct rtl8139_private *tp = dev->priv;
1528         void *ioaddr = tp->mmio_addr;
1529         int i;
1530         u8 tmp8;
1531 
1532         DPRINTK ("%s: Transmit timeout, status %2.2x %4.4x "
1533                  "media %2.2x.\n", dev->name,
1534                  RTL_R8 (ChipCmd),
1535                  RTL_R16 (IntrStatus),
1536                  RTL_R8 (MediaStatus));
1537 
1538         /* disable Tx ASAP, if not already */
1539         tmp8 = RTL_R8 (ChipCmd);
1540         if (tmp8 & CmdTxEnb)
1541                 RTL_W8 (ChipCmd, tmp8 & ~CmdTxEnb);
1542 
1543         /* Disable interrupts by clearing the interrupt mask. */
1544         RTL_W16 (IntrMask, 0x0000);
1545 
1546         /* Emit info to figure out what went wrong. */
1547         printk (KERN_DEBUG "%s: Tx queue start entry %d  dirty entry %d.\n",
1548                 dev->name, tp->cur_tx, tp->dirty_tx);
1549         for (i = 0; i < NUM_TX_DESC; i++)
1550                 printk (KERN_DEBUG "%s:  Tx descriptor %d is %8.8lx.%s\n",
1551                         dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
1552                         i == tp->dirty_tx % NUM_TX_DESC ?
1553                                 " (queue head)" : "");
1554 
1555         /* Stop a shared interrupt from scavenging while we are. */
1556         spin_lock_irq (&tp->lock);
1557         rtl8139_tx_clear (tp);
1558         spin_unlock_irq (&tp->lock);
1559 
1560         /* ...and finally, reset everything */
1561         rtl8139_hw_start (dev);
1562 }
1563 
1564 
1565 
1566 static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
1567 {
1568         struct rtl8139_private *tp = dev->priv;
1569         void *ioaddr = tp->mmio_addr;
1570         int entry;
1571 
1572         /* Calculate the next Tx descriptor entry. */
1573         entry = tp->cur_tx % NUM_TX_DESC;
1574 
1575         assert (tp->tx_info[entry].skb == NULL);
1576         assert (tp->tx_info[entry].mapping == 0);
1577 
1578         tp->tx_info[entry].skb = skb;
1579         if ((long) skb->data & 3) {     /* Must use alignment buffer. */
1580                 /* tp->tx_info[entry].mapping = 0; */
1581                 memcpy (tp->tx_buf[entry], skb->data, skb->len);
1582                 RTL_W32 (TxAddr0 + (entry * 4),
1583                          tp->tx_bufs_dma + (tp->tx_buf[entry] - tp->tx_bufs));
1584         } else {
1585                 tp->tx_info[entry].mapping =
1586                     pci_map_single (tp->pci_dev, skb->data, skb->len,
1587                                     PCI_DMA_TODEVICE);
1588                 RTL_W32 (TxAddr0 + (entry * 4), tp->tx_info[entry].mapping);
1589         }
1590 
1591         /* Note: the chip doesn't have auto-pad! */
1592         RTL_W32 (TxStatus0 + (entry * sizeof (u32)),
1593                  tp->tx_flag | (skb->len >= ETH_ZLEN ? skb->len : ETH_ZLEN));
1594 
1595         dev->trans_start = jiffies;
1596         tp->cur_tx++;
1597         mb();
1598         if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
1599                 netif_stop_queue (dev);
1600 
1601         DPRINTK ("%s: Queued Tx packet at %p size %u to slot %d.\n",
1602                  dev->name, skb->data, skb->len, entry);
1603 
1604         return 0;
1605 }
1606 
1607 
1608 static void rtl8139_tx_interrupt (struct net_device *dev,
1609                                   struct rtl8139_private *tp,
1610                                   void *ioaddr)
1611 {
1612         unsigned int dirty_tx, tx_left;
1613 
1614         assert (dev != NULL);
1615         assert (tp != NULL);
1616         assert (ioaddr != NULL);
1617 
1618         dirty_tx = tp->dirty_tx;
1619         tx_left = tp->cur_tx - dirty_tx;
1620         while (tx_left > 0) {
1621                 int entry = dirty_tx % NUM_TX_DESC;
1622                 int txstatus;
1623 
1624                 txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
1625 
1626                 if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
1627                         break;  /* It still hasn't been Txed */
1628 
1629                 /* Note: TxCarrierLost is always asserted at 100mbps. */
1630                 if (txstatus & (TxOutOfWindow | TxAborted)) {
1631                         /* There was an major error, log it. */
1632                         DPRINTK ("%s: Transmit error, Tx status %8.8x.\n",
1633                                  dev->name, txstatus);
1634                         tp->stats.tx_errors++;
1635                         if (txstatus & TxAborted) {
1636                                 tp->stats.tx_aborted_errors++;
1637                                 RTL_W32 (TxConfig, TxClearAbt | (TX_DMA_BURST << TxDMAShift));
1638                         }
1639                         if (txstatus & TxCarrierLost)
1640                                 tp->stats.tx_carrier_errors++;
1641                         if (txstatus & TxOutOfWindow)
1642                                 tp->stats.tx_window_errors++;
1643 #ifdef ETHER_STATS
1644                         if ((txstatus & 0x0f000000) == 0x0f000000)
1645                                 tp->stats.collisions16++;
1646 #endif
1647                 } else {
1648                         if (txstatus & TxUnderrun) {
1649                                 /* Add 64 to the Tx FIFO threshold. */
1650                                 if (tp->tx_flag < 0x00300000)
1651                                         tp->tx_flag += 0x00020000;
1652                                 tp->stats.tx_fifo_errors++;
1653                         }
1654                         tp->stats.collisions += (txstatus >> 24) & 15;
1655                         tp->stats.tx_bytes += txstatus & 0x7ff;
1656                         tp->stats.tx_packets++;
1657                 }
1658 
1659                 /* Free the original skb. */
1660                 if (tp->tx_info[entry].mapping != 0) {
1661                         pci_unmap_single(tp->pci_dev,
1662                                          tp->tx_info[entry].mapping,
1663                                          tp->tx_info[entry].skb->len,
1664                                          PCI_DMA_TODEVICE);
1665                         tp->tx_info[entry].mapping = 0;
1666                 }
1667                 dev_kfree_skb_irq (tp->tx_info[entry].skb);
1668                 tp->tx_info[entry].skb = NULL;
1669 
1670                 dirty_tx++;
1671                 tx_left--;
1672         }
1673 
1674 #ifndef RTL8139_NDEBUG
1675         if (tp->cur_tx - dirty_tx > NUM_TX_DESC) {
1676                 printk (KERN_ERR
1677                   "%s: Out-of-sync dirty pointer, %d vs. %d.\n",
1678                      dev->name, dirty_tx, tp->cur_tx);
1679                 dirty_tx += NUM_TX_DESC;
1680         }
1681 #endif /* RTL8139_NDEBUG */
1682 
1683         /* only wake the queue if we did work, and the queue is stopped */
1684         if (tp->dirty_tx != dirty_tx) {
1685                 tp->dirty_tx = dirty_tx;
1686                 mb();
1687                 if (netif_queue_stopped (dev))
1688                         netif_wake_queue (dev);
1689         }
1690 }
1691 
1692 
1693 /* TODO: clean this up!  Rx reset need not be this intensive */
1694 static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
1695                             struct rtl8139_private *tp, void *ioaddr)
1696 {
1697         u8 tmp8;
1698         int tmp_work = 1000;
1699 
1700         DPRINTK ("%s: Ethernet frame had errors, status %8.8x.\n",
1701                  dev->name, rx_status);
1702         if (rx_status & RxTooLong) {
1703                 DPRINTK ("%s: Oversized Ethernet frame, status %4.4x!\n",
1704                          dev->name, rx_status);
1705                 /* A.C.: The chip hangs here. */
1706         }
1707         tp->stats.rx_errors++;
1708         if (rx_status & (RxBadSymbol | RxBadAlign))
1709                 tp->stats.rx_frame_errors++;
1710         if (rx_status & (RxRunt | RxTooLong))
1711                 tp->stats.rx_length_errors++;
1712         if (rx_status & RxCRCErr)
1713                 tp->stats.rx_crc_errors++;
1714         /* Reset the receiver, based on RealTek recommendation. (Bug?) */
1715         tp->cur_rx = 0;
1716 
1717         /* disable receive */
1718         tmp8 = RTL_R8 (ChipCmd) & ChipCmdClear;
1719         RTL_W8_F (ChipCmd, tmp8 | CmdTxEnb);
1720 
1721         /* A.C.: Reset the multicast list. */
1722         rtl8139_set_rx_mode (dev);
1723 
1724         /* XXX potentially temporary hack to
1725          * restart hung receiver */
1726         while (--tmp_work > 0) {
1727                 tmp8 = RTL_R8 (ChipCmd);
1728                 if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
1729                         break;
1730                 RTL_W8_F (ChipCmd,
1731                           (tmp8 & ChipCmdClear) | CmdRxEnb | CmdTxEnb);
1732         }
1733 
1734         /* G.S.: Re-enable receiver */
1735         /* XXX temporary hack to work around receiver hang */
1736         rtl8139_set_rx_mode (dev);
1737 
1738         if (tmp_work <= 0)
1739                 printk (KERN_WARNING PFX "tx/rx enable wait too long\n");
1740 }
1741 
1742 
1743 /* The data sheet doesn't describe the Rx ring at all, so I'm guessing at the
1744    field alignments and semantics. */
1745 static void rtl8139_rx_interrupt (struct net_device *dev,
1746                                   struct rtl8139_private *tp, void *ioaddr)
1747 {
1748         unsigned char *rx_ring;
1749         u16 cur_rx;
1750 
1751         assert (dev != NULL);
1752         assert (tp != NULL);
1753         assert (ioaddr != NULL);
1754 
1755         rx_ring = tp->rx_ring;
1756         cur_rx = tp->cur_rx;
1757 
1758         DPRINTK ("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1759                  " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1760                  RTL_R16 (RxBufAddr),
1761                  RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1762 
1763         while ((RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
1764                 int ring_offset = cur_rx % RX_BUF_LEN;
1765                 u32 rx_status;
1766                 unsigned int rx_size;
1767                 unsigned int pkt_size;
1768                 struct sk_buff *skb;
1769 
1770                 /* read size+status of next frame from DMA ring buffer */
1771                 rx_status = le32_to_cpu (*(u32 *) (rx_ring + ring_offset));
1772                 rx_size = rx_status >> 16;
1773                 pkt_size = rx_size - 4;
1774 
1775                 DPRINTK ("%s:  rtl8139_rx() status %4.4x, size %4.4x,"
1776                          " cur %4.4x.\n", dev->name, rx_status,
1777                          rx_size, cur_rx);
1778 #if RTL8139_DEBUG > 2
1779                 {
1780                         int i;
1781                         DPRINTK ("%s: Frame contents ", dev->name);
1782                         for (i = 0; i < 70; i++)
1783                                 printk (" %2.2x",
1784                                         rx_ring[ring_offset + i]);
1785                         printk (".\n");
1786                 }
1787 #endif
1788 
1789                 /* E. Gill */
1790                 /* Note from BSD driver:
1791                  * Here's a totally undocumented fact for you. When the
1792                  * RealTek chip is in the process of copying a packet into
1793                  * RAM for you, the length will be 0xfff0. If you spot a
1794                  * packet header with this value, you need to stop. The
1795                  * datasheet makes absolutely no mention of this and
1796                  * RealTek should be shot for this.
1797                  */
1798                 if (rx_size == 0xfff0)
1799                         break;
1800 
1801                 /* If Rx err or invalid rx_size/rx_status received
1802                  * (which happens if we get lost in the ring),
1803                  * Rx process gets reset, so we abort any further
1804                  * Rx processing.
1805                  */
1806                 if ((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
1807                     (!(rx_status & RxStatusOK))) {
1808                         rtl8139_rx_err (rx_status, dev, tp, ioaddr);
1809                         return;
1810                 }
1811 
1812                 /* Malloc up new buffer, compatible with net-2e. */
1813                 /* Omit the four octet CRC from the length. */
1814 
1815                 /* TODO: consider allocating skb's outside of
1816                  * interrupt context, both to speed interrupt processing,
1817                  * and also to reduce the chances of having to
1818                  * drop packets here under memory pressure.
1819                  */
1820 
1821                 skb = dev_alloc_skb (pkt_size + 2);
1822                 if (skb) {
1823                         skb->dev = dev;
1824                         skb_reserve (skb, 2);   /* 16 byte align the IP fields. */
1825 
1826                         eth_copy_and_sum (skb, &rx_ring[ring_offset + 4], pkt_size, 0);
1827                         skb_put (skb, pkt_size);
1828 
1829                         skb->protocol = eth_type_trans (skb, dev);
1830                         netif_rx (skb);
1831                         tp->stats.rx_bytes += pkt_size;
1832                         tp->stats.rx_packets++;
1833                 } else {
1834                         printk (KERN_WARNING
1835                                 "%s: Memory squeeze, dropping packet.\n",
1836                                 dev->name);
1837                         tp->stats.rx_dropped++;
1838                 }
1839 
1840                 cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
1841                 RTL_W16_F (RxBufPtr, cur_rx - 16);
1842         }
1843 
1844         DPRINTK ("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1845                  " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1846                  RTL_R16 (RxBufAddr),
1847                  RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1848 
1849         tp->cur_rx = cur_rx;
1850 }
1851 
1852 
1853 static void rtl8139_weird_interrupt (struct net_device *dev,
1854                                      struct rtl8139_private *tp,
1855                                      void *ioaddr,
1856                                      int status, int link_changed)
1857 {
1858         printk (KERN_DEBUG "%s: Abnormal interrupt, status %8.8x.\n",
1859                 dev->name, status);
1860 
1861         assert (dev != NULL);
1862         assert (tp != NULL);
1863         assert (ioaddr != NULL);
1864 
1865         /* Update the error count. */
1866         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
1867         RTL_W32 (RxMissed, 0);
1868 
1869         if ((status & RxUnderrun) && link_changed &&
1870             (tp->drv_flags & HAS_LNK_CHNG)) {
1871                 /* Really link-change on new chips. */
1872                 int lpar = RTL_R16 (NWayLPAR);
1873                 int duplex = (lpar & 0x0100) || (lpar & 0x01C0) == 0x0040
1874                                 || tp->duplex_lock;
1875                 if (tp->full_duplex != duplex) {
1876                         tp->full_duplex = duplex;
1877                         RTL_W8 (Cfg9346, Cfg9346_Unlock);
1878                         RTL_W8 (Config1, tp->full_duplex ? 0x60 : 0x20);
1879                         RTL_W8 (Cfg9346, Cfg9346_Lock);
1880                 }
1881                 status &= ~RxUnderrun;
1882         }
1883 
1884         /* XXX along with rtl8139_rx_err, are we double-counting errors? */
1885         if (status &
1886             (RxUnderrun | RxOverflow | RxErr | RxFIFOOver))
1887                 tp->stats.rx_errors++;
1888 
1889         if (status & (PCSTimeout))
1890                 tp->stats.rx_length_errors++;
1891         if (status & (RxUnderrun | RxFIFOOver))
1892                 tp->stats.rx_fifo_errors++;
1893         if (status & RxOverflow) {
1894                 tp->stats.rx_over_errors++;
1895                 tp->cur_rx = RTL_R16 (RxBufAddr) % RX_BUF_LEN;
1896                 RTL_W16_F (RxBufPtr, tp->cur_rx - 16);
1897         }
1898         if (status & PCIErr) {
1899                 u16 pci_cmd_status;
1900                 pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
1901 
1902                 printk (KERN_ERR "%s: PCI Bus error %4.4x.\n",
1903                         dev->name, pci_cmd_status);
1904         }
1905 }
1906 
1907 
1908 /* The interrupt handler does all of the Rx thread work and cleans up
1909    after the Tx thread. */
1910 static void rtl8139_interrupt (int irq, void *dev_instance,
1911                                struct pt_regs *regs)
1912 {
1913         struct net_device *dev = (struct net_device *) dev_instance;
1914         struct rtl8139_private *tp = dev->priv;
1915         int boguscnt = max_interrupt_work;
1916         void *ioaddr = tp->mmio_addr;
1917         int status = 0, link_changed = 0; /* avoid bogus "uninit" warning */
1918 
1919         spin_lock (&tp->lock);
1920 
1921         do {
1922                 status = RTL_R16 (IntrStatus);
1923 
1924                 /* h/w no longer present (hotplug?) or major error, bail */
1925                 if (status == 0xFFFF)
1926                         break;
1927 
1928                 /* Acknowledge all of the current interrupt sources ASAP, but
1929                    an first get an additional status bit from CSCR. */
1930                 if (status & RxUnderrun)
1931                         link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
1932 
1933                 /* E. Gill */
1934                 /* In case of an RxFIFOOver we must also clear the RxOverflow
1935                    bit to avoid dropping frames for ever. Believe me, I got a
1936                    lot of troubles copying huge data (approximately 2 RxFIFOOver
1937                    errors per 1GB data transfer).
1938                    The following is written in the 'p-guide.pdf' file (RTL8139(A/B)
1939                    Programming guide V0.1, from 1999/1/15) on page 9 from REALTEC.
1940                    -----------------------------------------------------------
1941                    2. RxFIFOOvw handling:
1942                      When RxFIFOOvw occurs, all incoming packets are discarded.
1943                      Clear ISR(RxFIFOOvw) doesn't dismiss RxFIFOOvw event. To
1944                      dismiss RxFIFOOvw event, the ISR(RxBufOvw) must be written
1945                      with a '1'.
1946                    -----------------------------------------------------------
1947                    Unfortunately I was not able to find any reason for the
1948                    RxFIFOOver error (I got the feeling this depends on the
1949                    CPU speed, lower CPU speed --> more errors).
1950                    After clearing the RxOverflow bit the transfer of the
1951                    packet was repeated and all data are error free transfered */
1952                 RTL_W16_F (IntrStatus, (status & RxFIFOOver) ? (status | RxOverflow) : status);
1953 
1954                 DPRINTK ("%s: interrupt  status=%#4.4x new intstat=%#4.4x.\n",
1955                                 dev->name, status,
1956                                 RTL_R16 (IntrStatus));
1957 
1958                 if ((status &
1959                      (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
1960                       RxFIFOOver | TxErr | TxOK | RxErr | RxOK)) == 0)
1961                         break;
1962 
1963                 /* Check uncommon events with one test. */
1964                 if (status & (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
1965                               RxFIFOOver | TxErr | RxErr))
1966                         rtl8139_weird_interrupt (dev, tp, ioaddr,
1967                                                  status, link_changed);
1968 
1969                 if (status & (RxOK | RxUnderrun | RxOverflow | RxFIFOOver))     /* Rx interrupt */
1970                         rtl8139_rx_interrupt (dev, tp, ioaddr);
1971 
1972                 if (status & (TxOK | TxErr))
1973                         rtl8139_tx_interrupt (dev, tp, ioaddr);
1974 
1975                 boguscnt--;
1976         } while (boguscnt > 0);
1977 
1978         if (boguscnt <= 0) {
1979                 printk (KERN_WARNING
1980                         "%s: Too much work at interrupt, "
1981                         "IntrStatus=0x%4.4x.\n", dev->name,
1982                         status);
1983 
1984                 /* Clear all interrupt sources. */
1985                 RTL_W16 (IntrStatus, 0xffff);
1986         }
1987 
1988         spin_unlock (&tp->lock);
1989 
1990         DPRINTK ("%s: exiting interrupt, intr_status=%#4.4x.\n",
1991                  dev->name, RTL_R16 (IntrStatus));
1992 }
1993 
1994 
1995 static int rtl8139_close (struct net_device *dev)
1996 {
1997         struct rtl8139_private *tp = dev->priv;
1998         void *ioaddr = tp->mmio_addr;
1999         int ret = 0;
2000 
2001         DPRINTK ("ENTER\n");
2002 
2003         netif_stop_queue (dev);
2004 
2005         if (tp->thr_pid >= 0) {
2006                 ret = kill_proc (tp->thr_pid, SIGTERM, 1);
2007                 if (ret) {
2008                         printk (KERN_ERR "%s: unable to signal thread\n", dev->name);
2009                         return ret;
2010                 }
2011                 down (&tp->thr_exited);
2012         }
2013 
2014         DPRINTK ("%s: Shutting down ethercard, status was 0x%4.4x.\n",
2015                         dev->name, RTL_R16 (IntrStatus));
2016 
2017         spin_lock_irq (&tp->lock);
2018 
2019         /* Stop the chip's Tx and Rx DMA processes. */
2020         RTL_W8 (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear));
2021 
2022         /* Disable interrupts by clearing the interrupt mask. */
2023         RTL_W16 (IntrMask, 0x0000);
2024 
2025         /* Update the error counts. */
2026         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2027         RTL_W32 (RxMissed, 0);
2028 
2029         spin_unlock_irq (&tp->lock);
2030 
2031         synchronize_irq ();
2032         free_irq (dev->irq, dev);
2033 
2034         rtl8139_tx_clear (tp);
2035 
2036         pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
2037                             tp->rx_ring, tp->rx_ring_dma);
2038         pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
2039                             tp->tx_bufs, tp->tx_bufs_dma);
2040         tp->rx_ring = NULL;
2041         tp->tx_bufs = NULL;
2042 
2043         /* Green! Put the chip in low-power mode. */
2044         RTL_W8 (Cfg9346, Cfg9346_Unlock);
2045         RTL_W8 (Config1, 0x03);
2046         RTL_W8 (HltClk, 'H');   /* 'R' would leave the clock running. */
2047 
2048         DPRINTK ("EXIT\n");
2049         return 0;
2050 }
2051 
2052 
2053 static int mii_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
2054 {
2055         struct rtl8139_private *tp = dev->priv;
2056         u16 *data = (u16 *) & rq->ifr_data;
2057         int rc = 0;
2058 
2059         DPRINTK ("ENTER\n");
2060 
2061         switch (cmd) {
2062         case SIOCDEVPRIVATE:    /* Get the address of the PHY in use. */
2063                 data[0] = tp->phys[0] & 0x3f;
2064                 /* Fall Through */
2065 
2066         case SIOCDEVPRIVATE + 1:        /* Read the specified MII register. */
2067                 data[3] = mdio_read (dev, data[0], data[1] & 0x1f);
2068                 break;
2069 
2070         case SIOCDEVPRIVATE + 2:        /* Write the specified MII register */
2071                 if (!capable (CAP_NET_ADMIN)) {
2072                         rc = -EPERM;
2073                         break;
2074                 }
2075 
2076                 mdio_write (dev, data[0], data[1] & 0x1f, data[2]);
2077                 break;
2078 
2079         default:
2080                 rc = -EOPNOTSUPP;
2081                 break;
2082         }
2083 
2084         DPRINTK ("EXIT, returning %d\n", rc);
2085         return rc;
2086 }
2087 
2088 
2089 static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
2090 {
2091         struct rtl8139_private *tp = dev->priv;
2092         void *ioaddr = tp->mmio_addr;
2093 
2094         DPRINTK ("ENTER\n");
2095 
2096         if (netif_running(dev)) {
2097                 tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2098                 RTL_W32 (RxMissed, 0);
2099         }
2100 
2101         DPRINTK ("EXIT\n");
2102         return &tp->stats;
2103 }
2104 
2105 /* Set or clear the multicast filter for this adaptor.
2106    This routine is not state sensitive and need not be SMP locked. */
2107 
2108 static unsigned const ethernet_polynomial = 0x04c11db7U;
2109 static inline u32 ether_crc (int length, unsigned char *data)
2110 {
2111         int crc = -1;
2112 
2113         DPRINTK ("ENTER\n");
2114 
2115         while (--length >= 0) {
2116                 unsigned char current_octet = *data++;
2117                 int bit;
2118                 for (bit = 0; bit < 8; bit++, current_octet >>= 1)
2119                         crc = (crc << 1) ^
2120                             ((crc < 0) ^ (current_octet & 1) ?
2121                              ethernet_polynomial : 0);
2122         }
2123 
2124         DPRINTK ("EXIT\n");
2125         return crc;
2126 }
2127 
2128 
2129 static void rtl8139_set_rx_mode (struct net_device *dev)
2130 {
2131         struct rtl8139_private *tp = dev->priv;
2132         void *ioaddr = tp->mmio_addr;
2133         u32 mc_filter[2];       /* Multicast hash filter */
2134         int i, rx_mode;
2135         u32 tmp;
2136 
2137         DPRINTK ("ENTER\n");
2138 
2139         DPRINTK ("%s:   rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
2140                         dev->name, dev->flags, RTL_R32 (RxConfig));
2141 
2142         /* Note: do not reorder, GCC is clever about common statements. */
2143         if (dev->flags & IFF_PROMISC) {
2144                 /* Unconditionally log net taps. */
2145                 printk (KERN_NOTICE "%s: Promiscuous mode enabled.\n",
2146                         dev->name);
2147                 rx_mode =
2148                     AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
2149                     AcceptAllPhys;
2150                 mc_filter[1] = mc_filter[0] = 0xffffffff;
2151         } else if ((dev->mc_count > multicast_filter_limit)
2152                    || (dev->flags & IFF_ALLMULTI)) {
2153                 /* Too many to filter perfectly -- accept all multicasts. */
2154                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
2155                 mc_filter[1] = mc_filter[0] = 0xffffffff;
2156         } else {
2157                 struct dev_mc_list *mclist;
2158                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
2159                 mc_filter[1] = mc_filter[0] = 0;
2160                 for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
2161                      i++, mclist = mclist->next)
2162                         set_bit (ether_crc (ETH_ALEN, mclist->dmi_addr) >> 26,
2163                                  mc_filter);
2164         }
2165 
2166         /* if called from irq handler, lock already acquired */
2167         if (!in_irq ())
2168                 spin_lock_irq (&tp->lock);
2169 
2170         /* We can safely update without stopping the chip. */
2171         tmp = rtl8139_rx_config | rx_mode |
2172                 (RTL_R32 (RxConfig) & rtl_chip_info[tp->chipset].RxConfigMask);
2173         RTL_W32_F (RxConfig, tmp);
2174         RTL_W32_F (MAR0 + 0, mc_filter[0]);
2175         RTL_W32_F (MAR0 + 4, mc_filter[1]);
2176 
2177         if (!in_irq ())
2178                 spin_unlock_irq (&tp->lock);
2179 
2180         DPRINTK ("EXIT\n");
2181 }
2182 
2183 
2184 static void rtl8139_suspend (struct pci_dev *pdev)
2185 {
2186         struct net_device *dev = pdev->driver_data;
2187         struct rtl8139_private *tp = dev->priv;
2188         void *ioaddr = tp->mmio_addr;
2189         unsigned long flags;
2190 
2191         netif_device_detach (dev);
2192 
2193         spin_lock_irqsave (&tp->lock, flags);
2194 
2195         /* Disable interrupts, stop Tx and Rx. */
2196         RTL_W16 (IntrMask, 0x0000);
2197         RTL_W8 (ChipCmd, (RTL_R8 (ChipCmd) & ChipCmdClear));
2198 
2199         /* Update the error counts. */
2200         tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2201         RTL_W32 (RxMissed, 0);
2202 
2203         spin_unlock_irqrestore (&tp->lock, flags);
2204 }
2205 
2206 
2207 static void rtl8139_resume (struct pci_dev *pdev)
2208 {
2209         struct net_device *dev = pdev->driver_data;
2210 
2211         netif_device_attach (dev);
2212         rtl8139_hw_start (dev);
2213 }
2214 
2215 
2216 static struct pci_driver rtl8139_pci_driver = {
2217         name:           MODNAME,
2218         id_table:       rtl8139_pci_tbl,
2219         probe:          rtl8139_init_one,
2220         remove:         rtl8139_remove_one,
2221         suspend:        rtl8139_suspend,
2222         resume:         rtl8139_resume,
2223 };
2224 
2225 
2226 static int __init rtl8139_init_module (void)
2227 {
2228         return pci_module_init (&rtl8139_pci_driver);
2229 }
2230 
2231 
2232 static void __exit rtl8139_cleanup_module (void)
2233 {
2234         pci_unregister_driver (&rtl8139_pci_driver);
2235 }
2236 
2237 
2238 module_init(rtl8139_init_module);
2239 module_exit(rtl8139_cleanup_module);
2240 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.