Pull acpica into release branch
[pandora-kernel.git] / drivers / net / tulip / winbond-840.c
1 /* winbond-840.c: A Linux PCI network adapter device driver. */
2 /*
3         Written 1998-2001 by Donald Becker.
4
5         This software may be used and distributed according to the terms of
6         the GNU General Public License (GPL), incorporated herein by reference.
7         Drivers based on or derived from this code fall under the GPL and must
8         retain the authorship, copyright and license notice.  This file is not
9         a complete program and may only be used when the entire operating
10         system is licensed under the GPL.
11
12         The author may be reached as becker@scyld.com, or C/O
13         Scyld Computing Corporation
14         410 Severn Ave., Suite 210
15         Annapolis MD 21403
16
17         Support and updates available at
18         http://www.scyld.com/network/drivers.html
19
20         Do not remove the copyright information.
21         Do not change the version information unless an improvement has been made.
22         Merely removing my name, as Compex has done in the past, does not count
23         as an improvement.
24
25         Changelog:
26         * ported to 2.4
27                 ???
28         * spin lock update, memory barriers, new style dma mappings
29                 limit each tx buffer to < 1024 bytes
30                 remove DescIntr from Rx descriptors (that's an Tx flag)
31                 remove next pointer from Tx descriptors
32                 synchronize tx_q_bytes
33                 software reset in tx_timeout
34                         Copyright (C) 2000 Manfred Spraul
35         * further cleanups
36                 power management.
37                 support for big endian descriptors
38                         Copyright (C) 2001 Manfred Spraul
39         * ethtool support (jgarzik)
40         * Replace some MII-related magic numbers with constants (jgarzik)
41   
42         TODO:
43         * enable pci_power_off
44         * Wake-On-LAN
45 */
46   
47 #define DRV_NAME        "winbond-840"
48 #define DRV_VERSION     "1.01-d"
49 #define DRV_RELDATE     "Nov-17-2001"
50
51
52 /* Automatically extracted configuration info:
53 probe-func: winbond840_probe
54 config-in: tristate 'Winbond W89c840 Ethernet support' CONFIG_WINBOND_840
55
56 c-help-name: Winbond W89c840 PCI Ethernet support
57 c-help-symbol: CONFIG_WINBOND_840
58 c-help: This driver is for the Winbond W89c840 chip.  It also works with
59 c-help: the TX9882 chip on the Compex RL100-ATX board.
60 c-help: More specific information and updates are available from 
61 c-help: http://www.scyld.com/network/drivers.html
62 */
63
64 /* The user-configurable values.
65    These may be modified when a driver module is loaded.*/
66
67 static int debug = 1;                   /* 1 normal messages, 0 quiet .. 7 verbose. */
68 static int max_interrupt_work = 20;
69 /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
70    The '840 uses a 64 element hash table based on the Ethernet CRC.  */
71 static int multicast_filter_limit = 32;
72
73 /* Set the copy breakpoint for the copy-only-tiny-frames scheme.
74    Setting to > 1518 effectively disables this feature. */
75 static int rx_copybreak;
76
77 /* Used to pass the media type, etc.
78    Both 'options[]' and 'full_duplex[]' should exist for driver
79    interoperability.
80    The media type is usually passed in 'options[]'.
81 */
82 #define MAX_UNITS 8             /* More are supported, limit only on options */
83 static int options[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
84 static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
85
86 /* Operational parameters that are set at compile time. */
87
88 /* Keep the ring sizes a power of two for compile efficiency.
89    The compiler will convert <unsigned>'%'<2^N> into a bit mask.
90    Making the Tx ring too large decreases the effectiveness of channel
91    bonding and packet priority.
92    There are no ill effects from too-large receive rings. */
93 #define TX_RING_SIZE    16
94 #define TX_QUEUE_LEN    10              /* Limit ring entries actually used.  */
95 #define TX_QUEUE_LEN_RESTART    5
96 #define RX_RING_SIZE    32
97
98 #define TX_BUFLIMIT     (1024-128)
99
100 /* The presumed FIFO size for working around the Tx-FIFO-overflow bug.
101    To avoid overflowing we don't queue again until we have room for a
102    full-size packet.
103  */
104 #define TX_FIFO_SIZE (2048)
105 #define TX_BUG_FIFO_LIMIT (TX_FIFO_SIZE-1514-16)
106
107
108 /* Operational parameters that usually are not changed. */
109 /* Time in jiffies before concluding the transmitter is hung. */
110 #define TX_TIMEOUT  (2*HZ)
111
112 #define PKT_BUF_SZ              1536                    /* Size of each temporary Rx buffer.*/
113
114 /* Include files, designed to support most kernel versions 2.0.0 and later. */
115 #include <linux/module.h>
116 #include <linux/kernel.h>
117 #include <linux/string.h>
118 #include <linux/timer.h>
119 #include <linux/errno.h>
120 #include <linux/ioport.h>
121 #include <linux/slab.h>
122 #include <linux/interrupt.h>
123 #include <linux/pci.h>
124 #include <linux/dma-mapping.h>
125 #include <linux/netdevice.h>
126 #include <linux/etherdevice.h>
127 #include <linux/skbuff.h>
128 #include <linux/init.h>
129 #include <linux/delay.h>
130 #include <linux/ethtool.h>
131 #include <linux/mii.h>
132 #include <linux/rtnetlink.h>
133 #include <linux/crc32.h>
134 #include <linux/bitops.h>
135 #include <asm/uaccess.h>
136 #include <asm/processor.h>              /* Processor type for cache alignment. */
137 #include <asm/io.h>
138 #include <asm/irq.h>
139
140 /* These identify the driver base version and may not be removed. */
141 static char version[] __devinitdata =
142 KERN_INFO DRV_NAME ".c:v" DRV_VERSION " (2.4 port) " DRV_RELDATE "  Donald Becker <becker@scyld.com>\n"
143 KERN_INFO "  http://www.scyld.com/network/drivers.html\n";
144
145 MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
146 MODULE_DESCRIPTION("Winbond W89c840 Ethernet driver");
147 MODULE_LICENSE("GPL");
148 MODULE_VERSION(DRV_VERSION);
149
150 module_param(max_interrupt_work, int, 0);
151 module_param(debug, int, 0);
152 module_param(rx_copybreak, int, 0);
153 module_param(multicast_filter_limit, int, 0);
154 module_param_array(options, int, NULL, 0);
155 module_param_array(full_duplex, int, NULL, 0);
156 MODULE_PARM_DESC(max_interrupt_work, "winbond-840 maximum events handled per interrupt");
157 MODULE_PARM_DESC(debug, "winbond-840 debug level (0-6)");
158 MODULE_PARM_DESC(rx_copybreak, "winbond-840 copy breakpoint for copy-only-tiny-frames");
159 MODULE_PARM_DESC(multicast_filter_limit, "winbond-840 maximum number of filtered multicast addresses");
160 MODULE_PARM_DESC(options, "winbond-840: Bits 0-3: media type, bit 17: full duplex");
161 MODULE_PARM_DESC(full_duplex, "winbond-840 full duplex setting(s) (1)");
162
163 /*
164                                 Theory of Operation
165
166 I. Board Compatibility
167
168 This driver is for the Winbond w89c840 chip.
169
170 II. Board-specific settings
171
172 None.
173
174 III. Driver operation
175
176 This chip is very similar to the Digital 21*4* "Tulip" family.  The first
177 twelve registers and the descriptor format are nearly identical.  Read a
178 Tulip manual for operational details.
179
180 A significant difference is that the multicast filter and station address are
181 stored in registers rather than loaded through a pseudo-transmit packet.
182
183 Unlike the Tulip, transmit buffers are limited to 1KB.  To transmit a
184 full-sized packet we must use both data buffers in a descriptor.  Thus the
185 driver uses ring mode where descriptors are implicitly sequential in memory,
186 rather than using the second descriptor address as a chain pointer to
187 subsequent descriptors.
188
189 IV. Notes
190
191 If you are going to almost clone a Tulip, why not go all the way and avoid
192 the need for a new driver?
193
194 IVb. References
195
196 http://www.scyld.com/expert/100mbps.html
197 http://www.scyld.com/expert/NWay.html
198 http://www.winbond.com.tw/
199
200 IVc. Errata
201
202 A horrible bug exists in the transmit FIFO.  Apparently the chip doesn't
203 correctly detect a full FIFO, and queuing more than 2048 bytes may result in
204 silent data corruption.
205
206 Test with 'ping -s 10000' on a fast computer.
207
208 */
209
210 \f
211
212 /*
213   PCI probe table.
214 */
215 enum pci_id_flags_bits {
216         /* Set PCI command register bits before calling probe1(). */
217         PCI_USES_IO=1, PCI_USES_MEM=2, PCI_USES_MASTER=4,
218         /* Read and map the single following PCI BAR. */
219         PCI_ADDR0=0<<4, PCI_ADDR1=1<<4, PCI_ADDR2=2<<4, PCI_ADDR3=3<<4,
220         PCI_ADDR_64BITS=0x100, PCI_NO_ACPI_WAKE=0x200, PCI_NO_MIN_LATENCY=0x400,
221 };
222 enum chip_capability_flags {
223         CanHaveMII=1, HasBrokenTx=2, AlwaysFDX=4, FDXOnNoMII=8,};
224 #ifdef USE_IO_OPS
225 #define W840_FLAGS (PCI_USES_IO | PCI_ADDR0 | PCI_USES_MASTER)
226 #else
227 #define W840_FLAGS (PCI_USES_MEM | PCI_ADDR1 | PCI_USES_MASTER)
228 #endif
229
230 static struct pci_device_id w840_pci_tbl[] = {
231         { 0x1050, 0x0840, PCI_ANY_ID, 0x8153,     0, 0, 0 },
232         { 0x1050, 0x0840, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 1 },
233         { 0x11f6, 0x2011, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 2 },
234         { 0, }
235 };
236 MODULE_DEVICE_TABLE(pci, w840_pci_tbl);
237
238 struct pci_id_info {
239         const char *name;
240         struct match_info {
241                 int     pci, pci_mask, subsystem, subsystem_mask;
242                 int revision, revision_mask;                            /* Only 8 bits. */
243         } id;
244         enum pci_id_flags_bits pci_flags;
245         int io_size;                            /* Needed for I/O region check or ioremap(). */
246         int drv_flags;                          /* Driver use, intended as capability flags. */
247 };
248 static struct pci_id_info pci_id_tbl[] = {
249         {"Winbond W89c840",                     /* Sometime a Level-One switch card. */
250          { 0x08401050, 0xffffffff, 0x81530000, 0xffff0000 },
251          W840_FLAGS, 128, CanHaveMII | HasBrokenTx | FDXOnNoMII},
252         {"Winbond W89c840", { 0x08401050, 0xffffffff, },
253          W840_FLAGS, 128, CanHaveMII | HasBrokenTx},
254         {"Compex RL100-ATX", { 0x201111F6, 0xffffffff,},
255          W840_FLAGS, 128, CanHaveMII | HasBrokenTx},
256         {NULL,},                                        /* 0 terminated list. */
257 };
258
259 /* This driver was written to use PCI memory space, however some x86 systems
260    work only with I/O space accesses.  Pass -DUSE_IO_OPS to use PCI I/O space
261    accesses instead of memory space. */
262
263 /* Offsets to the Command and Status Registers, "CSRs".
264    While similar to the Tulip, these registers are longword aligned.
265    Note: It's not useful to define symbolic names for every register bit in
266    the device.  The name can only partially document the semantics and make
267    the driver longer and more difficult to read.
268 */
269 enum w840_offsets {
270         PCIBusCfg=0x00, TxStartDemand=0x04, RxStartDemand=0x08,
271         RxRingPtr=0x0C, TxRingPtr=0x10,
272         IntrStatus=0x14, NetworkConfig=0x18, IntrEnable=0x1C,
273         RxMissed=0x20, EECtrl=0x24, MIICtrl=0x24, BootRom=0x28, GPTimer=0x2C,
274         CurRxDescAddr=0x30, CurRxBufAddr=0x34,                  /* Debug use */
275         MulticastFilter0=0x38, MulticastFilter1=0x3C, StationAddr=0x40,
276         CurTxDescAddr=0x4C, CurTxBufAddr=0x50,
277 };
278
279 /* Bits in the interrupt status/enable registers. */
280 /* The bits in the Intr Status/Enable registers, mostly interrupt sources. */
281 enum intr_status_bits {
282         NormalIntr=0x10000, AbnormalIntr=0x8000,
283         IntrPCIErr=0x2000, TimerInt=0x800,
284         IntrRxDied=0x100, RxNoBuf=0x80, IntrRxDone=0x40,
285         TxFIFOUnderflow=0x20, RxErrIntr=0x10,
286         TxIdle=0x04, IntrTxStopped=0x02, IntrTxDone=0x01,
287 };
288
289 /* Bits in the NetworkConfig register. */
290 enum rx_mode_bits {
291         AcceptErr=0x80, AcceptRunt=0x40,
292         AcceptBroadcast=0x20, AcceptMulticast=0x10,
293         AcceptAllPhys=0x08, AcceptMyPhys=0x02,
294 };
295
296 enum mii_reg_bits {
297         MDIO_ShiftClk=0x10000, MDIO_DataIn=0x80000, MDIO_DataOut=0x20000,
298         MDIO_EnbOutput=0x40000, MDIO_EnbIn = 0x00000,
299 };
300
301 /* The Tulip Rx and Tx buffer descriptors. */
302 struct w840_rx_desc {
303         s32 status;
304         s32 length;
305         u32 buffer1;
306         u32 buffer2;
307 };
308
309 struct w840_tx_desc {
310         s32 status;
311         s32 length;
312         u32 buffer1, buffer2;
313 };
314
315 /* Bits in network_desc.status */
316 enum desc_status_bits {
317         DescOwn=0x80000000, DescEndRing=0x02000000, DescUseLink=0x01000000,
318         DescWholePkt=0x60000000, DescStartPkt=0x20000000, DescEndPkt=0x40000000,
319         DescIntr=0x80000000,
320 };
321
322 #define MII_CNT         1 /* winbond only supports one MII */
323 struct netdev_private {
324         struct w840_rx_desc *rx_ring;
325         dma_addr_t      rx_addr[RX_RING_SIZE];
326         struct w840_tx_desc *tx_ring;
327         dma_addr_t      tx_addr[TX_RING_SIZE];
328         dma_addr_t ring_dma_addr;
329         /* The addresses of receive-in-place skbuffs. */
330         struct sk_buff* rx_skbuff[RX_RING_SIZE];
331         /* The saved address of a sent-in-place packet/buffer, for later free(). */
332         struct sk_buff* tx_skbuff[TX_RING_SIZE];
333         struct net_device_stats stats;
334         struct timer_list timer;        /* Media monitoring timer. */
335         /* Frequently used values: keep some adjacent for cache effect. */
336         spinlock_t lock;
337         int chip_id, drv_flags;
338         struct pci_dev *pci_dev;
339         int csr6;
340         struct w840_rx_desc *rx_head_desc;
341         unsigned int cur_rx, dirty_rx;          /* Producer/consumer ring indices */
342         unsigned int rx_buf_sz;                         /* Based on MTU+slack. */
343         unsigned int cur_tx, dirty_tx;
344         unsigned int tx_q_bytes;
345         unsigned int tx_full;                           /* The Tx queue is full. */
346         /* MII transceiver section. */
347         int mii_cnt;                                            /* MII device addresses. */
348         unsigned char phys[MII_CNT];            /* MII device addresses, but only the first is used */
349         u32 mii;
350         struct mii_if_info mii_if;
351         void __iomem *base_addr;
352 };
353
354 static int  eeprom_read(void __iomem *ioaddr, int location);
355 static int  mdio_read(struct net_device *dev, int phy_id, int location);
356 static void mdio_write(struct net_device *dev, int phy_id, int location, int value);
357 static int  netdev_open(struct net_device *dev);
358 static int  update_link(struct net_device *dev);
359 static void netdev_timer(unsigned long data);
360 static void init_rxtx_rings(struct net_device *dev);
361 static void free_rxtx_rings(struct netdev_private *np);
362 static void init_registers(struct net_device *dev);
363 static void tx_timeout(struct net_device *dev);
364 static int alloc_ringdesc(struct net_device *dev);
365 static void free_ringdesc(struct netdev_private *np);
366 static int  start_tx(struct sk_buff *skb, struct net_device *dev);
367 static irqreturn_t intr_handler(int irq, void *dev_instance, struct pt_regs *regs);
368 static void netdev_error(struct net_device *dev, int intr_status);
369 static int  netdev_rx(struct net_device *dev);
370 static u32 __set_rx_mode(struct net_device *dev);
371 static void set_rx_mode(struct net_device *dev);
372 static struct net_device_stats *get_stats(struct net_device *dev);
373 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
374 static struct ethtool_ops netdev_ethtool_ops;
375 static int  netdev_close(struct net_device *dev);
376
377 \f
378
379 static int __devinit w840_probe1 (struct pci_dev *pdev,
380                                   const struct pci_device_id *ent)
381 {
382         struct net_device *dev;
383         struct netdev_private *np;
384         static int find_cnt;
385         int chip_idx = ent->driver_data;
386         int irq;
387         int i, option = find_cnt < MAX_UNITS ? options[find_cnt] : 0;
388         void __iomem *ioaddr;
389         int bar = 1;
390
391         i = pci_enable_device(pdev);
392         if (i) return i;
393
394         pci_set_master(pdev);
395
396         irq = pdev->irq;
397
398         if (pci_set_dma_mask(pdev, DMA_32BIT_MASK)) {
399                 printk(KERN_WARNING "Winbond-840: Device %s disabled due to DMA limitations.\n",
400                        pci_name(pdev));
401                 return -EIO;
402         }
403         dev = alloc_etherdev(sizeof(*np));
404         if (!dev)
405                 return -ENOMEM;
406         SET_MODULE_OWNER(dev);
407         SET_NETDEV_DEV(dev, &pdev->dev);
408
409         if (pci_request_regions(pdev, DRV_NAME))
410                 goto err_out_netdev;
411 #ifdef USE_IO_OPS
412         bar = 0;
413 #endif
414         ioaddr = pci_iomap(pdev, bar, pci_id_tbl[chip_idx].io_size);
415         if (!ioaddr)
416                 goto err_out_free_res;
417
418         for (i = 0; i < 3; i++)
419                 ((u16 *)dev->dev_addr)[i] = le16_to_cpu(eeprom_read(ioaddr, i));
420
421         /* Reset the chip to erase previous misconfiguration.
422            No hold time required! */
423         iowrite32(0x00000001, ioaddr + PCIBusCfg);
424
425         dev->base_addr = (unsigned long)ioaddr;
426         dev->irq = irq;
427
428         np = netdev_priv(dev);
429         np->pci_dev = pdev;
430         np->chip_id = chip_idx;
431         np->drv_flags = pci_id_tbl[chip_idx].drv_flags;
432         spin_lock_init(&np->lock);
433         np->mii_if.dev = dev;
434         np->mii_if.mdio_read = mdio_read;
435         np->mii_if.mdio_write = mdio_write;
436         np->base_addr = ioaddr;
437         
438         pci_set_drvdata(pdev, dev);
439
440         if (dev->mem_start)
441                 option = dev->mem_start;
442
443         /* The lower four bits are the media type. */
444         if (option > 0) {
445                 if (option & 0x200)
446                         np->mii_if.full_duplex = 1;
447                 if (option & 15)
448                         printk(KERN_INFO "%s: ignoring user supplied media type %d",
449                                 dev->name, option & 15);
450         }
451         if (find_cnt < MAX_UNITS  &&  full_duplex[find_cnt] > 0)
452                 np->mii_if.full_duplex = 1;
453
454         if (np->mii_if.full_duplex)
455                 np->mii_if.force_media = 1;
456
457         /* The chip-specific entries in the device structure. */
458         dev->open = &netdev_open;
459         dev->hard_start_xmit = &start_tx;
460         dev->stop = &netdev_close;
461         dev->get_stats = &get_stats;
462         dev->set_multicast_list = &set_rx_mode;
463         dev->do_ioctl = &netdev_ioctl;
464         dev->ethtool_ops = &netdev_ethtool_ops;
465         dev->tx_timeout = &tx_timeout;
466         dev->watchdog_timeo = TX_TIMEOUT;
467
468         i = register_netdev(dev);
469         if (i)
470                 goto err_out_cleardev;
471
472         printk(KERN_INFO "%s: %s at %p, ",
473                    dev->name, pci_id_tbl[chip_idx].name, ioaddr);
474         for (i = 0; i < 5; i++)
475                         printk("%2.2x:", dev->dev_addr[i]);
476         printk("%2.2x, IRQ %d.\n", dev->dev_addr[i], irq);
477
478         if (np->drv_flags & CanHaveMII) {
479                 int phy, phy_idx = 0;
480                 for (phy = 1; phy < 32 && phy_idx < MII_CNT; phy++) {
481                         int mii_status = mdio_read(dev, phy, MII_BMSR);
482                         if (mii_status != 0xffff  &&  mii_status != 0x0000) {
483                                 np->phys[phy_idx++] = phy;
484                                 np->mii_if.advertising = mdio_read(dev, phy, MII_ADVERTISE);
485                                 np->mii = (mdio_read(dev, phy, MII_PHYSID1) << 16)+
486                                                 mdio_read(dev, phy, MII_PHYSID2);
487                                 printk(KERN_INFO "%s: MII PHY %8.8xh found at address %d, status "
488                                            "0x%4.4x advertising %4.4x.\n",
489                                            dev->name, np->mii, phy, mii_status, np->mii_if.advertising);
490                         }
491                 }
492                 np->mii_cnt = phy_idx;
493                 np->mii_if.phy_id = np->phys[0];
494                 if (phy_idx == 0) {
495                                 printk(KERN_WARNING "%s: MII PHY not found -- this device may "
496                                            "not operate correctly.\n", dev->name);
497                 }
498         }
499
500         find_cnt++;
501         return 0;
502
503 err_out_cleardev:
504         pci_set_drvdata(pdev, NULL);
505         pci_iounmap(pdev, ioaddr);
506 err_out_free_res:
507         pci_release_regions(pdev);
508 err_out_netdev:
509         free_netdev (dev);
510         return -ENODEV;
511 }
512
513 \f
514 /* Read the EEPROM and MII Management Data I/O (MDIO) interfaces.  These are
515    often serial bit streams generated by the host processor.
516    The example below is for the common 93c46 EEPROM, 64 16 bit words. */
517
518 /* Delay between EEPROM clock transitions.
519    No extra delay is needed with 33Mhz PCI, but future 66Mhz access may need
520    a delay.  Note that pre-2.0.34 kernels had a cache-alignment bug that
521    made udelay() unreliable.
522    The old method of using an ISA access as a delay, __SLOW_DOWN_IO__, is
523    depricated.
524 */
525 #define eeprom_delay(ee_addr)   ioread32(ee_addr)
526
527 enum EEPROM_Ctrl_Bits {
528         EE_ShiftClk=0x02, EE_Write0=0x801, EE_Write1=0x805,
529         EE_ChipSelect=0x801, EE_DataIn=0x08,
530 };
531
532 /* The EEPROM commands include the alway-set leading bit. */
533 enum EEPROM_Cmds {
534         EE_WriteCmd=(5 << 6), EE_ReadCmd=(6 << 6), EE_EraseCmd=(7 << 6),
535 };
536
537 static int eeprom_read(void __iomem *addr, int location)
538 {
539         int i;
540         int retval = 0;
541         void __iomem *ee_addr = addr + EECtrl;
542         int read_cmd = location | EE_ReadCmd;
543         iowrite32(EE_ChipSelect, ee_addr);
544
545         /* Shift the read command bits out. */
546         for (i = 10; i >= 0; i--) {
547                 short dataval = (read_cmd & (1 << i)) ? EE_Write1 : EE_Write0;
548                 iowrite32(dataval, ee_addr);
549                 eeprom_delay(ee_addr);
550                 iowrite32(dataval | EE_ShiftClk, ee_addr);
551                 eeprom_delay(ee_addr);
552         }
553         iowrite32(EE_ChipSelect, ee_addr);
554         eeprom_delay(ee_addr);
555
556         for (i = 16; i > 0; i--) {
557                 iowrite32(EE_ChipSelect | EE_ShiftClk, ee_addr);
558                 eeprom_delay(ee_addr);
559                 retval = (retval << 1) | ((ioread32(ee_addr) & EE_DataIn) ? 1 : 0);
560                 iowrite32(EE_ChipSelect, ee_addr);
561                 eeprom_delay(ee_addr);
562         }
563
564         /* Terminate the EEPROM access. */
565         iowrite32(0, ee_addr);
566         return retval;
567 }
568
569 /*  MII transceiver control section.
570         Read and write the MII registers using software-generated serial
571         MDIO protocol.  See the MII specifications or DP83840A data sheet
572         for details.
573
574         The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
575         met by back-to-back 33Mhz PCI cycles. */
576 #define mdio_delay(mdio_addr) ioread32(mdio_addr)
577
578 /* Set iff a MII transceiver on any interface requires mdio preamble.
579    This only set with older transceivers, so the extra
580    code size of a per-interface flag is not worthwhile. */
581 static char mii_preamble_required = 1;
582
583 #define MDIO_WRITE0 (MDIO_EnbOutput)
584 #define MDIO_WRITE1 (MDIO_DataOut | MDIO_EnbOutput)
585
586 /* Generate the preamble required for initial synchronization and
587    a few older transceivers. */
588 static void mdio_sync(void __iomem *mdio_addr)
589 {
590         int bits = 32;
591
592         /* Establish sync by sending at least 32 logic ones. */
593         while (--bits >= 0) {
594                 iowrite32(MDIO_WRITE1, mdio_addr);
595                 mdio_delay(mdio_addr);
596                 iowrite32(MDIO_WRITE1 | MDIO_ShiftClk, mdio_addr);
597                 mdio_delay(mdio_addr);
598         }
599 }
600
601 static int mdio_read(struct net_device *dev, int phy_id, int location)
602 {
603         struct netdev_private *np = netdev_priv(dev);
604         void __iomem *mdio_addr = np->base_addr + MIICtrl;
605         int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
606         int i, retval = 0;
607
608         if (mii_preamble_required)
609                 mdio_sync(mdio_addr);
610
611         /* Shift the read command bits out. */
612         for (i = 15; i >= 0; i--) {
613                 int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
614
615                 iowrite32(dataval, mdio_addr);
616                 mdio_delay(mdio_addr);
617                 iowrite32(dataval | MDIO_ShiftClk, mdio_addr);
618                 mdio_delay(mdio_addr);
619         }
620         /* Read the two transition, 16 data, and wire-idle bits. */
621         for (i = 20; i > 0; i--) {
622                 iowrite32(MDIO_EnbIn, mdio_addr);
623                 mdio_delay(mdio_addr);
624                 retval = (retval << 1) | ((ioread32(mdio_addr) & MDIO_DataIn) ? 1 : 0);
625                 iowrite32(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
626                 mdio_delay(mdio_addr);
627         }
628         return (retval>>1) & 0xffff;
629 }
630
631 static void mdio_write(struct net_device *dev, int phy_id, int location, int value)
632 {
633         struct netdev_private *np = netdev_priv(dev);
634         void __iomem *mdio_addr = np->base_addr + MIICtrl;
635         int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location<<18) | value;
636         int i;
637
638         if (location == 4  &&  phy_id == np->phys[0])
639                 np->mii_if.advertising = value;
640
641         if (mii_preamble_required)
642                 mdio_sync(mdio_addr);
643
644         /* Shift the command bits out. */
645         for (i = 31; i >= 0; i--) {
646                 int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
647
648                 iowrite32(dataval, mdio_addr);
649                 mdio_delay(mdio_addr);
650                 iowrite32(dataval | MDIO_ShiftClk, mdio_addr);
651                 mdio_delay(mdio_addr);
652         }
653         /* Clear out extra bits. */
654         for (i = 2; i > 0; i--) {
655                 iowrite32(MDIO_EnbIn, mdio_addr);
656                 mdio_delay(mdio_addr);
657                 iowrite32(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
658                 mdio_delay(mdio_addr);
659         }
660         return;
661 }
662
663 \f
664 static int netdev_open(struct net_device *dev)
665 {
666         struct netdev_private *np = netdev_priv(dev);
667         void __iomem *ioaddr = np->base_addr;
668         int i;
669
670         iowrite32(0x00000001, ioaddr + PCIBusCfg);              /* Reset */
671
672         netif_device_detach(dev);
673         i = request_irq(dev->irq, &intr_handler, SA_SHIRQ, dev->name, dev);
674         if (i)
675                 goto out_err;
676
677         if (debug > 1)
678                 printk(KERN_DEBUG "%s: w89c840_open() irq %d.\n",
679                            dev->name, dev->irq);
680
681         if((i=alloc_ringdesc(dev)))
682                 goto out_err;
683
684         spin_lock_irq(&np->lock);
685         netif_device_attach(dev);
686         init_registers(dev);
687         spin_unlock_irq(&np->lock);
688
689         netif_start_queue(dev);
690         if (debug > 2)
691                 printk(KERN_DEBUG "%s: Done netdev_open().\n", dev->name);
692
693         /* Set the timer to check for link beat. */
694         init_timer(&np->timer);
695         np->timer.expires = jiffies + 1*HZ;
696         np->timer.data = (unsigned long)dev;
697         np->timer.function = &netdev_timer;                             /* timer handler */
698         add_timer(&np->timer);
699         return 0;
700 out_err:
701         netif_device_attach(dev);
702         return i;
703 }
704
705 #define MII_DAVICOM_DM9101      0x0181b800
706
707 static int update_link(struct net_device *dev)
708 {
709         struct netdev_private *np = netdev_priv(dev);
710         int duplex, fasteth, result, mii_reg;
711
712         /* BSMR */
713         mii_reg = mdio_read(dev, np->phys[0], MII_BMSR);
714
715         if (mii_reg == 0xffff)
716                 return np->csr6;
717         /* reread: the link status bit is sticky */
718         mii_reg = mdio_read(dev, np->phys[0], MII_BMSR);
719         if (!(mii_reg & 0x4)) {
720                 if (netif_carrier_ok(dev)) {
721                         if (debug)
722                                 printk(KERN_INFO "%s: MII #%d reports no link. Disabling watchdog.\n",
723                                         dev->name, np->phys[0]);
724                         netif_carrier_off(dev);
725                 }
726                 return np->csr6;
727         }
728         if (!netif_carrier_ok(dev)) {
729                 if (debug)
730                         printk(KERN_INFO "%s: MII #%d link is back. Enabling watchdog.\n",
731                                 dev->name, np->phys[0]);
732                 netif_carrier_on(dev);
733         }
734         
735         if ((np->mii & ~0xf) == MII_DAVICOM_DM9101) {
736                 /* If the link partner doesn't support autonegotiation
737                  * the MII detects it's abilities with the "parallel detection".
738                  * Some MIIs update the LPA register to the result of the parallel
739                  * detection, some don't.
740                  * The Davicom PHY [at least 0181b800] doesn't.
741                  * Instead bit 9 and 13 of the BMCR are updated to the result
742                  * of the negotiation..
743                  */
744                 mii_reg = mdio_read(dev, np->phys[0], MII_BMCR);
745                 duplex = mii_reg & BMCR_FULLDPLX;
746                 fasteth = mii_reg & BMCR_SPEED100;
747         } else {
748                 int negotiated;
749                 mii_reg = mdio_read(dev, np->phys[0], MII_LPA);
750                 negotiated = mii_reg & np->mii_if.advertising;
751
752                 duplex = (negotiated & LPA_100FULL) || ((negotiated & 0x02C0) == LPA_10FULL);
753                 fasteth = negotiated & 0x380;
754         }
755         duplex |= np->mii_if.force_media;
756         /* remove fastether and fullduplex */
757         result = np->csr6 & ~0x20000200;
758         if (duplex)
759                 result |= 0x200;
760         if (fasteth)
761                 result |= 0x20000000;
762         if (result != np->csr6 && debug)
763                 printk(KERN_INFO "%s: Setting %dMBit-%s-duplex based on MII#%d\n",
764                                  dev->name, fasteth ? 100 : 10, 
765                                 duplex ? "full" : "half", np->phys[0]);
766         return result;
767 }
768
769 #define RXTX_TIMEOUT    2000
770 static inline void update_csr6(struct net_device *dev, int new)
771 {
772         struct netdev_private *np = netdev_priv(dev);
773         void __iomem *ioaddr = np->base_addr;
774         int limit = RXTX_TIMEOUT;
775
776         if (!netif_device_present(dev))
777                 new = 0;
778         if (new==np->csr6)
779                 return;
780         /* stop both Tx and Rx processes */
781         iowrite32(np->csr6 & ~0x2002, ioaddr + NetworkConfig);
782         /* wait until they have really stopped */
783         for (;;) {
784                 int csr5 = ioread32(ioaddr + IntrStatus);
785                 int t;
786
787                 t = (csr5 >> 17) & 0x07;
788                 if (t==0||t==1) {
789                         /* rx stopped */
790                         t = (csr5 >> 20) & 0x07;
791                         if (t==0||t==1)
792                                 break;
793                 }
794
795                 limit--;
796                 if(!limit) {
797                         printk(KERN_INFO "%s: couldn't stop rxtx, IntrStatus %xh.\n",
798                                         dev->name, csr5);
799                         break;
800                 }
801                 udelay(1);
802         }
803         np->csr6 = new;
804         /* and restart them with the new configuration */
805         iowrite32(np->csr6, ioaddr + NetworkConfig);
806         if (new & 0x200)
807                 np->mii_if.full_duplex = 1;
808 }
809
810 static void netdev_timer(unsigned long data)
811 {
812         struct net_device *dev = (struct net_device *)data;
813         struct netdev_private *np = netdev_priv(dev);
814         void __iomem *ioaddr = np->base_addr;
815
816         if (debug > 2)
817                 printk(KERN_DEBUG "%s: Media selection timer tick, status %8.8x "
818                            "config %8.8x.\n",
819                            dev->name, ioread32(ioaddr + IntrStatus),
820                            ioread32(ioaddr + NetworkConfig));
821         spin_lock_irq(&np->lock);
822         update_csr6(dev, update_link(dev));
823         spin_unlock_irq(&np->lock);
824         np->timer.expires = jiffies + 10*HZ;
825         add_timer(&np->timer);
826 }
827
828 static void init_rxtx_rings(struct net_device *dev)
829 {
830         struct netdev_private *np = netdev_priv(dev);
831         int i;
832
833         np->rx_head_desc = &np->rx_ring[0];
834         np->tx_ring = (struct w840_tx_desc*)&np->rx_ring[RX_RING_SIZE];
835
836         /* Initial all Rx descriptors. */
837         for (i = 0; i < RX_RING_SIZE; i++) {
838                 np->rx_ring[i].length = np->rx_buf_sz;
839                 np->rx_ring[i].status = 0;
840                 np->rx_skbuff[i] = NULL;
841         }
842         /* Mark the last entry as wrapping the ring. */
843         np->rx_ring[i-1].length |= DescEndRing;
844
845         /* Fill in the Rx buffers.  Handle allocation failure gracefully. */
846         for (i = 0; i < RX_RING_SIZE; i++) {
847                 struct sk_buff *skb = dev_alloc_skb(np->rx_buf_sz);
848                 np->rx_skbuff[i] = skb;
849                 if (skb == NULL)
850                         break;
851                 skb->dev = dev;                 /* Mark as being used by this device. */
852                 np->rx_addr[i] = pci_map_single(np->pci_dev,skb->data,
853                                         np->rx_buf_sz,PCI_DMA_FROMDEVICE);
854
855                 np->rx_ring[i].buffer1 = np->rx_addr[i];
856                 np->rx_ring[i].status = DescOwn;
857         }
858
859         np->cur_rx = 0;
860         np->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
861
862         /* Initialize the Tx descriptors */
863         for (i = 0; i < TX_RING_SIZE; i++) {
864                 np->tx_skbuff[i] = NULL;
865                 np->tx_ring[i].status = 0;
866         }
867         np->tx_full = 0;
868         np->tx_q_bytes = np->dirty_tx = np->cur_tx = 0;
869
870         iowrite32(np->ring_dma_addr, np->base_addr + RxRingPtr);
871         iowrite32(np->ring_dma_addr+sizeof(struct w840_rx_desc)*RX_RING_SIZE,
872                 np->base_addr + TxRingPtr);
873
874 }
875
876 static void free_rxtx_rings(struct netdev_private* np)
877 {
878         int i;
879         /* Free all the skbuffs in the Rx queue. */
880         for (i = 0; i < RX_RING_SIZE; i++) {
881                 np->rx_ring[i].status = 0;
882                 if (np->rx_skbuff[i]) {
883                         pci_unmap_single(np->pci_dev,
884                                                 np->rx_addr[i],
885                                                 np->rx_skbuff[i]->len,
886                                                 PCI_DMA_FROMDEVICE);
887                         dev_kfree_skb(np->rx_skbuff[i]);
888                 }
889                 np->rx_skbuff[i] = NULL;
890         }
891         for (i = 0; i < TX_RING_SIZE; i++) {
892                 if (np->tx_skbuff[i]) {
893                         pci_unmap_single(np->pci_dev,
894                                                 np->tx_addr[i],
895                                                 np->tx_skbuff[i]->len,
896                                                 PCI_DMA_TODEVICE);
897                         dev_kfree_skb(np->tx_skbuff[i]);
898                 }
899                 np->tx_skbuff[i] = NULL;
900         }
901 }
902
903 static void init_registers(struct net_device *dev)
904 {
905         struct netdev_private *np = netdev_priv(dev);
906         void __iomem *ioaddr = np->base_addr;
907         int i;
908
909         for (i = 0; i < 6; i++)
910                 iowrite8(dev->dev_addr[i], ioaddr + StationAddr + i);
911
912         /* Initialize other registers. */
913 #ifdef __BIG_ENDIAN
914         i = (1<<20);    /* Big-endian descriptors */
915 #else
916         i = 0;
917 #endif
918         i |= (0x04<<2);         /* skip length 4 u32 */
919         i |= 0x02;              /* give Rx priority */
920
921         /* Configure the PCI bus bursts and FIFO thresholds.
922            486: Set 8 longword cache alignment, 8 longword burst.
923            586: Set 16 longword cache alignment, no burst limit.
924            Cache alignment bits 15:14        Burst length 13:8
925                 0000    <not allowed>           0000 align to cache     0800 8 longwords
926                 4000    8  longwords            0100 1 longword         1000 16 longwords
927                 8000    16 longwords            0200 2 longwords        2000 32 longwords
928                 C000    32  longwords           0400 4 longwords */
929
930 #if defined (__i386__) && !defined(MODULE)
931         /* When not a module we can work around broken '486 PCI boards. */
932         if (boot_cpu_data.x86 <= 4) {
933                 i |= 0x4800;
934                 printk(KERN_INFO "%s: This is a 386/486 PCI system, setting cache "
935                            "alignment to 8 longwords.\n", dev->name);
936         } else {
937                 i |= 0xE000;
938         }
939 #elif defined(__powerpc__) || defined(__i386__) || defined(__alpha__) || defined(__ia64__) || defined(__x86_64__)
940         i |= 0xE000;
941 #elif defined(__sparc__)
942         i |= 0x4800;
943 #else
944 #warning Processor architecture undefined
945         i |= 0x4800;
946 #endif
947         iowrite32(i, ioaddr + PCIBusCfg);
948
949         np->csr6 = 0;
950         /* 128 byte Tx threshold; 
951                 Transmit on; Receive on; */
952         update_csr6(dev, 0x00022002 | update_link(dev) | __set_rx_mode(dev));
953
954         /* Clear and Enable interrupts by setting the interrupt mask. */
955         iowrite32(0x1A0F5, ioaddr + IntrStatus);
956         iowrite32(0x1A0F5, ioaddr + IntrEnable);
957
958         iowrite32(0, ioaddr + RxStartDemand);
959 }
960
961 static void tx_timeout(struct net_device *dev)
962 {
963         struct netdev_private *np = netdev_priv(dev);
964         void __iomem *ioaddr = np->base_addr;
965
966         printk(KERN_WARNING "%s: Transmit timed out, status %8.8x,"
967                    " resetting...\n", dev->name, ioread32(ioaddr + IntrStatus));
968
969         {
970                 int i;
971                 printk(KERN_DEBUG "  Rx ring %p: ", np->rx_ring);
972                 for (i = 0; i < RX_RING_SIZE; i++)
973                         printk(" %8.8x", (unsigned int)np->rx_ring[i].status);
974                 printk("\n"KERN_DEBUG"  Tx ring %p: ", np->tx_ring);
975                 for (i = 0; i < TX_RING_SIZE; i++)
976                         printk(" %8.8x", np->tx_ring[i].status);
977                 printk("\n");
978         }
979         printk(KERN_DEBUG "Tx cur %d Tx dirty %d Tx Full %d, q bytes %d.\n",
980                                 np->cur_tx, np->dirty_tx, np->tx_full, np->tx_q_bytes);
981         printk(KERN_DEBUG "Tx Descriptor addr %xh.\n",ioread32(ioaddr+0x4C));
982
983         disable_irq(dev->irq);
984         spin_lock_irq(&np->lock);
985         /*
986          * Under high load dirty_tx and the internal tx descriptor pointer
987          * come out of sync, thus perform a software reset and reinitialize
988          * everything.
989          */
990
991         iowrite32(1, np->base_addr+PCIBusCfg);
992         udelay(1);
993
994         free_rxtx_rings(np);
995         init_rxtx_rings(dev);
996         init_registers(dev);
997         spin_unlock_irq(&np->lock);
998         enable_irq(dev->irq);
999
1000         netif_wake_queue(dev);
1001         dev->trans_start = jiffies;
1002         np->stats.tx_errors++;
1003         return;
1004 }
1005
1006 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1007 static int alloc_ringdesc(struct net_device *dev)
1008 {
1009         struct netdev_private *np = netdev_priv(dev);
1010
1011         np->rx_buf_sz = (dev->mtu <= 1500 ? PKT_BUF_SZ : dev->mtu + 32);
1012
1013         np->rx_ring = pci_alloc_consistent(np->pci_dev,
1014                         sizeof(struct w840_rx_desc)*RX_RING_SIZE +
1015                         sizeof(struct w840_tx_desc)*TX_RING_SIZE,
1016                         &np->ring_dma_addr);
1017         if(!np->rx_ring)
1018                 return -ENOMEM;
1019         init_rxtx_rings(dev);
1020         return 0;
1021 }
1022
1023 static void free_ringdesc(struct netdev_private *np)
1024 {
1025         pci_free_consistent(np->pci_dev,
1026                         sizeof(struct w840_rx_desc)*RX_RING_SIZE +
1027                         sizeof(struct w840_tx_desc)*TX_RING_SIZE,
1028                         np->rx_ring, np->ring_dma_addr);
1029
1030 }
1031
1032 static int start_tx(struct sk_buff *skb, struct net_device *dev)
1033 {
1034         struct netdev_private *np = netdev_priv(dev);
1035         unsigned entry;
1036
1037         /* Caution: the write order is important here, set the field
1038            with the "ownership" bits last. */
1039
1040         /* Calculate the next Tx descriptor entry. */
1041         entry = np->cur_tx % TX_RING_SIZE;
1042
1043         np->tx_addr[entry] = pci_map_single(np->pci_dev,
1044                                 skb->data,skb->len, PCI_DMA_TODEVICE);
1045         np->tx_skbuff[entry] = skb;
1046
1047         np->tx_ring[entry].buffer1 = np->tx_addr[entry];
1048         if (skb->len < TX_BUFLIMIT) {
1049                 np->tx_ring[entry].length = DescWholePkt | skb->len;
1050         } else {
1051                 int len = skb->len - TX_BUFLIMIT;
1052
1053                 np->tx_ring[entry].buffer2 = np->tx_addr[entry]+TX_BUFLIMIT;
1054                 np->tx_ring[entry].length = DescWholePkt | (len << 11) | TX_BUFLIMIT;
1055         }
1056         if(entry == TX_RING_SIZE-1)
1057                 np->tx_ring[entry].length |= DescEndRing;
1058
1059         /* Now acquire the irq spinlock.
1060          * The difficult race is the the ordering between
1061          * increasing np->cur_tx and setting DescOwn:
1062          * - if np->cur_tx is increased first the interrupt
1063          *   handler could consider the packet as transmitted
1064          *   since DescOwn is cleared.
1065          * - If DescOwn is set first the NIC could report the
1066          *   packet as sent, but the interrupt handler would ignore it
1067          *   since the np->cur_tx was not yet increased.
1068          */
1069         spin_lock_irq(&np->lock);
1070         np->cur_tx++;
1071
1072         wmb(); /* flush length, buffer1, buffer2 */
1073         np->tx_ring[entry].status = DescOwn;
1074         wmb(); /* flush status and kick the hardware */
1075         iowrite32(0, np->base_addr + TxStartDemand);
1076         np->tx_q_bytes += skb->len;
1077         /* Work around horrible bug in the chip by marking the queue as full
1078            when we do not have FIFO room for a maximum sized packet. */
1079         if (np->cur_tx - np->dirty_tx > TX_QUEUE_LEN ||
1080                 ((np->drv_flags & HasBrokenTx) && np->tx_q_bytes > TX_BUG_FIFO_LIMIT)) {
1081                 netif_stop_queue(dev);
1082                 wmb();
1083                 np->tx_full = 1;
1084         }
1085         spin_unlock_irq(&np->lock);
1086
1087         dev->trans_start = jiffies;
1088
1089         if (debug > 4) {
1090                 printk(KERN_DEBUG "%s: Transmit frame #%d queued in slot %d.\n",
1091                            dev->name, np->cur_tx, entry);
1092         }
1093         return 0;
1094 }
1095
1096 static void netdev_tx_done(struct net_device *dev)
1097 {
1098         struct netdev_private *np = netdev_priv(dev);
1099         for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
1100                 int entry = np->dirty_tx % TX_RING_SIZE;
1101                 int tx_status = np->tx_ring[entry].status;
1102
1103                 if (tx_status < 0)
1104                         break;
1105                 if (tx_status & 0x8000) {       /* There was an error, log it. */
1106 #ifndef final_version
1107                         if (debug > 1)
1108                                 printk(KERN_DEBUG "%s: Transmit error, Tx status %8.8x.\n",
1109                                            dev->name, tx_status);
1110 #endif
1111                         np->stats.tx_errors++;
1112                         if (tx_status & 0x0104) np->stats.tx_aborted_errors++;
1113                         if (tx_status & 0x0C80) np->stats.tx_carrier_errors++;
1114                         if (tx_status & 0x0200) np->stats.tx_window_errors++;
1115                         if (tx_status & 0x0002) np->stats.tx_fifo_errors++;
1116                         if ((tx_status & 0x0080) && np->mii_if.full_duplex == 0)
1117                                 np->stats.tx_heartbeat_errors++;
1118                 } else {
1119 #ifndef final_version
1120                         if (debug > 3)
1121                                 printk(KERN_DEBUG "%s: Transmit slot %d ok, Tx status %8.8x.\n",
1122                                            dev->name, entry, tx_status);
1123 #endif
1124                         np->stats.tx_bytes += np->tx_skbuff[entry]->len;
1125                         np->stats.collisions += (tx_status >> 3) & 15;
1126                         np->stats.tx_packets++;
1127                 }
1128                 /* Free the original skb. */
1129                 pci_unmap_single(np->pci_dev,np->tx_addr[entry],
1130                                         np->tx_skbuff[entry]->len,
1131                                         PCI_DMA_TODEVICE);
1132                 np->tx_q_bytes -= np->tx_skbuff[entry]->len;
1133                 dev_kfree_skb_irq(np->tx_skbuff[entry]);
1134                 np->tx_skbuff[entry] = NULL;
1135         }
1136         if (np->tx_full &&
1137                 np->cur_tx - np->dirty_tx < TX_QUEUE_LEN_RESTART &&
1138                 np->tx_q_bytes < TX_BUG_FIFO_LIMIT) {
1139                 /* The ring is no longer full, clear tbusy. */
1140                 np->tx_full = 0;
1141                 wmb();
1142                 netif_wake_queue(dev);
1143         }
1144 }
1145
1146 /* The interrupt handler does all of the Rx thread work and cleans up
1147    after the Tx thread. */
1148 static irqreturn_t intr_handler(int irq, void *dev_instance, struct pt_regs *rgs)
1149 {
1150         struct net_device *dev = (struct net_device *)dev_instance;
1151         struct netdev_private *np = netdev_priv(dev);
1152         void __iomem *ioaddr = np->base_addr;
1153         int work_limit = max_interrupt_work;
1154         int handled = 0;
1155
1156         if (!netif_device_present(dev))
1157                 return IRQ_NONE;
1158         do {
1159                 u32 intr_status = ioread32(ioaddr + IntrStatus);
1160
1161                 /* Acknowledge all of the current interrupt sources ASAP. */
1162                 iowrite32(intr_status & 0x001ffff, ioaddr + IntrStatus);
1163
1164                 if (debug > 4)
1165                         printk(KERN_DEBUG "%s: Interrupt, status %4.4x.\n",
1166                                    dev->name, intr_status);
1167
1168                 if ((intr_status & (NormalIntr|AbnormalIntr)) == 0)
1169                         break;
1170
1171                 handled = 1;
1172
1173                 if (intr_status & (IntrRxDone | RxNoBuf))
1174                         netdev_rx(dev);
1175                 if (intr_status & RxNoBuf)
1176                         iowrite32(0, ioaddr + RxStartDemand);
1177
1178                 if (intr_status & (TxIdle | IntrTxDone) &&
1179                         np->cur_tx != np->dirty_tx) {
1180                         spin_lock(&np->lock);
1181                         netdev_tx_done(dev);
1182                         spin_unlock(&np->lock);
1183                 }
1184
1185                 /* Abnormal error summary/uncommon events handlers. */
1186                 if (intr_status & (AbnormalIntr | TxFIFOUnderflow | IntrPCIErr |
1187                                                    TimerInt | IntrTxStopped))
1188                         netdev_error(dev, intr_status);
1189
1190                 if (--work_limit < 0) {
1191                         printk(KERN_WARNING "%s: Too much work at interrupt, "
1192                                    "status=0x%4.4x.\n", dev->name, intr_status);
1193                         /* Set the timer to re-enable the other interrupts after
1194                            10*82usec ticks. */
1195                         spin_lock(&np->lock);
1196                         if (netif_device_present(dev)) {
1197                                 iowrite32(AbnormalIntr | TimerInt, ioaddr + IntrEnable);
1198                                 iowrite32(10, ioaddr + GPTimer);
1199                         }
1200                         spin_unlock(&np->lock);
1201                         break;
1202                 }
1203         } while (1);
1204
1205         if (debug > 3)
1206                 printk(KERN_DEBUG "%s: exiting interrupt, status=%#4.4x.\n",
1207                            dev->name, ioread32(ioaddr + IntrStatus));
1208         return IRQ_RETVAL(handled);
1209 }
1210
1211 /* This routine is logically part of the interrupt handler, but separated
1212    for clarity and better register allocation. */
1213 static int netdev_rx(struct net_device *dev)
1214 {
1215         struct netdev_private *np = netdev_priv(dev);
1216         int entry = np->cur_rx % RX_RING_SIZE;
1217         int work_limit = np->dirty_rx + RX_RING_SIZE - np->cur_rx;
1218
1219         if (debug > 4) {
1220                 printk(KERN_DEBUG " In netdev_rx(), entry %d status %4.4x.\n",
1221                            entry, np->rx_ring[entry].status);
1222         }
1223
1224         /* If EOP is set on the next entry, it's a new packet. Send it up. */
1225         while (--work_limit >= 0) {
1226                 struct w840_rx_desc *desc = np->rx_head_desc;
1227                 s32 status = desc->status;
1228
1229                 if (debug > 4)
1230                         printk(KERN_DEBUG "  netdev_rx() status was %8.8x.\n",
1231                                    status);
1232                 if (status < 0)
1233                         break;
1234                 if ((status & 0x38008300) != 0x0300) {
1235                         if ((status & 0x38000300) != 0x0300) {
1236                                 /* Ingore earlier buffers. */
1237                                 if ((status & 0xffff) != 0x7fff) {
1238                                         printk(KERN_WARNING "%s: Oversized Ethernet frame spanned "
1239                                                    "multiple buffers, entry %#x status %4.4x!\n",
1240                                                    dev->name, np->cur_rx, status);
1241                                         np->stats.rx_length_errors++;
1242                                 }
1243                         } else if (status & 0x8000) {
1244                                 /* There was a fatal error. */
1245                                 if (debug > 2)
1246                                         printk(KERN_DEBUG "%s: Receive error, Rx status %8.8x.\n",
1247                                                    dev->name, status);
1248                                 np->stats.rx_errors++; /* end of a packet.*/
1249                                 if (status & 0x0890) np->stats.rx_length_errors++;
1250                                 if (status & 0x004C) np->stats.rx_frame_errors++;
1251                                 if (status & 0x0002) np->stats.rx_crc_errors++;
1252                         }
1253                 } else {
1254                         struct sk_buff *skb;
1255                         /* Omit the four octet CRC from the length. */
1256                         int pkt_len = ((status >> 16) & 0x7ff) - 4;
1257
1258 #ifndef final_version
1259                         if (debug > 4)
1260                                 printk(KERN_DEBUG "  netdev_rx() normal Rx pkt length %d"
1261                                            " status %x.\n", pkt_len, status);
1262 #endif
1263                         /* Check if the packet is long enough to accept without copying
1264                            to a minimally-sized skbuff. */
1265                         if (pkt_len < rx_copybreak
1266                                 && (skb = dev_alloc_skb(pkt_len + 2)) != NULL) {
1267                                 skb->dev = dev;
1268                                 skb_reserve(skb, 2);    /* 16 byte align the IP header */
1269                                 pci_dma_sync_single_for_cpu(np->pci_dev,np->rx_addr[entry],
1270                                                             np->rx_skbuff[entry]->len,
1271                                                             PCI_DMA_FROMDEVICE);
1272                                 eth_copy_and_sum(skb, np->rx_skbuff[entry]->data, pkt_len, 0);
1273                                 skb_put(skb, pkt_len);
1274                                 pci_dma_sync_single_for_device(np->pci_dev,np->rx_addr[entry],
1275                                                                np->rx_skbuff[entry]->len,
1276                                                                PCI_DMA_FROMDEVICE);
1277                         } else {
1278                                 pci_unmap_single(np->pci_dev,np->rx_addr[entry],
1279                                                         np->rx_skbuff[entry]->len,
1280                                                         PCI_DMA_FROMDEVICE);
1281                                 skb_put(skb = np->rx_skbuff[entry], pkt_len);
1282                                 np->rx_skbuff[entry] = NULL;
1283                         }
1284 #ifndef final_version                           /* Remove after testing. */
1285                         /* You will want this info for the initial debug. */
1286                         if (debug > 5)
1287                                 printk(KERN_DEBUG "  Rx data %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:"
1288                                            "%2.2x %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x %2.2x%2.2x "
1289                                            "%d.%d.%d.%d.\n",
1290                                            skb->data[0], skb->data[1], skb->data[2], skb->data[3],
1291                                            skb->data[4], skb->data[5], skb->data[6], skb->data[7],
1292                                            skb->data[8], skb->data[9], skb->data[10],
1293                                            skb->data[11], skb->data[12], skb->data[13],
1294                                            skb->data[14], skb->data[15], skb->data[16],
1295                                            skb->data[17]);
1296 #endif
1297                         skb->protocol = eth_type_trans(skb, dev);
1298                         netif_rx(skb);
1299                         dev->last_rx = jiffies;
1300                         np->stats.rx_packets++;
1301                         np->stats.rx_bytes += pkt_len;
1302                 }
1303                 entry = (++np->cur_rx) % RX_RING_SIZE;
1304                 np->rx_head_desc = &np->rx_ring[entry];
1305         }
1306
1307         /* Refill the Rx ring buffers. */
1308         for (; np->cur_rx - np->dirty_rx > 0; np->dirty_rx++) {
1309                 struct sk_buff *skb;
1310                 entry = np->dirty_rx % RX_RING_SIZE;
1311                 if (np->rx_skbuff[entry] == NULL) {
1312                         skb = dev_alloc_skb(np->rx_buf_sz);
1313                         np->rx_skbuff[entry] = skb;
1314                         if (skb == NULL)
1315                                 break;                  /* Better luck next round. */
1316                         skb->dev = dev;                 /* Mark as being used by this device. */
1317                         np->rx_addr[entry] = pci_map_single(np->pci_dev,
1318                                                         skb->data,
1319                                                         np->rx_buf_sz, PCI_DMA_FROMDEVICE);
1320                         np->rx_ring[entry].buffer1 = np->rx_addr[entry];
1321                 }
1322                 wmb();
1323                 np->rx_ring[entry].status = DescOwn;
1324         }
1325
1326         return 0;
1327 }
1328
1329 static void netdev_error(struct net_device *dev, int intr_status)
1330 {
1331         struct netdev_private *np = netdev_priv(dev);
1332         void __iomem *ioaddr = np->base_addr;
1333
1334         if (debug > 2)
1335                 printk(KERN_DEBUG "%s: Abnormal event, %8.8x.\n",
1336                            dev->name, intr_status);
1337         if (intr_status == 0xffffffff)
1338                 return;
1339         spin_lock(&np->lock);
1340         if (intr_status & TxFIFOUnderflow) {
1341                 int new;
1342                 /* Bump up the Tx threshold */
1343 #if 0
1344                 /* This causes lots of dropped packets,
1345                  * and under high load even tx_timeouts
1346                  */
1347                 new = np->csr6 + 0x4000;
1348 #else
1349                 new = (np->csr6 >> 14)&0x7f;
1350                 if (new < 64)
1351                         new *= 2;
1352                  else
1353                         new = 127; /* load full packet before starting */
1354                 new = (np->csr6 & ~(0x7F << 14)) | (new<<14);
1355 #endif
1356                 printk(KERN_DEBUG "%s: Tx underflow, new csr6 %8.8x.\n",
1357                            dev->name, new);
1358                 update_csr6(dev, new);
1359         }
1360         if (intr_status & IntrRxDied) {         /* Missed a Rx frame. */
1361                 np->stats.rx_errors++;
1362         }
1363         if (intr_status & TimerInt) {
1364                 /* Re-enable other interrupts. */
1365                 if (netif_device_present(dev))
1366                         iowrite32(0x1A0F5, ioaddr + IntrEnable);
1367         }
1368         np->stats.rx_missed_errors += ioread32(ioaddr + RxMissed) & 0xffff;
1369         iowrite32(0, ioaddr + RxStartDemand);
1370         spin_unlock(&np->lock);
1371 }
1372
1373 static struct net_device_stats *get_stats(struct net_device *dev)
1374 {
1375         struct netdev_private *np = netdev_priv(dev);
1376         void __iomem *ioaddr = np->base_addr;
1377
1378         /* The chip only need report frame silently dropped. */
1379         spin_lock_irq(&np->lock);
1380         if (netif_running(dev) && netif_device_present(dev))
1381                 np->stats.rx_missed_errors += ioread32(ioaddr + RxMissed) & 0xffff;
1382         spin_unlock_irq(&np->lock);
1383
1384         return &np->stats;
1385 }
1386
1387
1388 static u32 __set_rx_mode(struct net_device *dev)
1389 {
1390         struct netdev_private *np = netdev_priv(dev);
1391         void __iomem *ioaddr = np->base_addr;
1392         u32 mc_filter[2];                       /* Multicast hash filter */
1393         u32 rx_mode;
1394
1395         if (dev->flags & IFF_PROMISC) {                 /* Set promiscuous. */
1396                 /* Unconditionally log net taps. */
1397                 printk(KERN_NOTICE "%s: Promiscuous mode enabled.\n", dev->name);
1398                 memset(mc_filter, 0xff, sizeof(mc_filter));
1399                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptAllPhys
1400                         | AcceptMyPhys;
1401         } else if ((dev->mc_count > multicast_filter_limit)
1402                            ||  (dev->flags & IFF_ALLMULTI)) {
1403                 /* Too many to match, or accept all multicasts. */
1404                 memset(mc_filter, 0xff, sizeof(mc_filter));
1405                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
1406         } else {
1407                 struct dev_mc_list *mclist;
1408                 int i;
1409                 memset(mc_filter, 0, sizeof(mc_filter));
1410                 for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
1411                          i++, mclist = mclist->next) {
1412                         int filterbit = (ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26) ^ 0x3F;
1413                         filterbit &= 0x3f;
1414                         mc_filter[filterbit >> 5] |= 1 << (filterbit & 31);
1415                 }
1416                 rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
1417         }
1418         iowrite32(mc_filter[0], ioaddr + MulticastFilter0);
1419         iowrite32(mc_filter[1], ioaddr + MulticastFilter1);
1420         return rx_mode;
1421 }
1422
1423 static void set_rx_mode(struct net_device *dev)
1424 {
1425         struct netdev_private *np = netdev_priv(dev);
1426         u32 rx_mode = __set_rx_mode(dev);
1427         spin_lock_irq(&np->lock);
1428         update_csr6(dev, (np->csr6 & ~0x00F8) | rx_mode);
1429         spin_unlock_irq(&np->lock);
1430 }
1431
1432 static void netdev_get_drvinfo (struct net_device *dev, struct ethtool_drvinfo *info)
1433 {
1434         struct netdev_private *np = netdev_priv(dev);
1435
1436         strcpy (info->driver, DRV_NAME);
1437         strcpy (info->version, DRV_VERSION);
1438         strcpy (info->bus_info, pci_name(np->pci_dev));
1439 }
1440
1441 static int netdev_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1442 {
1443         struct netdev_private *np = netdev_priv(dev);
1444         int rc;
1445
1446         spin_lock_irq(&np->lock);
1447         rc = mii_ethtool_gset(&np->mii_if, cmd);
1448         spin_unlock_irq(&np->lock);
1449
1450         return rc;
1451 }
1452
1453 static int netdev_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1454 {
1455         struct netdev_private *np = netdev_priv(dev);
1456         int rc;
1457
1458         spin_lock_irq(&np->lock);
1459         rc = mii_ethtool_sset(&np->mii_if, cmd);
1460         spin_unlock_irq(&np->lock);
1461
1462         return rc;
1463 }
1464
1465 static int netdev_nway_reset(struct net_device *dev)
1466 {
1467         struct netdev_private *np = netdev_priv(dev);
1468         return mii_nway_restart(&np->mii_if);
1469 }
1470
1471 static u32 netdev_get_link(struct net_device *dev)
1472 {
1473         struct netdev_private *np = netdev_priv(dev);
1474         return mii_link_ok(&np->mii_if);
1475 }
1476
1477 static u32 netdev_get_msglevel(struct net_device *dev)
1478 {
1479         return debug;
1480 }
1481
1482 static void netdev_set_msglevel(struct net_device *dev, u32 value)
1483 {
1484         debug = value;
1485 }
1486
1487 static struct ethtool_ops netdev_ethtool_ops = {
1488         .get_drvinfo            = netdev_get_drvinfo,
1489         .get_settings           = netdev_get_settings,
1490         .set_settings           = netdev_set_settings,
1491         .nway_reset             = netdev_nway_reset,
1492         .get_link               = netdev_get_link,
1493         .get_msglevel           = netdev_get_msglevel,
1494         .set_msglevel           = netdev_set_msglevel,
1495         .get_sg                 = ethtool_op_get_sg,
1496         .get_tx_csum            = ethtool_op_get_tx_csum,
1497 };
1498
1499 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
1500 {
1501         struct mii_ioctl_data *data = if_mii(rq);
1502         struct netdev_private *np = netdev_priv(dev);
1503
1504         switch(cmd) {
1505         case SIOCGMIIPHY:               /* Get address of MII PHY in use. */
1506                 data->phy_id = ((struct netdev_private *)netdev_priv(dev))->phys[0] & 0x1f;
1507                 /* Fall Through */
1508
1509         case SIOCGMIIREG:               /* Read MII PHY register. */
1510                 spin_lock_irq(&np->lock);
1511                 data->val_out = mdio_read(dev, data->phy_id & 0x1f, data->reg_num & 0x1f);
1512                 spin_unlock_irq(&np->lock);
1513                 return 0;
1514
1515         case SIOCSMIIREG:               /* Write MII PHY register. */
1516                 if (!capable(CAP_NET_ADMIN))
1517                         return -EPERM;
1518                 spin_lock_irq(&np->lock);
1519                 mdio_write(dev, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in);
1520                 spin_unlock_irq(&np->lock);
1521                 return 0;
1522         default:
1523                 return -EOPNOTSUPP;
1524         }
1525 }
1526
1527 static int netdev_close(struct net_device *dev)
1528 {
1529         struct netdev_private *np = netdev_priv(dev);
1530         void __iomem *ioaddr = np->base_addr;
1531
1532         netif_stop_queue(dev);
1533
1534         if (debug > 1) {
1535                 printk(KERN_DEBUG "%s: Shutting down ethercard, status was %8.8x "
1536                            "Config %8.8x.\n", dev->name, ioread32(ioaddr + IntrStatus),
1537                            ioread32(ioaddr + NetworkConfig));
1538                 printk(KERN_DEBUG "%s: Queue pointers were Tx %d / %d,  Rx %d / %d.\n",
1539                            dev->name, np->cur_tx, np->dirty_tx, np->cur_rx, np->dirty_rx);
1540         }
1541
1542         /* Stop the chip's Tx and Rx processes. */
1543         spin_lock_irq(&np->lock);
1544         netif_device_detach(dev);
1545         update_csr6(dev, 0);
1546         iowrite32(0x0000, ioaddr + IntrEnable);
1547         spin_unlock_irq(&np->lock);
1548
1549         free_irq(dev->irq, dev);
1550         wmb();
1551         netif_device_attach(dev);
1552
1553         if (ioread32(ioaddr + NetworkConfig) != 0xffffffff)
1554                 np->stats.rx_missed_errors += ioread32(ioaddr + RxMissed) & 0xffff;
1555
1556 #ifdef __i386__
1557         if (debug > 2) {
1558                 int i;
1559
1560                 printk(KERN_DEBUG"  Tx ring at %8.8x:\n",
1561                            (int)np->tx_ring);
1562                 for (i = 0; i < TX_RING_SIZE; i++)
1563                         printk(KERN_DEBUG " #%d desc. %4.4x %4.4x %8.8x.\n",
1564                                    i, np->tx_ring[i].length,
1565                                    np->tx_ring[i].status, np->tx_ring[i].buffer1);
1566                 printk("\n"KERN_DEBUG "  Rx ring %8.8x:\n",
1567                            (int)np->rx_ring);
1568                 for (i = 0; i < RX_RING_SIZE; i++) {
1569                         printk(KERN_DEBUG " #%d desc. %4.4x %4.4x %8.8x\n",
1570                                    i, np->rx_ring[i].length,
1571                                    np->rx_ring[i].status, np->rx_ring[i].buffer1);
1572                 }
1573         }
1574 #endif /* __i386__ debugging only */
1575
1576         del_timer_sync(&np->timer);
1577
1578         free_rxtx_rings(np);
1579         free_ringdesc(np);
1580
1581         return 0;
1582 }
1583
1584 static void __devexit w840_remove1 (struct pci_dev *pdev)
1585 {
1586         struct net_device *dev = pci_get_drvdata(pdev);
1587         
1588         if (dev) {
1589                 struct netdev_private *np = netdev_priv(dev);
1590                 unregister_netdev(dev);
1591                 pci_release_regions(pdev);
1592                 pci_iounmap(pdev, np->base_addr);
1593                 free_netdev(dev);
1594         }
1595
1596         pci_set_drvdata(pdev, NULL);
1597 }
1598
1599 #ifdef CONFIG_PM
1600
1601 /*
1602  * suspend/resume synchronization:
1603  * - open, close, do_ioctl:
1604  *      rtnl_lock, & netif_device_detach after the rtnl_unlock.
1605  * - get_stats:
1606  *      spin_lock_irq(np->lock), doesn't touch hw if not present
1607  * - hard_start_xmit:
1608  *      netif_stop_queue + spin_unlock_wait(&dev->xmit_lock);
1609  * - tx_timeout:
1610  *      netif_device_detach + spin_unlock_wait(&dev->xmit_lock);
1611  * - set_multicast_list
1612  *      netif_device_detach + spin_unlock_wait(&dev->xmit_lock);
1613  * - interrupt handler
1614  *      doesn't touch hw if not present, synchronize_irq waits for
1615  *      running instances of the interrupt handler.
1616  *
1617  * Disabling hw requires clearing csr6 & IntrEnable.
1618  * update_csr6 & all function that write IntrEnable check netif_device_present
1619  * before settings any bits.
1620  *
1621  * Detach must occur under spin_unlock_irq(), interrupts from a detached
1622  * device would cause an irq storm.
1623  */
1624 static int w840_suspend (struct pci_dev *pdev, pm_message_t state)
1625 {
1626         struct net_device *dev = pci_get_drvdata (pdev);
1627         struct netdev_private *np = netdev_priv(dev);
1628         void __iomem *ioaddr = np->base_addr;
1629
1630         rtnl_lock();
1631         if (netif_running (dev)) {
1632                 del_timer_sync(&np->timer);
1633
1634                 spin_lock_irq(&np->lock);
1635                 netif_device_detach(dev);
1636                 update_csr6(dev, 0);
1637                 iowrite32(0, ioaddr + IntrEnable);
1638                 netif_stop_queue(dev);
1639                 spin_unlock_irq(&np->lock);
1640
1641                 spin_unlock_wait(&dev->xmit_lock);
1642                 synchronize_irq(dev->irq);
1643         
1644                 np->stats.rx_missed_errors += ioread32(ioaddr + RxMissed) & 0xffff;
1645
1646                 /* no more hardware accesses behind this line. */
1647
1648                 BUG_ON(np->csr6);
1649                 if (ioread32(ioaddr + IntrEnable)) BUG();
1650
1651                 /* pci_power_off(pdev, -1); */
1652
1653                 free_rxtx_rings(np);
1654         } else {
1655                 netif_device_detach(dev);
1656         }
1657         rtnl_unlock();
1658         return 0;
1659 }
1660
1661 static int w840_resume (struct pci_dev *pdev)
1662 {
1663         struct net_device *dev = pci_get_drvdata (pdev);
1664         struct netdev_private *np = netdev_priv(dev);
1665
1666         rtnl_lock();
1667         if (netif_device_present(dev))
1668                 goto out; /* device not suspended */
1669         if (netif_running(dev)) {
1670                 pci_enable_device(pdev);
1671         /*      pci_power_on(pdev); */
1672
1673                 spin_lock_irq(&np->lock);
1674                 iowrite32(1, np->base_addr+PCIBusCfg);
1675                 ioread32(np->base_addr+PCIBusCfg);
1676                 udelay(1);
1677                 netif_device_attach(dev);
1678                 init_rxtx_rings(dev);
1679                 init_registers(dev);
1680                 spin_unlock_irq(&np->lock);
1681
1682                 netif_wake_queue(dev);
1683
1684                 mod_timer(&np->timer, jiffies + 1*HZ);
1685         } else {
1686                 netif_device_attach(dev);
1687         }
1688 out:
1689         rtnl_unlock();
1690         return 0;
1691 }
1692 #endif
1693
1694 static struct pci_driver w840_driver = {
1695         .name           = DRV_NAME,
1696         .id_table       = w840_pci_tbl,
1697         .probe          = w840_probe1,
1698         .remove         = __devexit_p(w840_remove1),
1699 #ifdef CONFIG_PM
1700         .suspend        = w840_suspend,
1701         .resume         = w840_resume,
1702 #endif
1703 };
1704
1705 static int __init w840_init(void)
1706 {
1707         printk(version);
1708         return pci_module_init(&w840_driver);
1709 }
1710
1711 static void __exit w840_exit(void)
1712 {
1713         pci_unregister_driver(&w840_driver);
1714 }
1715
1716 module_init(w840_init);
1717 module_exit(w840_exit);