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