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