linux-bk/drivers/net/8139too.c
<<
>>
Prefs
   1/*
   2
   3        8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
   4
   5        Maintained by Jeff Garzik <jgarzik@mandrakesoft.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
 153static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
 154static 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. */
 157static 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.  */
 161static int multicast_filter_limit = 32;
 162
 163/* bitmapped message enable number */
 164static 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
 198enum {
 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
 212typedef 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 */
 230static 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
 250static 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};
 278MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
 279
 280static 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. */
 292enum 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
 331enum ClearBitMasks {
 332        MultiIntrClear = 0xF000,
 333        ChipCmdClear = 0xE2,
 334        Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
 335};
 336
 337enum ChipCmdBits {
 338        CmdReset = 0x10,
 339        CmdRxEnb = 0x08,
 340        CmdTxEnb = 0x04,
 341        RxBufEmpty = 0x01,
 342};
 343
 344/* Interrupt register bits, using my own meaningful names. */
 345enum 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
 359enum TxStatusBits {
 360        TxHostOwns = 0x2000,
 361        TxUnderrun = 0x4000,
 362        TxStatOK = 0x8000,
 363        TxOutOfWindow = 0x20000000,
 364        TxAborted = 0x40000000,
 365        TxCarrierLost = 0x80000000,
 366};
 367enum 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. */
 380enum 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. */
 390enum 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 */
 403enum 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 */
 417enum 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 */
 429enum Config4Bits {
 430        LWPTN = (1 << 2),       /* not on 8139, 8139A */
 431};
 432
 433/* Bits in Config5 */
 434enum 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
 444enum 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. */
 466enum CSCRBits {
 467        CSCR_LinkOKBit = 0x0400,
 468        CSCR_LinkChangeBit = 0x0800,
 469        CSCR_LinkStatusBits = 0x0f000,
 470        CSCR_LinkDownOffCmd = 0x003c0,
 471        CSCR_LinkDownCmd = 0x0f3c0,
 472};
 473
 474
 475enum Cfg9346Bits {
 476        Cfg9346_Lock = 0x00,
 477        Cfg9346_Unlock = 0xC0,
 478};
 479
 480#ifdef CONFIG_8139TOO_TUNE_TWISTER
 481
 482enum TwisterParamVals {
 483        PARA78_default  = 0x78fa8388,
 484        PARA7c_default  = 0xcb38de43,   /* param[0][3] */
 485        PARA7c_xxx      = 0xcb38de43,
 486};
 487
 488static 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
 497typedef 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
 506enum chip_flags {
 507        HasHltClk = (1 << 0),
 508        HasLWake = (1 << 1),
 509};
 510
 511
 512/* directly indexed by chip_t, above */
 513const 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
 557struct 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
 564struct 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        unsigned int medialock:1;       /* Don't sense media type. */
 582        spinlock_t lock;
 583        chip_t chipset;
 584        pid_t thr_pid;
 585        wait_queue_head_t thr_wait;
 586        struct completion thr_exited;
 587        u32 rx_config;
 588        struct rtl_extra_stats xstats;
 589        int time_to_die;
 590        struct mii_if_info mii;
 591        unsigned int regs_len;
 592};
 593
 594MODULE_AUTHOR ("Jeff Garzik <jgarzik@mandrakesoft.com>");
 595MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver");
 596MODULE_LICENSE("GPL");
 597
 598MODULE_PARM (multicast_filter_limit, "i");
 599MODULE_PARM (max_interrupt_work, "i");
 600MODULE_PARM (media, "1-" __MODULE_STRING(MAX_UNITS) "i");
 601MODULE_PARM (full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
 602MODULE_PARM (debug, "i");
 603MODULE_PARM_DESC (debug, "8139too bitmapped message enable number");
 604MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses");
 605MODULE_PARM_DESC (max_interrupt_work, "8139too maximum events handled per interrupt");
 606MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps");
 607MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)");
 608
 609static int read_eeprom (void *ioaddr, int location, int addr_len);
 610static int rtl8139_open (struct net_device *dev);
 611static int mdio_read (struct net_device *dev, int phy_id, int location);
 612static void mdio_write (struct net_device *dev, int phy_id, int location,
 613                        int val);
 614static int rtl8139_thread (void *data);
 615static void rtl8139_tx_timeout (struct net_device *dev);
 616static void rtl8139_init_ring (struct net_device *dev);
 617static int rtl8139_start_xmit (struct sk_buff *skb,
 618                               struct net_device *dev);
 619static void rtl8139_interrupt (int irq, void *dev_instance,
 620                               struct pt_regs *regs);
 621static int rtl8139_close (struct net_device *dev);
 622static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
 623static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
 624static void rtl8139_set_rx_mode (struct net_device *dev);
 625static void __set_rx_mode (struct net_device *dev);
 626static void rtl8139_hw_start (struct net_device *dev);
 627
 628#ifdef USE_IO_OPS
 629
 630#define RTL_R8(reg)             inb (((unsigned long)ioaddr) + (reg))
 631#define RTL_R16(reg)            inw (((unsigned long)ioaddr) + (reg))
 632#define RTL_R32(reg)            ((unsigned long) inl (((unsigned long)ioaddr) + (reg)))
 633#define RTL_W8(reg, val8)       outb ((val8), ((unsigned long)ioaddr) + (reg))
 634#define RTL_W16(reg, val16)     outw ((val16), ((unsigned long)ioaddr) + (reg))
 635#define RTL_W32(reg, val32)     outl ((val32), ((unsigned long)ioaddr) + (reg))
 636#define RTL_W8_F                RTL_W8
 637#define RTL_W16_F               RTL_W16
 638#define RTL_W32_F               RTL_W32
 639#undef readb
 640#undef readw
 641#undef readl
 642#undef writeb
 643#undef writew
 644#undef writel
 645#define readb(addr) inb((unsigned long)(addr))
 646#define readw(addr) inw((unsigned long)(addr))
 647#define readl(addr) inl((unsigned long)(addr))
 648#define writeb(val,addr) outb((val),(unsigned long)(addr))
 649#define writew(val,addr) outw((val),(unsigned long)(addr))
 650#define writel(val,addr) outl((val),(unsigned long)(addr))
 651
 652#else
 653
 654/* write MMIO register, with flush */
 655/* Flush avoids rtl8139 bug w/ posted MMIO writes */
 656#define RTL_W8_F(reg, val8)     do { writeb ((val8), ioaddr + (reg)); readb (ioaddr + (reg)); } while (0)
 657#define RTL_W16_F(reg, val16)   do { writew ((val16), ioaddr + (reg)); readw (ioaddr + (reg)); } while (0)
 658#define RTL_W32_F(reg, val32)   do { writel ((val32), ioaddr + (reg)); readl (ioaddr + (reg)); } while (0)
 659
 660
 661#define MMIO_FLUSH_AUDIT_COMPLETE 1
 662#if MMIO_FLUSH_AUDIT_COMPLETE
 663
 664/* write MMIO register */
 665#define RTL_W8(reg, val8)       writeb ((val8), ioaddr + (reg))
 666#define RTL_W16(reg, val16)     writew ((val16), ioaddr + (reg))
 667#define RTL_W32(reg, val32)     writel ((val32), ioaddr + (reg))
 668
 669#else
 670
 671/* write MMIO register, then flush */
 672#define RTL_W8          RTL_W8_F
 673#define RTL_W16         RTL_W16_F
 674#define RTL_W32         RTL_W32_F
 675
 676#endif /* MMIO_FLUSH_AUDIT_COMPLETE */
 677
 678/* read MMIO register */
 679#define RTL_R8(reg)             readb (ioaddr + (reg))
 680#define RTL_R16(reg)            readw (ioaddr + (reg))
 681#define RTL_R32(reg)            ((unsigned long) readl (ioaddr + (reg)))
 682
 683#endif /* USE_IO_OPS */
 684
 685
 686static const u16 rtl8139_intr_mask =
 687        PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
 688        TxErr | TxOK | RxErr | RxOK;
 689
 690static const unsigned int rtl8139_rx_config =
 691        RxCfgRcv32K | RxNoWrap |
 692        (RX_FIFO_THRESH << RxCfgFIFOShift) |
 693        (RX_DMA_BURST << RxCfgDMAShift);
 694
 695static const unsigned int rtl8139_tx_config =
 696        (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift);
 697
 698static void __rtl8139_cleanup_dev (struct net_device *dev)
 699{
 700        struct rtl8139_private *tp;
 701        struct pci_dev *pdev;
 702
 703        assert (dev != NULL);
 704        assert (dev->priv != NULL);
 705
 706        tp = dev->priv;
 707        assert (tp->pci_dev != NULL);
 708        pdev = tp->pci_dev;
 709
 710#ifndef USE_IO_OPS
 711        if (tp->mmio_addr)
 712                iounmap (tp->mmio_addr);
 713#endif /* !USE_IO_OPS */
 714
 715        /* it's ok to call this even if we have no regions to free */
 716        pci_release_regions (pdev);
 717
 718#ifndef RTL8139_NDEBUG
 719        /* poison memory before freeing */
 720        memset (dev, 0xBC,
 721                sizeof (struct net_device) +
 722                sizeof (struct rtl8139_private));
 723#endif /* RTL8139_NDEBUG */
 724
 725        kfree (dev);
 726
 727        pci_set_drvdata (pdev, NULL);
 728}
 729
 730
 731static void rtl8139_chip_reset (void *ioaddr)
 732{
 733        int i;
 734
 735        /* Soft reset the chip. */
 736        RTL_W8 (ChipCmd, CmdReset);
 737
 738        /* Check that the chip has finished the reset. */
 739        for (i = 1000; i > 0; i--) {
 740                barrier();
 741                if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
 742                        break;
 743                udelay (10);
 744        }
 745}
 746
 747
 748static int __devinit rtl8139_init_board (struct pci_dev *pdev,
 749                                         struct net_device **dev_out)
 750{
 751        void *ioaddr;
 752        struct net_device *dev;
 753        struct rtl8139_private *tp;
 754        u8 tmp8;
 755        int rc;
 756        unsigned int i;
 757        u32 pio_start, pio_end, pio_flags, pio_len;
 758        unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
 759        u32 tmp;
 760
 761        assert (pdev != NULL);
 762
 763        *dev_out = NULL;
 764
 765        /* dev and dev->priv zeroed in alloc_etherdev */
 766        dev = alloc_etherdev (sizeof (*tp));
 767        if (dev == NULL) {
 768                printk (KERN_ERR PFX "%s: Unable to alloc new net device\n", pdev->slot_name);
 769                return -ENOMEM;
 770        }
 771        SET_MODULE_OWNER(dev);
 772        tp = dev->priv;
 773        tp->pci_dev = pdev;
 774
 775        /* enable device (incl. PCI PM wakeup and hotplug setup) */
 776        rc = pci_enable_device (pdev);
 777        if (rc)
 778                goto err_out;
 779
 780        pio_start = pci_resource_start (pdev, 0);
 781        pio_end = pci_resource_end (pdev, 0);
 782        pio_flags = pci_resource_flags (pdev, 0);
 783        pio_len = pci_resource_len (pdev, 0);
 784
 785        mmio_start = pci_resource_start (pdev, 1);
 786        mmio_end = pci_resource_end (pdev, 1);
 787        mmio_flags = pci_resource_flags (pdev, 1);
 788        mmio_len = pci_resource_len (pdev, 1);
 789
 790        /* set this immediately, we need to know before
 791         * we talk to the chip directly */
 792        DPRINTK("PIO region size == 0x%02X\n", pio_len);
 793        DPRINTK("MMIO region size == 0x%02lX\n", mmio_len);
 794
 795#ifdef USE_IO_OPS
 796        /* make sure PCI base addr 0 is PIO */
 797        if (!(pio_flags & IORESOURCE_IO)) {
 798                printk (KERN_ERR PFX "%s: region #0 not a PIO resource, aborting\n", pdev->slot_name);
 799                rc = -ENODEV;
 800                goto err_out;
 801        }
 802        /* check for weird/broken PCI region reporting */
 803        if (pio_len < RTL_MIN_IO_SIZE) {
 804                printk (KERN_ERR PFX "%s: Invalid PCI I/O region size(s), aborting\n", pdev->slot_name);
 805                rc = -ENODEV;
 806                goto err_out;
 807        }
 808#else
 809        /* make sure PCI base addr 1 is MMIO */
 810        if (!(mmio_flags & IORESOURCE_MEM)) {
 811                printk (KERN_ERR PFX "%s: region #1 not an MMIO resource, aborting\n", pdev->slot_name);
 812                rc = -ENODEV;
 813                goto err_out;
 814        }
 815        if (mmio_len < RTL_MIN_IO_SIZE) {
 816                printk (KERN_ERR PFX "%s: Invalid PCI mem region size(s), aborting\n", pdev->slot_name);
 817                rc = -ENODEV;
 818                goto err_out;
 819        }
 820#endif
 821
 822        rc = pci_request_regions (pdev, "8139too");
 823        if (rc)
 824                goto err_out;
 825
 826        /* enable PCI bus-mastering */
 827        pci_set_master (pdev);
 828
 829#ifdef USE_IO_OPS
 830        ioaddr = (void *) pio_start;
 831        dev->base_addr = pio_start;
 832        tp->mmio_addr = ioaddr;
 833        tp->regs_len = pio_len;
 834#else
 835        /* ioremap MMIO region */
 836        ioaddr = ioremap (mmio_start, mmio_len);
 837        if (ioaddr == NULL) {
 838                printk (KERN_ERR PFX "%s: cannot remap MMIO, aborting\n", pdev->slot_name);
 839                rc = -EIO;
 840                goto err_out;
 841        }
 842        dev->base_addr = (long) ioaddr;
 843        tp->mmio_addr = ioaddr;
 844        tp->regs_len = mmio_len;
 845#endif /* USE_IO_OPS */
 846
 847        /* Bring old chips out of low-power mode. */
 848        RTL_W8 (HltClk, 'R');
 849
 850        /* check for missing/broken hardware */
 851        if (RTL_R32 (TxConfig) == 0xFFFFFFFF) {
 852                printk (KERN_ERR PFX "%s: Chip not responding, ignoring board\n",
 853                        pdev->slot_name);
 854                rc = -EIO;
 855                goto err_out;
 856        }
 857
 858        /* identify chip attached to board */
 859        tmp = RTL_R8 (ChipVersion);
 860        for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++)
 861                if (tmp == rtl_chip_info[i].version) {
 862                        tp->chipset = i;
 863                        goto match;
 864                }
 865
 866        /* if unknown chip, assume array element #0, original RTL-8139 in this case */
 867        printk (KERN_DEBUG PFX "%s: unknown chip version, assuming RTL-8139\n",
 868                pdev->slot_name);
 869        printk (KERN_DEBUG PFX "%s: TxConfig = 0x%lx\n", pdev->slot_name, RTL_R32 (TxConfig));
 870        tp->chipset = 0;
 871
 872match:
 873        DPRINTK ("chipset id (%d) == index %d, '%s'\n",
 874                tmp,
 875                tp->chipset,
 876                rtl_chip_info[tp->chipset].name);
 877
 878        if (tp->chipset >= CH_8139B) {
 879                u8 new_tmp8 = tmp8 = RTL_R8 (Config1);
 880                DPRINTK("PCI PM wakeup\n");
 881                if ((rtl_chip_info[tp->chipset].flags & HasLWake) &&
 882                    (tmp8 & LWAKE))
 883                        new_tmp8 &= ~LWAKE;
 884                new_tmp8 |= Cfg1_PM_Enable;
 885                if (new_tmp8 != tmp8) {
 886                        RTL_W8 (Cfg9346, Cfg9346_Unlock);
 887                        RTL_W8 (Config1, tmp8);
 888                        RTL_W8 (Cfg9346, Cfg9346_Lock);
 889                }
 890                if (rtl_chip_info[tp->chipset].flags & HasLWake) {
 891                        tmp8 = RTL_R8 (Config4);
 892                        if (tmp8 & LWPTN)
 893                                RTL_W8 (Config4, tmp8 & ~LWPTN);
 894                }
 895        } else {
 896                DPRINTK("Old chip wakeup\n");
 897                tmp8 = RTL_R8 (Config1);
 898                tmp8 &= ~(SLEEP | PWRDN);
 899                RTL_W8 (Config1, tmp8);
 900        }
 901
 902        rtl8139_chip_reset (ioaddr);
 903
 904        *dev_out = dev;
 905        return 0;
 906
 907err_out:
 908        __rtl8139_cleanup_dev (dev);
 909        return rc;
 910}
 911
 912
 913static int __devinit rtl8139_init_one (struct pci_dev *pdev,
 914                                       const struct pci_device_id *ent)
 915{
 916        struct net_device *dev = NULL;
 917        struct rtl8139_private *tp;
 918        int i, addr_len, option;
 919        void *ioaddr;
 920        static int board_idx = -1;
 921        u8 pci_rev;
 922
 923        assert (pdev != NULL);
 924        assert (ent != NULL);
 925
 926        board_idx++;
 927
 928        /* when we're built into the kernel, the driver version message
 929         * is only printed if at least one 8139 board has been found
 930         */
 931#ifndef MODULE
 932        {
 933                static int printed_version;
 934                if (!printed_version++)
 935                        printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
 936        }
 937#endif
 938
 939        pci_read_config_byte(pdev, PCI_REVISION_ID, &pci_rev);
 940
 941        if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
 942            pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pci_rev >= 0x20) {
 943                printk(KERN_INFO PFX "pci dev %s (id %04x:%04x rev %02x) is an enhanced 8139C+ chip\n",
 944                       pdev->slot_name, pdev->vendor, pdev->device, pci_rev);
 945                printk(KERN_INFO PFX "Use the \"8139cp\" driver for improved performance and stability.\n");
 946        }
 947
 948        i = rtl8139_init_board (pdev, &dev);
 949        if (i < 0)
 950                return i;
 951
 952        tp = dev->priv;
 953        ioaddr = tp->mmio_addr;
 954
 955        assert (ioaddr != NULL);
 956        assert (dev != NULL);
 957        assert (tp != NULL);
 958
 959        addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
 960        for (i = 0; i < 3; i++)
 961                ((u16 *) (dev->dev_addr))[i] =
 962                    le16_to_cpu (read_eeprom (ioaddr, i + 7, addr_len));
 963
 964        /* The Rtl8139-specific entries in the device structure. */
 965        dev->open = rtl8139_open;
 966        dev->hard_start_xmit = rtl8139_start_xmit;
 967        dev->stop = rtl8139_close;
 968        dev->get_stats = rtl8139_get_stats;
 969        dev->set_multicast_list = rtl8139_set_rx_mode;
 970        dev->do_ioctl = netdev_ioctl;
 971        dev->tx_timeout = rtl8139_tx_timeout;
 972        dev->watchdog_timeo = TX_TIMEOUT;
 973        dev->features |= NETIF_F_SG|NETIF_F_HW_CSUM;
 974
 975        dev->irq = pdev->irq;
 976
 977        /* dev->priv/tp zeroed and aligned in init_etherdev */
 978        tp = dev->priv;
 979
 980        /* note: tp->chipset set in rtl8139_init_board */
 981        tp->drv_flags = board_info[ent->driver_data].hw_flags;
 982        tp->mmio_addr = ioaddr;
 983        spin_lock_init (&tp->lock);
 984        init_waitqueue_head (&tp->thr_wait);
 985        init_completion (&tp->thr_exited);
 986        tp->mii.dev = dev;
 987        tp->mii.mdio_read = mdio_read;
 988        tp->mii.mdio_write = mdio_write;
 989
 990        /* dev is fully set up and ready to use now */
 991        DPRINTK("about to register device named %s (%p)...\n", dev->name, dev);
 992        i = register_netdev (dev);
 993        if (i) goto err_out;
 994
 995        pci_set_drvdata (pdev, dev);
 996
 997        printk (KERN_INFO "%s: %s at 0x%lx, "
 998                "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x, "
 999                "IRQ %d\n",
1000                dev->name,
1001                board_info[ent->driver_data].name,
1002                dev->base_addr,
1003                dev->dev_addr[0], dev->dev_addr[1],
1004                dev->dev_addr[2], dev->dev_addr[3],
1005                dev->dev_addr[4], dev->dev_addr[5],
1006                dev->irq);
1007
1008        printk (KERN_DEBUG "%s:  Identified 8139 chip type '%s'\n",
1009                dev->name, rtl_chip_info[tp->chipset].name);
1010
1011        /* Find the connected MII xcvrs.
1012           Doing this in open() would allow detecting external xcvrs later, but
1013           takes too much time. */
1014#ifdef CONFIG_8139TOO_8129
1015        if (tp->drv_flags & HAS_MII_XCVR) {
1016                int phy, phy_idx = 0;
1017                for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) {
1018                        int mii_status = mdio_read(dev, phy, 1);
1019                        if (mii_status != 0xffff  &&  mii_status != 0x0000) {
1020                                u16 advertising = mdio_read(dev, phy, 4);
1021                                tp->phys[phy_idx++] = phy;
1022                                printk(KERN_INFO "%s: MII transceiver %d status 0x%4.4x "
1023                                           "advertising %4.4x.\n",
1024                                           dev->name, phy, mii_status, advertising);
1025                        }
1026                }
1027                if (phy_idx == 0) {
1028                        printk(KERN_INFO "%s: No MII transceivers found!  Assuming SYM "
1029                                   "transceiver.\n",
1030                                   dev->name);
1031                        tp->phys[0] = 32;
1032                }
1033        } else
1034#endif
1035                tp->phys[0] = 32;
1036        tp->mii.phy_id = tp->phys[0];
1037
1038        /* The lower four bits are the media type. */
1039        option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
1040        if (option > 0) {
1041                tp->mii.full_duplex = (option & 0x210) ? 1 : 0;
1042                tp->default_port = option & 0xFF;
1043                if (tp->default_port)
1044                        tp->medialock = 1;
1045        }
1046        if (board_idx < MAX_UNITS  &&  full_duplex[board_idx] > 0)
1047                tp->mii.full_duplex = full_duplex[board_idx];
1048        if (tp->mii.full_duplex) {
1049                printk(KERN_INFO "%s: Media type forced to Full Duplex.\n", dev->name);
1050                /* Changing the MII-advertised media because might prevent
1051                   re-connection. */
1052                tp->mii.duplex_lock = 1;
1053        }
1054        if (tp->default_port) {
1055                printk(KERN_INFO "  Forcing %dMbps %s-duplex operation.\n",
1056                           (option & 0x20 ? 100 : 10),
1057                           (option & 0x10 ? "full" : "half"));
1058                mdio_write(dev, tp->phys[0], 0,
1059                                   ((option & 0x20) ? 0x2000 : 0) |     /* 100Mbps? */
1060                                   ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
1061        }
1062
1063        /* Put the chip into low-power mode. */
1064        if (rtl_chip_info[tp->chipset].flags & HasHltClk)
1065                RTL_W8 (HltClk, 'H');   /* 'R' would leave the clock running. */
1066
1067        return 0;
1068
1069err_out:
1070        __rtl8139_cleanup_dev (dev);
1071        return i;
1072}
1073
1074
1075static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
1076{
1077        struct net_device *dev = pci_get_drvdata (pdev);
1078        struct rtl8139_private *np;
1079
1080        assert (dev != NULL);
1081        np = dev->priv;
1082        assert (np != NULL);
1083
1084        unregister_netdev (dev);
1085
1086        __rtl8139_cleanup_dev (dev);
1087}
1088
1089
1090/* Serial EEPROM section. */
1091
1092/*  EEPROM_Ctrl bits. */
1093#define EE_SHIFT_CLK    0x04    /* EEPROM shift clock. */
1094#define EE_CS                   0x08    /* EEPROM chip select. */
1095#define EE_DATA_WRITE   0x02    /* EEPROM chip data in. */
1096#define EE_WRITE_0              0x00
1097#define EE_WRITE_1              0x02
1098#define EE_DATA_READ    0x01    /* EEPROM chip data out. */
1099#define EE_ENB                  (0x80 | EE_CS)
1100
1101/* Delay between EEPROM clock transitions.
1102   No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
1103 */
1104
1105#define eeprom_delay()  readl(ee_addr)
1106
1107/* The EEPROM commands include the alway-set leading bit. */
1108#define EE_WRITE_CMD    (5)
1109#define EE_READ_CMD             (6)
1110#define EE_ERASE_CMD    (7)
1111
1112static int __devinit read_eeprom (void *ioaddr, int location, int addr_len)
1113{
1114        int i;
1115        unsigned retval = 0;
1116        void *ee_addr = ioaddr + Cfg9346;
1117        int read_cmd = location | (EE_READ_CMD << addr_len);
1118
1119        writeb (EE_ENB & ~EE_CS, ee_addr);
1120        writeb (EE_ENB, ee_addr);
1121        eeprom_delay ();
1122
1123        /* Shift the read command bits out. */
1124        for (i = 4 + addr_len; i >= 0; i--) {
1125                int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
1126                writeb (EE_ENB | dataval, ee_addr);
1127                eeprom_delay ();
1128                writeb (EE_ENB | dataval | EE_SHIFT_CLK, ee_addr);
1129                eeprom_delay ();
1130        }
1131        writeb (EE_ENB, ee_addr);
1132        eeprom_delay ();
1133
1134        for (i = 16; i > 0; i--) {
1135                writeb (EE_ENB | EE_SHIFT_CLK, ee_addr);
1136                eeprom_delay ();
1137                retval =
1138                    (retval << 1) | ((readb (ee_addr) & EE_DATA_READ) ? 1 :
1139                                     0);
1140                writeb (EE_ENB, ee_addr);
1141                eeprom_delay ();
1142        }
1143
1144        /* Terminate the EEPROM access. */
1145        writeb (~EE_CS, ee_addr);
1146        eeprom_delay ();
1147
1148        return retval;
1149}
1150
1151/* MII serial management: mostly bogus for now. */
1152/* Read and write the MII management registers using software-generated
1153   serial MDIO protocol.
1154   The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
1155   met by back-to-back PCI I/O cycles, but we insert a delay to avoid
1156   "overclocking" issues. */
1157#define MDIO_DIR                0x80
1158#define MDIO_DATA_OUT   0x04
1159#define MDIO_DATA_IN    0x02
1160#define MDIO_CLK                0x01
1161#define MDIO_WRITE0 (MDIO_DIR)
1162#define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
1163
1164#define mdio_delay(mdio_addr)   readb(mdio_addr)
1165
1166
1167static char mii_2_8139_map[8] = {
1168        BasicModeCtrl,
1169        BasicModeStatus,
1170        0,
1171        0,
1172        NWayAdvert,
1173        NWayLPAR,
1174        NWayExpansion,
1175        0
1176};
1177
1178
1179#ifdef CONFIG_8139TOO_8129
1180/* Syncronize the MII management interface by shifting 32 one bits out. */
1181static void mdio_sync (void *mdio_addr)
1182{
1183        int i;
1184
1185        for (i = 32; i >= 0; i--) {
1186                writeb (MDIO_WRITE1, mdio_addr);
1187                mdio_delay (mdio_addr);
1188                writeb (MDIO_WRITE1 | MDIO_CLK, mdio_addr);
1189                mdio_delay (mdio_addr);
1190        }
1191}
1192#endif
1193
1194static int mdio_read (struct net_device *dev, int phy_id, int location)
1195{
1196        struct rtl8139_private *tp = dev->priv;
1197        int retval = 0;
1198#ifdef CONFIG_8139TOO_8129
1199        void *mdio_addr = tp->mmio_addr + Config4;
1200        int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
1201        int i;
1202#endif
1203
1204        if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1205                return location < 8 && mii_2_8139_map[location] ?
1206                    readw (tp->mmio_addr + mii_2_8139_map[location]) : 0;
1207        }
1208
1209#ifdef CONFIG_8139TOO_8129
1210        mdio_sync (mdio_addr);
1211        /* Shift the read command bits out. */
1212        for (i = 15; i >= 0; i--) {
1213                int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
1214
1215                writeb (MDIO_DIR | dataval, mdio_addr);
1216                mdio_delay (mdio_addr);
1217                writeb (MDIO_DIR | dataval | MDIO_CLK, mdio_addr);
1218                mdio_delay (mdio_addr);
1219        }
1220
1221        /* Read the two transition, 16 data, and wire-idle bits. */
1222        for (i = 19; i > 0; i--) {
1223                writeb (0, mdio_addr);
1224                mdio_delay (mdio_addr);
1225                retval = (retval << 1) | ((readb (mdio_addr) & MDIO_DATA_IN) ? 1 : 0);
1226                writeb (MDIO_CLK, mdio_addr);
1227                mdio_delay (mdio_addr);
1228        }
1229#endif
1230
1231        return (retval >> 1) & 0xffff;
1232}
1233
1234
1235static void mdio_write (struct net_device *dev, int phy_id, int location,
1236                        int value)
1237{
1238        struct rtl8139_private *tp = dev->priv;
1239#ifdef CONFIG_8139TOO_8129
1240        void *mdio_addr = tp->mmio_addr + Config4;
1241        int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
1242        int i;
1243#endif
1244
1245        if (phy_id > 31) {      /* Really a 8139.  Use internal registers. */
1246                void *ioaddr = tp->mmio_addr;
1247                if (location == 0) {
1248                        RTL_W8 (Cfg9346, Cfg9346_Unlock);
1249                        RTL_W16 (BasicModeCtrl, value);
1250                        RTL_W8 (Cfg9346, Cfg9346_Lock);
1251                } else if (location < 8 && mii_2_8139_map[location])
1252                        RTL_W16 (mii_2_8139_map[location], value);
1253                return;
1254        }
1255
1256#ifdef CONFIG_8139TOO_8129
1257        mdio_sync (mdio_addr);
1258
1259        /* Shift the command bits out. */
1260        for (i = 31; i >= 0; i--) {
1261                int dataval =
1262                    (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
1263                writeb (dataval, mdio_addr);
1264                mdio_delay (mdio_addr);
1265                writeb (dataval | MDIO_CLK, mdio_addr);
1266                mdio_delay (mdio_addr);
1267        }
1268        /* Clear out extra bits. */
1269        for (i = 2; i > 0; i--) {
1270                writeb (0, mdio_addr);
1271                mdio_delay (mdio_addr);
1272                writeb (MDIO_CLK, mdio_addr);
1273                mdio_delay (mdio_addr);
1274        }
1275#endif
1276}
1277
1278
1279static int rtl8139_open (struct net_device *dev)
1280{
1281        struct rtl8139_private *tp = dev->priv;
1282        int retval;
1283#ifdef RTL8139_DEBUG
1284        void *ioaddr = tp->mmio_addr;
1285#endif
1286
1287        retval = request_irq (dev->irq, rtl8139_interrupt, SA_SHIRQ, dev->name, dev);
1288        if (retval)
1289                return retval;
1290
1291        tp->tx_bufs = pci_alloc_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1292                                           &tp->tx_bufs_dma);
1293        tp->rx_ring = pci_alloc_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1294                                           &tp->rx_ring_dma);
1295        if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
1296                free_irq(dev->irq, dev);
1297
1298                if (tp->tx_bufs)
1299                        pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
1300                                            tp->tx_bufs, tp->tx_bufs_dma);
1301                if (tp->rx_ring)
1302                        pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
1303                                            tp->rx_ring, tp->rx_ring_dma);
1304
1305                return -ENOMEM;
1306
1307        }
1308
1309        tp->mii.full_duplex = tp->mii.duplex_lock;
1310        tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
1311        tp->twistie = (tp->chipset == CH_8139_K) ? 1 : 0;
1312        tp->time_to_die = 0;
1313
1314        rtl8139_init_ring (dev);
1315        rtl8139_hw_start (dev);
1316
1317        DPRINTK ("%s: rtl8139_open() ioaddr %#lx IRQ %d"
1318                        " GP Pins %2.2x %s-duplex.\n",
1319                        dev->name, pci_resource_start (tp->pci_dev, 1),
1320                        dev->irq, RTL_R8 (MediaStatus),
1321                        tp->mii.full_duplex ? "full" : "half");
1322
1323        tp->thr_pid = kernel_thread (rtl8139_thread, dev, CLONE_FS | CLONE_FILES);
1324        if (tp->thr_pid < 0)
1325                printk (KERN_WARNING "%s: unable to start kernel thread\n",
1326                        dev->name);
1327
1328        return 0;
1329}
1330
1331
1332static void rtl_check_media (struct net_device *dev)
1333{
1334        struct rtl8139_private *tp = dev->priv;
1335
1336        if (tp->phys[0] >= 0) {
1337                u16 mii_lpa = mdio_read(dev, tp->phys[0], MII_LPA);
1338                if (mii_lpa == 0xffff)
1339                        ;                                       /* Not there */
1340                else if ((mii_lpa & LPA_100FULL) == LPA_100FULL
1341                                 || (mii_lpa & 0x00C0) == LPA_10FULL)
1342                        tp->mii.full_duplex = 1;
1343
1344                printk (KERN_INFO"%s: Setting %s%s-duplex based on"
1345                                " auto-negotiated partner ability %4.4x.\n",
1346                        dev->name, mii_lpa == 0 ? "" :
1347                                (mii_lpa & 0x0180) ? "100mbps " : "10mbps ",
1348                        tp->mii.full_duplex ? "full" : "half", mii_lpa);
1349        }
1350}
1351
1352/* Start the hardware at open or resume. */
1353static void rtl8139_hw_start (struct net_device *dev)
1354{
1355        struct rtl8139_private *tp = dev->priv;
1356        void *ioaddr = tp->mmio_addr;
1357        u32 i;
1358        u8 tmp;
1359
1360        /* Bring old chips out of low-power mode. */
1361        if (rtl_chip_info[tp->chipset].flags & HasHltClk)
1362                RTL_W8 (HltClk, 'R');
1363
1364        rtl8139_chip_reset (ioaddr);
1365
1366        /* unlock Config[01234] and BMCR register writes */
1367        RTL_W8_F (Cfg9346, Cfg9346_Unlock);
1368        /* Restore our idea of the MAC address. */
1369        RTL_W32_F (MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
1370        RTL_W32_F (MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
1371
1372        /* Must enable Tx/Rx before setting transfer thresholds! */
1373        RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1374
1375        tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
1376        RTL_W32 (RxConfig, tp->rx_config);
1377
1378        /* Check this value: the documentation for IFG contradicts ifself. */
1379        RTL_W32 (TxConfig, rtl8139_tx_config);
1380
1381        tp->cur_rx = 0;
1382
1383        rtl_check_media (dev);
1384
1385        if (tp->chipset >= CH_8139B) {
1386                /* Disable magic packet scanning, which is enabled
1387                 * when PM is enabled in Config1.  It can be reenabled
1388                 * via ETHTOOL_SWOL if desired.  */
1389                RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic);
1390        }
1391
1392        DPRINTK("init buffer addresses\n");
1393
1394        /* Lock Config[01234] and BMCR register writes */
1395        RTL_W8 (Cfg9346, Cfg9346_Lock);
1396
1397        /* init Rx ring buffer DMA address */
1398        RTL_W32_F (RxBuf, tp->rx_ring_dma);
1399
1400        /* init Tx buffer DMA addresses */
1401        for (i = 0; i < NUM_TX_DESC; i++)
1402                RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
1403
1404        RTL_W32 (RxMissed, 0);
1405
1406        rtl8139_set_rx_mode (dev);
1407
1408        /* no early-rx interrupts */
1409        RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
1410
1411        /* make sure RxTx has started */
1412        tmp = RTL_R8 (ChipCmd);
1413        if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb)))
1414                RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1415
1416        /* Enable all known interrupts by setting the interrupt mask. */
1417        RTL_W16 (IntrMask, rtl8139_intr_mask);
1418
1419        netif_start_queue (dev);
1420}
1421
1422
1423/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1424static void rtl8139_init_ring (struct net_device *dev)
1425{
1426        struct rtl8139_private *tp = dev->priv;
1427        int i;
1428
1429        tp->cur_rx = 0;
1430        tp->cur_tx = 0;
1431        tp->dirty_tx = 0;
1432
1433        for (i = 0; i < NUM_TX_DESC; i++)
1434                tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
1435}
1436
1437
1438/* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
1439static int next_tick = 3 * HZ;
1440
1441#ifndef CONFIG_8139TOO_TUNE_TWISTER
1442static inline void rtl8139_tune_twister (struct net_device *dev,
1443                                  struct rtl8139_private *tp) {}
1444#else
1445static void rtl8139_tune_twister (struct net_device *dev,
1446                                  struct rtl8139_private *tp)
1447{
1448        int linkcase;
1449        void *ioaddr = tp->mmio_addr;
1450
1451        /* This is a complicated state machine to configure the "twister" for
1452           impedance/echos based on the cable length.
1453           All of this is magic and undocumented.
1454         */
1455        switch (tp->twistie) {
1456        case 1:
1457                if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
1458                        /* We have link beat, let us tune the twister. */
1459                        RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
1460                        tp->twistie = 2;        /* Change to state 2. */
1461                        next_tick = HZ / 10;
1462                } else {
1463                        /* Just put in some reasonable defaults for when beat returns. */
1464                        RTL_W16 (CSCR, CSCR_LinkDownCmd);
1465                        RTL_W32 (FIFOTMS, 0x20);        /* Turn on cable test mode. */
1466                        RTL_W32 (PARA78, PARA78_default);
1467                        RTL_W32 (PARA7c, PARA7c_default);
1468                        tp->twistie = 0;        /* Bail from future actions. */
1469                }
1470                break;
1471        case 2:
1472                /* Read how long it took to hear the echo. */
1473                linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
1474                if (linkcase == 0x7000)
1475                        tp->twist_row = 3;
1476                else if (linkcase == 0x3000)
1477                        tp->twist_row = 2;
1478                else if (linkcase == 0x1000)
1479                        tp->twist_row = 1;
1480                else
1481                        tp->twist_row = 0;
1482                tp->twist_col = 0;
1483                tp->twistie = 3;        /* Change to state 2. */
1484                next_tick = HZ / 10;
1485                break;
1486        case 3:
1487                /* Put out four tuning parameters, one per 100msec. */
1488                if (tp->twist_col == 0)
1489                        RTL_W16 (FIFOTMS, 0);
1490                RTL_W32 (PARA7c, param[(int) tp->twist_row]
1491                         [(int) tp->twist_col]);
1492                next_tick = HZ / 10;
1493                if (++tp->twist_col >= 4) {
1494                        /* For short cables we are done.
1495                           For long cables (row == 3) check for mistune. */
1496                        tp->twistie =
1497                            (tp->twist_row == 3) ? 4 : 0;
1498                }
1499                break;
1500        case 4:
1501                /* Special case for long cables: check for mistune. */
1502                if ((RTL_R16 (CSCR) &
1503                     CSCR_LinkStatusBits) == 0x7000) {
1504                        tp->twistie = 0;
1505                        break;
1506                } else {
1507                        RTL_W32 (PARA7c, 0xfb38de03);
1508                        tp->twistie = 5;
1509                        next_tick = HZ / 10;
1510                }
1511                break;
1512        case 5:
1513                /* Retune for shorter cable (column 2). */
1514                RTL_W32 (FIFOTMS, 0x20);
1515                RTL_W32 (PARA78, PARA78_default);
1516                RTL_W32 (PARA7c, PARA7c_default);
1517                RTL_W32 (FIFOTMS, 0x00);
1518                tp->twist_row = 2;
1519                tp->twist_col = 0;
1520                tp->twistie = 3;
1521                next_tick = HZ / 10;
1522                break;
1523
1524        default:
1525                /* do nothing */
1526                break;
1527        }
1528}
1529#endif /* CONFIG_8139TOO_TUNE_TWISTER */
1530
1531
1532static inline void rtl8139_thread_iter (struct net_device *dev,
1533                                 struct rtl8139_private *tp,
1534                                 void *ioaddr)
1535{
1536        int mii_lpa;
1537
1538        mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA);
1539
1540        if (!tp->mii.duplex_lock && mii_lpa != 0xffff) {
1541                int duplex = (mii_lpa & LPA_100FULL)
1542                    || (mii_lpa & 0x01C0) == 0x0040;
1543                if (tp->mii.full_duplex != duplex) {
1544                        tp->mii.full_duplex = duplex;
1545
1546                        if (mii_lpa) {
1547                                printk (KERN_INFO
1548                                        "%s: Setting %s-duplex based on MII #%d link"
1549                                        " partner ability of %4.4x.\n",
1550                                        dev->name,
1551                                        tp->mii.full_duplex ? "full" : "half",
1552                                        tp->phys[0], mii_lpa);
1553                        } else {
1554                                printk(KERN_INFO"%s: media is unconnected, link down, or incompatible connection\n",
1555                                       dev->name);
1556                        }
1557#if 0
1558                        RTL_W8 (Cfg9346, Cfg9346_Unlock);
1559                        RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
1560                        RTL_W8 (Cfg9346, Cfg9346_Lock);
1561#endif
1562                }
1563        }
1564
1565        next_tick = HZ * 60;
1566
1567        rtl8139_tune_twister (dev, tp);
1568
1569        DPRINTK ("%s: Media selection tick, Link partner %4.4x.\n",
1570                 dev->name, RTL_R16 (NWayLPAR));
1571        DPRINTK ("%s:  Other registers are IntMask %4.4x IntStatus %4.4x\n",
1572                 dev->name, RTL_R16 (IntrMask), RTL_R16 (IntrStatus));
1573        DPRINTK ("%s:  Chip config %2.2x %2.2x.\n",
1574                 dev->name, RTL_R8 (Config0),
1575                 RTL_R8 (Config1));
1576}
1577
1578
1579static int rtl8139_thread (void *data)
1580{
1581        struct net_device *dev = data;
1582        struct rtl8139_private *tp = dev->priv;
1583        unsigned long timeout;
1584
1585        daemonize();
1586        spin_lock_irq(&current->sigmask_lock);
1587        sigemptyset(&current->blocked);
1588        recalc_sigpending();
1589        spin_unlock_irq(&current->sigmask_lock);
1590
1591        strncpy (current->comm, dev->name, sizeof(current->comm) - 1);
1592        current->comm[sizeof(current->comm) - 1] = '\0';
1593
1594        while (1) {
1595                timeout = next_tick;
1596                do {
1597                        timeout = interruptible_sleep_on_timeout (&tp->thr_wait, timeout);
1598                } while (!signal_pending (current) && (timeout > 0));
1599
1600                if (signal_pending (current)) {
1601                        spin_lock_irq(&current->sigmask_lock);
1602                        flush_signals(current);
1603                        spin_unlock_irq(&current->sigmask_lock);
1604                }
1605
1606                if (tp->time_to_die)
1607                        break;
1608
1609                rtnl_lock ();
1610                rtl8139_thread_iter (dev, tp, tp->mmio_addr);
1611                rtnl_unlock ();
1612        }
1613
1614        complete_and_exit (&tp->thr_exited, 0);
1615}
1616
1617
1618static void rtl8139_tx_clear (struct rtl8139_private *tp)
1619{
1620        tp->cur_tx = 0;
1621        tp->dirty_tx = 0;
1622
1623        /* XXX account for unsent Tx packets in tp->stats.tx_dropped */
1624}
1625
1626
1627static void rtl8139_tx_timeout (struct net_device *dev)
1628{
1629        struct rtl8139_private *tp = dev->priv;
1630        void *ioaddr = tp->mmio_addr;
1631        int i;
1632        u8 tmp8;
1633        unsigned long flags;
1634
1635        DPRINTK ("%s: Transmit timeout, status %2.2x %4.4x "
1636                 "media %2.2x.\n", dev->name,
1637                 RTL_R8 (ChipCmd),
1638                 RTL_R16 (IntrStatus),
1639                 RTL_R8 (MediaStatus));
1640
1641        tp->xstats.tx_timeouts++;
1642
1643        /* disable Tx ASAP, if not already */
1644        tmp8 = RTL_R8 (ChipCmd);
1645        if (tmp8 & CmdTxEnb)
1646                RTL_W8 (ChipCmd, CmdRxEnb);
1647
1648        /* Disable interrupts by clearing the interrupt mask. */
1649        RTL_W16 (IntrMask, 0x0000);
1650
1651        /* Emit info to figure out what went wrong. */
1652        printk (KERN_DEBUG "%s: Tx queue start entry %ld  dirty entry %ld.\n",
1653                dev->name, tp->cur_tx, tp->dirty_tx);
1654        for (i = 0; i < NUM_TX_DESC; i++)
1655                printk (KERN_DEBUG "%s:  Tx descriptor %d is %8.8lx.%s\n",
1656                        dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
1657                        i == tp->dirty_tx % NUM_TX_DESC ?
1658                                " (queue head)" : "");
1659
1660        /* Stop a shared interrupt from scavenging while we are. */
1661        spin_lock_irqsave (&tp->lock, flags);
1662        rtl8139_tx_clear (tp);
1663        spin_unlock_irqrestore (&tp->lock, flags);
1664
1665        /* ...and finally, reset everything */
1666        rtl8139_hw_start (dev);
1667
1668        netif_wake_queue (dev);
1669}
1670
1671
1672static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
1673{
1674        struct rtl8139_private *tp = dev->priv;
1675        void *ioaddr = tp->mmio_addr;
1676        unsigned int entry;
1677        unsigned int len = skb->len;
1678
1679        /* Calculate the next Tx descriptor entry. */
1680        entry = tp->cur_tx % NUM_TX_DESC;
1681
1682        if (likely(len < TX_BUF_SIZE)) {
1683                skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
1684                dev_kfree_skb(skb);
1685        } else {
1686                dev_kfree_skb(skb);
1687                tp->stats.tx_dropped++;
1688                return 0;
1689        }
1690
1691        /* Note: the chip doesn't have auto-pad! */
1692        spin_lock_irq(&tp->lock);
1693        RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
1694                   tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
1695
1696        dev->trans_start = jiffies;
1697
1698        tp->cur_tx++;
1699        wmb();
1700
1701        if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
1702                netif_stop_queue (dev);
1703        spin_unlock_irq(&tp->lock);
1704
1705        DPRINTK ("%s: Queued Tx packet size %u to slot %d.\n",
1706                 dev->name, len, entry);
1707
1708        return 0;
1709}
1710
1711
1712static void rtl8139_tx_interrupt (struct net_device *dev,
1713                                  struct rtl8139_private *tp,
1714                                  void *ioaddr)
1715{
1716        unsigned long dirty_tx, tx_left;
1717
1718        assert (dev != NULL);
1719        assert (tp != NULL);
1720        assert (ioaddr != NULL);
1721
1722        dirty_tx = tp->dirty_tx;
1723        tx_left = tp->cur_tx - dirty_tx;
1724        while (tx_left > 0) {
1725                int entry = dirty_tx % NUM_TX_DESC;
1726                int txstatus;
1727
1728                txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
1729
1730                if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
1731                        break;  /* It still hasn't been Txed */
1732
1733                /* Note: TxCarrierLost is always asserted at 100mbps. */
1734                if (txstatus & (TxOutOfWindow | TxAborted)) {
1735                        /* There was an major error, log it. */
1736                        DPRINTK ("%s: Transmit error, Tx status %8.8x.\n",
1737                                 dev->name, txstatus);
1738                        tp->stats.tx_errors++;
1739                        if (txstatus & TxAborted) {
1740                                tp->stats.tx_aborted_errors++;
1741                                RTL_W32 (TxConfig, TxClearAbt);
1742                                RTL_W16 (IntrStatus, TxErr);
1743                                wmb();
1744                        }
1745                        if (txstatus & TxCarrierLost)
1746                                tp->stats.tx_carrier_errors++;
1747                        if (txstatus & TxOutOfWindow)
1748                                tp->stats.tx_window_errors++;
1749                } else {
1750                        if (txstatus & TxUnderrun) {
1751                                /* Add 64 to the Tx FIFO threshold. */
1752                                if (tp->tx_flag < 0x00300000)
1753                                        tp->tx_flag += 0x00020000;
1754                                tp->stats.tx_fifo_errors++;
1755                        }
1756                        tp->stats.collisions += (txstatus >> 24) & 15;
1757                        tp->stats.tx_bytes += txstatus & 0x7ff;
1758                        tp->stats.tx_packets++;
1759                }
1760
1761                dirty_tx++;
1762                tx_left--;
1763        }
1764
1765#ifndef RTL8139_NDEBUG
1766        if (tp->cur_tx - dirty_tx > NUM_TX_DESC) {
1767                printk (KERN_ERR "%s: Out-of-sync dirty pointer, %ld vs. %ld.\n",
1768                        dev->name, dirty_tx, tp->cur_tx);
1769                dirty_tx += NUM_TX_DESC;
1770        }
1771#endif /* RTL8139_NDEBUG */
1772
1773        /* only wake the queue if we did work, and the queue is stopped */
1774        if (tp->dirty_tx != dirty_tx) {
1775                tp->dirty_tx = dirty_tx;
1776                mb();
1777                if (netif_queue_stopped (dev))
1778                        netif_wake_queue (dev);
1779        }
1780}
1781
1782
1783/* TODO: clean this up!  Rx reset need not be this intensive */
1784static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
1785                            struct rtl8139_private *tp, void *ioaddr)
1786{
1787        u8 tmp8;
1788#ifdef CONFIG_8139_OLD_RX_RESET
1789        int tmp_work;
1790#endif
1791
1792        DPRINTK ("%s: Ethernet frame had errors, status %8.8x.\n",
1793                 dev->name, rx_status);
1794        tp->stats.rx_errors++;
1795        if (!(rx_status & RxStatusOK)) {
1796                if (rx_status & RxTooLong) {
1797                        DPRINTK ("%s: Oversized Ethernet frame, status %4.4x!\n",
1798                                dev->name, rx_status);
1799                        /* A.C.: The chip hangs here. */
1800                }
1801                if (rx_status & (RxBadSymbol | RxBadAlign))
1802                        tp->stats.rx_frame_errors++;
1803                if (rx_status & (RxRunt | RxTooLong))
1804                        tp->stats.rx_length_errors++;
1805                if (rx_status & RxCRCErr)
1806                        tp->stats.rx_crc_errors++;
1807        } else {
1808                tp->xstats.rx_lost_in_ring++;
1809        }
1810
1811#ifndef CONFIG_8139_OLD_RX_RESET
1812        tmp8 = RTL_R8 (ChipCmd);
1813        RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb);
1814        RTL_W8 (ChipCmd, tmp8);
1815        RTL_W32 (RxConfig, tp->rx_config);
1816        tp->cur_rx = 0;
1817#else
1818        /* Reset the receiver, based on RealTek recommendation. (Bug?) */
1819
1820        /* disable receive */
1821        RTL_W8_F (ChipCmd, CmdTxEnb);
1822        tmp_work = 200;
1823        while (--tmp_work > 0) {
1824                udelay(1);
1825                tmp8 = RTL_R8 (ChipCmd);
1826                if (!(tmp8 & CmdRxEnb))
1827                        break;
1828        }
1829        if (tmp_work <= 0)
1830                printk (KERN_WARNING PFX "rx stop wait too long\n");
1831        /* restart receive */
1832        tmp_work = 200;
1833        while (--tmp_work > 0) {
1834                RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb);
1835                udelay(1);
1836                tmp8 = RTL_R8 (ChipCmd);
1837                if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
1838                        break;
1839        }
1840        if (tmp_work <= 0)
1841                printk (KERN_WARNING PFX "tx/rx enable wait too long\n");
1842
1843        /* and reinitialize all rx related registers */
1844        RTL_W8_F (Cfg9346, Cfg9346_Unlock);
1845        /* Must enable Tx/Rx before setting transfer thresholds! */
1846        RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
1847
1848        tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
1849        RTL_W32 (RxConfig, tp->rx_config);
1850        tp->cur_rx = 0;
1851
1852        DPRINTK("init buffer addresses\n");
1853
1854        /* Lock Config[01234] and BMCR register writes */
1855        RTL_W8 (Cfg9346, Cfg9346_Lock);
1856
1857        /* init Rx ring buffer DMA address */
1858        RTL_W32_F (RxBuf, tp->rx_ring_dma);
1859
1860        /* A.C.: Reset the multicast list. */
1861        __set_rx_mode (dev);
1862#endif
1863}
1864
1865static void rtl8139_rx_interrupt (struct net_device *dev,
1866                                  struct rtl8139_private *tp, void *ioaddr)
1867{
1868        unsigned char *rx_ring;
1869        u16 cur_rx;
1870
1871        assert (dev != NULL);
1872        assert (tp != NULL);
1873        assert (ioaddr != NULL);
1874
1875        rx_ring = tp->rx_ring;
1876        cur_rx = tp->cur_rx;
1877
1878        DPRINTK ("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1879                 " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1880                 RTL_R16 (RxBufAddr),
1881                 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1882
1883        while ((RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
1884                int ring_offset = cur_rx % RX_BUF_LEN;
1885                u32 rx_status;
1886                unsigned int rx_size;
1887                unsigned int pkt_size;
1888                struct sk_buff *skb;
1889
1890                rmb();
1891
1892                /* read size+status of next frame from DMA ring buffer */
1893                rx_status = le32_to_cpu (*(u32 *) (rx_ring + ring_offset));
1894                rx_size = rx_status >> 16;
1895                pkt_size = rx_size - 4;
1896
1897                DPRINTK ("%s:  rtl8139_rx() status %4.4x, size %4.4x,"
1898                         " cur %4.4x.\n", dev->name, rx_status,
1899                         rx_size, cur_rx);
1900#if RTL8139_DEBUG > 2
1901                {
1902                        int i;
1903                        DPRINTK ("%s: Frame contents ", dev->name);
1904                        for (i = 0; i < 70; i++)
1905                                printk (" %2.2x",
1906                                        rx_ring[ring_offset + i]);
1907                        printk (".\n");
1908                }
1909#endif
1910
1911                /* Packet copy from FIFO still in progress.
1912                 * Theoretically, this should never happen
1913                 * since EarlyRx is disabled.
1914                 */
1915                if (rx_size == 0xfff0) {
1916                        tp->xstats.early_rx++;
1917                        break;
1918                }
1919
1920                /* If Rx err or invalid rx_size/rx_status received
1921                 * (which happens if we get lost in the ring),
1922                 * Rx process gets reset, so we abort any further
1923                 * Rx processing.
1924                 */
1925                if ((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
1926                    (rx_size < 8) ||
1927                    (!(rx_status & RxStatusOK))) {
1928                        rtl8139_rx_err (rx_status, dev, tp, ioaddr);
1929                        return;
1930                }
1931
1932                /* Malloc up new buffer, compatible with net-2e. */
1933                /* Omit the four octet CRC from the length. */
1934
1935                /* TODO: consider allocating skb's outside of
1936                 * interrupt context, both to speed interrupt processing,
1937                 * and also to reduce the chances of having to
1938                 * drop packets here under memory pressure.
1939                 */
1940
1941                skb = dev_alloc_skb (pkt_size + 2);
1942                if (skb) {
1943                        skb->dev = dev;
1944                        skb_reserve (skb, 2);   /* 16 byte align the IP fields. */
1945
1946                        eth_copy_and_sum (skb, &rx_ring[ring_offset + 4], pkt_size, 0);
1947                        skb_put (skb, pkt_size);
1948
1949                        skb->protocol = eth_type_trans (skb, dev);
1950                        netif_rx (skb);
1951                        dev->last_rx = jiffies;
1952                        tp->stats.rx_bytes += pkt_size;
1953                        tp->stats.rx_packets++;
1954                } else {
1955                        printk (KERN_WARNING
1956                                "%s: Memory squeeze, dropping packet.\n",
1957                                dev->name);
1958                        tp->stats.rx_dropped++;
1959                }
1960
1961                cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
1962                RTL_W16 (RxBufPtr, cur_rx - 16);
1963
1964                if (RTL_R16 (IntrStatus) & RxAckBits)
1965                        RTL_W16_F (IntrStatus, RxAckBits);
1966        }
1967
1968        DPRINTK ("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
1969                 " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
1970                 RTL_R16 (RxBufAddr),
1971                 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
1972
1973        tp->cur_rx = cur_rx;
1974}
1975
1976
1977static void rtl8139_weird_interrupt (struct net_device *dev,
1978                                     struct rtl8139_private *tp,
1979                                     void *ioaddr,
1980                                     int status, int link_changed)
1981{
1982        DPRINTK ("%s: Abnormal interrupt, status %8.8x.\n",
1983                 dev->name, status);
1984
1985        assert (dev != NULL);
1986        assert (tp != NULL);
1987        assert (ioaddr != NULL);
1988
1989        /* Update the error count. */
1990        tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
1991        RTL_W32 (RxMissed, 0);
1992
1993        if ((status & RxUnderrun) && link_changed &&
1994            (tp->drv_flags & HAS_LNK_CHNG)) {
1995                /* Really link-change on new chips. */
1996                int lpar = RTL_R16 (NWayLPAR);
1997                int duplex = (lpar & LPA_100FULL) || (lpar & 0x01C0) == 0x0040
1998                                || tp->mii.duplex_lock;
1999                if (tp->mii.full_duplex != duplex) {
2000                        tp->mii.full_duplex = duplex;
2001#if 0
2002                        RTL_W8 (Cfg9346, Cfg9346_Unlock);
2003                        RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
2004                        RTL_W8 (Cfg9346, Cfg9346_Lock);
2005#endif
2006                }
2007                status &= ~RxUnderrun;
2008        }
2009
2010        /* XXX along with rtl8139_rx_err, are we double-counting errors? */
2011        if (status &
2012            (RxUnderrun | RxOverflow | RxErr | RxFIFOOver))
2013                tp->stats.rx_errors++;
2014
2015        if (status & PCSTimeout)
2016                tp->stats.rx_length_errors++;
2017        if (status & (RxUnderrun | RxFIFOOver))
2018                tp->stats.rx_fifo_errors++;
2019        if (status & PCIErr) {
2020                u16 pci_cmd_status;
2021                pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
2022                pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status);
2023
2024                printk (KERN_ERR "%s: PCI Bus error %4.4x.\n",
2025                        dev->name, pci_cmd_status);
2026        }
2027}
2028
2029
2030/* The interrupt handler does all of the Rx thread work and cleans up
2031   after the Tx thread. */
2032static void rtl8139_interrupt (int irq, void *dev_instance,
2033                               struct pt_regs *regs)
2034{
2035        struct net_device *dev = (struct net_device *) dev_instance;
2036        struct rtl8139_private *tp = dev->priv;
2037        int boguscnt = max_interrupt_work;
2038        void *ioaddr = tp->mmio_addr;
2039        int ackstat, status;
2040        int link_changed = 0; /* avoid bogus "uninit" warning */
2041
2042        spin_lock (&tp->lock);
2043
2044        do {
2045                status = RTL_R16 (IntrStatus);
2046
2047                /* h/w no longer present (hotplug?) or major error, bail */
2048                if (status == 0xFFFF)
2049                        break;
2050
2051                if ((status &
2052                     (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
2053                      RxFIFOOver | TxErr | TxOK | RxErr | RxOK)) == 0)
2054                        break;
2055
2056                /* Acknowledge all of the current interrupt sources ASAP, but
2057                   an first get an additional status bit from CSCR. */
2058                if (status & RxUnderrun)
2059                        link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
2060
2061                /* The chip takes special action when we clear RxAckBits,
2062                 * so we clear them later in rtl8139_rx_interrupt
2063                 */
2064                ackstat = status & ~(RxAckBits | TxErr);
2065                RTL_W16 (IntrStatus, ackstat);
2066
2067                DPRINTK ("%s: interrupt  status=%#4.4x ackstat=%#4.4x new intstat=%#4.4x.\n",
2068                         dev->name, ackstat, status, RTL_R16 (IntrStatus));
2069
2070                if (netif_running (dev) && (status & RxAckBits))
2071                        rtl8139_rx_interrupt (dev, tp, ioaddr);
2072
2073                /* Check uncommon events with one test. */
2074                if (status & (PCIErr | PCSTimeout | RxUnderrun | RxOverflow |
2075                              RxFIFOOver | RxErr))
2076                        rtl8139_weird_interrupt (dev, tp, ioaddr,
2077                                                 status, link_changed);
2078
2079                if (netif_running (dev) && (status & (TxOK | TxErr))) {
2080                        rtl8139_tx_interrupt (dev, tp, ioaddr);
2081                        if (status & TxErr)
2082                                RTL_W16 (IntrStatus, TxErr);
2083                }
2084
2085                boguscnt--;
2086        } while (boguscnt > 0);
2087
2088        if (boguscnt <= 0) {
2089                printk (KERN_WARNING "%s: Too much work at interrupt, "
2090                        "IntrStatus=0x%4.4x.\n", dev->name, status);
2091
2092                /* Clear all interrupt sources. */
2093                RTL_W16 (IntrStatus, 0xffff);
2094        }
2095
2096        spin_unlock (&tp->lock);
2097
2098        DPRINTK ("%s: exiting interrupt, intr_status=%#4.4x.\n",
2099                 dev->name, RTL_R16 (IntrStatus));
2100}
2101
2102
2103static int rtl8139_close (struct net_device *dev)
2104{
2105        struct rtl8139_private *tp = dev->priv;
2106        void *ioaddr = tp->mmio_addr;
2107        int ret = 0;
2108        unsigned long flags;
2109
2110        netif_stop_queue (dev);
2111
2112        if (tp->thr_pid >= 0) {
2113                tp->time_to_die = 1;
2114                wmb();
2115                ret = kill_proc (tp->thr_pid, SIGTERM, 1);
2116                if (ret) {
2117                        printk (KERN_ERR "%s: unable to signal thread\n", dev->name);
2118                        return ret;
2119                }
2120                wait_for_completion (&tp->thr_exited);
2121        }
2122
2123        DPRINTK ("%s: Shutting down ethercard, status was 0x%4.4x.\n",
2124                        dev->name, RTL_R16 (IntrStatus));
2125
2126        spin_lock_irqsave (&tp->lock, flags);
2127
2128        /* Stop the chip's Tx and Rx DMA processes. */
2129        RTL_W8 (ChipCmd, 0);
2130
2131        /* Disable interrupts by clearing the interrupt mask. */
2132        RTL_W16 (IntrMask, 0);
2133
2134        /* Update the error counts. */
2135        tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2136        RTL_W32 (RxMissed, 0);
2137
2138        spin_unlock_irqrestore (&tp->lock, flags);
2139
2140        /* TODO: isn't this code racy? we synchronize the IRQ and then free it, */ 
2141        /* but another IRQ could've happened in between the sync and free */ 
2142        synchronize_irq (dev->irq);
2143        free_irq (dev->irq, dev);
2144
2145        rtl8139_tx_clear (tp);
2146
2147        pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
2148                            tp->rx_ring, tp->rx_ring_dma);
2149        pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
2150                            tp->tx_bufs, tp->tx_bufs_dma);
2151        tp->rx_ring = NULL;
2152        tp->tx_bufs = NULL;
2153
2154        /* Green! Put the chip in low-power mode. */
2155        RTL_W8 (Cfg9346, Cfg9346_Unlock);
2156
2157        if (rtl_chip_info[tp->chipset].flags & HasHltClk)
2158                RTL_W8 (HltClk, 'H');   /* 'R' would leave the clock running. */
2159
2160        return 0;
2161}
2162
2163
2164/* Get the ethtool Wake-on-LAN settings.  Assumes that wol points to
2165   kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and
2166   other threads or interrupts aren't messing with the 8139.  */
2167static void netdev_get_wol (struct net_device *dev, struct ethtool_wolinfo *wol)
2168{
2169        struct rtl8139_private *np = dev->priv;
2170        void *ioaddr = np->mmio_addr;
2171
2172        if (rtl_chip_info[np->chipset].flags & HasLWake) {
2173                u8 cfg3 = RTL_R8 (Config3);
2174                u8 cfg5 = RTL_R8 (Config5);
2175
2176                wol->supported = WAKE_PHY | WAKE_MAGIC
2177                        | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST;
2178
2179                wol->wolopts = 0;
2180                if (cfg3 & Cfg3_LinkUp)
2181                        wol->wolopts |= WAKE_PHY;
2182                if (cfg3 & Cfg3_Magic)
2183                        wol->wolopts |= WAKE_MAGIC;
2184                /* (KON)FIXME: See how netdev_set_wol() handles the
2185                   following constants.  */
2186                if (cfg5 & Cfg5_UWF)
2187                        wol->wolopts |= WAKE_UCAST;
2188                if (cfg5 & Cfg5_MWF)
2189                        wol->wolopts |= WAKE_MCAST;
2190                if (cfg5 & Cfg5_BWF)
2191                        wol->wolopts |= WAKE_BCAST;
2192        }
2193}
2194
2195
2196/* Set the ethtool Wake-on-LAN settings.  Return 0 or -errno.  Assumes
2197   that wol points to kernel memory and other threads or interrupts
2198   aren't messing with the 8139.  */
2199static int netdev_set_wol (struct net_device *dev,
2200                           const struct ethtool_wolinfo *wol)
2201{
2202        struct rtl8139_private *np = dev->priv;
2203        void *ioaddr = np->mmio_addr;
2204        u32 support;
2205        u8 cfg3, cfg5;
2206
2207        support = ((rtl_chip_info[np->chipset].flags & HasLWake)
2208                   ? (WAKE_PHY | WAKE_MAGIC
2209                      | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)
2210                   : 0);
2211        if (wol->wolopts & ~support)
2212                return -EINVAL;
2213
2214        cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic);
2215        if (wol->wolopts & WAKE_PHY)
2216                cfg3 |= Cfg3_LinkUp;
2217        if (wol->wolopts & WAKE_MAGIC)
2218                cfg3 |= Cfg3_Magic;
2219        RTL_W8 (Cfg9346, Cfg9346_Unlock);
2220        RTL_W8 (Config3, cfg3);
2221        RTL_W8 (Cfg9346, Cfg9346_Lock);
2222
2223        cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF);
2224        /* (KON)FIXME: These are untested.  We may have to set the
2225           CRC0, Wakeup0 and LSBCRC0 registers too, but I have no
2226           documentation.  */
2227        if (wol->wolopts & WAKE_UCAST)
2228                cfg5 |= Cfg5_UWF;
2229        if (wol->wolopts & WAKE_MCAST)
2230                cfg5 |= Cfg5_MWF;
2231        if (wol->wolopts & WAKE_BCAST)
2232                cfg5 |= Cfg5_BWF;
2233        RTL_W8 (Config5, cfg5); /* need not unlock via Cfg9346 */
2234
2235        return 0;
2236}
2237
2238static int netdev_ethtool_ioctl (struct net_device *dev, void *useraddr)
2239{
2240        struct rtl8139_private *np = dev->priv;
2241        u32 ethcmd;
2242
2243        /* dev_ioctl() in ../../net/core/dev.c has already checked
2244           capable(CAP_NET_ADMIN), so don't bother with that here.  */
2245
2246        if (get_user(ethcmd, (u32 *)useraddr))
2247                return -EFAULT;
2248
2249        switch (ethcmd) {
2250
2251        case ETHTOOL_GDRVINFO: {
2252                struct ethtool_drvinfo info = { ETHTOOL_GDRVINFO };
2253                strcpy (info.driver, DRV_NAME);
2254                strcpy (info.version, DRV_VERSION);
2255                strcpy (info.bus_info, np->pci_dev->slot_name);
2256                info.regdump_len = np->regs_len;
2257                if (copy_to_user (useraddr, &info, sizeof (info)))
2258                        return -EFAULT;
2259                return 0;
2260        }
2261
2262        /* get settings */
2263        case ETHTOOL_GSET: {
2264                struct ethtool_cmd ecmd = { ETHTOOL_GSET };
2265                spin_lock_irq(&np->lock);
2266                mii_ethtool_gset(&np->mii, &ecmd);
2267                spin_unlock_irq(&np->lock);
2268                if (copy_to_user(useraddr, &ecmd, sizeof(ecmd)))
2269                        return -EFAULT;
2270                return 0;
2271        }
2272        /* set settings */
2273        case ETHTOOL_SSET: {
2274                int r;
2275                struct ethtool_cmd ecmd;
2276                if (copy_from_user(&ecmd, useraddr, sizeof(ecmd)))
2277                        return -EFAULT;
2278                spin_lock_irq(&np->lock);
2279                r = mii_ethtool_sset(&np->mii, &ecmd);
2280                spin_unlock_irq(&np->lock);
2281                return r;
2282        }
2283        /* restart autonegotiation */
2284        case ETHTOOL_NWAY_RST: {
2285                return mii_nway_restart(&np->mii);
2286        }
2287        /* get link status */
2288        case ETHTOOL_GLINK: {
2289                struct ethtool_value edata = {ETHTOOL_GLINK};
2290                edata.data = mii_link_ok(&np->mii);
2291                if (copy_to_user(useraddr, &edata, sizeof(edata)))
2292                        return -EFAULT;
2293                return 0;
2294        }
2295
2296        /* get message-level */
2297        case ETHTOOL_GMSGLVL: {
2298                struct ethtool_value edata = {ETHTOOL_GMSGLVL};
2299                edata.data = debug;
2300                if (copy_to_user(useraddr, &edata, sizeof(edata)))
2301                        return -EFAULT;
2302                return 0;
2303        }
2304        /* set message-level */
2305        case ETHTOOL_SMSGLVL: {
2306                struct ethtool_value edata;
2307                if (copy_from_user(&edata, useraddr, sizeof(edata)))
2308                        return -EFAULT;
2309                debug = edata.data;
2310                return 0;
2311        }
2312
2313        case ETHTOOL_GWOL:
2314                {
2315                        struct ethtool_wolinfo wol = { ETHTOOL_GWOL };
2316                        spin_lock_irq (&np->lock);
2317                        netdev_get_wol (dev, &wol);
2318                        spin_unlock_irq (&np->lock);
2319                        if (copy_to_user (useraddr, &wol, sizeof (wol)))
2320                                return -EFAULT;
2321                        return 0;
2322                }
2323
2324        case ETHTOOL_SWOL:
2325                {
2326                        struct ethtool_wolinfo wol;
2327                        int rc;
2328                        if (copy_from_user (&wol, useraddr, sizeof (wol)))
2329                                return -EFAULT;
2330                        spin_lock_irq (&np->lock);
2331                        rc = netdev_set_wol (dev, &wol);
2332                        spin_unlock_irq (&np->lock);
2333                        return rc;
2334                }
2335
2336/* TODO: we are too slack to do reg dumping for pio, for now */
2337#ifndef CONFIG_8139TOO_PIO
2338        /* NIC register dump */
2339        case ETHTOOL_GREGS: {
2340                struct ethtool_regs regs;
2341                unsigned int regs_len = np->regs_len;
2342                u8 *regbuf = kmalloc(regs_len, GFP_KERNEL);
2343                int rc;
2344
2345                if (!regbuf)
2346                        return -ENOMEM;
2347                memset(regbuf, 0, regs_len);
2348
2349                rc = copy_from_user(&regs, useraddr, sizeof(regs));
2350                if (rc) {
2351                        rc = -EFAULT;
2352                        goto err_out_gregs;
2353                }
2354                
2355                if (regs.len > regs_len)
2356                        regs.len = regs_len;
2357                if (regs.len < regs_len) {
2358                        rc = -EINVAL;
2359                        goto err_out_gregs;
2360                }
2361
2362                regs.version = RTL_REGS_VER;
2363                rc = copy_to_user(useraddr, &regs, sizeof(regs));
2364                if (rc) {
2365                        rc = -EFAULT;
2366                        goto err_out_gregs;
2367                }
2368
2369                useraddr += offsetof(struct ethtool_regs, data);
2370
2371                spin_lock_irq(&np->lock);
2372                memcpy_fromio(regbuf, np->mmio_addr, regs_len);
2373                spin_unlock_irq(&np->lock);
2374
2375                if (copy_to_user(useraddr, regbuf, regs_len))
2376                        rc = -EFAULT;
2377
2378err_out_gregs:
2379                kfree(regbuf);
2380                return rc;
2381        }
2382#endif /* CONFIG_8139TOO_PIO */
2383
2384        /* get string list(s) */
2385        case ETHTOOL_GSTRINGS: {
2386                struct ethtool_gstrings estr = { ETHTOOL_GSTRINGS };
2387
2388                if (copy_from_user(&estr, useraddr, sizeof(estr)))
2389                        return -EFAULT;
2390                if (estr.string_set != ETH_SS_STATS)
2391                        return -EINVAL;
2392
2393                estr.len = RTL_NUM_STATS;
2394                if (copy_to_user(useraddr, &estr, sizeof(estr)))
2395                        return -EFAULT;
2396                if (copy_to_user(useraddr + sizeof(estr),
2397                                 &ethtool_stats_keys,
2398                                 sizeof(ethtool_stats_keys)))
2399                        return -EFAULT;
2400                return 0;
2401        }
2402
2403        /* get NIC-specific statistics */
2404        case ETHTOOL_GSTATS: {
2405                struct ethtool_stats estats = { ETHTOOL_GSTATS };
2406                u64 *tmp_stats;
2407                const unsigned int sz = sizeof(u64) * RTL_NUM_STATS;
2408                int i;
2409
2410                estats.n_stats = RTL_NUM_STATS;
2411                if (copy_to_user(useraddr, &estats, sizeof(estats)))
2412                        return -EFAULT;
2413
2414                tmp_stats = kmalloc(sz, GFP_KERNEL);
2415                if (!tmp_stats)
2416                        return -ENOMEM;
2417                memset(tmp_stats, 0, sz);
2418
2419                i = 0;
2420                tmp_stats[i++] = np->xstats.early_rx;
2421                tmp_stats[i++] = np->xstats.tx_buf_mapped;
2422                tmp_stats[i++] = np->xstats.tx_timeouts;
2423                tmp_stats[i++] = np->xstats.rx_lost_in_ring;
2424                if (i != RTL_NUM_STATS)
2425                        BUG();
2426
2427                i = copy_to_user(useraddr + sizeof(estats), tmp_stats, sz);
2428                kfree(tmp_stats);
2429
2430                if (i)
2431                        return -EFAULT;
2432                return 0;
2433        }
2434        default:
2435                break;
2436        }
2437
2438        return -EOPNOTSUPP;
2439}
2440
2441
2442static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
2443{
2444        struct rtl8139_private *tp = dev->priv;
2445        struct mii_ioctl_data *data = (struct mii_ioctl_data *)&rq->ifr_data;
2446        int rc = 0;
2447        int phy = tp->phys[0] & 0x3f;
2448
2449        if (!netif_running(dev))
2450                return -EINVAL;
2451
2452        if (cmd != SIOCETHTOOL) {
2453                /* With SIOCETHTOOL, this would corrupt the pointer.  */
2454                data->phy_id &= 0x3f;
2455                data->reg_num &= 0x1f;
2456        }
2457
2458        switch (cmd) {
2459        case SIOCETHTOOL:
2460                return netdev_ethtool_ioctl(dev, (void *) rq->ifr_data);
2461
2462        case SIOCGMIIPHY:       /* Get the address of the PHY in use. */
2463                data->phy_id = phy;
2464                /* Fall Through */
2465
2466        case SIOCGMIIREG:       /* Read the specified MII register. */
2467                data->val_out = mdio_read (dev, data->phy_id, data->reg_num);
2468                break;
2469
2470        case SIOCSMIIREG:       /* Write the specified MII register */
2471                if (!capable (CAP_NET_ADMIN)) {
2472                        rc = -EPERM;
2473                        break;
2474                }
2475
2476                if (data->phy_id == phy) {
2477                        u16 value = data->val_in;
2478                        switch (data->reg_num) {
2479                        case 0:
2480                                /* Check for autonegotiation on or reset. */
2481                                tp->medialock = (value & 0x9000) ? 0 : 1;
2482                                if (tp->medialock)
2483                                        tp->mii.full_duplex = (value & 0x0100) ? 1 : 0;
2484                                break;
2485                        case 4: tp->mii.advertising = value; break;
2486                        }
2487                }
2488                mdio_write(dev, data->phy_id, data->reg_num, data->val_in);
2489                break;
2490
2491        default:
2492                rc = -EOPNOTSUPP;
2493                break;
2494        }
2495
2496        return rc;
2497}
2498
2499
2500static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
2501{
2502        struct rtl8139_private *tp = dev->priv;
2503        void *ioaddr = tp->mmio_addr;
2504        unsigned long flags;
2505
2506        if (netif_running(dev)) {
2507                spin_lock_irqsave (&tp->lock, flags);
2508                tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2509                RTL_W32 (RxMissed, 0);
2510                spin_unlock_irqrestore (&tp->lock, flags);
2511        }
2512
2513        return &tp->stats;
2514}
2515
2516/* Set or clear the multicast filter for this adaptor.
2517   This routine is not state sensitive and need not be SMP locked. */
2518
2519static void __set_rx_mode (struct net_device *dev)
2520{
2521        struct rtl8139_private *tp = dev->priv;
2522        void *ioaddr = tp->mmio_addr;
2523        u32 mc_filter[2];       /* Multicast hash filter */
2524        int i, rx_mode;
2525        u32 tmp;
2526
2527        DPRINTK ("%s:   rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
2528                        dev->name, dev->flags, RTL_R32 (RxConfig));
2529
2530        /* Note: do not reorder, GCC is clever about common statements. */
2531        if (dev->flags & IFF_PROMISC) {
2532                /* Unconditionally log net taps. */
2533                printk (KERN_NOTICE "%s: Promiscuous mode enabled.\n",
2534                        dev->name);
2535                rx_mode =
2536                    AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
2537                    AcceptAllPhys;
2538                mc_filter[1] = mc_filter[0] = 0xffffffff;
2539        } else if ((dev->mc_count > multicast_filter_limit)
2540                   || (dev->flags & IFF_ALLMULTI)) {
2541                /* Too many to filter perfectly -- accept all multicasts. */
2542                rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
2543                mc_filter[1] = mc_filter[0] = 0xffffffff;
2544        } else {
2545                struct dev_mc_list *mclist;
2546                rx_mode = AcceptBroadcast | AcceptMyPhys;
2547                mc_filter[1] = mc_filter[0] = 0;
2548                for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
2549                     i++, mclist = mclist->next) {
2550                        int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
2551
2552                        mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
2553                        rx_mode |= AcceptMulticast;
2554                }
2555        }
2556
2557        /* We can safely update without stopping the chip. */
2558        tmp = rtl8139_rx_config | rx_mode;
2559        if (tp->rx_config != tmp) {
2560                RTL_W32_F (RxConfig, tmp);
2561                tp->rx_config = tmp;
2562        }
2563        RTL_W32_F (MAR0 + 0, mc_filter[0]);
2564        RTL_W32_F (MAR0 + 4, mc_filter[1]);
2565}
2566
2567static void rtl8139_set_rx_mode (struct net_device *dev)
2568{
2569        unsigned long flags;
2570        struct rtl8139_private *tp = dev->priv;
2571
2572        spin_lock_irqsave (&tp->lock, flags);
2573        __set_rx_mode(dev);
2574        spin_unlock_irqrestore (&tp->lock, flags);
2575}
2576
2577#ifdef CONFIG_PM
2578
2579static int rtl8139_suspend (struct pci_dev *pdev, u32 state)
2580{
2581        struct net_device *dev = pci_get_drvdata (pdev);
2582        struct rtl8139_private *tp = dev->priv;
2583        void *ioaddr = tp->mmio_addr;
2584        unsigned long flags;
2585
2586        if (!netif_running (dev))
2587                return 0;
2588
2589        netif_device_detach (dev);
2590
2591        spin_lock_irqsave (&tp->lock, flags);
2592
2593        /* Disable interrupts, stop Tx and Rx. */
2594        RTL_W16 (IntrMask, 0);
2595        RTL_W8 (ChipCmd, 0);
2596
2597        /* Update the error counts. */
2598        tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
2599        RTL_W32 (RxMissed, 0);
2600
2601        spin_unlock_irqrestore (&tp->lock, flags);
2602        return 0;
2603}
2604
2605
2606static int rtl8139_resume (struct pci_dev *pdev)
2607{
2608        struct net_device *dev = pci_get_drvdata (pdev);
2609
2610        if (!netif_running (dev))
2611                return 0;
2612        netif_device_attach (dev);
2613        rtl8139_hw_start (dev);
2614        return 0;
2615}
2616
2617#endif /* CONFIG_PM */
2618
2619
2620static struct pci_driver rtl8139_pci_driver = {
2621        .name           = DRV_NAME,
2622        .id_table       = rtl8139_pci_tbl,
2623        .probe          = rtl8139_init_one,
2624        .remove         = __devexit_p(rtl8139_remove_one),
2625#ifdef CONFIG_PM
2626        .suspend        = rtl8139_suspend,
2627        .resume         = rtl8139_resume,
2628#endif /* CONFIG_PM */
2629};
2630
2631
2632static int __init rtl8139_init_module (void)
2633{
2634        /* when we're a module, we always print a version message,
2635         * even if no 8139 board is found.
2636         */
2637#ifdef MODULE
2638        printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
2639#endif
2640
2641        return pci_module_init (&rtl8139_pci_driver);
2642}
2643
2644
2645static void __exit rtl8139_cleanup_module (void)
2646{
2647        pci_unregister_driver (&rtl8139_pci_driver);
2648}
2649
2650
2651module_init(rtl8139_init_module);
2652module_exit(rtl8139_cleanup_module);
2653
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.