patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / net / natsemi.c
1 /* natsemi.c: A Linux PCI Ethernet driver for the NatSemi DP8381x series. */
2 /*
3         Written/copyright 1999-2001 by Donald Becker.
4         Portions copyright (c) 2001,2002 Sun Microsystems (thockin@sun.com)
5         Portions copyright 2001,2002 Manfred Spraul (manfred@colorfullife.com)
6
7         This software may be used and distributed according to the terms of
8         the GNU General Public License (GPL), incorporated herein by reference.
9         Drivers based on or derived from this code fall under the GPL and must
10         retain the authorship, copyright and license notice.  This file is not
11         a complete program and may only be used when the entire operating
12         system is licensed under the GPL.  License for under other terms may be
13         available.  Contact the original author for details.
14
15         The original author may be reached as becker@scyld.com, or at
16         Scyld Computing Corporation
17         410 Severn Ave., Suite 210
18         Annapolis MD 21403
19
20         Support information and updates available at
21         http://www.scyld.com/network/netsemi.html
22
23
24         Linux kernel modifications:
25
26         Version 1.0.1:
27                 - Spinlock fixes
28                 - Bug fixes and better intr performance (Tjeerd)
29         Version 1.0.2:
30                 - Now reads correct MAC address from eeprom
31         Version 1.0.3:
32                 - Eliminate redundant priv->tx_full flag
33                 - Call netif_start_queue from dev->tx_timeout
34                 - wmb() in start_tx() to flush data
35                 - Update Tx locking
36                 - Clean up PCI enable (davej)
37         Version 1.0.4:
38                 - Merge Donald Becker's natsemi.c version 1.07
39         Version 1.0.5:
40                 - { fill me in }
41         Version 1.0.6:
42                 * ethtool support (jgarzik)
43                 * Proper initialization of the card (which sometimes
44                 fails to occur and leaves the card in a non-functional
45                 state). (uzi)
46
47                 * Some documented register settings to optimize some
48                 of the 100Mbit autodetection circuitry in rev C cards. (uzi)
49
50                 * Polling of the PHY intr for stuff like link state
51                 change and auto- negotiation to finally work properly. (uzi)
52
53                 * One-liner removal of a duplicate declaration of
54                 netdev_error(). (uzi)
55
56         Version 1.0.7: (Manfred Spraul)
57                 * pci dma
58                 * SMP locking update
59                 * full reset added into tx_timeout
60                 * correct multicast hash generation (both big and little endian)
61                         [copied from a natsemi driver version
62                          from Myrio Corporation, Greg Smith]
63                 * suspend/resume
64
65         version 1.0.8 (Tim Hockin <thockin@sun.com>)
66                 * ETHTOOL_* support
67                 * Wake on lan support (Erik Gilling)
68                 * MXDMA fixes for serverworks
69                 * EEPROM reload
70
71         version 1.0.9 (Manfred Spraul)
72                 * Main change: fix lack of synchronize
73                 netif_close/netif_suspend against a last interrupt
74                 or packet.
75                 * do not enable superflous interrupts (e.g. the
76                 drivers relies on TxDone - TxIntr not needed)
77                 * wait that the hardware has really stopped in close
78                 and suspend.
79                 * workaround for the (at least) gcc-2.95.1 compiler
80                 problem. Also simplifies the code a bit.
81                 * disable_irq() in tx_timeout - needed to protect
82                 against rx interrupts.
83                 * stop the nic before switching into silent rx mode
84                 for wol (required according to docu).
85
86         version 1.0.10:
87                 * use long for ee_addr (various)
88                 * print pointers properly (DaveM)
89                 * include asm/irq.h (?)
90
91         version 1.0.11:
92                 * check and reset if PHY errors appear (Adrian Sun)
93                 * WoL cleanup (Tim Hockin)
94                 * Magic number cleanup (Tim Hockin)
95                 * Don't reload EEPROM on every reset (Tim Hockin)
96                 * Save and restore EEPROM state across reset (Tim Hockin)
97                 * MDIO Cleanup (Tim Hockin)
98                 * Reformat register offsets/bits (jgarzik)
99
100         version 1.0.12:
101                 * ETHTOOL_* further support (Tim Hockin)
102
103         version 1.0.13:
104                 * ETHTOOL_[G]EEPROM support (Tim Hockin)
105
106         version 1.0.13:
107                 * crc cleanup (Matt Domsch <Matt_Domsch@dell.com>)
108
109         version 1.0.14:
110                 * Cleanup some messages and autoneg in ethtool (Tim Hockin)
111
112         version 1.0.15:
113                 * Get rid of cable_magic flag
114                 * use new (National provided) solution for cable magic issue
115
116         version 1.0.16:
117                 * call netdev_rx() for RxErrors (Manfred Spraul)
118                 * formatting and cleanups
119                 * change options and full_duplex arrays to be zero
120                   initialized
121                 * enable only the WoL and PHY interrupts in wol mode
122
123         version 1.0.17:
124                 * only do cable_magic on 83815 and early 83816 (Tim Hockin)
125                 * create a function for rx refill (Manfred Spraul)
126                 * combine drain_ring and init_ring (Manfred Spraul)
127                 * oom handling (Manfred Spraul)
128                 * hands_off instead of playing with netif_device_{de,a}ttach
129                   (Manfred Spraul)
130                 * be sure to write the MAC back to the chip (Manfred Spraul)
131                 * lengthen EEPROM timeout, and always warn about timeouts
132                   (Manfred Spraul)
133                 * comments update (Manfred)
134                 * do the right thing on a phy-reset (Manfred and Tim)
135
136         TODO:
137         * big endian support with CFG:BEM instead of cpu_to_le32
138         * support for an external PHY
139         * NAPI
140 */
141
142 #if !defined(__OPTIMIZE__)
143 #warning  You must compile this file with the correct options!
144 #warning  See the last lines of the source file.
145 #error You must compile this driver with "-O".
146 #endif
147
148 #include <linux/config.h>
149 #include <linux/module.h>
150 #include <linux/kernel.h>
151 #include <linux/string.h>
152 #include <linux/timer.h>
153 #include <linux/errno.h>
154 #include <linux/ioport.h>
155 #include <linux/slab.h>
156 #include <linux/interrupt.h>
157 #include <linux/pci.h>
158 #include <linux/netdevice.h>
159 #include <linux/etherdevice.h>
160 #include <linux/skbuff.h>
161 #include <linux/init.h>
162 #include <linux/spinlock.h>
163 #include <linux/ethtool.h>
164 #include <linux/delay.h>
165 #include <linux/rtnetlink.h>
166 #include <linux/mii.h>
167 #include <linux/crc32.h>
168 #include <asm/processor.h>      /* Processor type for cache alignment. */
169 #include <asm/bitops.h>
170 #include <asm/io.h>
171 #include <asm/irq.h>
172 #include <asm/uaccess.h>
173
174 #define DRV_NAME        "natsemi"
175 #define DRV_VERSION     "1.07+LK1.0.17"
176 #define DRV_RELDATE     "Sep 27, 2002"
177
178 #define RX_OFFSET       2
179
180 /* Updated to recommendations in pci-skeleton v2.03. */
181
182 /* The user-configurable values.
183    These may be modified when a driver module is loaded.*/
184
185 #define NATSEMI_DEF_MSG         (NETIF_MSG_DRV          | \
186                                  NETIF_MSG_LINK         | \
187                                  NETIF_MSG_WOL          | \
188                                  NETIF_MSG_RX_ERR       | \
189                                  NETIF_MSG_TX_ERR)
190 static int debug = -1;
191
192 /* Maximum events (Rx packets, etc.) to handle at each interrupt. */
193 static int max_interrupt_work = 20;
194 static int mtu;
195
196 /* Maximum number of multicast addresses to filter (vs. rx-all-multicast).
197    This chip uses a 512 element hash table based on the Ethernet CRC.  */
198 static int multicast_filter_limit = 100;
199
200 /* Set the copy breakpoint for the copy-only-tiny-frames scheme.
201    Setting to > 1518 effectively disables this feature. */
202 static int rx_copybreak;
203
204 /* Used to pass the media type, etc.
205    Both 'options[]' and 'full_duplex[]' should exist for driver
206    interoperability.
207    The media type is usually passed in 'options[]'.
208 */
209 #define MAX_UNITS 8             /* More are supported, limit only on options */
210 static int options[MAX_UNITS];
211 static int full_duplex[MAX_UNITS];
212
213 /* Operational parameters that are set at compile time. */
214
215 /* Keep the ring sizes a power of two for compile efficiency.
216    The compiler will convert <unsigned>'%'<2^N> into a bit mask.
217    Making the Tx ring too large decreases the effectiveness of channel
218    bonding and packet priority.
219    There are no ill effects from too-large receive rings. */
220 #define TX_RING_SIZE    16
221 #define TX_QUEUE_LEN    10 /* Limit ring entries actually used, min 4. */
222 #define RX_RING_SIZE    32
223
224 /* Operational parameters that usually are not changed. */
225 /* Time in jiffies before concluding the transmitter is hung. */
226 #define TX_TIMEOUT  (2*HZ)
227
228 #define NATSEMI_HW_TIMEOUT      400
229 #define NATSEMI_TIMER_FREQ      3*HZ
230 #define NATSEMI_PG0_NREGS       64
231 #define NATSEMI_RFDR_NREGS      8
232 #define NATSEMI_PG1_NREGS       4
233 #define NATSEMI_NREGS           (NATSEMI_PG0_NREGS + NATSEMI_RFDR_NREGS + \
234                                  NATSEMI_PG1_NREGS)
235 #define NATSEMI_REGS_VER        1 /* v1 added RFDR registers */
236 #define NATSEMI_REGS_SIZE       (NATSEMI_NREGS * sizeof(u32))
237 #define NATSEMI_EEPROM_SIZE     24 /* 12 16-bit values */
238
239 #define PKT_BUF_SZ              1536 /* Size of each temporary Rx buffer. */
240
241 /* These identify the driver base version and may not be removed. */
242 static char version[] __devinitdata =
243   KERN_INFO DRV_NAME " dp8381x driver, version "
244       DRV_VERSION ", " DRV_RELDATE "\n"
245   KERN_INFO "  originally by Donald Becker <becker@scyld.com>\n"
246   KERN_INFO "  http://www.scyld.com/network/natsemi.html\n"
247   KERN_INFO "  2.4.x kernel port by Jeff Garzik, Tjeerd Mulder\n";
248
249 MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
250 MODULE_DESCRIPTION("National Semiconductor DP8381x series PCI Ethernet driver");
251 MODULE_LICENSE("GPL");
252
253 MODULE_PARM(max_interrupt_work, "i");
254 MODULE_PARM(mtu, "i");
255 MODULE_PARM(debug, "i");
256 MODULE_PARM(rx_copybreak, "i");
257 MODULE_PARM(options, "1-" __MODULE_STRING(MAX_UNITS) "i");
258 MODULE_PARM(full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
259 MODULE_PARM_DESC(max_interrupt_work, 
260         "DP8381x maximum events handled per interrupt");
261 MODULE_PARM_DESC(mtu, "DP8381x MTU (all boards)");
262 MODULE_PARM_DESC(debug, "DP8381x default debug level");
263 MODULE_PARM_DESC(rx_copybreak, 
264         "DP8381x copy breakpoint for copy-only-tiny-frames");
265 MODULE_PARM_DESC(options, 
266         "DP8381x: Bits 0-3: media type, bit 17: full duplex");
267 MODULE_PARM_DESC(full_duplex, "DP8381x full duplex setting(s) (1)");
268
269 /*
270                                 Theory of Operation
271
272 I. Board Compatibility
273
274 This driver is designed for National Semiconductor DP83815 PCI Ethernet NIC.
275 It also works with other chips in in the DP83810 series.
276
277 II. Board-specific settings
278
279 This driver requires the PCI interrupt line to be valid.
280 It honors the EEPROM-set values.
281
282 III. Driver operation
283
284 IIIa. Ring buffers
285
286 This driver uses two statically allocated fixed-size descriptor lists
287 formed into rings by a branch from the final descriptor to the beginning of
288 the list.  The ring sizes are set at compile time by RX/TX_RING_SIZE.
289 The NatSemi design uses a 'next descriptor' pointer that the driver forms
290 into a list.
291
292 IIIb/c. Transmit/Receive Structure
293
294 This driver uses a zero-copy receive and transmit scheme.
295 The driver allocates full frame size skbuffs for the Rx ring buffers at
296 open() time and passes the skb->data field to the chip as receive data
297 buffers.  When an incoming frame is less than RX_COPYBREAK bytes long,
298 a fresh skbuff is allocated and the frame is copied to the new skbuff.
299 When the incoming frame is larger, the skbuff is passed directly up the
300 protocol stack.  Buffers consumed this way are replaced by newly allocated
301 skbuffs in a later phase of receives.
302
303 The RX_COPYBREAK value is chosen to trade-off the memory wasted by
304 using a full-sized skbuff for small frames vs. the copying costs of larger
305 frames.  New boards are typically used in generously configured machines
306 and the underfilled buffers have negligible impact compared to the benefit of
307 a single allocation size, so the default value of zero results in never
308 copying packets.  When copying is done, the cost is usually mitigated by using
309 a combined copy/checksum routine.  Copying also preloads the cache, which is
310 most useful with small frames.
311
312 A subtle aspect of the operation is that unaligned buffers are not permitted
313 by the hardware.  Thus the IP header at offset 14 in an ethernet frame isn't
314 longword aligned for further processing.  On copies frames are put into the
315 skbuff at an offset of "+2", 16-byte aligning the IP header.
316
317 IIId. Synchronization
318
319 Most operations are synchronized on the np->lock irq spinlock, except the
320 performance critical codepaths:
321
322 The rx process only runs in the interrupt handler. Access from outside
323 the interrupt handler is only permitted after disable_irq().
324
325 The rx process usually runs under the dev->xmit_lock. If np->intr_tx_reap
326 is set, then access is permitted under spin_lock_irq(&np->lock).
327
328 Thus configuration functions that want to access everything must call
329         disable_irq(dev->irq);
330         spin_lock_bh(dev->xmit_lock);
331         spin_lock_irq(&np->lock);
332
333 IV. Notes
334
335 NatSemi PCI network controllers are very uncommon.
336
337 IVb. References
338
339 http://www.scyld.com/expert/100mbps.html
340 http://www.scyld.com/expert/NWay.html
341 Datasheet is available from:
342 http://www.national.com/pf/DP/DP83815.html
343
344 IVc. Errata
345
346 None characterised.
347 */
348
349
350
351 enum pcistuff {
352         PCI_USES_IO = 0x01,
353         PCI_USES_MEM = 0x02,
354         PCI_USES_MASTER = 0x04,
355         PCI_ADDR0 = 0x08,
356         PCI_ADDR1 = 0x10,
357 };
358
359 /* MMIO operations required */
360 #define PCI_IOTYPE (PCI_USES_MASTER | PCI_USES_MEM | PCI_ADDR1)
361
362
363 /* array of board data directly indexed by pci_tbl[x].driver_data */
364 static struct {
365         const char *name;
366         unsigned long flags;
367 } natsemi_pci_info[] __devinitdata = {
368         { "NatSemi DP8381[56]", PCI_IOTYPE },
369 };
370
371 static struct pci_device_id natsemi_pci_tbl[] = {
372         { PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_83815, PCI_ANY_ID, PCI_ANY_ID, },
373         { 0, },
374 };
375 MODULE_DEVICE_TABLE(pci, natsemi_pci_tbl);
376
377 /* Offsets to the device registers.
378    Unlike software-only systems, device drivers interact with complex hardware.
379    It's not useful to define symbolic names for every register bit in the
380    device.
381 */
382 enum register_offsets {
383         ChipCmd                 = 0x00,
384         ChipConfig              = 0x04,
385         EECtrl                  = 0x08,
386         PCIBusCfg               = 0x0C,
387         IntrStatus              = 0x10,
388         IntrMask                = 0x14,
389         IntrEnable              = 0x18,
390         IntrHoldoff             = 0x1C, /* DP83816 only */
391         TxRingPtr               = 0x20,
392         TxConfig                = 0x24,
393         RxRingPtr               = 0x30,
394         RxConfig                = 0x34,
395         ClkRun                  = 0x3C,
396         WOLCmd                  = 0x40,
397         PauseCmd                = 0x44,
398         RxFilterAddr            = 0x48,
399         RxFilterData            = 0x4C,
400         BootRomAddr             = 0x50,
401         BootRomData             = 0x54,
402         SiliconRev              = 0x58,
403         StatsCtrl               = 0x5C,
404         StatsData               = 0x60,
405         RxPktErrs               = 0x60,
406         RxMissed                = 0x68,
407         RxCRCErrs               = 0x64,
408         BasicControl            = 0x80,
409         BasicStatus             = 0x84,
410         AnegAdv                 = 0x90,
411         AnegPeer                = 0x94,
412         PhyStatus               = 0xC0,
413         MIntrCtrl               = 0xC4,
414         MIntrStatus             = 0xC8,
415         PhyCtrl                 = 0xE4,
416
417         /* These are from the spec, around page 78... on a separate table.
418          * The meaning of these registers depend on the value of PGSEL. */
419         PGSEL                   = 0xCC,
420         PMDCSR                  = 0xE4,
421         TSTDAT                  = 0xFC,
422         DSPCFG                  = 0xF4,
423         SDCFG                   = 0xF8
424 };
425 /* the values for the 'magic' registers above (PGSEL=1) */
426 #define PMDCSR_VAL      0x189c  /* enable preferred adaptation circuitry */
427 #define TSTDAT_VAL      0x0
428 #define DSPCFG_VAL      0x5040
429 #define SDCFG_VAL       0x008c  /* set voltage thresholds for Signal Detect */
430 #define DSPCFG_LOCK     0x20    /* coefficient lock bit in DSPCFG */
431 #define TSTDAT_FIXED    0xe8    /* magic number for bad coefficients */
432
433 /* misc PCI space registers */
434 enum pci_register_offsets {
435         PCIPM                   = 0x44,
436 };
437
438 enum ChipCmd_bits {
439         ChipReset               = 0x100,
440         RxReset                 = 0x20,
441         TxReset                 = 0x10,
442         RxOff                   = 0x08,
443         RxOn                    = 0x04,
444         TxOff                   = 0x02,
445         TxOn                    = 0x01,
446 };
447
448 enum ChipConfig_bits {
449         CfgPhyDis               = 0x200,
450         CfgPhyRst               = 0x400,
451         CfgExtPhy               = 0x1000,
452         CfgAnegEnable           = 0x2000,
453         CfgAneg100              = 0x4000,
454         CfgAnegFull             = 0x8000,
455         CfgAnegDone             = 0x8000000,
456         CfgFullDuplex           = 0x20000000,
457         CfgSpeed100             = 0x40000000,
458         CfgLink                 = 0x80000000,
459 };
460
461 enum EECtrl_bits {
462         EE_ShiftClk             = 0x04,
463         EE_DataIn               = 0x01,
464         EE_ChipSelect           = 0x08,
465         EE_DataOut              = 0x02,
466 };
467
468 enum PCIBusCfg_bits {
469         EepromReload            = 0x4,
470 };
471
472 /* Bits in the interrupt status/mask registers. */
473 enum IntrStatus_bits {
474         IntrRxDone              = 0x0001,
475         IntrRxIntr              = 0x0002,
476         IntrRxErr               = 0x0004,
477         IntrRxEarly             = 0x0008,
478         IntrRxIdle              = 0x0010,
479         IntrRxOverrun           = 0x0020,
480         IntrTxDone              = 0x0040,
481         IntrTxIntr              = 0x0080,
482         IntrTxErr               = 0x0100,
483         IntrTxIdle              = 0x0200,
484         IntrTxUnderrun          = 0x0400,
485         StatsMax                = 0x0800,
486         SWInt                   = 0x1000,
487         WOLPkt                  = 0x2000,
488         LinkChange              = 0x4000,
489         IntrHighBits            = 0x8000,
490         RxStatusFIFOOver        = 0x10000,
491         IntrPCIErr              = 0xf00000,
492         RxResetDone             = 0x1000000,
493         TxResetDone             = 0x2000000,
494         IntrAbnormalSummary     = 0xCD20,
495 };
496
497 /*
498  * Default Interrupts:
499  * Rx OK, Rx Packet Error, Rx Overrun,
500  * Tx OK, Tx Packet Error, Tx Underrun,
501  * MIB Service, Phy Interrupt, High Bits,
502  * Rx Status FIFO overrun,
503  * Received Target Abort, Received Master Abort,
504  * Signalled System Error, Received Parity Error
505  */
506 #define DEFAULT_INTR 0x00f1cd65
507
508 enum TxConfig_bits {
509         TxDrthMask              = 0x3f,
510         TxFlthMask              = 0x3f00,
511         TxMxdmaMask             = 0x700000,
512         TxMxdma_512             = 0x0,
513         TxMxdma_4               = 0x100000,
514         TxMxdma_8               = 0x200000,
515         TxMxdma_16              = 0x300000,
516         TxMxdma_32              = 0x400000,
517         TxMxdma_64              = 0x500000,
518         TxMxdma_128             = 0x600000,
519         TxMxdma_256             = 0x700000,
520         TxCollRetry             = 0x800000,
521         TxAutoPad               = 0x10000000,
522         TxMacLoop               = 0x20000000,
523         TxHeartIgn              = 0x40000000,
524         TxCarrierIgn            = 0x80000000
525 };
526
527 enum RxConfig_bits {
528         RxDrthMask              = 0x3e,
529         RxMxdmaMask             = 0x700000,
530         RxMxdma_512             = 0x0,
531         RxMxdma_4               = 0x100000,
532         RxMxdma_8               = 0x200000,
533         RxMxdma_16              = 0x300000,
534         RxMxdma_32              = 0x400000,
535         RxMxdma_64              = 0x500000,
536         RxMxdma_128             = 0x600000,
537         RxMxdma_256             = 0x700000,
538         RxAcceptLong            = 0x8000000,
539         RxAcceptTx              = 0x10000000,
540         RxAcceptRunt            = 0x40000000,
541         RxAcceptErr             = 0x80000000
542 };
543
544 enum ClkRun_bits {
545         PMEEnable               = 0x100,
546         PMEStatus               = 0x8000,
547 };
548
549 enum WolCmd_bits {
550         WakePhy                 = 0x1,
551         WakeUnicast             = 0x2,
552         WakeMulticast           = 0x4,
553         WakeBroadcast           = 0x8,
554         WakeArp                 = 0x10,
555         WakePMatch0             = 0x20,
556         WakePMatch1             = 0x40,
557         WakePMatch2             = 0x80,
558         WakePMatch3             = 0x100,
559         WakeMagic               = 0x200,
560         WakeMagicSecure         = 0x400,
561         SecureHack              = 0x100000,
562         WokePhy                 = 0x400000,
563         WokeUnicast             = 0x800000,
564         WokeMulticast           = 0x1000000,
565         WokeBroadcast           = 0x2000000,
566         WokeArp                 = 0x4000000,
567         WokePMatch0             = 0x8000000,
568         WokePMatch1             = 0x10000000,
569         WokePMatch2             = 0x20000000,
570         WokePMatch3             = 0x40000000,
571         WokeMagic               = 0x80000000,
572         WakeOptsSummary         = 0x7ff
573 };
574
575 enum RxFilterAddr_bits {
576         RFCRAddressMask         = 0x3ff,
577         AcceptMulticast         = 0x00200000,
578         AcceptMyPhys            = 0x08000000,
579         AcceptAllPhys           = 0x10000000,
580         AcceptAllMulticast      = 0x20000000,
581         AcceptBroadcast         = 0x40000000,
582         RxFilterEnable          = 0x80000000
583 };
584
585 enum StatsCtrl_bits {
586         StatsWarn               = 0x1,
587         StatsFreeze             = 0x2,
588         StatsClear              = 0x4,
589         StatsStrobe             = 0x8,
590 };
591
592 enum MIntrCtrl_bits {
593         MICRIntEn               = 0x2,
594 };
595
596 enum PhyCtrl_bits {
597         PhyAddrMask             = 0xf,
598 };
599
600 /* values we might find in the silicon revision register */
601 #define SRR_DP83815_C   0x0302
602 #define SRR_DP83815_D   0x0403
603 #define SRR_DP83816_A4  0x0504
604 #define SRR_DP83816_A5  0x0505
605
606 /* The Rx and Tx buffer descriptors. */
607 /* Note that using only 32 bit fields simplifies conversion to big-endian
608    architectures. */
609 struct netdev_desc {
610         u32 next_desc;
611         s32 cmd_status;
612         u32 addr;
613         u32 software_use;
614 };
615
616 /* Bits in network_desc.status */
617 enum desc_status_bits {
618         DescOwn=0x80000000, DescMore=0x40000000, DescIntr=0x20000000,
619         DescNoCRC=0x10000000, DescPktOK=0x08000000,
620         DescSizeMask=0xfff,
621
622         DescTxAbort=0x04000000, DescTxFIFO=0x02000000,
623         DescTxCarrier=0x01000000, DescTxDefer=0x00800000,
624         DescTxExcDefer=0x00400000, DescTxOOWCol=0x00200000,
625         DescTxExcColl=0x00100000, DescTxCollCount=0x000f0000,
626
627         DescRxAbort=0x04000000, DescRxOver=0x02000000,
628         DescRxDest=0x01800000, DescRxLong=0x00400000,
629         DescRxRunt=0x00200000, DescRxInvalid=0x00100000,
630         DescRxCRC=0x00080000, DescRxAlign=0x00040000,
631         DescRxLoop=0x00020000, DesRxColl=0x00010000,
632 };
633
634 struct netdev_private {
635         /* Descriptor rings first for alignment */
636         dma_addr_t ring_dma;
637         struct netdev_desc *rx_ring;
638         struct netdev_desc *tx_ring;
639         /* The addresses of receive-in-place skbuffs */
640         struct sk_buff *rx_skbuff[RX_RING_SIZE];
641         dma_addr_t rx_dma[RX_RING_SIZE];
642         /* address of a sent-in-place packet/buffer, for later free() */
643         struct sk_buff *tx_skbuff[TX_RING_SIZE];
644         dma_addr_t tx_dma[TX_RING_SIZE];
645         struct net_device_stats stats;
646         /* Media monitoring timer */
647         struct timer_list timer;
648         /* Frequently used values: keep some adjacent for cache effect */
649         struct pci_dev *pci_dev;
650         struct netdev_desc *rx_head_desc;
651         /* Producer/consumer ring indices */
652         unsigned int cur_rx, dirty_rx;
653         unsigned int cur_tx, dirty_tx;
654         /* Based on MTU+slack. */
655         unsigned int rx_buf_sz;
656         int oom;
657         /* Do not touch the nic registers */
658         int hands_off;
659         /* These values are keep track of the transceiver/media in use */
660         unsigned int full_duplex;
661         /* Rx filter */
662         u32 cur_rx_mode;
663         u32 rx_filter[16];
664         /* FIFO and PCI burst thresholds */
665         u32 tx_config, rx_config;
666         /* original contents of ClkRun register */
667         u32 SavedClkRun;
668         /* silicon revision */
669         u32 srr;
670         /* expected DSPCFG value */
671         u16 dspcfg;
672         /* MII transceiver section */
673         u16 advertising;
674         unsigned int iosize;
675         spinlock_t lock;
676         u32 msg_enable;
677 };
678
679 static int eeprom_read(long ioaddr, int location);
680 static int mdio_read(struct net_device *dev, int phy_id, int reg);
681 static void mdio_write(struct net_device *dev, int phy_id, int reg, u16 data);
682 static void natsemi_reset(struct net_device *dev);
683 static void natsemi_reload_eeprom(struct net_device *dev);
684 static void natsemi_stop_rxtx(struct net_device *dev);
685 static int netdev_open(struct net_device *dev);
686 static void do_cable_magic(struct net_device *dev);
687 static void undo_cable_magic(struct net_device *dev);
688 static void check_link(struct net_device *dev);
689 static void netdev_timer(unsigned long data);
690 static void dump_ring(struct net_device *dev);
691 static void tx_timeout(struct net_device *dev);
692 static int alloc_ring(struct net_device *dev);
693 static void refill_rx(struct net_device *dev);
694 static void init_ring(struct net_device *dev);
695 static void drain_tx(struct net_device *dev);
696 static void drain_ring(struct net_device *dev);
697 static void free_ring(struct net_device *dev);
698 static void reinit_ring(struct net_device *dev);
699 static void init_registers(struct net_device *dev);
700 static int start_tx(struct sk_buff *skb, struct net_device *dev);
701 static irqreturn_t intr_handler(int irq, void *dev_instance, struct pt_regs *regs);
702 static void netdev_error(struct net_device *dev, int intr_status);
703 static void netdev_rx(struct net_device *dev);
704 static void netdev_tx_done(struct net_device *dev);
705 static void __set_rx_mode(struct net_device *dev);
706 static void set_rx_mode(struct net_device *dev);
707 static void __get_stats(struct net_device *dev);
708 static struct net_device_stats *get_stats(struct net_device *dev);
709 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
710 static int netdev_set_wol(struct net_device *dev, u32 newval);
711 static int netdev_get_wol(struct net_device *dev, u32 *supported, u32 *cur);
712 static int netdev_set_sopass(struct net_device *dev, u8 *newval);
713 static int netdev_get_sopass(struct net_device *dev, u8 *data);
714 static int netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd);
715 static int netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd);
716 static void enable_wol_mode(struct net_device *dev, int enable_intr);
717 static int netdev_close(struct net_device *dev);
718 static int netdev_get_regs(struct net_device *dev, u8 *buf);
719 static int netdev_get_eeprom(struct net_device *dev, u8 *buf);
720
721
722 static int __devinit natsemi_probe1 (struct pci_dev *pdev,
723         const struct pci_device_id *ent)
724 {
725         struct net_device *dev;
726         struct netdev_private *np;
727         int i, option, irq, chip_idx = ent->driver_data;
728         static int find_cnt = -1;
729         unsigned long ioaddr, iosize;
730         const int pcibar = 1; /* PCI base address register */
731         int prev_eedata;
732         u32 tmp;
733
734 /* when built into the kernel, we only print version if device is found */
735 #ifndef MODULE
736         static int printed_version;
737         if (!printed_version++)
738                 printk(version);
739 #endif
740
741         i = pci_enable_device(pdev);
742         if (i) return i;
743
744         /* natsemi has a non-standard PM control register
745          * in PCI config space.  Some boards apparently need
746          * to be brought to D0 in this manner.
747          */
748         pci_read_config_dword(pdev, PCIPM, &tmp);
749         if (tmp & PCI_PM_CTRL_STATE_MASK) {
750                 /* D0 state, disable PME assertion */
751                 u32 newtmp = tmp & ~PCI_PM_CTRL_STATE_MASK;
752                 pci_write_config_dword(pdev, PCIPM, newtmp);
753         }
754
755         find_cnt++;
756         ioaddr = pci_resource_start(pdev, pcibar);
757         iosize = pci_resource_len(pdev, pcibar);
758         irq = pdev->irq;
759
760         if (natsemi_pci_info[chip_idx].flags & PCI_USES_MASTER)
761                 pci_set_master(pdev);
762
763         dev = alloc_etherdev(sizeof (struct netdev_private));
764         if (!dev)
765                 return -ENOMEM;
766         SET_MODULE_OWNER(dev);
767         SET_NETDEV_DEV(dev, &pdev->dev);
768
769         i = pci_request_regions(pdev, dev->name);
770         if (i)
771                 goto err_pci_request_regions;
772
773         ioaddr = (unsigned long) ioremap (ioaddr, iosize);
774         if (!ioaddr) {
775                 i = -ENOMEM;
776                 goto err_ioremap;
777         }
778
779         /* Work around the dropped serial bit. */
780         prev_eedata = eeprom_read(ioaddr, 6);
781         for (i = 0; i < 3; i++) {
782                 int eedata = eeprom_read(ioaddr, i + 7);
783                 dev->dev_addr[i*2] = (eedata << 1) + (prev_eedata >> 15);
784                 dev->dev_addr[i*2+1] = eedata >> 7;
785                 prev_eedata = eedata;
786         }
787
788         dev->base_addr = ioaddr;
789         dev->irq = irq;
790
791         np = dev->priv;
792
793         np->pci_dev = pdev;
794         pci_set_drvdata(pdev, dev);
795         np->iosize = iosize;
796         spin_lock_init(&np->lock);
797         np->msg_enable = (debug >= 0) ? (1<<debug)-1 : NATSEMI_DEF_MSG;
798         np->hands_off = 0;
799
800         /* Reset the chip to erase previous misconfiguration. */
801         natsemi_reload_eeprom(dev);
802         natsemi_reset(dev);
803
804         option = find_cnt < MAX_UNITS ? options[find_cnt] : 0;
805         if (dev->mem_start)
806                 option = dev->mem_start;
807
808         /* The lower four bits are the media type. */
809         if (option) {
810                 if (option & 0x200)
811                         np->full_duplex = 1;
812                 if (option & 15)
813                         printk(KERN_INFO
814                                 "%s: ignoring user supplied media type %d",
815                                 dev->name, option & 15);
816         }
817         if (find_cnt < MAX_UNITS  &&  full_duplex[find_cnt])
818                 np->full_duplex = 1;
819
820         /* The chip-specific entries in the device structure. */
821         dev->open = &netdev_open;
822         dev->hard_start_xmit = &start_tx;
823         dev->stop = &netdev_close;
824         dev->get_stats = &get_stats;
825         dev->set_multicast_list = &set_rx_mode;
826         dev->do_ioctl = &netdev_ioctl;
827         dev->tx_timeout = &tx_timeout;
828         dev->watchdog_timeo = TX_TIMEOUT;
829
830         if (mtu)
831                 dev->mtu = mtu;
832
833         i = register_netdev(dev);
834         if (i)
835                 goto err_register_netdev;
836
837         netif_carrier_off(dev);
838
839         if (netif_msg_drv(np)) {
840                 printk(KERN_INFO "%s: %s at %#08lx, ",
841                         dev->name, natsemi_pci_info[chip_idx].name, ioaddr);
842                 for (i = 0; i < ETH_ALEN-1; i++)
843                                 printk("%02x:", dev->dev_addr[i]);
844                 printk("%02x, IRQ %d.\n", dev->dev_addr[i], irq);
845         }
846
847         np->advertising = mdio_read(dev, 1, MII_ADVERTISE);
848         if ((readl(ioaddr + ChipConfig) & 0xe000) != 0xe000
849          && netif_msg_probe(np)) {
850                 u32 chip_config = readl(ioaddr + ChipConfig);
851                 printk(KERN_INFO "%s: Transceiver default autonegotiation %s "
852                         "10%s %s duplex.\n",
853                         dev->name,
854                         chip_config & CfgAnegEnable ?
855                           "enabled, advertise" : "disabled, force",
856                         chip_config & CfgAneg100 ? "0" : "",
857                         chip_config & CfgAnegFull ? "full" : "half");
858         }
859         if (netif_msg_probe(np))
860                 printk(KERN_INFO
861                         "%s: Transceiver status %#04x advertising %#04x.\n",
862                         dev->name, mdio_read(dev, 1, MII_BMSR),
863                         np->advertising);
864
865         /* save the silicon revision for later querying */
866         np->srr = readl(ioaddr + SiliconRev);
867         if (netif_msg_hw(np))
868                 printk(KERN_INFO "%s: silicon revision %#04x.\n",
869                                 dev->name, np->srr);
870
871
872         return 0;
873
874  err_register_netdev:
875         iounmap ((void *) dev->base_addr);
876
877  err_ioremap:
878         pci_release_regions(pdev);
879         pci_set_drvdata(pdev, NULL);
880
881  err_pci_request_regions:
882         free_netdev(dev);
883         return i;
884 }
885
886
887 /* Read the EEPROM and MII Management Data I/O (MDIO) interfaces.
888    The EEPROM code is for the common 93c06/46 EEPROMs with 6 bit addresses. */
889
890 /* Delay between EEPROM clock transitions.
891    No extra delay is needed with 33Mhz PCI, but future 66Mhz access may need
892    a delay.  Note that pre-2.0.34 kernels had a cache-alignment bug that
893    made udelay() unreliable.
894    The old method of using an ISA access as a delay, __SLOW_DOWN_IO__, is
895    depricated.
896 */
897 #define eeprom_delay(ee_addr)   readl(ee_addr)
898
899 #define EE_Write0 (EE_ChipSelect)
900 #define EE_Write1 (EE_ChipSelect | EE_DataIn)
901
902 /* The EEPROM commands include the alway-set leading bit. */
903 enum EEPROM_Cmds {
904         EE_WriteCmd=(5 << 6), EE_ReadCmd=(6 << 6), EE_EraseCmd=(7 << 6),
905 };
906
907 static int eeprom_read(long addr, int location)
908 {
909         int i;
910         int retval = 0;
911         long ee_addr = addr + EECtrl;
912         int read_cmd = location | EE_ReadCmd;
913         writel(EE_Write0, ee_addr);
914
915         /* Shift the read command bits out. */
916         for (i = 10; i >= 0; i--) {
917                 short dataval = (read_cmd & (1 << i)) ? EE_Write1 : EE_Write0;
918                 writel(dataval, ee_addr);
919                 eeprom_delay(ee_addr);
920                 writel(dataval | EE_ShiftClk, ee_addr);
921                 eeprom_delay(ee_addr);
922         }
923         writel(EE_ChipSelect, ee_addr);
924         eeprom_delay(ee_addr);
925
926         for (i = 0; i < 16; i++) {
927                 writel(EE_ChipSelect | EE_ShiftClk, ee_addr);
928                 eeprom_delay(ee_addr);
929                 retval |= (readl(ee_addr) & EE_DataOut) ? 1 << i : 0;
930                 writel(EE_ChipSelect, ee_addr);
931                 eeprom_delay(ee_addr);
932         }
933
934         /* Terminate the EEPROM access. */
935         writel(EE_Write0, ee_addr);
936         writel(0, ee_addr);
937         return retval;
938 }
939
940 /* MII transceiver control section.
941  * The 83815 series has an internal transceiver, and we present the
942  * management registers as if they were MII connected. */
943
944 static int mdio_read(struct net_device *dev, int phy_id, int reg)
945 {
946         if (phy_id == 1 && reg < 32)
947                 return readl(dev->base_addr+BasicControl+(reg<<2))&0xffff;
948         else
949                 return 0xffff;
950 }
951
952 static void mdio_write(struct net_device *dev, int phy_id, int reg, u16 data)
953 {
954         struct netdev_private *np = dev->priv;
955         if (phy_id == 1 && reg < 32) {
956                 writew(data, dev->base_addr+BasicControl+(reg<<2));
957                 switch (reg) {
958                         case MII_ADVERTISE: np->advertising = data; break;
959                 }
960         }
961 }
962
963 /* CFG bits [13:16] [18:23] */
964 #define CFG_RESET_SAVE 0xfde000
965 /* WCSR bits [0:4] [9:10] */
966 #define WCSR_RESET_SAVE 0x61f
967 /* RFCR bits [20] [22] [27:31] */
968 #define RFCR_RESET_SAVE 0xf8500000;
969
970 static void natsemi_reset(struct net_device *dev)
971 {
972         int i;
973         u32 cfg;
974         u32 wcsr;
975         u32 rfcr;
976         u16 pmatch[3];
977         u16 sopass[3];
978         struct netdev_private *np = dev->priv;
979
980         /*
981          * Resetting the chip causes some registers to be lost.
982          * Natsemi suggests NOT reloading the EEPROM while live, so instead
983          * we save the state that would have been loaded from EEPROM
984          * on a normal power-up (see the spec EEPROM map).  This assumes
985          * whoever calls this will follow up with init_registers() eventually.
986          */
987
988         /* CFG */
989         cfg = readl(dev->base_addr + ChipConfig) & CFG_RESET_SAVE;
990         /* WCSR */
991         wcsr = readl(dev->base_addr + WOLCmd) & WCSR_RESET_SAVE;
992         /* RFCR */
993         rfcr = readl(dev->base_addr + RxFilterAddr) & RFCR_RESET_SAVE;
994         /* PMATCH */
995         for (i = 0; i < 3; i++) {
996                 writel(i*2, dev->base_addr + RxFilterAddr);
997                 pmatch[i] = readw(dev->base_addr + RxFilterData);
998         }
999         /* SOPAS */
1000         for (i = 0; i < 3; i++) {
1001                 writel(0xa+(i*2), dev->base_addr + RxFilterAddr);
1002                 sopass[i] = readw(dev->base_addr + RxFilterData);
1003         }
1004
1005         /* now whack the chip */
1006         writel(ChipReset, dev->base_addr + ChipCmd);
1007         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1008                 if (!(readl(dev->base_addr + ChipCmd) & ChipReset))
1009                         break;
1010                 udelay(5);
1011         }
1012         if (i==NATSEMI_HW_TIMEOUT) {
1013                 printk(KERN_WARNING "%s: reset did not complete in %d usec.\n",
1014                         dev->name, i*5);
1015         } else if (netif_msg_hw(np)) {
1016                 printk(KERN_DEBUG "%s: reset completed in %d usec.\n",
1017                         dev->name, i*5);
1018         }
1019
1020         /* restore CFG */
1021         cfg |= readl(dev->base_addr + ChipConfig) & ~CFG_RESET_SAVE;
1022         writel(cfg, dev->base_addr + ChipConfig);
1023         /* restore WCSR */
1024         wcsr |= readl(dev->base_addr + WOLCmd) & ~WCSR_RESET_SAVE;
1025         writel(wcsr, dev->base_addr + WOLCmd);
1026         /* read RFCR */
1027         rfcr |= readl(dev->base_addr + RxFilterAddr) & ~RFCR_RESET_SAVE;
1028         /* restore PMATCH */
1029         for (i = 0; i < 3; i++) {
1030                 writel(i*2, dev->base_addr + RxFilterAddr);
1031                 writew(pmatch[i], dev->base_addr + RxFilterData);
1032         }
1033         for (i = 0; i < 3; i++) {
1034                 writel(0xa+(i*2), dev->base_addr + RxFilterAddr);
1035                 writew(sopass[i], dev->base_addr + RxFilterData);
1036         }
1037         /* restore RFCR */
1038         writel(rfcr, dev->base_addr + RxFilterAddr);
1039 }
1040
1041 static void natsemi_reload_eeprom(struct net_device *dev)
1042 {
1043         struct netdev_private *np = dev->priv;
1044         int i;
1045
1046         writel(EepromReload, dev->base_addr + PCIBusCfg);
1047         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1048                 udelay(50);
1049                 if (!(readl(dev->base_addr + PCIBusCfg) & EepromReload))
1050                         break;
1051         }
1052         if (i==NATSEMI_HW_TIMEOUT) {
1053                 printk(KERN_WARNING "%s: EEPROM did not reload in %d usec.\n",
1054                         dev->name, i*50);
1055         } else if (netif_msg_hw(np)) {
1056                 printk(KERN_DEBUG "%s: EEPROM reloaded in %d usec.\n",
1057                         dev->name, i*50);
1058         }
1059 }
1060
1061 static void natsemi_stop_rxtx(struct net_device *dev)
1062 {
1063         long ioaddr = dev->base_addr;
1064         struct netdev_private *np = dev->priv;
1065         int i;
1066
1067         writel(RxOff | TxOff, ioaddr + ChipCmd);
1068         for(i=0;i< NATSEMI_HW_TIMEOUT;i++) {
1069                 if ((readl(ioaddr + ChipCmd) & (TxOn|RxOn)) == 0)
1070                         break;
1071                 udelay(5);
1072         }
1073         if (i==NATSEMI_HW_TIMEOUT) {
1074                 printk(KERN_WARNING "%s: Tx/Rx process did not stop in %d usec.\n",
1075                         dev->name, i*5);
1076         } else if (netif_msg_hw(np)) {
1077                 printk(KERN_DEBUG "%s: Tx/Rx process stopped in %d usec.\n",
1078                         dev->name, i*5);
1079         }
1080 }
1081
1082 static int netdev_open(struct net_device *dev)
1083 {
1084         struct netdev_private *np = dev->priv;
1085         long ioaddr = dev->base_addr;
1086         int i;
1087
1088         /* Reset the chip, just in case. */
1089         natsemi_reset(dev);
1090
1091         i = request_irq(dev->irq, &intr_handler, SA_SHIRQ, dev->name, dev);
1092         if (i) return i;
1093
1094         if (netif_msg_ifup(np))
1095                 printk(KERN_DEBUG "%s: netdev_open() irq %d.\n",
1096                         dev->name, dev->irq);
1097         i = alloc_ring(dev);
1098         if (i < 0) {
1099                 free_irq(dev->irq, dev);
1100                 return i;
1101         }
1102         init_ring(dev);
1103         spin_lock_irq(&np->lock);
1104         init_registers(dev);
1105         /* now set the MAC address according to dev->dev_addr */
1106         for (i = 0; i < 3; i++) {
1107                 u16 mac = (dev->dev_addr[2*i+1]<<8) + dev->dev_addr[2*i];
1108
1109                 writel(i*2, ioaddr + RxFilterAddr);
1110                 writew(mac, ioaddr + RxFilterData);
1111         }
1112         writel(np->cur_rx_mode, ioaddr + RxFilterAddr);
1113         spin_unlock_irq(&np->lock);
1114
1115         netif_start_queue(dev);
1116
1117         if (netif_msg_ifup(np))
1118                 printk(KERN_DEBUG "%s: Done netdev_open(), status: %#08x.\n",
1119                         dev->name, (int)readl(ioaddr + ChipCmd));
1120
1121         /* Set the timer to check for link beat. */
1122         init_timer(&np->timer);
1123         np->timer.expires = jiffies + NATSEMI_TIMER_FREQ;
1124         np->timer.data = (unsigned long)dev;
1125         np->timer.function = &netdev_timer; /* timer handler */
1126         add_timer(&np->timer);
1127
1128         return 0;
1129 }
1130
1131 static void do_cable_magic(struct net_device *dev)
1132 {
1133         struct netdev_private *np = dev->priv;
1134
1135         if (np->srr >= SRR_DP83816_A5)
1136                 return;
1137
1138         /*
1139          * 100 MBit links with short cables can trip an issue with the chip.
1140          * The problem manifests as lots of CRC errors and/or flickering
1141          * activity LED while idle.  This process is based on instructions
1142          * from engineers at National.
1143          */
1144         if (readl(dev->base_addr + ChipConfig) & CfgSpeed100) {
1145                 u16 data;
1146
1147                 writew(1, dev->base_addr + PGSEL);
1148                 /*
1149                  * coefficient visibility should already be enabled via
1150                  * DSPCFG | 0x1000
1151                  */
1152                 data = readw(dev->base_addr + TSTDAT) & 0xff;
1153                 /*
1154                  * the value must be negative, and within certain values
1155                  * (these values all come from National)
1156                  */
1157                 if (!(data & 0x80) || ((data >= 0xd8) && (data <= 0xff))) {
1158                         struct netdev_private *np = dev->priv;
1159
1160                         /* the bug has been triggered - fix the coefficient */
1161                         writew(TSTDAT_FIXED, dev->base_addr + TSTDAT);
1162                         /* lock the value */
1163                         data = readw(dev->base_addr + DSPCFG);
1164                         np->dspcfg = data | DSPCFG_LOCK;
1165                         writew(np->dspcfg, dev->base_addr + DSPCFG);
1166                 }
1167                 writew(0, dev->base_addr + PGSEL);
1168         }
1169 }
1170
1171 static void undo_cable_magic(struct net_device *dev)
1172 {
1173         u16 data;
1174         struct netdev_private *np = dev->priv;
1175
1176         if (np->srr >= SRR_DP83816_A5)
1177                 return;
1178
1179         writew(1, dev->base_addr + PGSEL);
1180         /* make sure the lock bit is clear */
1181         data = readw(dev->base_addr + DSPCFG);
1182         np->dspcfg = data & ~DSPCFG_LOCK;
1183         writew(np->dspcfg, dev->base_addr + DSPCFG);
1184         writew(0, dev->base_addr + PGSEL);
1185 }
1186
1187 static void check_link(struct net_device *dev)
1188 {
1189         struct netdev_private *np = dev->priv;
1190         long ioaddr = dev->base_addr;
1191         int duplex;
1192         int chipcfg = readl(ioaddr + ChipConfig);
1193
1194         if (!(chipcfg & CfgLink)) {
1195                 if (netif_carrier_ok(dev)) {
1196                         if (netif_msg_link(np))
1197                                 printk(KERN_NOTICE "%s: link down.\n",
1198                                         dev->name);
1199                         netif_carrier_off(dev);
1200                         undo_cable_magic(dev);
1201                 }
1202                 return;
1203         }
1204         if (!netif_carrier_ok(dev)) {
1205                 if (netif_msg_link(np))
1206                         printk(KERN_NOTICE "%s: link up.\n", dev->name);
1207                 netif_carrier_on(dev);
1208                 do_cable_magic(dev);
1209         }
1210
1211         duplex = np->full_duplex || (chipcfg & CfgFullDuplex ? 1 : 0);
1212
1213         /* if duplex is set then bit 28 must be set, too */
1214         if (duplex ^ !!(np->rx_config & RxAcceptTx)) {
1215                 if (netif_msg_link(np))
1216                         printk(KERN_INFO
1217                                 "%s: Setting %s-duplex based on negotiated "
1218                                 "link capability.\n", dev->name,
1219                                 duplex ? "full" : "half");
1220                 if (duplex) {
1221                         np->rx_config |= RxAcceptTx;
1222                         np->tx_config |= TxCarrierIgn | TxHeartIgn;
1223                 } else {
1224                         np->rx_config &= ~RxAcceptTx;
1225                         np->tx_config &= ~(TxCarrierIgn | TxHeartIgn);
1226                 }
1227                 writel(np->tx_config, ioaddr + TxConfig);
1228                 writel(np->rx_config, ioaddr + RxConfig);
1229         }
1230 }
1231
1232 static void init_registers(struct net_device *dev)
1233 {
1234         struct netdev_private *np = dev->priv;
1235         long ioaddr = dev->base_addr;
1236         int i;
1237
1238         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1239                 if (readl(dev->base_addr + ChipConfig) & CfgAnegDone)
1240                         break;
1241                 udelay(10);
1242         }
1243         if (i==NATSEMI_HW_TIMEOUT && netif_msg_link(np)) {
1244                 printk(KERN_INFO
1245                         "%s: autonegotiation did not complete in %d usec.\n",
1246                         dev->name, i*10);
1247         }
1248
1249         /* On page 78 of the spec, they recommend some settings for "optimum
1250            performance" to be done in sequence.  These settings optimize some
1251            of the 100Mbit autodetection circuitry.  They say we only want to
1252            do this for rev C of the chip, but engineers at NSC (Bradley
1253            Kennedy) recommends always setting them.  If you don't, you get
1254            errors on some autonegotiations that make the device unusable.
1255         */
1256         writew(1, ioaddr + PGSEL);
1257         writew(PMDCSR_VAL, ioaddr + PMDCSR);
1258         writew(TSTDAT_VAL, ioaddr + TSTDAT);
1259         writew(DSPCFG_VAL, ioaddr + DSPCFG);
1260         writew(SDCFG_VAL, ioaddr + SDCFG);
1261         writew(0, ioaddr + PGSEL);
1262         np->dspcfg = DSPCFG_VAL;
1263
1264         /* Enable PHY Specific event based interrupts.  Link state change
1265            and Auto-Negotiation Completion are among the affected.
1266            Read the intr status to clear it (needed for wake events).
1267         */
1268         readw(ioaddr + MIntrStatus);
1269         writew(MICRIntEn, ioaddr + MIntrCtrl);
1270
1271         /* clear any interrupts that are pending, such as wake events */
1272         readl(ioaddr + IntrStatus);
1273
1274         writel(np->ring_dma, ioaddr + RxRingPtr);
1275         writel(np->ring_dma + RX_RING_SIZE * sizeof(struct netdev_desc),
1276                 ioaddr + TxRingPtr);
1277
1278         /* Initialize other registers.
1279          * Configure the PCI bus bursts and FIFO thresholds.
1280          * Configure for standard, in-spec Ethernet.
1281          * Start with half-duplex. check_link will update
1282          * to the correct settings.
1283          */
1284
1285         /* DRTH: 2: start tx if 64 bytes are in the fifo
1286          * FLTH: 0x10: refill with next packet if 512 bytes are free
1287          * MXDMA: 0: up to 256 byte bursts.
1288          *      MXDMA must be <= FLTH
1289          * ECRETRY=1
1290          * ATP=1
1291          */
1292         np->tx_config = TxAutoPad | TxCollRetry | TxMxdma_256 | (0x1002);
1293         writel(np->tx_config, ioaddr + TxConfig);
1294
1295         /* DRTH 0x10: start copying to memory if 128 bytes are in the fifo
1296          * MXDMA 0: up to 256 byte bursts
1297          */
1298         np->rx_config = RxMxdma_256 | 0x20;
1299         writel(np->rx_config, ioaddr + RxConfig);
1300
1301         /* Disable PME:
1302          * The PME bit is initialized from the EEPROM contents.
1303          * PCI cards probably have PME disabled, but motherboard
1304          * implementations may have PME set to enable WakeOnLan.
1305          * With PME set the chip will scan incoming packets but
1306          * nothing will be written to memory. */
1307         np->SavedClkRun = readl(ioaddr + ClkRun);
1308         writel(np->SavedClkRun & ~PMEEnable, ioaddr + ClkRun);
1309         if (np->SavedClkRun & PMEStatus && netif_msg_wol(np)) {
1310                 printk(KERN_NOTICE "%s: Wake-up event %#08x\n",
1311                         dev->name, readl(ioaddr + WOLCmd));
1312         }
1313
1314         check_link(dev);
1315         __set_rx_mode(dev);
1316
1317         /* Enable interrupts by setting the interrupt mask. */
1318         writel(DEFAULT_INTR, ioaddr + IntrMask);
1319         writel(1, ioaddr + IntrEnable);
1320
1321         writel(RxOn | TxOn, ioaddr + ChipCmd);
1322         writel(StatsClear, ioaddr + StatsCtrl); /* Clear Stats */
1323 }
1324
1325 /*
1326  * netdev_timer:
1327  * Purpose:
1328  * 1) check for link changes. Usually they are handled by the MII interrupt
1329  *    but it doesn't hurt to check twice.
1330  * 2) check for sudden death of the NIC:
1331  *    It seems that a reference set for this chip went out with incorrect info,
1332  *    and there exist boards that aren't quite right.  An unexpected voltage
1333  *    drop can cause the PHY to get itself in a weird state (basically reset).
1334  *    NOTE: this only seems to affect revC chips.
1335  * 3) check of death of the RX path due to OOM
1336  */
1337 static void netdev_timer(unsigned long data)
1338 {
1339         struct net_device *dev = (struct net_device *)data;
1340         struct netdev_private *np = dev->priv;
1341         int next_tick = 5*HZ;
1342         long ioaddr = dev->base_addr;
1343         u16 dspcfg;
1344
1345         if (netif_msg_timer(np)) {
1346                 /* DO NOT read the IntrStatus register,
1347                  * a read clears any pending interrupts.
1348                  */
1349                 printk(KERN_DEBUG "%s: Media selection timer tick.\n",
1350                         dev->name);
1351         }
1352
1353         spin_lock_irq(&np->lock);
1354
1355         /* check for a nasty random phy-reset - use dspcfg as a flag */
1356         writew(1, ioaddr+PGSEL);
1357         dspcfg = readw(ioaddr+DSPCFG);
1358         writew(0, ioaddr+PGSEL);
1359         if (dspcfg != np->dspcfg) {
1360                 if (!netif_queue_stopped(dev)) {
1361                         spin_unlock_irq(&np->lock);
1362                         if (netif_msg_hw(np))
1363                                 printk(KERN_NOTICE "%s: possible phy reset: "
1364                                         "re-initializing\n", dev->name);
1365                         disable_irq(dev->irq);
1366                         spin_lock_irq(&np->lock);
1367                         natsemi_stop_rxtx(dev);
1368                         dump_ring(dev);
1369                         reinit_ring(dev);
1370                         init_registers(dev);
1371                         spin_unlock_irq(&np->lock);
1372                         enable_irq(dev->irq);
1373                 } else {
1374                         /* hurry back */
1375                         next_tick = HZ;
1376                         spin_unlock_irq(&np->lock);
1377                 }
1378         } else {
1379                 /* init_registers() calls check_link() for the above case */
1380                 check_link(dev);
1381                 spin_unlock_irq(&np->lock);
1382         }
1383         if (np->oom) {
1384                 disable_irq(dev->irq);
1385                 np->oom = 0;
1386                 refill_rx(dev);
1387                 enable_irq(dev->irq);
1388                 if (!np->oom) {
1389                         writel(RxOn, dev->base_addr + ChipCmd);
1390                 } else {
1391                         next_tick = 1;
1392                 }
1393         }
1394         mod_timer(&np->timer, jiffies + next_tick);
1395 }
1396
1397 static void dump_ring(struct net_device *dev)
1398 {
1399         struct netdev_private *np = dev->priv;
1400
1401         if (netif_msg_pktdata(np)) {
1402                 int i;
1403                 printk(KERN_DEBUG "  Tx ring at %p:\n", np->tx_ring);
1404                 for (i = 0; i < TX_RING_SIZE; i++) {
1405                         printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
1406                                 i, np->tx_ring[i].next_desc,
1407                                 np->tx_ring[i].cmd_status,
1408                                 np->tx_ring[i].addr);
1409                 }
1410                 printk(KERN_DEBUG "  Rx ring %p:\n", np->rx_ring);
1411                 for (i = 0; i < RX_RING_SIZE; i++) {
1412                         printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
1413                                 i, np->rx_ring[i].next_desc,
1414                                 np->rx_ring[i].cmd_status,
1415                                 np->rx_ring[i].addr);
1416                 }
1417         }
1418 }
1419
1420 static void tx_timeout(struct net_device *dev)
1421 {
1422         struct netdev_private *np = dev->priv;
1423         long ioaddr = dev->base_addr;
1424
1425         disable_irq(dev->irq);
1426         spin_lock_irq(&np->lock);
1427         if (!np->hands_off) {
1428                 if (netif_msg_tx_err(np))
1429                         printk(KERN_WARNING
1430                                 "%s: Transmit timed out, status %#08x,"
1431                                 " resetting...\n",
1432                                 dev->name, readl(ioaddr + IntrStatus));
1433                 dump_ring(dev);
1434
1435                 natsemi_reset(dev);
1436                 reinit_ring(dev);
1437                 init_registers(dev);
1438         } else {
1439                 printk(KERN_WARNING
1440                         "%s: tx_timeout while in hands_off state?\n",
1441                         dev->name);
1442         }
1443         spin_unlock_irq(&np->lock);
1444         enable_irq(dev->irq);
1445
1446         dev->trans_start = jiffies;
1447         np->stats.tx_errors++;
1448         netif_wake_queue(dev);
1449 }
1450
1451 static int alloc_ring(struct net_device *dev)
1452 {
1453         struct netdev_private *np = dev->priv;
1454         np->rx_ring = pci_alloc_consistent(np->pci_dev,
1455                 sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
1456                 &np->ring_dma);
1457         if (!np->rx_ring)
1458                 return -ENOMEM;
1459         np->tx_ring = &np->rx_ring[RX_RING_SIZE];
1460         return 0;
1461 }
1462
1463 static void refill_rx(struct net_device *dev)
1464 {
1465         struct netdev_private *np = dev->priv;
1466
1467         /* Refill the Rx ring buffers. */
1468         for (; np->cur_rx - np->dirty_rx > 0; np->dirty_rx++) {
1469                 struct sk_buff *skb;
1470                 int entry = np->dirty_rx % RX_RING_SIZE;
1471                 if (np->rx_skbuff[entry] == NULL) {
1472                         unsigned int buflen = np->rx_buf_sz + RX_OFFSET;
1473                         skb = dev_alloc_skb(buflen);
1474                         np->rx_skbuff[entry] = skb;
1475                         if (skb == NULL)
1476                                 break; /* Better luck next round. */
1477                         skb->dev = dev; /* Mark as being used by this device. */
1478                         np->rx_dma[entry] = pci_map_single(np->pci_dev,
1479                                 skb->tail, buflen, PCI_DMA_FROMDEVICE);
1480                         np->rx_ring[entry].addr = cpu_to_le32(np->rx_dma[entry]);
1481                 }
1482                 np->rx_ring[entry].cmd_status = cpu_to_le32(np->rx_buf_sz);
1483         }
1484         if (np->cur_rx - np->dirty_rx == RX_RING_SIZE) {
1485                 if (netif_msg_rx_err(np))
1486                         printk(KERN_WARNING "%s: going OOM.\n", dev->name);
1487                 np->oom = 1;
1488         }
1489 }
1490
1491 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1492 static void init_ring(struct net_device *dev)
1493 {
1494         struct netdev_private *np = dev->priv;
1495         int i;
1496
1497         /* 1) TX ring */
1498         np->dirty_tx = np->cur_tx = 0;
1499         for (i = 0; i < TX_RING_SIZE; i++) {
1500                 np->tx_skbuff[i] = NULL;
1501                 np->tx_ring[i].next_desc = cpu_to_le32(np->ring_dma
1502                         +sizeof(struct netdev_desc)
1503                         *((i+1)%TX_RING_SIZE+RX_RING_SIZE));
1504                 np->tx_ring[i].cmd_status = 0;
1505         }
1506
1507         /* 2) RX ring */
1508         np->dirty_rx = 0;
1509         np->cur_rx = RX_RING_SIZE;
1510         np->rx_buf_sz = (dev->mtu <= 1500 ? PKT_BUF_SZ : dev->mtu + 32);
1511         np->oom = 0;
1512         np->rx_head_desc = &np->rx_ring[0];
1513
1514         /* Please be carefull before changing this loop - at least gcc-2.95.1
1515          * miscompiles it otherwise.
1516          */
1517         /* Initialize all Rx descriptors. */
1518         for (i = 0; i < RX_RING_SIZE; i++) {
1519                 np->rx_ring[i].next_desc = cpu_to_le32(np->ring_dma
1520                                 +sizeof(struct netdev_desc)
1521                                 *((i+1)%RX_RING_SIZE));
1522                 np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
1523                 np->rx_skbuff[i] = NULL;
1524         }
1525         refill_rx(dev);
1526         dump_ring(dev);
1527 }
1528
1529 static void drain_tx(struct net_device *dev)
1530 {
1531         struct netdev_private *np = dev->priv;
1532         int i;
1533
1534         for (i = 0; i < TX_RING_SIZE; i++) {
1535                 if (np->tx_skbuff[i]) {
1536                         pci_unmap_single(np->pci_dev,
1537                                 np->tx_dma[i], np->tx_skbuff[i]->len,
1538                                 PCI_DMA_TODEVICE);
1539                         dev_kfree_skb(np->tx_skbuff[i]);
1540                         np->stats.tx_dropped++;
1541                 }
1542                 np->tx_skbuff[i] = NULL;
1543         }
1544 }
1545
1546 static void drain_ring(struct net_device *dev)
1547 {
1548         struct netdev_private *np = dev->priv;
1549         unsigned int buflen = np->rx_buf_sz + RX_OFFSET;
1550         int i;
1551
1552         /* Free all the skbuffs in the Rx queue. */
1553         for (i = 0; i < RX_RING_SIZE; i++) {
1554                 np->rx_ring[i].cmd_status = 0;
1555                 np->rx_ring[i].addr = 0xBADF00D0; /* An invalid address. */
1556                 if (np->rx_skbuff[i]) {
1557                         pci_unmap_single(np->pci_dev,
1558                                 np->rx_dma[i], buflen,
1559                                 PCI_DMA_FROMDEVICE);
1560                         dev_kfree_skb(np->rx_skbuff[i]);
1561                 }
1562                 np->rx_skbuff[i] = NULL;
1563         }
1564         drain_tx(dev);
1565 }
1566
1567 static void free_ring(struct net_device *dev)
1568 {
1569         struct netdev_private *np = dev->priv;
1570         pci_free_consistent(np->pci_dev,
1571                 sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
1572                 np->rx_ring, np->ring_dma);
1573 }
1574
1575 static void reinit_ring(struct net_device *dev)
1576 {
1577         struct netdev_private *np = dev->priv;
1578         int i;
1579
1580         /* drain TX ring */
1581         drain_tx(dev);
1582         np->dirty_tx = np->cur_tx = 0;
1583         for (i=0;i<TX_RING_SIZE;i++)
1584                 np->tx_ring[i].cmd_status = 0;
1585
1586         /* RX Ring */
1587         np->dirty_rx = 0;
1588         np->cur_rx = RX_RING_SIZE;
1589         np->rx_head_desc = &np->rx_ring[0];
1590         /* Initialize all Rx descriptors. */
1591         for (i = 0; i < RX_RING_SIZE; i++)
1592                 np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
1593
1594         refill_rx(dev);
1595 }
1596
1597 static int start_tx(struct sk_buff *skb, struct net_device *dev)
1598 {
1599         struct netdev_private *np = dev->priv;
1600         unsigned entry;
1601
1602         /* Note: Ordering is important here, set the field with the
1603            "ownership" bit last, and only then increment cur_tx. */
1604
1605         /* Calculate the next Tx descriptor entry. */
1606         entry = np->cur_tx % TX_RING_SIZE;
1607
1608         np->tx_skbuff[entry] = skb;
1609         np->tx_dma[entry] = pci_map_single(np->pci_dev,
1610                                 skb->data,skb->len, PCI_DMA_TODEVICE);
1611
1612         np->tx_ring[entry].addr = cpu_to_le32(np->tx_dma[entry]);
1613
1614         spin_lock_irq(&np->lock);
1615
1616         if (!np->hands_off) {
1617                 np->tx_ring[entry].cmd_status = cpu_to_le32(DescOwn | skb->len);
1618                 /* StrongARM: Explicitly cache flush np->tx_ring and
1619                  * skb->data,skb->len. */
1620                 wmb();
1621                 np->cur_tx++;
1622                 if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1) {
1623                         netdev_tx_done(dev);
1624                         if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1)
1625                                 netif_stop_queue(dev);
1626                 }
1627                 /* Wake the potentially-idle transmit channel. */
1628                 writel(TxOn, dev->base_addr + ChipCmd);
1629         } else {
1630                 dev_kfree_skb_irq(skb);
1631                 np->stats.tx_dropped++;
1632         }
1633         spin_unlock_irq(&np->lock);
1634
1635         dev->trans_start = jiffies;
1636
1637         if (netif_msg_tx_queued(np)) {
1638                 printk(KERN_DEBUG "%s: Transmit frame #%d queued in slot %d.\n",
1639                         dev->name, np->cur_tx, entry);
1640         }
1641         return 0;
1642 }
1643
1644 static void netdev_tx_done(struct net_device *dev)
1645 {
1646         struct netdev_private *np = dev->priv;
1647
1648         for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
1649                 int entry = np->dirty_tx % TX_RING_SIZE;
1650                 if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescOwn))
1651                         break;
1652                 if (netif_msg_tx_done(np))
1653                         printk(KERN_DEBUG
1654                                 "%s: tx frame #%d finished, status %#08x.\n",
1655                                         dev->name, np->dirty_tx,
1656                                         le32_to_cpu(np->tx_ring[entry].cmd_status));
1657                 if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescPktOK)) {
1658                         np->stats.tx_packets++;
1659                         np->stats.tx_bytes += np->tx_skbuff[entry]->len;
1660                 } else { /* Various Tx errors */
1661                         int tx_status =
1662                                 le32_to_cpu(np->tx_ring[entry].cmd_status);
1663                         if (tx_status & (DescTxAbort|DescTxExcColl))
1664                                 np->stats.tx_aborted_errors++;
1665                         if (tx_status & DescTxFIFO)
1666                                 np->stats.tx_fifo_errors++;
1667                         if (tx_status & DescTxCarrier)
1668                                 np->stats.tx_carrier_errors++;
1669                         if (tx_status & DescTxOOWCol)
1670                                 np->stats.tx_window_errors++;
1671                         np->stats.tx_errors++;
1672                 }
1673                 pci_unmap_single(np->pci_dev,np->tx_dma[entry],
1674                                         np->tx_skbuff[entry]->len,
1675                                         PCI_DMA_TODEVICE);
1676                 /* Free the original skb. */
1677                 dev_kfree_skb_irq(np->tx_skbuff[entry]);
1678                 np->tx_skbuff[entry] = NULL;
1679         }
1680         if (netif_queue_stopped(dev)
1681                 && np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
1682                 /* The ring is no longer full, wake queue. */
1683                 netif_wake_queue(dev);
1684         }
1685 }
1686
1687 /* The interrupt handler does all of the Rx thread work and cleans up
1688    after the Tx thread. */
1689 static irqreturn_t intr_handler(int irq, void *dev_instance, struct pt_regs *rgs)
1690 {
1691         struct net_device *dev = dev_instance;
1692         struct netdev_private *np = dev->priv;
1693         long ioaddr = dev->base_addr;
1694         int boguscnt = max_interrupt_work;
1695         unsigned int handled = 0;
1696
1697         if (np->hands_off)
1698                 return IRQ_NONE;
1699         do {
1700                 /* Reading automatically acknowledges all int sources. */
1701                 u32 intr_status = readl(ioaddr + IntrStatus);
1702
1703                 if (netif_msg_intr(np))
1704                         printk(KERN_DEBUG
1705                                 "%s: Interrupt, status %#08x, mask %#08x.\n",
1706                                 dev->name, intr_status,
1707                                 readl(ioaddr + IntrMask));
1708
1709                 if (intr_status == 0)
1710                         break;
1711                 handled = 1;
1712
1713                 if (intr_status &
1714                    (IntrRxDone | IntrRxIntr | RxStatusFIFOOver |
1715                     IntrRxErr | IntrRxOverrun)) {
1716                         netdev_rx(dev);
1717                 }
1718
1719                 if (intr_status &
1720                    (IntrTxDone | IntrTxIntr | IntrTxIdle | IntrTxErr)) {
1721                         spin_lock(&np->lock);
1722                         netdev_tx_done(dev);
1723                         spin_unlock(&np->lock);
1724                 }
1725
1726                 /* Abnormal error summary/uncommon events handlers. */
1727                 if (intr_status & IntrAbnormalSummary)
1728                         netdev_error(dev, intr_status);
1729
1730                 if (--boguscnt < 0) {
1731                         if (netif_msg_intr(np))
1732                                 printk(KERN_WARNING
1733                                         "%s: Too much work at interrupt, "
1734                                         "status=%#08x.\n",
1735                                         dev->name, intr_status);
1736                         break;
1737                 }
1738         } while (1);
1739
1740         if (netif_msg_intr(np))
1741                 printk(KERN_DEBUG "%s: exiting interrupt.\n", dev->name);
1742
1743         return IRQ_RETVAL(handled);
1744 }
1745
1746 /* This routine is logically part of the interrupt handler, but separated
1747    for clarity and better register allocation. */
1748 static void netdev_rx(struct net_device *dev)
1749 {
1750         struct netdev_private *np = dev->priv;
1751         int entry = np->cur_rx % RX_RING_SIZE;
1752         int boguscnt = np->dirty_rx + RX_RING_SIZE - np->cur_rx;
1753         s32 desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
1754         unsigned int buflen = np->rx_buf_sz + RX_OFFSET;
1755
1756         /* If the driver owns the next entry it's a new packet. Send it up. */
1757         while (desc_status < 0) { /* e.g. & DescOwn */
1758                 if (netif_msg_rx_status(np))
1759                         printk(KERN_DEBUG
1760                                 "  netdev_rx() entry %d status was %#08x.\n",
1761                                 entry, desc_status);
1762                 if (--boguscnt < 0)
1763                         break;
1764                 if ((desc_status&(DescMore|DescPktOK|DescRxLong)) != DescPktOK){
1765                         if (desc_status & DescMore) {
1766                                 if (netif_msg_rx_err(np))
1767                                         printk(KERN_WARNING
1768                                                 "%s: Oversized(?) Ethernet "
1769                                                 "frame spanned multiple "
1770                                                 "buffers, entry %#08x "
1771                                                 "status %#08x.\n", dev->name,
1772                                                 np->cur_rx, desc_status);
1773                                 np->stats.rx_length_errors++;
1774                         } else {
1775                                 /* There was an error. */
1776                                 np->stats.rx_errors++;
1777                                 if (desc_status & (DescRxAbort|DescRxOver))
1778                                         np->stats.rx_over_errors++;
1779                                 if (desc_status & (DescRxLong|DescRxRunt))
1780                                         np->stats.rx_length_errors++;
1781                                 if (desc_status & (DescRxInvalid|DescRxAlign))
1782                                         np->stats.rx_frame_errors++;
1783                                 if (desc_status & DescRxCRC)
1784                                         np->stats.rx_crc_errors++;
1785                         }
1786                 } else {
1787                         struct sk_buff *skb;
1788                         /* Omit CRC size. */
1789                         int pkt_len = (desc_status & DescSizeMask) - 4;
1790                         /* Check if the packet is long enough to accept
1791                          * without copying to a minimally-sized skbuff. */
1792                         if (pkt_len < rx_copybreak
1793                             && (skb = dev_alloc_skb(pkt_len + RX_OFFSET)) != NULL) {
1794                                 skb->dev = dev;
1795                                 /* 16 byte align the IP header */
1796                                 skb_reserve(skb, RX_OFFSET);
1797                                 pci_dma_sync_single_for_cpu(np->pci_dev,
1798                                         np->rx_dma[entry],
1799                                         buflen,
1800                                         PCI_DMA_FROMDEVICE);
1801 #if HAS_IP_COPYSUM
1802                                 eth_copy_and_sum(skb,
1803                                         np->rx_skbuff[entry]->tail, pkt_len, 0);
1804                                 skb_put(skb, pkt_len);
1805 #else
1806                                 memcpy(skb_put(skb, pkt_len),
1807                                         np->rx_skbuff[entry]->tail, pkt_len);
1808 #endif
1809                                 pci_dma_sync_single_for_device(np->pci_dev,
1810                                         np->rx_dma[entry],
1811                                         buflen,
1812                                         PCI_DMA_FROMDEVICE);
1813                         } else {
1814                                 pci_unmap_single(np->pci_dev, np->rx_dma[entry],
1815                                         buflen, PCI_DMA_FROMDEVICE);
1816                                 skb_put(skb = np->rx_skbuff[entry], pkt_len);
1817                                 np->rx_skbuff[entry] = NULL;
1818                         }
1819                         skb->protocol = eth_type_trans(skb, dev);
1820                         netif_rx(skb);
1821                         dev->last_rx = jiffies;
1822                         np->stats.rx_packets++;
1823                         np->stats.rx_bytes += pkt_len;
1824                 }
1825                 entry = (++np->cur_rx) % RX_RING_SIZE;
1826                 np->rx_head_desc = &np->rx_ring[entry];
1827                 desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
1828         }
1829         refill_rx(dev);
1830
1831         /* Restart Rx engine if stopped. */
1832         if (np->oom)
1833                 mod_timer(&np->timer, jiffies + 1);
1834         else
1835                 writel(RxOn, dev->base_addr + ChipCmd);
1836 }
1837
1838 static void netdev_error(struct net_device *dev, int intr_status)
1839 {
1840         struct netdev_private *np = dev->priv;
1841         long ioaddr = dev->base_addr;
1842
1843         spin_lock(&np->lock);
1844         if (intr_status & LinkChange) {
1845                 u16 adv = mdio_read(dev, 1, MII_ADVERTISE);
1846                 u16 lpa = mdio_read(dev, 1, MII_LPA);
1847                 if (mdio_read(dev, 1, MII_BMCR) & BMCR_ANENABLE
1848                  && netif_msg_link(np)) {
1849                         printk(KERN_INFO
1850                                 "%s: Autonegotiation advertising"
1851                                 " %#04x  partner %#04x.\n", dev->name,
1852                                 adv, lpa);
1853                 }
1854
1855                 /* read MII int status to clear the flag */
1856                 readw(ioaddr + MIntrStatus);
1857                 check_link(dev);
1858         }
1859         if (intr_status & StatsMax) {
1860                 __get_stats(dev);
1861         }
1862         if (intr_status & IntrTxUnderrun) {
1863                 if ((np->tx_config & TxDrthMask) < 62)
1864                         np->tx_config += 2;
1865                 if (netif_msg_tx_err(np))
1866                         printk(KERN_NOTICE
1867                                 "%s: increased Tx threshold, txcfg %#08x.\n",
1868                                 dev->name, np->tx_config);
1869                 writel(np->tx_config, ioaddr + TxConfig);
1870         }
1871         if (intr_status & WOLPkt && netif_msg_wol(np)) {
1872                 int wol_status = readl(ioaddr + WOLCmd);
1873                 printk(KERN_NOTICE "%s: Link wake-up event %#08x\n",
1874                         dev->name, wol_status);
1875         }
1876         if (intr_status & RxStatusFIFOOver) {
1877                 if (netif_msg_rx_err(np) && netif_msg_intr(np)) {
1878                         printk(KERN_NOTICE "%s: Rx status FIFO overrun\n",
1879                                 dev->name);
1880                 }
1881                 np->stats.rx_fifo_errors++;
1882         }
1883         /* Hmmmmm, it's not clear how to recover from PCI faults. */
1884         if (intr_status & IntrPCIErr) {
1885                 printk(KERN_NOTICE "%s: PCI error %#08x\n", dev->name,
1886                         intr_status & IntrPCIErr);
1887                 np->stats.tx_fifo_errors++;
1888                 np->stats.rx_fifo_errors++;
1889         }
1890         spin_unlock(&np->lock);
1891 }
1892
1893 static void __get_stats(struct net_device *dev)
1894 {
1895         long ioaddr = dev->base_addr;
1896         struct netdev_private *np = dev->priv;
1897
1898         /* The chip only need report frame silently dropped. */
1899         np->stats.rx_crc_errors += readl(ioaddr + RxCRCErrs);
1900         np->stats.rx_missed_errors += readl(ioaddr + RxMissed);
1901 }
1902
1903 static struct net_device_stats *get_stats(struct net_device *dev)
1904 {
1905         struct netdev_private *np = dev->priv;
1906
1907         /* The chip only need report frame silently dropped. */
1908         spin_lock_irq(&np->lock);
1909         if (netif_running(dev) && !np->hands_off)
1910                 __get_stats(dev);
1911         spin_unlock_irq(&np->lock);
1912
1913         return &np->stats;
1914 }
1915
1916 #define HASH_TABLE      0x200
1917 static void __set_rx_mode(struct net_device *dev)
1918 {
1919         long ioaddr = dev->base_addr;
1920         struct netdev_private *np = dev->priv;
1921         u8 mc_filter[64]; /* Multicast hash filter */
1922         u32 rx_mode;
1923
1924         if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
1925                 /* Unconditionally log net taps. */
1926                 printk(KERN_NOTICE "%s: Promiscuous mode enabled.\n",
1927                         dev->name);
1928                 rx_mode = RxFilterEnable | AcceptBroadcast
1929                         | AcceptAllMulticast | AcceptAllPhys | AcceptMyPhys;
1930         } else if ((dev->mc_count > multicast_filter_limit)
1931           || (dev->flags & IFF_ALLMULTI)) {
1932                 rx_mode = RxFilterEnable | AcceptBroadcast
1933                         | AcceptAllMulticast | AcceptMyPhys;
1934         } else {
1935                 struct dev_mc_list *mclist;
1936                 int i;
1937                 memset(mc_filter, 0, sizeof(mc_filter));
1938                 for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
1939                          i++, mclist = mclist->next) {
1940                         int i = (ether_crc(ETH_ALEN, mclist->dmi_addr) >> 23) & 0x1ff;
1941                         mc_filter[i/8] |= (1 << (i & 0x07));
1942                 }
1943                 rx_mode = RxFilterEnable | AcceptBroadcast
1944                         | AcceptMulticast | AcceptMyPhys;
1945                 for (i = 0; i < 64; i += 2) {
1946                         writew(HASH_TABLE + i, ioaddr + RxFilterAddr);
1947                         writew((mc_filter[i+1]<<8) + mc_filter[i],
1948                                 ioaddr + RxFilterData);
1949                 }
1950         }
1951         writel(rx_mode, ioaddr + RxFilterAddr);
1952         np->cur_rx_mode = rx_mode;
1953 }
1954
1955 static void set_rx_mode(struct net_device *dev)
1956 {
1957         struct netdev_private *np = dev->priv;
1958         spin_lock_irq(&np->lock);
1959         if (!np->hands_off)
1960                 __set_rx_mode(dev);
1961         spin_unlock_irq(&np->lock);
1962 }
1963
1964 static int netdev_ethtool_ioctl(struct net_device *dev, void __user *useraddr)
1965 {
1966         struct netdev_private *np = dev->priv;
1967         u32 cmd;
1968
1969         if (get_user(cmd, (u32 __user *)useraddr))
1970                 return -EFAULT;
1971
1972         switch (cmd) {
1973         /* get driver info */
1974         case ETHTOOL_GDRVINFO: {
1975                 struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
1976                 strncpy(info.driver, DRV_NAME, ETHTOOL_BUSINFO_LEN);
1977                 strncpy(info.version, DRV_VERSION, ETHTOOL_BUSINFO_LEN);
1978                 info.fw_version[0] = '\0';
1979                 strncpy(info.bus_info, pci_name(np->pci_dev),
1980                         ETHTOOL_BUSINFO_LEN);
1981                 info.eedump_len = NATSEMI_EEPROM_SIZE;
1982                 info.regdump_len = NATSEMI_REGS_SIZE;
1983                 if (copy_to_user(useraddr, &info, sizeof(info)))
1984                         return -EFAULT;
1985                 return 0;
1986         }
1987         /* get settings */
1988         case ETHTOOL_GSET: {
1989                 struct ethtool_cmd ecmd = { ETHTOOL_GSET };
1990                 spin_lock_irq(&np->lock);
1991                 netdev_get_ecmd(dev, &ecmd);
1992                 spin_unlock_irq(&np->lock);
1993                 if (copy_to_user(useraddr, &ecmd, sizeof(ecmd)))
1994                         return -EFAULT;
1995                 return 0;
1996         }
1997         /* set settings */
1998         case ETHTOOL_SSET: {
1999                 struct ethtool_cmd ecmd;
2000                 int r;
2001                 if (copy_from_user(&ecmd, useraddr, sizeof(ecmd)))
2002                         return -EFAULT;
2003                 spin_lock_irq(&np->lock);
2004                 r = netdev_set_ecmd(dev, &ecmd);
2005                 spin_unlock_irq(&np->lock);
2006                 return r;
2007         }
2008         /* get wake-on-lan */
2009         case ETHTOOL_GWOL: {
2010                 struct ethtool_wolinfo wol = {ETHTOOL_GWOL};
2011                 spin_lock_irq(&np->lock);
2012                 netdev_get_wol(dev, &wol.supported, &wol.wolopts);
2013                 netdev_get_sopass(dev, wol.sopass);
2014                 spin_unlock_irq(&np->lock);
2015                 if (copy_to_user(useraddr, &wol, sizeof(wol)))
2016                         return -EFAULT;
2017                 return 0;
2018         }
2019         /* set wake-on-lan */
2020         case ETHTOOL_SWOL: {
2021                 struct ethtool_wolinfo wol;
2022                 int r;
2023                 if (copy_from_user(&wol, useraddr, sizeof(wol)))
2024                         return -EFAULT;
2025                 spin_lock_irq(&np->lock);
2026                 netdev_set_wol(dev, wol.wolopts);
2027                 r = netdev_set_sopass(dev, wol.sopass);
2028                 spin_unlock_irq(&np->lock);
2029                 return r;
2030         }
2031         /* get registers */
2032         case ETHTOOL_GREGS: {
2033                 struct ethtool_regs regs;
2034                 u8 regbuf[NATSEMI_REGS_SIZE];
2035                 int r;
2036
2037                 if (copy_from_user(&regs, useraddr, sizeof(regs)))
2038                         return -EFAULT;
2039
2040                 if (regs.len > NATSEMI_REGS_SIZE) {
2041                         regs.len = NATSEMI_REGS_SIZE;
2042                 }
2043                 regs.version = NATSEMI_REGS_VER;
2044                 if (copy_to_user(useraddr, &regs, sizeof(regs)))
2045                         return -EFAULT;
2046
2047                 useraddr += offsetof(struct ethtool_regs, data);
2048
2049                 spin_lock_irq(&np->lock);
2050                 r = netdev_get_regs(dev, regbuf);
2051                 spin_unlock_irq(&np->lock);
2052
2053                 if (r)
2054                         return r;
2055                 if (copy_to_user(useraddr, regbuf, regs.len))
2056                         return -EFAULT;
2057                 return 0;
2058         }
2059         /* get message-level */
2060         case ETHTOOL_GMSGLVL: {
2061                 struct ethtool_value edata = {ETHTOOL_GMSGLVL};
2062                 edata.data = np->msg_enable;
2063                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2064                         return -EFAULT;
2065                 return 0;
2066         }
2067         /* set message-level */
2068         case ETHTOOL_SMSGLVL: {
2069                 struct ethtool_value edata;
2070                 if (copy_from_user(&edata, useraddr, sizeof(edata)))
2071                         return -EFAULT;
2072                 np->msg_enable = edata.data;
2073                 return 0;
2074         }
2075         /* restart autonegotiation */
2076         case ETHTOOL_NWAY_RST: {
2077                 int tmp;
2078                 int r = -EINVAL;
2079                 /* if autoneg is off, it's an error */
2080                 tmp = mdio_read(dev, 1, MII_BMCR);
2081                 if (tmp & BMCR_ANENABLE) {
2082                         tmp |= (BMCR_ANRESTART);
2083                         mdio_write(dev, 1, MII_BMCR, tmp);
2084                         r = 0;
2085                 }
2086                 return r;
2087         }
2088         /* get link status */
2089         case ETHTOOL_GLINK: {
2090                 struct ethtool_value edata = {ETHTOOL_GLINK};
2091                 /* LSTATUS is latched low until a read - so read twice */
2092                 mdio_read(dev, 1, MII_BMSR);
2093                 edata.data = (mdio_read(dev, 1, MII_BMSR)&BMSR_LSTATUS) ? 1:0;
2094                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2095                         return -EFAULT;
2096                 return 0;
2097         }
2098         /* get EEPROM */
2099         case ETHTOOL_GEEPROM: {
2100                 struct ethtool_eeprom eeprom;
2101                 u8 eebuf[NATSEMI_EEPROM_SIZE];
2102                 int r;
2103
2104                 if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
2105                         return -EFAULT;
2106
2107                 if (eeprom.offset > eeprom.offset+eeprom.len)
2108                         return -EINVAL;
2109
2110                 if ((eeprom.offset+eeprom.len) > NATSEMI_EEPROM_SIZE) {
2111                         eeprom.len = NATSEMI_EEPROM_SIZE-eeprom.offset;
2112                 }
2113                 eeprom.magic = PCI_VENDOR_ID_NS | (PCI_DEVICE_ID_NS_83815<<16);
2114                 if (copy_to_user(useraddr, &eeprom, sizeof(eeprom)))
2115                         return -EFAULT;
2116
2117                 useraddr += offsetof(struct ethtool_eeprom, data);
2118
2119                 spin_lock_irq(&np->lock);
2120                 r = netdev_get_eeprom(dev, eebuf);
2121                 spin_unlock_irq(&np->lock);
2122
2123                 if (r)
2124                         return r;
2125                 if (copy_to_user(useraddr, eebuf+eeprom.offset, eeprom.len))
2126                         return -EFAULT;
2127                 return 0;
2128         }
2129
2130         }
2131
2132         return -EOPNOTSUPP;
2133 }
2134
2135 static int netdev_set_wol(struct net_device *dev, u32 newval)
2136 {
2137         struct netdev_private *np = dev->priv;
2138         u32 data = readl(dev->base_addr + WOLCmd) & ~WakeOptsSummary;
2139
2140         /* translate to bitmasks this chip understands */
2141         if (newval & WAKE_PHY)
2142                 data |= WakePhy;
2143         if (newval & WAKE_UCAST)
2144                 data |= WakeUnicast;
2145         if (newval & WAKE_MCAST)
2146                 data |= WakeMulticast;
2147         if (newval & WAKE_BCAST)
2148                 data |= WakeBroadcast;
2149         if (newval & WAKE_ARP)
2150                 data |= WakeArp;
2151         if (newval & WAKE_MAGIC)
2152                 data |= WakeMagic;
2153         if (np->srr >= SRR_DP83815_D) {
2154                 if (newval & WAKE_MAGICSECURE) {
2155                         data |= WakeMagicSecure;
2156                 }
2157         }
2158
2159         writel(data, dev->base_addr + WOLCmd);
2160
2161         return 0;
2162 }
2163
2164 static int netdev_get_wol(struct net_device *dev, u32 *supported, u32 *cur)
2165 {
2166         struct netdev_private *np = dev->priv;
2167         u32 regval = readl(dev->base_addr + WOLCmd);
2168
2169         *supported = (WAKE_PHY | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST
2170                         | WAKE_ARP | WAKE_MAGIC);
2171
2172         if (np->srr >= SRR_DP83815_D) {
2173                 /* SOPASS works on revD and higher */
2174                 *supported |= WAKE_MAGICSECURE;
2175         }
2176         *cur = 0;
2177
2178         /* translate from chip bitmasks */
2179         if (regval & WakePhy)
2180                 *cur |= WAKE_PHY;
2181         if (regval & WakeUnicast)
2182                 *cur |= WAKE_UCAST;
2183         if (regval & WakeMulticast)
2184                 *cur |= WAKE_MCAST;
2185         if (regval & WakeBroadcast)
2186                 *cur |= WAKE_BCAST;
2187         if (regval & WakeArp)
2188                 *cur |= WAKE_ARP;
2189         if (regval & WakeMagic)
2190                 *cur |= WAKE_MAGIC;
2191         if (regval & WakeMagicSecure) {
2192                 /* this can be on in revC, but it's broken */
2193                 *cur |= WAKE_MAGICSECURE;
2194         }
2195
2196         return 0;
2197 }
2198
2199 static int netdev_set_sopass(struct net_device *dev, u8 *newval)
2200 {
2201         struct netdev_private *np = dev->priv;
2202         u16 *sval = (u16 *)newval;
2203         u32 addr;
2204
2205         if (np->srr < SRR_DP83815_D) {
2206                 return 0;
2207         }
2208
2209         /* enable writing to these registers by disabling the RX filter */
2210         addr = readl(dev->base_addr + RxFilterAddr) & ~RFCRAddressMask;
2211         addr &= ~RxFilterEnable;
2212         writel(addr, dev->base_addr + RxFilterAddr);
2213
2214         /* write the three words to (undocumented) RFCR vals 0xa, 0xc, 0xe */
2215         writel(addr | 0xa, dev->base_addr + RxFilterAddr);
2216         writew(sval[0], dev->base_addr + RxFilterData);
2217
2218         writel(addr | 0xc, dev->base_addr + RxFilterAddr);
2219         writew(sval[1], dev->base_addr + RxFilterData);
2220
2221         writel(addr | 0xe, dev->base_addr + RxFilterAddr);
2222         writew(sval[2], dev->base_addr + RxFilterData);
2223
2224         /* re-enable the RX filter */
2225         writel(addr | RxFilterEnable, dev->base_addr + RxFilterAddr);
2226
2227         return 0;
2228 }
2229
2230 static int netdev_get_sopass(struct net_device *dev, u8 *data)
2231 {
2232         struct netdev_private *np = dev->priv;
2233         u16 *sval = (u16 *)data;
2234         u32 addr;
2235
2236         if (np->srr < SRR_DP83815_D) {
2237                 sval[0] = sval[1] = sval[2] = 0;
2238                 return 0;
2239         }
2240
2241         /* read the three words from (undocumented) RFCR vals 0xa, 0xc, 0xe */
2242         addr = readl(dev->base_addr + RxFilterAddr) & ~RFCRAddressMask;
2243
2244         writel(addr | 0xa, dev->base_addr + RxFilterAddr);
2245         sval[0] = readw(dev->base_addr + RxFilterData);
2246
2247         writel(addr | 0xc, dev->base_addr + RxFilterAddr);
2248         sval[1] = readw(dev->base_addr + RxFilterData);
2249
2250         writel(addr | 0xe, dev->base_addr + RxFilterAddr);
2251         sval[2] = readw(dev->base_addr + RxFilterData);
2252
2253         writel(addr, dev->base_addr + RxFilterAddr);
2254
2255         return 0;
2256 }
2257
2258 static int netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
2259 {
2260         u32 tmp;
2261
2262         ecmd->supported =
2263                 (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
2264                 SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
2265                 SUPPORTED_Autoneg | SUPPORTED_TP | SUPPORTED_MII);
2266
2267         /* only supports twisted-pair or MII */
2268         tmp = readl(dev->base_addr + ChipConfig);
2269         if (tmp & CfgExtPhy)
2270                 ecmd->port = PORT_MII;
2271         else
2272                 ecmd->port = PORT_TP;
2273
2274         /* only supports internal transceiver */
2275         ecmd->transceiver = XCVR_INTERNAL;
2276
2277         /* not sure what this is for */
2278         ecmd->phy_address = readw(dev->base_addr + PhyCtrl) & PhyAddrMask;
2279
2280         ecmd->advertising = ADVERTISED_TP | ADVERTISED_MII;
2281         tmp = mdio_read(dev, 1, MII_ADVERTISE);
2282         if (tmp & ADVERTISE_10HALF)
2283                 ecmd->advertising |= ADVERTISED_10baseT_Half;
2284         if (tmp & ADVERTISE_10FULL)
2285                 ecmd->advertising |= ADVERTISED_10baseT_Full;
2286         if (tmp & ADVERTISE_100HALF)
2287                 ecmd->advertising |= ADVERTISED_100baseT_Half;
2288         if (tmp & ADVERTISE_100FULL)
2289                 ecmd->advertising |= ADVERTISED_100baseT_Full;
2290
2291         tmp = mdio_read(dev, 1, MII_BMCR);
2292         if (tmp & BMCR_ANENABLE) {
2293                 ecmd->advertising |= ADVERTISED_Autoneg;
2294                 ecmd->autoneg = AUTONEG_ENABLE;
2295         } else {
2296                 ecmd->autoneg = AUTONEG_DISABLE;
2297         }
2298
2299         tmp = readl(dev->base_addr + ChipConfig);
2300         if (tmp & CfgSpeed100) {
2301                 ecmd->speed = SPEED_100;
2302         } else {
2303                 ecmd->speed = SPEED_10;
2304         }
2305
2306         if (tmp & CfgFullDuplex) {
2307                 ecmd->duplex = DUPLEX_FULL;
2308         } else {
2309                 ecmd->duplex = DUPLEX_HALF;
2310         }
2311
2312         /* ignore maxtxpkt, maxrxpkt for now */
2313
2314         return 0;
2315 }
2316
2317 static int netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
2318 {
2319         struct netdev_private *np = dev->priv;
2320         u32 tmp;
2321
2322         if (ecmd->speed != SPEED_10 && ecmd->speed != SPEED_100)
2323                 return -EINVAL;
2324         if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL)
2325                 return -EINVAL;
2326         if (ecmd->port != PORT_TP && ecmd->port != PORT_MII)
2327                 return -EINVAL;
2328         if (ecmd->transceiver != XCVR_INTERNAL)
2329                 return -EINVAL;
2330         if (ecmd->autoneg != AUTONEG_DISABLE && ecmd->autoneg != AUTONEG_ENABLE)
2331                 return -EINVAL;
2332         /* ignore phy_address, maxtxpkt, maxrxpkt for now */
2333
2334         /* WHEW! now lets bang some bits */
2335
2336         tmp = mdio_read(dev, 1, MII_BMCR);
2337         if (ecmd->autoneg == AUTONEG_ENABLE) {
2338                 /* turn on autonegotiation */
2339                 tmp |= BMCR_ANENABLE;
2340                 np->advertising = mdio_read(dev, 1, MII_ADVERTISE);
2341         } else {
2342                 /* turn off auto negotiation, set speed and duplexity */
2343                 tmp &= ~(BMCR_ANENABLE | BMCR_SPEED100 | BMCR_FULLDPLX);
2344                 if (ecmd->speed == SPEED_100)
2345                         tmp |= BMCR_SPEED100;
2346                 if (ecmd->duplex == DUPLEX_FULL)
2347                         tmp |= BMCR_FULLDPLX;
2348                 else
2349                         np->full_duplex = 0;
2350         }
2351         mdio_write(dev, 1, MII_BMCR, tmp);
2352         return 0;
2353 }
2354
2355 static int netdev_get_regs(struct net_device *dev, u8 *buf)
2356 {
2357         int i;
2358         int j;
2359         u32 rfcr;
2360         u32 *rbuf = (u32 *)buf;
2361
2362         /* read all of page 0 of registers */
2363         for (i = 0; i < NATSEMI_PG0_NREGS; i++) {
2364                 rbuf[i] = readl(dev->base_addr + i*4);
2365         }
2366
2367         /* read only the 'magic' registers from page 1 */
2368         writew(1, dev->base_addr + PGSEL);
2369         rbuf[i++] = readw(dev->base_addr + PMDCSR);
2370         rbuf[i++] = readw(dev->base_addr + TSTDAT);
2371         rbuf[i++] = readw(dev->base_addr + DSPCFG);
2372         rbuf[i++] = readw(dev->base_addr + SDCFG);
2373         writew(0, dev->base_addr + PGSEL);
2374
2375         /* read RFCR indexed registers */
2376         rfcr = readl(dev->base_addr + RxFilterAddr);
2377         for (j = 0; j < NATSEMI_RFDR_NREGS; j++) {
2378                 writel(j*2, dev->base_addr + RxFilterAddr);
2379                 rbuf[i++] = readw(dev->base_addr + RxFilterData);
2380         }
2381         writel(rfcr, dev->base_addr + RxFilterAddr);
2382
2383         /* the interrupt status is clear-on-read - see if we missed any */
2384         if (rbuf[4] & rbuf[5]) {
2385                 printk(KERN_WARNING
2386                         "%s: shoot, we dropped an interrupt (%#08x)\n",
2387                         dev->name, rbuf[4] & rbuf[5]);
2388         }
2389
2390         return 0;
2391 }
2392
2393 #define SWAP_BITS(x)    ( (((x) & 0x0001) << 15) | (((x) & 0x0002) << 13) \
2394                         | (((x) & 0x0004) << 11) | (((x) & 0x0008) << 9)  \
2395                         | (((x) & 0x0010) << 7)  | (((x) & 0x0020) << 5)  \
2396                         | (((x) & 0x0040) << 3)  | (((x) & 0x0080) << 1)  \
2397                         | (((x) & 0x0100) >> 1)  | (((x) & 0x0200) >> 3)  \
2398                         | (((x) & 0x0400) >> 5)  | (((x) & 0x0800) >> 7)  \
2399                         | (((x) & 0x1000) >> 9)  | (((x) & 0x2000) >> 11) \
2400                         | (((x) & 0x4000) >> 13) | (((x) & 0x8000) >> 15) )
2401
2402 static int netdev_get_eeprom(struct net_device *dev, u8 *buf)
2403 {
2404         int i;
2405         u16 *ebuf = (u16 *)buf;
2406
2407         /* eeprom_read reads 16 bits, and indexes by 16 bits */
2408         for (i = 0; i < NATSEMI_EEPROM_SIZE/2; i++) {
2409                 ebuf[i] = eeprom_read(dev->base_addr, i);
2410                 /* The EEPROM itself stores data bit-swapped, but eeprom_read
2411                  * reads it back "sanely". So we swap it back here in order to
2412                  * present it to userland as it is stored. */
2413                 ebuf[i] = SWAP_BITS(ebuf[i]);
2414         }
2415         return 0;
2416 }
2417
2418 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2419 {
2420         struct mii_ioctl_data *data = if_mii(rq);
2421
2422         switch(cmd) {
2423         case SIOCETHTOOL:
2424                 return netdev_ethtool_ioctl(dev, rq->ifr_data);
2425         case SIOCGMIIPHY:               /* Get address of MII PHY in use. */
2426         case SIOCDEVPRIVATE:            /* for binary compat, remove in 2.5 */
2427                 data->phy_id = 1;
2428                 /* Fall Through */
2429
2430         case SIOCGMIIREG:               /* Read MII PHY register. */
2431         case SIOCDEVPRIVATE+1:          /* for binary compat, remove in 2.5 */
2432                 data->val_out = mdio_read(dev, data->phy_id & 0x1f,
2433                         data->reg_num & 0x1f);
2434                 return 0;
2435
2436         case SIOCSMIIREG:               /* Write MII PHY register. */
2437         case SIOCDEVPRIVATE+2:          /* for binary compat, remove in 2.5 */
2438                 if (!capable(CAP_NET_ADMIN))
2439                         return -EPERM;
2440                 mdio_write(dev, data->phy_id & 0x1f, data->reg_num & 0x1f,
2441                         data->val_in);
2442                 return 0;
2443         default:
2444                 return -EOPNOTSUPP;
2445         }
2446 }
2447
2448 static void enable_wol_mode(struct net_device *dev, int enable_intr)
2449 {
2450         long ioaddr = dev->base_addr;
2451         struct netdev_private *np = dev->priv;
2452
2453         if (netif_msg_wol(np))
2454                 printk(KERN_INFO "%s: remaining active for wake-on-lan\n",
2455                         dev->name);
2456
2457         /* For WOL we must restart the rx process in silent mode.
2458          * Write NULL to the RxRingPtr. Only possible if
2459          * rx process is stopped
2460          */
2461         writel(0, ioaddr + RxRingPtr);
2462
2463         /* read WoL status to clear */
2464         readl(ioaddr + WOLCmd);
2465
2466         /* PME on, clear status */
2467         writel(np->SavedClkRun | PMEEnable | PMEStatus, ioaddr + ClkRun);
2468
2469         /* and restart the rx process */
2470         writel(RxOn, ioaddr + ChipCmd);
2471
2472         if (enable_intr) {
2473                 /* enable the WOL interrupt.
2474                  * Could be used to send a netlink message.
2475                  */
2476                 writel(WOLPkt | LinkChange, ioaddr + IntrMask);
2477                 writel(1, ioaddr + IntrEnable);
2478         }
2479 }
2480
2481 static int netdev_close(struct net_device *dev)
2482 {
2483         long ioaddr = dev->base_addr;
2484         struct netdev_private *np = dev->priv;
2485
2486         if (netif_msg_ifdown(np))
2487                 printk(KERN_DEBUG
2488                         "%s: Shutting down ethercard, status was %#04x.\n",
2489                         dev->name, (int)readl(ioaddr + ChipCmd));
2490         if (netif_msg_pktdata(np))
2491                 printk(KERN_DEBUG
2492                         "%s: Queue pointers were Tx %d / %d,  Rx %d / %d.\n",
2493                         dev->name, np->cur_tx, np->dirty_tx,
2494                         np->cur_rx, np->dirty_rx);
2495
2496         /*
2497          * FIXME: what if someone tries to close a device
2498          * that is suspended?
2499          * Should we reenable the nic to switch to
2500          * the final WOL settings?
2501          */
2502
2503         del_timer_sync(&np->timer);
2504         disable_irq(dev->irq);
2505         spin_lock_irq(&np->lock);
2506         /* Disable interrupts, and flush posted writes */
2507         writel(0, ioaddr + IntrEnable);
2508         readl(ioaddr + IntrEnable);
2509         np->hands_off = 1;
2510         spin_unlock_irq(&np->lock);
2511         enable_irq(dev->irq);
2512
2513         free_irq(dev->irq, dev);
2514
2515         /* Interrupt disabled, interrupt handler released,
2516          * queue stopped, timer deleted, rtnl_lock held
2517          * All async codepaths that access the driver are disabled.
2518          */
2519         spin_lock_irq(&np->lock);
2520         np->hands_off = 0;
2521         readl(ioaddr + IntrMask);
2522         readw(ioaddr + MIntrStatus);
2523
2524         /* Freeze Stats */
2525         writel(StatsFreeze, ioaddr + StatsCtrl);
2526
2527         /* Stop the chip's Tx and Rx processes. */
2528         natsemi_stop_rxtx(dev);
2529
2530         __get_stats(dev);
2531         spin_unlock_irq(&np->lock);
2532
2533         /* clear the carrier last - an interrupt could reenable it otherwise */
2534         netif_carrier_off(dev);
2535         netif_stop_queue(dev);
2536
2537         dump_ring(dev);
2538         drain_ring(dev);
2539         free_ring(dev);
2540
2541         {
2542                 u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
2543                 if (wol) {
2544                         /* restart the NIC in WOL mode.
2545                          * The nic must be stopped for this.
2546                          */
2547                         enable_wol_mode(dev, 0);
2548                 } else {
2549                         /* Restore PME enable bit unmolested */
2550                         writel(np->SavedClkRun, ioaddr + ClkRun);
2551                 }
2552         }
2553         return 0;
2554 }
2555
2556
2557 static void __devexit natsemi_remove1 (struct pci_dev *pdev)
2558 {
2559         struct net_device *dev = pci_get_drvdata(pdev);
2560
2561         unregister_netdev (dev);
2562         pci_release_regions (pdev);
2563         iounmap ((char *) dev->base_addr);
2564         free_netdev (dev);
2565         pci_set_drvdata(pdev, NULL);
2566 }
2567
2568 #ifdef CONFIG_PM
2569
2570 /*
2571  * The ns83815 chip doesn't have explicit RxStop bits.
2572  * Kicking the Rx or Tx process for a new packet reenables the Rx process
2573  * of the nic, thus this function must be very careful:
2574  *
2575  * suspend/resume synchronization:
2576  * entry points:
2577  *   netdev_open, netdev_close, netdev_ioctl, set_rx_mode, intr_handler,
2578  *   start_tx, tx_timeout
2579  *
2580  * No function accesses the hardware without checking np->hands_off.
2581  *      the check occurs under spin_lock_irq(&np->lock);
2582  * exceptions:
2583  *      * netdev_ioctl: noncritical access.
2584  *      * netdev_open: cannot happen due to the device_detach
2585  *      * netdev_close: doesn't hurt.
2586  *      * netdev_timer: timer stopped by natsemi_suspend.
2587  *      * intr_handler: doesn't acquire the spinlock. suspend calls
2588  *              disable_irq() to enforce synchronization.
2589  *
2590  * Interrupts must be disabled, otherwise hands_off can cause irq storms.
2591  */
2592
2593 static int natsemi_suspend (struct pci_dev *pdev, u32 state)
2594 {
2595         struct net_device *dev = pci_get_drvdata (pdev);
2596         struct netdev_private *np = dev->priv;
2597         long ioaddr = dev->base_addr;
2598
2599         rtnl_lock();
2600         if (netif_running (dev)) {
2601                 del_timer_sync(&np->timer);
2602
2603                 disable_irq(dev->irq);
2604                 spin_lock_irq(&np->lock);
2605
2606                 writel(0, ioaddr + IntrEnable);
2607                 np->hands_off = 1;
2608                 natsemi_stop_rxtx(dev);
2609                 netif_stop_queue(dev);
2610
2611                 spin_unlock_irq(&np->lock);
2612                 enable_irq(dev->irq);
2613
2614                 /* Update the error counts. */
2615                 __get_stats(dev);
2616
2617                 /* pci_power_off(pdev, -1); */
2618                 drain_ring(dev);
2619                 {
2620                         u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
2621                         /* Restore PME enable bit */
2622                         if (wol) {
2623                                 /* restart the NIC in WOL mode.
2624                                  * The nic must be stopped for this.
2625                                  * FIXME: use the WOL interrupt
2626                                  */
2627                                 enable_wol_mode(dev, 0);
2628                         } else {
2629                                 /* Restore PME enable bit unmolested */
2630                                 writel(np->SavedClkRun, ioaddr + ClkRun);
2631                         }
2632                 }
2633         }
2634         netif_device_detach(dev);
2635         rtnl_unlock();
2636         return 0;
2637 }
2638
2639
2640 static int natsemi_resume (struct pci_dev *pdev)
2641 {
2642         struct net_device *dev = pci_get_drvdata (pdev);
2643         struct netdev_private *np = dev->priv;
2644
2645         rtnl_lock();
2646         if (netif_device_present(dev))
2647                 goto out;
2648         if (netif_running(dev)) {
2649                 BUG_ON(!np->hands_off);
2650                 pci_enable_device(pdev);
2651         /*      pci_power_on(pdev); */
2652
2653                 natsemi_reset(dev);
2654                 init_ring(dev);
2655                 disable_irq(dev->irq);
2656                 spin_lock_irq(&np->lock);
2657                 np->hands_off = 0;
2658                 init_registers(dev);
2659                 netif_device_attach(dev);
2660                 spin_unlock_irq(&np->lock);
2661                 enable_irq(dev->irq);
2662
2663                 mod_timer(&np->timer, jiffies + 1*HZ);
2664         }
2665         netif_device_attach(dev);
2666 out:
2667         rtnl_unlock();
2668         return 0;
2669 }
2670
2671 #endif /* CONFIG_PM */
2672
2673 static struct pci_driver natsemi_driver = {
2674         .name           = DRV_NAME,
2675         .id_table       = natsemi_pci_tbl,
2676         .probe          = natsemi_probe1,
2677         .remove         = __devexit_p(natsemi_remove1),
2678 #ifdef CONFIG_PM
2679         .suspend        = natsemi_suspend,
2680         .resume         = natsemi_resume,
2681 #endif
2682 };
2683
2684 static int __init natsemi_init_mod (void)
2685 {
2686 /* when a module, this is printed whether or not devices are found in probe */
2687 #ifdef MODULE
2688         printk(version);
2689 #endif
2690
2691         return pci_module_init (&natsemi_driver);
2692 }
2693
2694 static void __exit natsemi_exit_mod (void)
2695 {
2696         pci_unregister_driver (&natsemi_driver);
2697 }
2698
2699 module_init(natsemi_init_mod);
2700 module_exit(natsemi_exit_mod);
2701