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