vserver 1.9.3
[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 <asm/processor.h>      /* Processor type for cache alignment. */
163 #include <asm/bitops.h>
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
772 static inline void __iomem *ns_ioaddr(struct net_device *dev)
773 {
774         return (void __iomem *) dev->base_addr;
775 }
776
777 static void move_int_phy(struct net_device *dev, int addr)
778 {
779         struct netdev_private *np = netdev_priv(dev);
780         void __iomem *ioaddr = ns_ioaddr(dev);
781         int target = 31;
782
783         /* 
784          * The internal phy is visible on the external mii bus. Therefore we must
785          * move it away before we can send commands to an external phy.
786          * There are two addresses we must avoid:
787          * - the address on the external phy that is used for transmission.
788          * - the address that we want to access. User space can access phys
789          *   on the mii bus with SIOCGMIIREG/SIOCSMIIREG, independant from the
790          *   phy that is used for transmission.
791          */
792
793         if (target == addr)
794                 target--;
795         if (target == np->phy_addr_external)
796                 target--;
797         writew(target, ioaddr + PhyCtrl);
798         readw(ioaddr + PhyCtrl);
799         udelay(1);
800 }
801
802 static int __devinit natsemi_probe1 (struct pci_dev *pdev,
803         const struct pci_device_id *ent)
804 {
805         struct net_device *dev;
806         struct netdev_private *np;
807         int i, option, irq, chip_idx = ent->driver_data;
808         static int find_cnt = -1;
809         unsigned long iostart, iosize;
810         void __iomem *ioaddr;
811         const int pcibar = 1; /* PCI base address register */
812         int prev_eedata;
813         u32 tmp;
814
815 /* when built into the kernel, we only print version if device is found */
816 #ifndef MODULE
817         static int printed_version;
818         if (!printed_version++)
819                 printk(version);
820 #endif
821
822         i = pci_enable_device(pdev);
823         if (i) return i;
824
825         /* natsemi has a non-standard PM control register
826          * in PCI config space.  Some boards apparently need
827          * to be brought to D0 in this manner.
828          */
829         pci_read_config_dword(pdev, PCIPM, &tmp);
830         if (tmp & PCI_PM_CTRL_STATE_MASK) {
831                 /* D0 state, disable PME assertion */
832                 u32 newtmp = tmp & ~PCI_PM_CTRL_STATE_MASK;
833                 pci_write_config_dword(pdev, PCIPM, newtmp);
834         }
835
836         find_cnt++;
837         iostart = pci_resource_start(pdev, pcibar);
838         iosize = pci_resource_len(pdev, pcibar);
839         irq = pdev->irq;
840
841         if (natsemi_pci_info[chip_idx].flags & PCI_USES_MASTER)
842                 pci_set_master(pdev);
843
844         dev = alloc_etherdev(sizeof (struct netdev_private));
845         if (!dev)
846                 return -ENOMEM;
847         SET_MODULE_OWNER(dev);
848         SET_NETDEV_DEV(dev, &pdev->dev);
849
850         i = pci_request_regions(pdev, DRV_NAME);
851         if (i)
852                 goto err_pci_request_regions;
853
854         ioaddr = ioremap(iostart, iosize);
855         if (!ioaddr) {
856                 i = -ENOMEM;
857                 goto err_ioremap;
858         }
859
860         /* Work around the dropped serial bit. */
861         prev_eedata = eeprom_read(ioaddr, 6);
862         for (i = 0; i < 3; i++) {
863                 int eedata = eeprom_read(ioaddr, i + 7);
864                 dev->dev_addr[i*2] = (eedata << 1) + (prev_eedata >> 15);
865                 dev->dev_addr[i*2+1] = eedata >> 7;
866                 prev_eedata = eedata;
867         }
868
869         dev->base_addr = (unsigned long __force) ioaddr;
870         dev->irq = irq;
871
872         np = netdev_priv(dev);
873
874         np->pci_dev = pdev;
875         pci_set_drvdata(pdev, dev);
876         np->iosize = iosize;
877         spin_lock_init(&np->lock);
878         np->msg_enable = (debug >= 0) ? (1<<debug)-1 : NATSEMI_DEF_MSG;
879         np->hands_off = 0;
880
881         /* Initial port:
882          * - If the nic was configured to use an external phy and if find_mii
883          *   finds a phy: use external port, first phy that replies.
884          * - Otherwise: internal port.
885          * Note that the phy address for the internal phy doesn't matter:
886          * The address would be used to access a phy over the mii bus, but
887          * the internal phy is accessed through mapped registers.
888          */
889         if (readl(ioaddr + ChipConfig) & CfgExtPhy)
890                 dev->if_port = PORT_MII;
891         else
892                 dev->if_port = PORT_TP;
893         /* Reset the chip to erase previous misconfiguration. */
894         natsemi_reload_eeprom(dev);
895         natsemi_reset(dev);
896
897         if (dev->if_port != PORT_TP) {
898                 np->phy_addr_external = find_mii(dev);
899                 if (np->phy_addr_external == PHY_ADDR_NONE) {
900                         dev->if_port = PORT_TP;
901                         np->phy_addr_external = PHY_ADDR_INTERNAL;
902                 }
903         } else {
904                 np->phy_addr_external = PHY_ADDR_INTERNAL;
905         }
906
907         option = find_cnt < MAX_UNITS ? options[find_cnt] : 0;
908         if (dev->mem_start)
909                 option = dev->mem_start;
910
911         /* The lower four bits are the media type. */
912         if (option) {
913                 if (option & 0x200)
914                         np->full_duplex = 1;
915                 if (option & 15)
916                         printk(KERN_INFO
917                                 "natsemi %s: ignoring user supplied media type %d",
918                                 pci_name(np->pci_dev), option & 15);
919         }
920         if (find_cnt < MAX_UNITS  &&  full_duplex[find_cnt])
921                 np->full_duplex = 1;
922
923         /* The chip-specific entries in the device structure. */
924         dev->open = &netdev_open;
925         dev->hard_start_xmit = &start_tx;
926         dev->stop = &netdev_close;
927         dev->get_stats = &get_stats;
928         dev->set_multicast_list = &set_rx_mode;
929         dev->change_mtu = &natsemi_change_mtu;
930         dev->do_ioctl = &netdev_ioctl;
931         dev->tx_timeout = &tx_timeout;
932         dev->watchdog_timeo = TX_TIMEOUT;
933 #ifdef CONFIG_NET_POLL_CONTROLLER
934         dev->poll_controller = &natsemi_poll_controller;
935 #endif
936
937         if (mtu)
938                 dev->mtu = mtu;
939
940         netif_carrier_off(dev);
941
942         /* get the initial settings from hardware */
943         tmp            = mdio_read(dev, MII_BMCR);
944         np->speed      = (tmp & BMCR_SPEED100)? SPEED_100     : SPEED_10;
945         np->duplex     = (tmp & BMCR_FULLDPLX)? DUPLEX_FULL   : DUPLEX_HALF;
946         np->autoneg    = (tmp & BMCR_ANENABLE)? AUTONEG_ENABLE: AUTONEG_DISABLE;
947         np->advertising= mdio_read(dev, MII_ADVERTISE);
948
949         if ((np->advertising & ADVERTISE_ALL) != ADVERTISE_ALL
950          && netif_msg_probe(np)) {
951                 printk(KERN_INFO "natsemi %s: Transceiver default autonegotiation %s "
952                         "10%s %s duplex.\n",
953                         pci_name(np->pci_dev),
954                         (mdio_read(dev, MII_BMCR) & BMCR_ANENABLE)?
955                           "enabled, advertise" : "disabled, force",
956                         (np->advertising &
957                           (ADVERTISE_100FULL|ADVERTISE_100HALF))?
958                             "0" : "",
959                         (np->advertising &
960                           (ADVERTISE_100FULL|ADVERTISE_10FULL))?
961                             "full" : "half");
962         }
963         if (netif_msg_probe(np))
964                 printk(KERN_INFO
965                         "natsemi %s: Transceiver status %#04x advertising %#04x.\n",
966                         pci_name(np->pci_dev), mdio_read(dev, MII_BMSR),
967                         np->advertising);
968
969         /* save the silicon revision for later querying */
970         np->srr = readl(ioaddr + SiliconRev);
971         if (netif_msg_hw(np))
972                 printk(KERN_INFO "natsemi %s: silicon revision %#04x.\n",
973                                 pci_name(np->pci_dev), np->srr);
974
975         i = register_netdev(dev);
976         if (i)
977                 goto err_register_netdev;
978
979         if (netif_msg_drv(np)) {
980                 printk(KERN_INFO "natsemi %s: %s at %#08lx (%s), ",
981                         dev->name, natsemi_pci_info[chip_idx].name, iostart,
982                         pci_name(np->pci_dev));
983                 for (i = 0; i < ETH_ALEN-1; i++)
984                                 printk("%02x:", dev->dev_addr[i]);
985                 printk("%02x, IRQ %d", dev->dev_addr[i], irq);
986                 if (dev->if_port == PORT_TP)
987                         printk(", port TP.\n");
988                 else
989                         printk(", port MII, phy ad %d.\n", np->phy_addr_external);
990         }
991         return 0;
992
993  err_register_netdev:
994         iounmap(ioaddr);
995
996  err_ioremap:
997         pci_release_regions(pdev);
998         pci_set_drvdata(pdev, NULL);
999
1000  err_pci_request_regions:
1001         free_netdev(dev);
1002         return i;
1003 }
1004
1005
1006 /* Read the EEPROM and MII Management Data I/O (MDIO) interfaces.
1007    The EEPROM code is for the common 93c06/46 EEPROMs with 6 bit addresses. */
1008
1009 /* Delay between EEPROM clock transitions.
1010    No extra delay is needed with 33Mhz PCI, but future 66Mhz access may need
1011    a delay.  Note that pre-2.0.34 kernels had a cache-alignment bug that
1012    made udelay() unreliable.
1013    The old method of using an ISA access as a delay, __SLOW_DOWN_IO__, is
1014    depricated.
1015 */
1016 #define eeprom_delay(ee_addr)   readl(ee_addr)
1017
1018 #define EE_Write0 (EE_ChipSelect)
1019 #define EE_Write1 (EE_ChipSelect | EE_DataIn)
1020
1021 /* The EEPROM commands include the alway-set leading bit. */
1022 enum EEPROM_Cmds {
1023         EE_WriteCmd=(5 << 6), EE_ReadCmd=(6 << 6), EE_EraseCmd=(7 << 6),
1024 };
1025
1026 static int eeprom_read(void __iomem *addr, int location)
1027 {
1028         int i;
1029         int retval = 0;
1030         void __iomem *ee_addr = addr + EECtrl;
1031         int read_cmd = location | EE_ReadCmd;
1032
1033         writel(EE_Write0, ee_addr);
1034
1035         /* Shift the read command bits out. */
1036         for (i = 10; i >= 0; i--) {
1037                 short dataval = (read_cmd & (1 << i)) ? EE_Write1 : EE_Write0;
1038                 writel(dataval, ee_addr);
1039                 eeprom_delay(ee_addr);
1040                 writel(dataval | EE_ShiftClk, ee_addr);
1041                 eeprom_delay(ee_addr);
1042         }
1043         writel(EE_ChipSelect, ee_addr);
1044         eeprom_delay(ee_addr);
1045
1046         for (i = 0; i < 16; i++) {
1047                 writel(EE_ChipSelect | EE_ShiftClk, ee_addr);
1048                 eeprom_delay(ee_addr);
1049                 retval |= (readl(ee_addr) & EE_DataOut) ? 1 << i : 0;
1050                 writel(EE_ChipSelect, ee_addr);
1051                 eeprom_delay(ee_addr);
1052         }
1053
1054         /* Terminate the EEPROM access. */
1055         writel(EE_Write0, ee_addr);
1056         writel(0, ee_addr);
1057         return retval;
1058 }
1059
1060 /* MII transceiver control section.
1061  * The 83815 series has an internal transceiver, and we present the
1062  * internal management registers as if they were MII connected.
1063  * External Phy registers are referenced through the MII interface.
1064  */
1065
1066 /* clock transitions >= 20ns (25MHz)
1067  * One readl should be good to PCI @ 100MHz
1068  */
1069 #define mii_delay(ioaddr)  readl(ioaddr + EECtrl)
1070
1071 static int mii_getbit (struct net_device *dev)
1072 {
1073         int data;
1074         void __iomem *ioaddr = ns_ioaddr(dev);
1075
1076         writel(MII_ShiftClk, ioaddr + EECtrl);
1077         data = readl(ioaddr + EECtrl);
1078         writel(0, ioaddr + EECtrl);
1079         mii_delay(ioaddr);
1080         return (data & MII_Data)? 1 : 0;
1081 }
1082
1083 static void mii_send_bits (struct net_device *dev, u32 data, int len)
1084 {
1085         u32 i;
1086         void __iomem *ioaddr = ns_ioaddr(dev);
1087
1088         for (i = (1 << (len-1)); i; i >>= 1)
1089         {
1090                 u32 mdio_val = MII_Write | ((data & i)? MII_Data : 0);
1091                 writel(mdio_val, ioaddr + EECtrl);
1092                 mii_delay(ioaddr);
1093                 writel(mdio_val | MII_ShiftClk, ioaddr + EECtrl);
1094                 mii_delay(ioaddr);
1095         }
1096         writel(0, ioaddr + EECtrl);
1097         mii_delay(ioaddr);
1098 }
1099
1100 static int miiport_read(struct net_device *dev, int phy_id, int reg)
1101 {
1102         u32 cmd;
1103         int i;
1104         u32 retval = 0;
1105
1106         /* Ensure sync */
1107         mii_send_bits (dev, 0xffffffff, 32);
1108         /* ST(2), OP(2), ADDR(5), REG#(5), TA(2), Data(16) total 32 bits */
1109         /* ST,OP = 0110'b for read operation */
1110         cmd = (0x06 << 10) | (phy_id << 5) | reg;
1111         mii_send_bits (dev, cmd, 14);
1112         /* Turnaround */
1113         if (mii_getbit (dev))
1114                 return 0;
1115         /* Read data */
1116         for (i = 0; i < 16; i++) {
1117                 retval <<= 1;
1118                 retval |= mii_getbit (dev);
1119         }
1120         /* End cycle */
1121         mii_getbit (dev);
1122         return retval;
1123 }
1124
1125 static void miiport_write(struct net_device *dev, int phy_id, int reg, u16 data)
1126 {
1127         u32 cmd;
1128
1129         /* Ensure sync */
1130         mii_send_bits (dev, 0xffffffff, 32);
1131         /* ST(2), OP(2), ADDR(5), REG#(5), TA(2), Data(16) total 32 bits */
1132         /* ST,OP,AAAAA,RRRRR,TA = 0101xxxxxxxxxx10'b = 0x5002 for write */
1133         cmd = (0x5002 << 16) | (phy_id << 23) | (reg << 18) | data;
1134         mii_send_bits (dev, cmd, 32);
1135         /* End cycle */
1136         mii_getbit (dev);
1137 }
1138
1139 static int mdio_read(struct net_device *dev, int reg)
1140 {
1141         struct netdev_private *np = netdev_priv(dev);
1142         void __iomem *ioaddr = ns_ioaddr(dev);
1143
1144         /* The 83815 series has two ports:
1145          * - an internal transceiver
1146          * - an external mii bus
1147          */
1148         if (dev->if_port == PORT_TP)
1149                 return readw(ioaddr+BasicControl+(reg<<2));
1150         else
1151                 return miiport_read(dev, np->phy_addr_external, reg);
1152 }
1153
1154 static void mdio_write(struct net_device *dev, int reg, u16 data)
1155 {
1156         struct netdev_private *np = netdev_priv(dev);
1157         void __iomem *ioaddr = ns_ioaddr(dev);
1158
1159         /* The 83815 series has an internal transceiver; handle separately */
1160         if (dev->if_port == PORT_TP)
1161                 writew(data, ioaddr+BasicControl+(reg<<2));
1162         else
1163                 miiport_write(dev, np->phy_addr_external, reg, data);
1164 }
1165
1166 static void init_phy_fixup(struct net_device *dev)
1167 {
1168         struct netdev_private *np = netdev_priv(dev);
1169         void __iomem *ioaddr = ns_ioaddr(dev);
1170         int i;
1171         u32 cfg;
1172         u16 tmp;
1173
1174         /* restore stuff lost when power was out */
1175         tmp = mdio_read(dev, MII_BMCR);
1176         if (np->autoneg == AUTONEG_ENABLE) {
1177                 /* renegotiate if something changed */
1178                 if ((tmp & BMCR_ANENABLE) == 0
1179                  || np->advertising != mdio_read(dev, MII_ADVERTISE))
1180                 {
1181                         /* turn on autonegotiation and force negotiation */
1182                         tmp |= (BMCR_ANENABLE | BMCR_ANRESTART);
1183                         mdio_write(dev, MII_ADVERTISE, np->advertising);
1184                 }
1185         } else {
1186                 /* turn off auto negotiation, set speed and duplexity */
1187                 tmp &= ~(BMCR_ANENABLE | BMCR_SPEED100 | BMCR_FULLDPLX);
1188                 if (np->speed == SPEED_100)
1189                         tmp |= BMCR_SPEED100;
1190                 if (np->duplex == DUPLEX_FULL)
1191                         tmp |= BMCR_FULLDPLX;
1192                 /* 
1193                  * Note: there is no good way to inform the link partner
1194                  * that our capabilities changed. The user has to unplug
1195                  * and replug the network cable after some changes, e.g.
1196                  * after switching from 10HD, autoneg off to 100 HD,
1197                  * autoneg off.
1198                  */
1199         }
1200         mdio_write(dev, MII_BMCR, tmp);
1201         readl(ioaddr + ChipConfig);
1202         udelay(1);
1203
1204         /* find out what phy this is */
1205         np->mii = (mdio_read(dev, MII_PHYSID1) << 16)
1206                                 + mdio_read(dev, MII_PHYSID2);
1207
1208         /* handle external phys here */
1209         switch (np->mii) {
1210         case PHYID_AM79C874:
1211                 /* phy specific configuration for fibre/tp operation */
1212                 tmp = mdio_read(dev, MII_MCTRL);
1213                 tmp &= ~(MII_FX_SEL | MII_EN_SCRM);
1214                 if (dev->if_port == PORT_FIBRE)
1215                         tmp |= MII_FX_SEL;
1216                 else
1217                         tmp |= MII_EN_SCRM;
1218                 mdio_write(dev, MII_MCTRL, tmp);
1219                 break;
1220         default:
1221                 break;
1222         }
1223         cfg = readl(ioaddr + ChipConfig);
1224         if (cfg & CfgExtPhy)
1225                 return;
1226
1227         /* On page 78 of the spec, they recommend some settings for "optimum
1228            performance" to be done in sequence.  These settings optimize some
1229            of the 100Mbit autodetection circuitry.  They say we only want to
1230            do this for rev C of the chip, but engineers at NSC (Bradley
1231            Kennedy) recommends always setting them.  If you don't, you get
1232            errors on some autonegotiations that make the device unusable.
1233
1234            It seems that the DSP needs a few usec to reinitialize after
1235            the start of the phy. Just retry writing these values until they
1236            stick.
1237         */
1238         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1239
1240                 int dspcfg;
1241                 writew(1, ioaddr + PGSEL);
1242                 writew(PMDCSR_VAL, ioaddr + PMDCSR);
1243                 writew(TSTDAT_VAL, ioaddr + TSTDAT);
1244                 np->dspcfg = DSPCFG_VAL;
1245                 writew(np->dspcfg, ioaddr + DSPCFG);
1246                 writew(SDCFG_VAL, ioaddr + SDCFG);
1247                 writew(0, ioaddr + PGSEL);
1248                 readl(ioaddr + ChipConfig);
1249                 udelay(10);
1250
1251                 writew(1, ioaddr + PGSEL);
1252                 dspcfg = readw(ioaddr + DSPCFG);
1253                 writew(0, ioaddr + PGSEL);
1254                 if (np->dspcfg == dspcfg)
1255                         break;
1256         }
1257
1258         if (netif_msg_link(np)) {
1259                 if (i==NATSEMI_HW_TIMEOUT) {
1260                         printk(KERN_INFO
1261                                 "%s: DSPCFG mismatch after retrying for %d usec.\n",
1262                                 dev->name, i*10);
1263                 } else {
1264                         printk(KERN_INFO
1265                                 "%s: DSPCFG accepted after %d usec.\n",
1266                                 dev->name, i*10);
1267                 }
1268         }
1269         /*
1270          * Enable PHY Specific event based interrupts.  Link state change
1271          * and Auto-Negotiation Completion are among the affected.
1272          * Read the intr status to clear it (needed for wake events).
1273          */
1274         readw(ioaddr + MIntrStatus);
1275         writew(MICRIntEn, ioaddr + MIntrCtrl);
1276 }
1277
1278 static int switch_port_external(struct net_device *dev)
1279 {
1280         struct netdev_private *np = netdev_priv(dev);
1281         void __iomem *ioaddr = ns_ioaddr(dev);
1282         u32 cfg;
1283
1284         cfg = readl(ioaddr + ChipConfig);
1285         if (cfg & CfgExtPhy)
1286                 return 0;
1287
1288         if (netif_msg_link(np)) {
1289                 printk(KERN_INFO "%s: switching to external transceiver.\n",
1290                                 dev->name);
1291         }
1292
1293         /* 1) switch back to external phy */
1294         writel(cfg | (CfgExtPhy | CfgPhyDis), ioaddr + ChipConfig);
1295         readl(ioaddr + ChipConfig);
1296         udelay(1);
1297
1298         /* 2) reset the external phy: */
1299         /* resetting the external PHY has been known to cause a hub supplying
1300          * power over Ethernet to kill the power.  We don't want to kill
1301          * power to this computer, so we avoid resetting the phy.
1302          */
1303
1304         /* 3) reinit the phy fixup, it got lost during power down. */
1305         move_int_phy(dev, np->phy_addr_external);
1306         init_phy_fixup(dev);
1307
1308         return 1;
1309 }
1310
1311 static int switch_port_internal(struct net_device *dev)
1312 {
1313         struct netdev_private *np = netdev_priv(dev);
1314         void __iomem *ioaddr = ns_ioaddr(dev);
1315         int i;
1316         u32 cfg;
1317         u16 bmcr;
1318
1319         cfg = readl(ioaddr + ChipConfig);
1320         if (!(cfg &CfgExtPhy))
1321                 return 0;
1322
1323         if (netif_msg_link(np)) {
1324                 printk(KERN_INFO "%s: switching to internal transceiver.\n",
1325                                 dev->name);
1326         }
1327         /* 1) switch back to internal phy: */
1328         cfg = cfg & ~(CfgExtPhy | CfgPhyDis);
1329         writel(cfg, ioaddr + ChipConfig);
1330         readl(ioaddr + ChipConfig);
1331         udelay(1);
1332         
1333         /* 2) reset the internal phy: */
1334         bmcr = readw(ioaddr+BasicControl+(MII_BMCR<<2));
1335         writel(bmcr | BMCR_RESET, ioaddr+BasicControl+(MII_BMCR<<2));
1336         readl(ioaddr + ChipConfig);
1337         udelay(10);
1338         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1339                 bmcr = readw(ioaddr+BasicControl+(MII_BMCR<<2));
1340                 if (!(bmcr & BMCR_RESET))
1341                         break;
1342                 udelay(10);
1343         }
1344         if (i==NATSEMI_HW_TIMEOUT && netif_msg_link(np)) {
1345                 printk(KERN_INFO
1346                         "%s: phy reset did not complete in %d usec.\n",
1347                         dev->name, i*10);
1348         }
1349         /* 3) reinit the phy fixup, it got lost during power down. */
1350         init_phy_fixup(dev);
1351
1352         return 1;
1353 }
1354
1355 /* Scan for a PHY on the external mii bus.
1356  * There are two tricky points:
1357  * - Do not scan while the internal phy is enabled. The internal phy will
1358  *   crash: e.g. reads from the DSPCFG register will return odd values and
1359  *   the nasty random phy reset code will reset the nic every few seconds.
1360  * - The internal phy must be moved around, an external phy could
1361  *   have the same address as the internal phy.
1362  */
1363 static int find_mii(struct net_device *dev)
1364 {
1365         struct netdev_private *np = netdev_priv(dev);
1366         int tmp;
1367         int i;
1368         int did_switch;
1369
1370         /* Switch to external phy */
1371         did_switch = switch_port_external(dev);
1372                 
1373         /* Scan the possible phy addresses:
1374          *
1375          * PHY address 0 means that the phy is in isolate mode. Not yet
1376          * supported due to lack of test hardware. User space should
1377          * handle it through ethtool.
1378          */
1379         for (i = 1; i <= 31; i++) {
1380                 move_int_phy(dev, i);
1381                 tmp = miiport_read(dev, i, MII_BMSR);
1382                 if (tmp != 0xffff && tmp != 0x0000) {
1383                         /* found something! */
1384                         np->mii = (mdio_read(dev, MII_PHYSID1) << 16)
1385                                         + mdio_read(dev, MII_PHYSID2);
1386                         if (netif_msg_probe(np)) {
1387                                 printk(KERN_INFO "natsemi %s: found external phy %08x at address %d.\n",
1388                                                 pci_name(np->pci_dev), np->mii, i);
1389                         }
1390                         break;
1391                 }
1392         }
1393         /* And switch back to internal phy: */
1394         if (did_switch)
1395                 switch_port_internal(dev);
1396         return i;
1397 }
1398
1399 /* CFG bits [13:16] [18:23] */
1400 #define CFG_RESET_SAVE 0xfde000
1401 /* WCSR bits [0:4] [9:10] */
1402 #define WCSR_RESET_SAVE 0x61f
1403 /* RFCR bits [20] [22] [27:31] */
1404 #define RFCR_RESET_SAVE 0xf8500000;
1405
1406 static void natsemi_reset(struct net_device *dev)
1407 {
1408         int i;
1409         u32 cfg;
1410         u32 wcsr;
1411         u32 rfcr;
1412         u16 pmatch[3];
1413         u16 sopass[3];
1414         struct netdev_private *np = netdev_priv(dev);
1415         void __iomem *ioaddr = ns_ioaddr(dev);
1416
1417         /*
1418          * Resetting the chip causes some registers to be lost.
1419          * Natsemi suggests NOT reloading the EEPROM while live, so instead
1420          * we save the state that would have been loaded from EEPROM
1421          * on a normal power-up (see the spec EEPROM map).  This assumes
1422          * whoever calls this will follow up with init_registers() eventually.
1423          */
1424
1425         /* CFG */
1426         cfg = readl(ioaddr + ChipConfig) & CFG_RESET_SAVE;
1427         /* WCSR */
1428         wcsr = readl(ioaddr + WOLCmd) & WCSR_RESET_SAVE;
1429         /* RFCR */
1430         rfcr = readl(ioaddr + RxFilterAddr) & RFCR_RESET_SAVE;
1431         /* PMATCH */
1432         for (i = 0; i < 3; i++) {
1433                 writel(i*2, ioaddr + RxFilterAddr);
1434                 pmatch[i] = readw(ioaddr + RxFilterData);
1435         }
1436         /* SOPAS */
1437         for (i = 0; i < 3; i++) {
1438                 writel(0xa+(i*2), ioaddr + RxFilterAddr);
1439                 sopass[i] = readw(ioaddr + RxFilterData);
1440         }
1441
1442         /* now whack the chip */
1443         writel(ChipReset, ioaddr + ChipCmd);
1444         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1445                 if (!(readl(ioaddr + ChipCmd) & ChipReset))
1446                         break;
1447                 udelay(5);
1448         }
1449         if (i==NATSEMI_HW_TIMEOUT) {
1450                 printk(KERN_WARNING "%s: reset did not complete in %d usec.\n",
1451                         dev->name, i*5);
1452         } else if (netif_msg_hw(np)) {
1453                 printk(KERN_DEBUG "%s: reset completed in %d usec.\n",
1454                         dev->name, i*5);
1455         }
1456
1457         /* restore CFG */
1458         cfg |= readl(ioaddr + ChipConfig) & ~CFG_RESET_SAVE;
1459         /* turn on external phy if it was selected */
1460         if (dev->if_port == PORT_TP)
1461                 cfg &= ~(CfgExtPhy | CfgPhyDis);
1462         else
1463                 cfg |= (CfgExtPhy | CfgPhyDis);
1464         writel(cfg, ioaddr + ChipConfig);
1465         /* restore WCSR */
1466         wcsr |= readl(ioaddr + WOLCmd) & ~WCSR_RESET_SAVE;
1467         writel(wcsr, ioaddr + WOLCmd);
1468         /* read RFCR */
1469         rfcr |= readl(ioaddr + RxFilterAddr) & ~RFCR_RESET_SAVE;
1470         /* restore PMATCH */
1471         for (i = 0; i < 3; i++) {
1472                 writel(i*2, ioaddr + RxFilterAddr);
1473                 writew(pmatch[i], ioaddr + RxFilterData);
1474         }
1475         for (i = 0; i < 3; i++) {
1476                 writel(0xa+(i*2), ioaddr + RxFilterAddr);
1477                 writew(sopass[i], ioaddr + RxFilterData);
1478         }
1479         /* restore RFCR */
1480         writel(rfcr, ioaddr + RxFilterAddr);
1481 }
1482
1483 static void natsemi_reload_eeprom(struct net_device *dev)
1484 {
1485         struct netdev_private *np = netdev_priv(dev);
1486         void __iomem *ioaddr = ns_ioaddr(dev);
1487         int i;
1488
1489         writel(EepromReload, ioaddr + PCIBusCfg);
1490         for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
1491                 udelay(50);
1492                 if (!(readl(ioaddr + PCIBusCfg) & EepromReload))
1493                         break;
1494         }
1495         if (i==NATSEMI_HW_TIMEOUT) {
1496                 printk(KERN_WARNING "natsemi %s: EEPROM did not reload in %d usec.\n",
1497                         pci_name(np->pci_dev), i*50);
1498         } else if (netif_msg_hw(np)) {
1499                 printk(KERN_DEBUG "natsemi %s: EEPROM reloaded in %d usec.\n",
1500                         pci_name(np->pci_dev), i*50);
1501         }
1502 }
1503
1504 static void natsemi_stop_rxtx(struct net_device *dev)
1505 {
1506         void __iomem * ioaddr = ns_ioaddr(dev);
1507         struct netdev_private *np = netdev_priv(dev);
1508         int i;
1509
1510         writel(RxOff | TxOff, ioaddr + ChipCmd);
1511         for(i=0;i< NATSEMI_HW_TIMEOUT;i++) {
1512                 if ((readl(ioaddr + ChipCmd) & (TxOn|RxOn)) == 0)
1513                         break;
1514                 udelay(5);
1515         }
1516         if (i==NATSEMI_HW_TIMEOUT) {
1517                 printk(KERN_WARNING "%s: Tx/Rx process did not stop in %d usec.\n",
1518                         dev->name, i*5);
1519         } else if (netif_msg_hw(np)) {
1520                 printk(KERN_DEBUG "%s: Tx/Rx process stopped in %d usec.\n",
1521                         dev->name, i*5);
1522         }
1523 }
1524
1525 static int netdev_open(struct net_device *dev)
1526 {
1527         struct netdev_private *np = netdev_priv(dev);
1528         void __iomem * ioaddr = ns_ioaddr(dev);
1529         int i;
1530
1531         /* Reset the chip, just in case. */
1532         natsemi_reset(dev);
1533
1534         i = request_irq(dev->irq, &intr_handler, SA_SHIRQ, dev->name, dev);
1535         if (i) return i;
1536
1537         if (netif_msg_ifup(np))
1538                 printk(KERN_DEBUG "%s: netdev_open() irq %d.\n",
1539                         dev->name, dev->irq);
1540         i = alloc_ring(dev);
1541         if (i < 0) {
1542                 free_irq(dev->irq, dev);
1543                 return i;
1544         }
1545         init_ring(dev);
1546         spin_lock_irq(&np->lock);
1547         init_registers(dev);
1548         /* now set the MAC address according to dev->dev_addr */
1549         for (i = 0; i < 3; i++) {
1550                 u16 mac = (dev->dev_addr[2*i+1]<<8) + dev->dev_addr[2*i];
1551
1552                 writel(i*2, ioaddr + RxFilterAddr);
1553                 writew(mac, ioaddr + RxFilterData);
1554         }
1555         writel(np->cur_rx_mode, ioaddr + RxFilterAddr);
1556         spin_unlock_irq(&np->lock);
1557
1558         netif_start_queue(dev);
1559
1560         if (netif_msg_ifup(np))
1561                 printk(KERN_DEBUG "%s: Done netdev_open(), status: %#08x.\n",
1562                         dev->name, (int)readl(ioaddr + ChipCmd));
1563
1564         /* Set the timer to check for link beat. */
1565         init_timer(&np->timer);
1566         np->timer.expires = jiffies + NATSEMI_TIMER_FREQ;
1567         np->timer.data = (unsigned long)dev;
1568         np->timer.function = &netdev_timer; /* timer handler */
1569         add_timer(&np->timer);
1570
1571         return 0;
1572 }
1573
1574 static void do_cable_magic(struct net_device *dev)
1575 {
1576         struct netdev_private *np = netdev_priv(dev);
1577         void __iomem *ioaddr = ns_ioaddr(dev);
1578
1579         if (dev->if_port != PORT_TP)
1580                 return;
1581
1582         if (np->srr >= SRR_DP83816_A5)
1583                 return;
1584
1585         /*
1586          * 100 MBit links with short cables can trip an issue with the chip.
1587          * The problem manifests as lots of CRC errors and/or flickering
1588          * activity LED while idle.  This process is based on instructions
1589          * from engineers at National.
1590          */
1591         if (readl(ioaddr + ChipConfig) & CfgSpeed100) {
1592                 u16 data;
1593
1594                 writew(1, ioaddr + PGSEL);
1595                 /*
1596                  * coefficient visibility should already be enabled via
1597                  * DSPCFG | 0x1000
1598                  */
1599                 data = readw(ioaddr + TSTDAT) & 0xff;
1600                 /*
1601                  * the value must be negative, and within certain values
1602                  * (these values all come from National)
1603                  */
1604                 if (!(data & 0x80) || ((data >= 0xd8) && (data <= 0xff))) {
1605                         struct netdev_private *np = netdev_priv(dev);
1606
1607                         /* the bug has been triggered - fix the coefficient */
1608                         writew(TSTDAT_FIXED, ioaddr + TSTDAT);
1609                         /* lock the value */
1610                         data = readw(ioaddr + DSPCFG);
1611                         np->dspcfg = data | DSPCFG_LOCK;
1612                         writew(np->dspcfg, ioaddr + DSPCFG);
1613                 }
1614                 writew(0, ioaddr + PGSEL);
1615         }
1616 }
1617
1618 static void undo_cable_magic(struct net_device *dev)
1619 {
1620         u16 data;
1621         struct netdev_private *np = netdev_priv(dev);
1622         void __iomem * ioaddr = ns_ioaddr(dev);
1623
1624         if (dev->if_port != PORT_TP)
1625                 return;
1626
1627         if (np->srr >= SRR_DP83816_A5)
1628                 return;
1629
1630         writew(1, ioaddr + PGSEL);
1631         /* make sure the lock bit is clear */
1632         data = readw(ioaddr + DSPCFG);
1633         np->dspcfg = data & ~DSPCFG_LOCK;
1634         writew(np->dspcfg, ioaddr + DSPCFG);
1635         writew(0, ioaddr + PGSEL);
1636 }
1637
1638 static void check_link(struct net_device *dev)
1639 {
1640         struct netdev_private *np = netdev_priv(dev);
1641         void __iomem * ioaddr = ns_ioaddr(dev);
1642         int duplex;
1643         u16 bmsr;
1644        
1645         /* The link status field is latched: it remains low after a temporary
1646          * link failure until it's read. We need the current link status,
1647          * thus read twice.
1648          */
1649         mdio_read(dev, MII_BMSR);
1650         bmsr = mdio_read(dev, MII_BMSR);
1651
1652         if (!(bmsr & BMSR_LSTATUS)) {
1653                 if (netif_carrier_ok(dev)) {
1654                         if (netif_msg_link(np))
1655                                 printk(KERN_NOTICE "%s: link down.\n",
1656                                         dev->name);
1657                         netif_carrier_off(dev);
1658                         undo_cable_magic(dev);
1659                 }
1660                 return;
1661         }
1662         if (!netif_carrier_ok(dev)) {
1663                 if (netif_msg_link(np))
1664                         printk(KERN_NOTICE "%s: link up.\n", dev->name);
1665                 netif_carrier_on(dev);
1666                 do_cable_magic(dev);
1667         }
1668
1669         duplex = np->full_duplex;
1670         if (!duplex) {
1671                 if (bmsr & BMSR_ANEGCOMPLETE) {
1672                         int tmp = mii_nway_result(
1673                                 np->advertising & mdio_read(dev, MII_LPA));
1674                         if (tmp == LPA_100FULL || tmp == LPA_10FULL)
1675                                 duplex = 1;
1676                 } else if (mdio_read(dev, MII_BMCR) & BMCR_FULLDPLX)
1677                         duplex = 1;
1678         }
1679
1680         /* if duplex is set then bit 28 must be set, too */
1681         if (duplex ^ !!(np->rx_config & RxAcceptTx)) {
1682                 if (netif_msg_link(np))
1683                         printk(KERN_INFO
1684                                 "%s: Setting %s-duplex based on negotiated "
1685                                 "link capability.\n", dev->name,
1686                                 duplex ? "full" : "half");
1687                 if (duplex) {
1688                         np->rx_config |= RxAcceptTx;
1689                         np->tx_config |= TxCarrierIgn | TxHeartIgn;
1690                 } else {
1691                         np->rx_config &= ~RxAcceptTx;
1692                         np->tx_config &= ~(TxCarrierIgn | TxHeartIgn);
1693                 }
1694                 writel(np->tx_config, ioaddr + TxConfig);
1695                 writel(np->rx_config, ioaddr + RxConfig);
1696         }
1697 }
1698
1699 static void init_registers(struct net_device *dev)
1700 {
1701         struct netdev_private *np = netdev_priv(dev);
1702         void __iomem * ioaddr = ns_ioaddr(dev);
1703
1704         init_phy_fixup(dev);
1705
1706         /* clear any interrupts that are pending, such as wake events */
1707         readl(ioaddr + IntrStatus);
1708
1709         writel(np->ring_dma, ioaddr + RxRingPtr);
1710         writel(np->ring_dma + RX_RING_SIZE * sizeof(struct netdev_desc),
1711                 ioaddr + TxRingPtr);
1712
1713         /* Initialize other registers.
1714          * Configure the PCI bus bursts and FIFO thresholds.
1715          * Configure for standard, in-spec Ethernet.
1716          * Start with half-duplex. check_link will update
1717          * to the correct settings.
1718          */
1719
1720         /* DRTH: 2: start tx if 64 bytes are in the fifo
1721          * FLTH: 0x10: refill with next packet if 512 bytes are free
1722          * MXDMA: 0: up to 256 byte bursts.
1723          *      MXDMA must be <= FLTH
1724          * ECRETRY=1
1725          * ATP=1
1726          */
1727         np->tx_config = TxAutoPad | TxCollRetry | TxMxdma_256 |
1728                                 TX_FLTH_VAL | TX_DRTH_VAL_START;
1729         writel(np->tx_config, ioaddr + TxConfig);
1730
1731         /* DRTH 0x10: start copying to memory if 128 bytes are in the fifo
1732          * MXDMA 0: up to 256 byte bursts
1733          */
1734         np->rx_config = RxMxdma_256 | RX_DRTH_VAL;
1735         /* if receive ring now has bigger buffers than normal, enable jumbo */
1736         if (np->rx_buf_sz > NATSEMI_LONGPKT)
1737                 np->rx_config |= RxAcceptLong;
1738
1739         writel(np->rx_config, ioaddr + RxConfig);
1740
1741         /* Disable PME:
1742          * The PME bit is initialized from the EEPROM contents.
1743          * PCI cards probably have PME disabled, but motherboard
1744          * implementations may have PME set to enable WakeOnLan.
1745          * With PME set the chip will scan incoming packets but
1746          * nothing will be written to memory. */
1747         np->SavedClkRun = readl(ioaddr + ClkRun);
1748         writel(np->SavedClkRun & ~PMEEnable, ioaddr + ClkRun);
1749         if (np->SavedClkRun & PMEStatus && netif_msg_wol(np)) {
1750                 printk(KERN_NOTICE "%s: Wake-up event %#08x\n",
1751                         dev->name, readl(ioaddr + WOLCmd));
1752         }
1753
1754         check_link(dev);
1755         __set_rx_mode(dev);
1756
1757         /* Enable interrupts by setting the interrupt mask. */
1758         writel(DEFAULT_INTR, ioaddr + IntrMask);
1759         writel(1, ioaddr + IntrEnable);
1760
1761         writel(RxOn | TxOn, ioaddr + ChipCmd);
1762         writel(StatsClear, ioaddr + StatsCtrl); /* Clear Stats */
1763 }
1764
1765 /*
1766  * netdev_timer:
1767  * Purpose:
1768  * 1) check for link changes. Usually they are handled by the MII interrupt
1769  *    but it doesn't hurt to check twice.
1770  * 2) check for sudden death of the NIC:
1771  *    It seems that a reference set for this chip went out with incorrect info,
1772  *    and there exist boards that aren't quite right.  An unexpected voltage
1773  *    drop can cause the PHY to get itself in a weird state (basically reset).
1774  *    NOTE: this only seems to affect revC chips.
1775  * 3) check of death of the RX path due to OOM
1776  */
1777 static void netdev_timer(unsigned long data)
1778 {
1779         struct net_device *dev = (struct net_device *)data;
1780         struct netdev_private *np = netdev_priv(dev);
1781         void __iomem * ioaddr = ns_ioaddr(dev);
1782         int next_tick = 5*HZ;
1783
1784         if (netif_msg_timer(np)) {
1785                 /* DO NOT read the IntrStatus register,
1786                  * a read clears any pending interrupts.
1787                  */
1788                 printk(KERN_DEBUG "%s: Media selection timer tick.\n",
1789                         dev->name);
1790         }
1791
1792         if (dev->if_port == PORT_TP) {
1793                 u16 dspcfg;
1794
1795                 spin_lock_irq(&np->lock);
1796                 /* check for a nasty random phy-reset - use dspcfg as a flag */
1797                 writew(1, ioaddr+PGSEL);
1798                 dspcfg = readw(ioaddr+DSPCFG);
1799                 writew(0, ioaddr+PGSEL);
1800                 if (dspcfg != np->dspcfg) {
1801                         if (!netif_queue_stopped(dev)) {
1802                                 spin_unlock_irq(&np->lock);
1803                                 if (netif_msg_hw(np))
1804                                         printk(KERN_NOTICE "%s: possible phy reset: "
1805                                                 "re-initializing\n", dev->name);
1806                                 disable_irq(dev->irq);
1807                                 spin_lock_irq(&np->lock);
1808                                 natsemi_stop_rxtx(dev);
1809                                 dump_ring(dev);
1810                                 reinit_ring(dev);
1811                                 init_registers(dev);
1812                                 spin_unlock_irq(&np->lock);
1813                                 enable_irq(dev->irq);
1814                         } else {
1815                                 /* hurry back */
1816                                 next_tick = HZ;
1817                                 spin_unlock_irq(&np->lock);
1818                         }
1819                 } else {
1820                         /* init_registers() calls check_link() for the above case */
1821                         check_link(dev);
1822                         spin_unlock_irq(&np->lock);
1823                 }
1824         } else {
1825                 spin_lock_irq(&np->lock);
1826                 check_link(dev);
1827                 spin_unlock_irq(&np->lock);
1828         }
1829         if (np->oom) {
1830                 disable_irq(dev->irq);
1831                 np->oom = 0;
1832                 refill_rx(dev);
1833                 enable_irq(dev->irq);
1834                 if (!np->oom) {
1835                         writel(RxOn, ioaddr + ChipCmd);
1836                 } else {
1837                         next_tick = 1;
1838                 }
1839         }
1840         mod_timer(&np->timer, jiffies + next_tick);
1841 }
1842
1843 static void dump_ring(struct net_device *dev)
1844 {
1845         struct netdev_private *np = netdev_priv(dev);
1846
1847         if (netif_msg_pktdata(np)) {
1848                 int i;
1849                 printk(KERN_DEBUG "  Tx ring at %p:\n", np->tx_ring);
1850                 for (i = 0; i < TX_RING_SIZE; i++) {
1851                         printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
1852                                 i, np->tx_ring[i].next_desc,
1853                                 np->tx_ring[i].cmd_status,
1854                                 np->tx_ring[i].addr);
1855                 }
1856                 printk(KERN_DEBUG "  Rx ring %p:\n", np->rx_ring);
1857                 for (i = 0; i < RX_RING_SIZE; i++) {
1858                         printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
1859                                 i, np->rx_ring[i].next_desc,
1860                                 np->rx_ring[i].cmd_status,
1861                                 np->rx_ring[i].addr);
1862                 }
1863         }
1864 }
1865
1866 static void tx_timeout(struct net_device *dev)
1867 {
1868         struct netdev_private *np = netdev_priv(dev);
1869         void __iomem * ioaddr = ns_ioaddr(dev);
1870
1871         disable_irq(dev->irq);
1872         spin_lock_irq(&np->lock);
1873         if (!np->hands_off) {
1874                 if (netif_msg_tx_err(np))
1875                         printk(KERN_WARNING
1876                                 "%s: Transmit timed out, status %#08x,"
1877                                 " resetting...\n",
1878                                 dev->name, readl(ioaddr + IntrStatus));
1879                 dump_ring(dev);
1880
1881                 natsemi_reset(dev);
1882                 reinit_ring(dev);
1883                 init_registers(dev);
1884         } else {
1885                 printk(KERN_WARNING
1886                         "%s: tx_timeout while in hands_off state?\n",
1887                         dev->name);
1888         }
1889         spin_unlock_irq(&np->lock);
1890         enable_irq(dev->irq);
1891
1892         dev->trans_start = jiffies;
1893         np->stats.tx_errors++;
1894         netif_wake_queue(dev);
1895 }
1896
1897 static int alloc_ring(struct net_device *dev)
1898 {
1899         struct netdev_private *np = netdev_priv(dev);
1900         np->rx_ring = pci_alloc_consistent(np->pci_dev,
1901                 sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
1902                 &np->ring_dma);
1903         if (!np->rx_ring)
1904                 return -ENOMEM;
1905         np->tx_ring = &np->rx_ring[RX_RING_SIZE];
1906         return 0;
1907 }
1908
1909 static void refill_rx(struct net_device *dev)
1910 {
1911         struct netdev_private *np = netdev_priv(dev);
1912
1913         /* Refill the Rx ring buffers. */
1914         for (; np->cur_rx - np->dirty_rx > 0; np->dirty_rx++) {
1915                 struct sk_buff *skb;
1916                 int entry = np->dirty_rx % RX_RING_SIZE;
1917                 if (np->rx_skbuff[entry] == NULL) {
1918                         unsigned int buflen = np->rx_buf_sz+NATSEMI_PADDING;
1919                         skb = dev_alloc_skb(buflen);
1920                         np->rx_skbuff[entry] = skb;
1921                         if (skb == NULL)
1922                                 break; /* Better luck next round. */
1923                         skb->dev = dev; /* Mark as being used by this device. */
1924                         np->rx_dma[entry] = pci_map_single(np->pci_dev,
1925                                 skb->tail, buflen, PCI_DMA_FROMDEVICE);
1926                         np->rx_ring[entry].addr = cpu_to_le32(np->rx_dma[entry]);
1927                 }
1928                 np->rx_ring[entry].cmd_status = cpu_to_le32(np->rx_buf_sz);
1929         }
1930         if (np->cur_rx - np->dirty_rx == RX_RING_SIZE) {
1931                 if (netif_msg_rx_err(np))
1932                         printk(KERN_WARNING "%s: going OOM.\n", dev->name);
1933                 np->oom = 1;
1934         }
1935 }
1936
1937 static void set_bufsize(struct net_device *dev)
1938 {
1939         struct netdev_private *np = netdev_priv(dev);
1940         if (dev->mtu <= ETH_DATA_LEN)
1941                 np->rx_buf_sz = ETH_DATA_LEN + NATSEMI_HEADERS;
1942         else
1943                 np->rx_buf_sz = dev->mtu + NATSEMI_HEADERS;
1944 }
1945
1946 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1947 static void init_ring(struct net_device *dev)
1948 {
1949         struct netdev_private *np = netdev_priv(dev);
1950         int i;
1951
1952         /* 1) TX ring */
1953         np->dirty_tx = np->cur_tx = 0;
1954         for (i = 0; i < TX_RING_SIZE; i++) {
1955                 np->tx_skbuff[i] = NULL;
1956                 np->tx_ring[i].next_desc = cpu_to_le32(np->ring_dma
1957                         +sizeof(struct netdev_desc)
1958                         *((i+1)%TX_RING_SIZE+RX_RING_SIZE));
1959                 np->tx_ring[i].cmd_status = 0;
1960         }
1961
1962         /* 2) RX ring */
1963         np->dirty_rx = 0;
1964         np->cur_rx = RX_RING_SIZE;
1965         np->oom = 0;
1966         set_bufsize(dev);
1967
1968         np->rx_head_desc = &np->rx_ring[0];
1969
1970         /* Please be carefull before changing this loop - at least gcc-2.95.1
1971          * miscompiles it otherwise.
1972          */
1973         /* Initialize all Rx descriptors. */
1974         for (i = 0; i < RX_RING_SIZE; i++) {
1975                 np->rx_ring[i].next_desc = cpu_to_le32(np->ring_dma
1976                                 +sizeof(struct netdev_desc)
1977                                 *((i+1)%RX_RING_SIZE));
1978                 np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
1979                 np->rx_skbuff[i] = NULL;
1980         }
1981         refill_rx(dev);
1982         dump_ring(dev);
1983 }
1984
1985 static void drain_tx(struct net_device *dev)
1986 {
1987         struct netdev_private *np = netdev_priv(dev);
1988         int i;
1989
1990         for (i = 0; i < TX_RING_SIZE; i++) {
1991                 if (np->tx_skbuff[i]) {
1992                         pci_unmap_single(np->pci_dev,
1993                                 np->tx_dma[i], np->tx_skbuff[i]->len,
1994                                 PCI_DMA_TODEVICE);
1995                         dev_kfree_skb(np->tx_skbuff[i]);
1996                         np->stats.tx_dropped++;
1997                 }
1998                 np->tx_skbuff[i] = NULL;
1999         }
2000 }
2001
2002 static void drain_rx(struct net_device *dev)
2003 {
2004         struct netdev_private *np = netdev_priv(dev);
2005         unsigned int buflen = np->rx_buf_sz;
2006         int i;
2007
2008         /* Free all the skbuffs in the Rx queue. */
2009         for (i = 0; i < RX_RING_SIZE; i++) {
2010                 np->rx_ring[i].cmd_status = 0;
2011                 np->rx_ring[i].addr = 0xBADF00D0; /* An invalid address. */
2012                 if (np->rx_skbuff[i]) {
2013                         pci_unmap_single(np->pci_dev,
2014                                 np->rx_dma[i], buflen,
2015                                 PCI_DMA_FROMDEVICE);
2016                         dev_kfree_skb(np->rx_skbuff[i]);
2017                 }
2018                 np->rx_skbuff[i] = NULL;
2019         }
2020 }
2021
2022 static void drain_ring(struct net_device *dev)
2023 {
2024         drain_rx(dev);
2025         drain_tx(dev);
2026 }
2027
2028 static void free_ring(struct net_device *dev)
2029 {
2030         struct netdev_private *np = netdev_priv(dev);
2031         pci_free_consistent(np->pci_dev,
2032                 sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
2033                 np->rx_ring, np->ring_dma);
2034 }
2035
2036 static void reinit_rx(struct net_device *dev)
2037 {
2038         struct netdev_private *np = netdev_priv(dev);
2039         int i;
2040
2041         /* RX Ring */
2042         np->dirty_rx = 0;
2043         np->cur_rx = RX_RING_SIZE;
2044         np->rx_head_desc = &np->rx_ring[0];
2045         /* Initialize all Rx descriptors. */
2046         for (i = 0; i < RX_RING_SIZE; i++)
2047                 np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
2048
2049         refill_rx(dev);
2050 }
2051
2052 static void reinit_ring(struct net_device *dev)
2053 {
2054         struct netdev_private *np = netdev_priv(dev);
2055         int i;
2056
2057         /* drain TX ring */
2058         drain_tx(dev);
2059         np->dirty_tx = np->cur_tx = 0;
2060         for (i=0;i<TX_RING_SIZE;i++)
2061                 np->tx_ring[i].cmd_status = 0;
2062
2063         reinit_rx(dev);
2064 }
2065
2066 static int start_tx(struct sk_buff *skb, struct net_device *dev)
2067 {
2068         struct netdev_private *np = netdev_priv(dev);
2069         void __iomem * ioaddr = ns_ioaddr(dev);
2070         unsigned entry;
2071
2072         /* Note: Ordering is important here, set the field with the
2073            "ownership" bit last, and only then increment cur_tx. */
2074
2075         /* Calculate the next Tx descriptor entry. */
2076         entry = np->cur_tx % TX_RING_SIZE;
2077
2078         np->tx_skbuff[entry] = skb;
2079         np->tx_dma[entry] = pci_map_single(np->pci_dev,
2080                                 skb->data,skb->len, PCI_DMA_TODEVICE);
2081
2082         np->tx_ring[entry].addr = cpu_to_le32(np->tx_dma[entry]);
2083
2084         spin_lock_irq(&np->lock);
2085
2086         if (!np->hands_off) {
2087                 np->tx_ring[entry].cmd_status = cpu_to_le32(DescOwn | skb->len);
2088                 /* StrongARM: Explicitly cache flush np->tx_ring and
2089                  * skb->data,skb->len. */
2090                 wmb();
2091                 np->cur_tx++;
2092                 if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1) {
2093                         netdev_tx_done(dev);
2094                         if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1)
2095                                 netif_stop_queue(dev);
2096                 }
2097                 /* Wake the potentially-idle transmit channel. */
2098                 writel(TxOn, ioaddr + ChipCmd);
2099         } else {
2100                 dev_kfree_skb_irq(skb);
2101                 np->stats.tx_dropped++;
2102         }
2103         spin_unlock_irq(&np->lock);
2104
2105         dev->trans_start = jiffies;
2106
2107         if (netif_msg_tx_queued(np)) {
2108                 printk(KERN_DEBUG "%s: Transmit frame #%d queued in slot %d.\n",
2109                         dev->name, np->cur_tx, entry);
2110         }
2111         return 0;
2112 }
2113
2114 static void netdev_tx_done(struct net_device *dev)
2115 {
2116         struct netdev_private *np = netdev_priv(dev);
2117
2118         for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
2119                 int entry = np->dirty_tx % TX_RING_SIZE;
2120                 if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescOwn))
2121                         break;
2122                 if (netif_msg_tx_done(np))
2123                         printk(KERN_DEBUG
2124                                 "%s: tx frame #%d finished, status %#08x.\n",
2125                                         dev->name, np->dirty_tx,
2126                                         le32_to_cpu(np->tx_ring[entry].cmd_status));
2127                 if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescPktOK)) {
2128                         np->stats.tx_packets++;
2129                         np->stats.tx_bytes += np->tx_skbuff[entry]->len;
2130                 } else { /* Various Tx errors */
2131                         int tx_status =
2132                                 le32_to_cpu(np->tx_ring[entry].cmd_status);
2133                         if (tx_status & (DescTxAbort|DescTxExcColl))
2134                                 np->stats.tx_aborted_errors++;
2135                         if (tx_status & DescTxFIFO)
2136                                 np->stats.tx_fifo_errors++;
2137                         if (tx_status & DescTxCarrier)
2138                                 np->stats.tx_carrier_errors++;
2139                         if (tx_status & DescTxOOWCol)
2140                                 np->stats.tx_window_errors++;
2141                         np->stats.tx_errors++;
2142                 }
2143                 pci_unmap_single(np->pci_dev,np->tx_dma[entry],
2144                                         np->tx_skbuff[entry]->len,
2145                                         PCI_DMA_TODEVICE);
2146                 /* Free the original skb. */
2147                 dev_kfree_skb_irq(np->tx_skbuff[entry]);
2148                 np->tx_skbuff[entry] = NULL;
2149         }
2150         if (netif_queue_stopped(dev)
2151                 && np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
2152                 /* The ring is no longer full, wake queue. */
2153                 netif_wake_queue(dev);
2154         }
2155 }
2156
2157 /* The interrupt handler does all of the Rx thread work and cleans up
2158    after the Tx thread. */
2159 static irqreturn_t intr_handler(int irq, void *dev_instance, struct pt_regs *rgs)
2160 {
2161         struct net_device *dev = dev_instance;
2162         struct netdev_private *np = netdev_priv(dev);
2163         void __iomem * ioaddr = ns_ioaddr(dev);
2164         int boguscnt = max_interrupt_work;
2165         unsigned int handled = 0;
2166
2167         if (np->hands_off)
2168                 return IRQ_NONE;
2169         do {
2170                 /* Reading automatically acknowledges all int sources. */
2171                 u32 intr_status = readl(ioaddr + IntrStatus);
2172
2173                 if (netif_msg_intr(np))
2174                         printk(KERN_DEBUG
2175                                 "%s: Interrupt, status %#08x, mask %#08x.\n",
2176                                 dev->name, intr_status,
2177                                 readl(ioaddr + IntrMask));
2178
2179                 if (intr_status == 0)
2180                         break;
2181                 handled = 1;
2182
2183                 if (intr_status &
2184                    (IntrRxDone | IntrRxIntr | RxStatusFIFOOver |
2185                     IntrRxErr | IntrRxOverrun)) {
2186                         netdev_rx(dev);
2187                 }
2188
2189                 if (intr_status &
2190                    (IntrTxDone | IntrTxIntr | IntrTxIdle | IntrTxErr)) {
2191                         spin_lock(&np->lock);
2192                         netdev_tx_done(dev);
2193                         spin_unlock(&np->lock);
2194                 }
2195
2196                 /* Abnormal error summary/uncommon events handlers. */
2197                 if (intr_status & IntrAbnormalSummary)
2198                         netdev_error(dev, intr_status);
2199
2200                 if (--boguscnt < 0) {
2201                         if (netif_msg_intr(np))
2202                                 printk(KERN_WARNING
2203                                         "%s: Too much work at interrupt, "
2204                                         "status=%#08x.\n",
2205                                         dev->name, intr_status);
2206                         break;
2207                 }
2208         } while (1);
2209
2210         if (netif_msg_intr(np))
2211                 printk(KERN_DEBUG "%s: exiting interrupt.\n", dev->name);
2212
2213         return IRQ_RETVAL(handled);
2214 }
2215
2216 /* This routine is logically part of the interrupt handler, but separated
2217    for clarity and better register allocation. */
2218 static void netdev_rx(struct net_device *dev)
2219 {
2220         struct netdev_private *np = netdev_priv(dev);
2221         int entry = np->cur_rx % RX_RING_SIZE;
2222         int boguscnt = np->dirty_rx + RX_RING_SIZE - np->cur_rx;
2223         s32 desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
2224         unsigned int buflen = np->rx_buf_sz;
2225         void __iomem * ioaddr = ns_ioaddr(dev);
2226
2227         /* If the driver owns the next entry it's a new packet. Send it up. */
2228         while (desc_status < 0) { /* e.g. & DescOwn */
2229                 int pkt_len;
2230                 if (netif_msg_rx_status(np))
2231                         printk(KERN_DEBUG
2232                                 "  netdev_rx() entry %d status was %#08x.\n",
2233                                 entry, desc_status);
2234                 if (--boguscnt < 0)
2235                         break;
2236                 pkt_len = (desc_status & DescSizeMask) - 4;
2237                 if ((desc_status&(DescMore|DescPktOK|DescRxLong)) != DescPktOK){
2238                         if (desc_status & DescMore) {
2239                                 if (netif_msg_rx_err(np))
2240                                         printk(KERN_WARNING
2241                                                 "%s: Oversized(?) Ethernet "
2242                                                 "frame spanned multiple "
2243                                                 "buffers, entry %#08x "
2244                                                 "status %#08x.\n", dev->name,
2245                                                 np->cur_rx, desc_status);
2246                                 np->stats.rx_length_errors++;
2247                         } else {
2248                                 /* There was an error. */
2249                                 np->stats.rx_errors++;
2250                                 if (desc_status & (DescRxAbort|DescRxOver))
2251                                         np->stats.rx_over_errors++;
2252                                 if (desc_status & (DescRxLong|DescRxRunt))
2253                                         np->stats.rx_length_errors++;
2254                                 if (desc_status & (DescRxInvalid|DescRxAlign))
2255                                         np->stats.rx_frame_errors++;
2256                                 if (desc_status & DescRxCRC)
2257                                         np->stats.rx_crc_errors++;
2258                         }
2259                 } else if (pkt_len > np->rx_buf_sz) {
2260                         /* if this is the tail of a double buffer
2261                          * packet, we've already counted the error
2262                          * on the first part.  Ignore the second half.
2263                          */
2264                 } else {
2265                         struct sk_buff *skb;
2266                         /* Omit CRC size. */
2267                         /* Check if the packet is long enough to accept
2268                          * without copying to a minimally-sized skbuff. */
2269                         if (pkt_len < rx_copybreak
2270                             && (skb = dev_alloc_skb(pkt_len + RX_OFFSET)) != NULL) {
2271                                 skb->dev = dev;
2272                                 /* 16 byte align the IP header */
2273                                 skb_reserve(skb, RX_OFFSET);
2274                                 pci_dma_sync_single_for_cpu(np->pci_dev,
2275                                         np->rx_dma[entry],
2276                                         buflen,
2277                                         PCI_DMA_FROMDEVICE);
2278                                 eth_copy_and_sum(skb,
2279                                         np->rx_skbuff[entry]->tail, pkt_len, 0);
2280                                 skb_put(skb, pkt_len);
2281                                 pci_dma_sync_single_for_device(np->pci_dev,
2282                                         np->rx_dma[entry],
2283                                         buflen,
2284                                         PCI_DMA_FROMDEVICE);
2285                         } else {
2286                                 pci_unmap_single(np->pci_dev, np->rx_dma[entry],
2287                                         buflen, PCI_DMA_FROMDEVICE);
2288                                 skb_put(skb = np->rx_skbuff[entry], pkt_len);
2289                                 np->rx_skbuff[entry] = NULL;
2290                         }
2291                         skb->protocol = eth_type_trans(skb, dev);
2292                         netif_rx(skb);
2293                         dev->last_rx = jiffies;
2294                         np->stats.rx_packets++;
2295                         np->stats.rx_bytes += pkt_len;
2296                 }
2297                 entry = (++np->cur_rx) % RX_RING_SIZE;
2298                 np->rx_head_desc = &np->rx_ring[entry];
2299                 desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
2300         }
2301         refill_rx(dev);
2302
2303         /* Restart Rx engine if stopped. */
2304         if (np->oom)
2305                 mod_timer(&np->timer, jiffies + 1);
2306         else
2307                 writel(RxOn, ioaddr + ChipCmd);
2308 }
2309
2310 static void netdev_error(struct net_device *dev, int intr_status)
2311 {
2312         struct netdev_private *np = netdev_priv(dev);
2313         void __iomem * ioaddr = ns_ioaddr(dev);
2314
2315         spin_lock(&np->lock);
2316         if (intr_status & LinkChange) {
2317                 u16 lpa = mdio_read(dev, MII_LPA);
2318                 if (mdio_read(dev, MII_BMCR) & BMCR_ANENABLE
2319                  && netif_msg_link(np)) {
2320                         printk(KERN_INFO
2321                                 "%s: Autonegotiation advertising"
2322                                 " %#04x  partner %#04x.\n", dev->name,
2323                                 np->advertising, lpa);
2324                 }
2325
2326                 /* read MII int status to clear the flag */
2327                 readw(ioaddr + MIntrStatus);
2328                 check_link(dev);
2329         }
2330         if (intr_status & StatsMax) {
2331                 __get_stats(dev);
2332         }
2333         if (intr_status & IntrTxUnderrun) {
2334                 if ((np->tx_config & TxDrthMask) < TX_DRTH_VAL_LIMIT) {
2335                         np->tx_config += TX_DRTH_VAL_INC;
2336                         if (netif_msg_tx_err(np))
2337                                 printk(KERN_NOTICE
2338                                         "%s: increased tx threshold, txcfg %#08x.\n",
2339                                         dev->name, np->tx_config);
2340                 } else {
2341                         if (netif_msg_tx_err(np))
2342                                 printk(KERN_NOTICE
2343                                         "%s: tx underrun with maximum tx threshold, txcfg %#08x.\n",
2344                                         dev->name, np->tx_config);
2345                 }
2346                 writel(np->tx_config, ioaddr + TxConfig);
2347         }
2348         if (intr_status & WOLPkt && netif_msg_wol(np)) {
2349                 int wol_status = readl(ioaddr + WOLCmd);
2350                 printk(KERN_NOTICE "%s: Link wake-up event %#08x\n",
2351                         dev->name, wol_status);
2352         }
2353         if (intr_status & RxStatusFIFOOver) {
2354                 if (netif_msg_rx_err(np) && netif_msg_intr(np)) {
2355                         printk(KERN_NOTICE "%s: Rx status FIFO overrun\n",
2356                                 dev->name);
2357                 }
2358                 np->stats.rx_fifo_errors++;
2359         }
2360         /* Hmmmmm, it's not clear how to recover from PCI faults. */
2361         if (intr_status & IntrPCIErr) {
2362                 printk(KERN_NOTICE "%s: PCI error %#08x\n", dev->name,
2363                         intr_status & IntrPCIErr);
2364                 np->stats.tx_fifo_errors++;
2365                 np->stats.rx_fifo_errors++;
2366         }
2367         spin_unlock(&np->lock);
2368 }
2369
2370 static void __get_stats(struct net_device *dev)
2371 {
2372         void __iomem * ioaddr = ns_ioaddr(dev);
2373         struct netdev_private *np = netdev_priv(dev);
2374
2375         /* The chip only need report frame silently dropped. */
2376         np->stats.rx_crc_errors += readl(ioaddr + RxCRCErrs);
2377         np->stats.rx_missed_errors += readl(ioaddr + RxMissed);
2378 }
2379
2380 static struct net_device_stats *get_stats(struct net_device *dev)
2381 {
2382         struct netdev_private *np = netdev_priv(dev);
2383
2384         /* The chip only need report frame silently dropped. */
2385         spin_lock_irq(&np->lock);
2386         if (netif_running(dev) && !np->hands_off)
2387                 __get_stats(dev);
2388         spin_unlock_irq(&np->lock);
2389
2390         return &np->stats;
2391 }
2392
2393 #ifdef CONFIG_NET_POLL_CONTROLLER
2394 static void natsemi_poll_controller(struct net_device *dev)
2395 {
2396         disable_irq(dev->irq);
2397         intr_handler(dev->irq, dev, NULL);
2398         enable_irq(dev->irq);
2399 }
2400 #endif
2401
2402 #define HASH_TABLE      0x200
2403 static void __set_rx_mode(struct net_device *dev)
2404 {
2405         void __iomem * ioaddr = ns_ioaddr(dev);
2406         struct netdev_private *np = netdev_priv(dev);
2407         u8 mc_filter[64]; /* Multicast hash filter */
2408         u32 rx_mode;
2409
2410         if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
2411                 /* Unconditionally log net taps. */
2412                 printk(KERN_NOTICE "%s: Promiscuous mode enabled.\n",
2413                         dev->name);
2414                 rx_mode = RxFilterEnable | AcceptBroadcast
2415                         | AcceptAllMulticast | AcceptAllPhys | AcceptMyPhys;
2416         } else if ((dev->mc_count > multicast_filter_limit)
2417           || (dev->flags & IFF_ALLMULTI)) {
2418                 rx_mode = RxFilterEnable | AcceptBroadcast
2419                         | AcceptAllMulticast | AcceptMyPhys;
2420         } else {
2421                 struct dev_mc_list *mclist;
2422                 int i;
2423                 memset(mc_filter, 0, sizeof(mc_filter));
2424                 for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
2425                          i++, mclist = mclist->next) {
2426                         int i = (ether_crc(ETH_ALEN, mclist->dmi_addr) >> 23) & 0x1ff;
2427                         mc_filter[i/8] |= (1 << (i & 0x07));
2428                 }
2429                 rx_mode = RxFilterEnable | AcceptBroadcast
2430                         | AcceptMulticast | AcceptMyPhys;
2431                 for (i = 0; i < 64; i += 2) {
2432                         writew(HASH_TABLE + i, ioaddr + RxFilterAddr);
2433                         writew((mc_filter[i+1]<<8) + mc_filter[i],
2434                                 ioaddr + RxFilterData);
2435                 }
2436         }
2437         writel(rx_mode, ioaddr + RxFilterAddr);
2438         np->cur_rx_mode = rx_mode;
2439 }
2440
2441 static int natsemi_change_mtu(struct net_device *dev, int new_mtu)
2442 {
2443         if (new_mtu < 64 || new_mtu > NATSEMI_RX_LIMIT-NATSEMI_HEADERS)
2444                 return -EINVAL;
2445
2446         dev->mtu = new_mtu;
2447
2448         /* synchronized against open : rtnl_lock() held by caller */
2449         if (netif_running(dev)) {
2450                 struct netdev_private *np = netdev_priv(dev);
2451                 void __iomem * ioaddr = ns_ioaddr(dev);
2452
2453                 disable_irq(dev->irq);
2454                 spin_lock(&np->lock);
2455                 /* stop engines */
2456                 natsemi_stop_rxtx(dev);
2457                 /* drain rx queue */
2458                 drain_rx(dev);
2459                 /* change buffers */
2460                 set_bufsize(dev);
2461                 reinit_rx(dev);
2462                 writel(np->ring_dma, ioaddr + RxRingPtr);
2463                 /* restart engines */
2464                 writel(RxOn | TxOn, ioaddr + ChipCmd);
2465                 spin_unlock(&np->lock);
2466                 enable_irq(dev->irq);
2467         }
2468         return 0;
2469 }
2470
2471 static void set_rx_mode(struct net_device *dev)
2472 {
2473         struct netdev_private *np = netdev_priv(dev);
2474         spin_lock_irq(&np->lock);
2475         if (!np->hands_off)
2476                 __set_rx_mode(dev);
2477         spin_unlock_irq(&np->lock);
2478 }
2479
2480 static int netdev_ethtool_ioctl(struct net_device *dev, void __user *useraddr)
2481 {
2482         struct netdev_private *np = netdev_priv(dev);
2483         u32 cmd;
2484
2485         if (get_user(cmd, (u32 __user *)useraddr))
2486                 return -EFAULT;
2487
2488         switch (cmd) {
2489         /* get driver info */
2490         case ETHTOOL_GDRVINFO: {
2491                 struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
2492                 strncpy(info.driver, DRV_NAME, ETHTOOL_BUSINFO_LEN);
2493                 strncpy(info.version, DRV_VERSION, ETHTOOL_BUSINFO_LEN);
2494                 info.fw_version[0] = '\0';
2495                 strncpy(info.bus_info, pci_name(np->pci_dev),
2496                         ETHTOOL_BUSINFO_LEN);
2497                 info.eedump_len = NATSEMI_EEPROM_SIZE;
2498                 info.regdump_len = NATSEMI_REGS_SIZE;
2499                 if (copy_to_user(useraddr, &info, sizeof(info)))
2500                         return -EFAULT;
2501                 return 0;
2502         }
2503         /* get settings */
2504         case ETHTOOL_GSET: {
2505                 struct ethtool_cmd ecmd = { ETHTOOL_GSET };
2506                 spin_lock_irq(&np->lock);
2507                 netdev_get_ecmd(dev, &ecmd);
2508                 spin_unlock_irq(&np->lock);
2509                 if (copy_to_user(useraddr, &ecmd, sizeof(ecmd)))
2510                         return -EFAULT;
2511                 return 0;
2512         }
2513         /* set settings */
2514         case ETHTOOL_SSET: {
2515                 struct ethtool_cmd ecmd;
2516                 int r;
2517                 if (copy_from_user(&ecmd, useraddr, sizeof(ecmd)))
2518                         return -EFAULT;
2519                 spin_lock_irq(&np->lock);
2520                 r = netdev_set_ecmd(dev, &ecmd);
2521                 spin_unlock_irq(&np->lock);
2522                 return r;
2523         }
2524         /* get wake-on-lan */
2525         case ETHTOOL_GWOL: {
2526                 struct ethtool_wolinfo wol = {ETHTOOL_GWOL};
2527                 spin_lock_irq(&np->lock);
2528                 netdev_get_wol(dev, &wol.supported, &wol.wolopts);
2529                 netdev_get_sopass(dev, wol.sopass);
2530                 spin_unlock_irq(&np->lock);
2531                 if (copy_to_user(useraddr, &wol, sizeof(wol)))
2532                         return -EFAULT;
2533                 return 0;
2534         }
2535         /* set wake-on-lan */
2536         case ETHTOOL_SWOL: {
2537                 struct ethtool_wolinfo wol;
2538                 int r;
2539                 if (copy_from_user(&wol, useraddr, sizeof(wol)))
2540                         return -EFAULT;
2541                 spin_lock_irq(&np->lock);
2542                 netdev_set_wol(dev, wol.wolopts);
2543                 r = netdev_set_sopass(dev, wol.sopass);
2544                 spin_unlock_irq(&np->lock);
2545                 return r;
2546         }
2547         /* get registers */
2548         case ETHTOOL_GREGS: {
2549                 struct ethtool_regs regs;
2550                 u8 regbuf[NATSEMI_REGS_SIZE];
2551                 int r;
2552
2553                 if (copy_from_user(&regs, useraddr, sizeof(regs)))
2554                         return -EFAULT;
2555
2556                 if (regs.len > NATSEMI_REGS_SIZE) {
2557                         regs.len = NATSEMI_REGS_SIZE;
2558                 }
2559                 regs.version = NATSEMI_REGS_VER;
2560                 if (copy_to_user(useraddr, &regs, sizeof(regs)))
2561                         return -EFAULT;
2562
2563                 useraddr += offsetof(struct ethtool_regs, data);
2564
2565                 spin_lock_irq(&np->lock);
2566                 r = netdev_get_regs(dev, regbuf);
2567                 spin_unlock_irq(&np->lock);
2568
2569                 if (r)
2570                         return r;
2571                 if (copy_to_user(useraddr, regbuf, regs.len))
2572                         return -EFAULT;
2573                 return 0;
2574         }
2575         /* get message-level */
2576         case ETHTOOL_GMSGLVL: {
2577                 struct ethtool_value edata = {ETHTOOL_GMSGLVL};
2578                 edata.data = np->msg_enable;
2579                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2580                         return -EFAULT;
2581                 return 0;
2582         }
2583         /* set message-level */
2584         case ETHTOOL_SMSGLVL: {
2585                 struct ethtool_value edata;
2586                 if (copy_from_user(&edata, useraddr, sizeof(edata)))
2587                         return -EFAULT;
2588                 np->msg_enable = edata.data;
2589                 return 0;
2590         }
2591         /* restart autonegotiation */
2592         case ETHTOOL_NWAY_RST: {
2593                 int tmp;
2594                 int r = -EINVAL;
2595                 /* if autoneg is off, it's an error */
2596                 tmp = mdio_read(dev, MII_BMCR);
2597                 if (tmp & BMCR_ANENABLE) {
2598                         tmp |= (BMCR_ANRESTART);
2599                         mdio_write(dev, MII_BMCR, tmp);
2600                         r = 0;
2601                 }
2602                 return r;
2603         }
2604         /* get link status */
2605         case ETHTOOL_GLINK: {
2606                 struct ethtool_value edata = {ETHTOOL_GLINK};
2607                 /* LSTATUS is latched low until a read - so read twice */
2608                 mdio_read(dev, MII_BMSR);
2609                 edata.data = (mdio_read(dev, MII_BMSR)&BMSR_LSTATUS) ? 1:0;
2610                 if (copy_to_user(useraddr, &edata, sizeof(edata)))
2611                         return -EFAULT;
2612                 return 0;
2613         }
2614         /* get EEPROM */
2615         case ETHTOOL_GEEPROM: {
2616                 struct ethtool_eeprom eeprom;
2617                 u8 eebuf[NATSEMI_EEPROM_SIZE];
2618                 int r;
2619
2620                 if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
2621                         return -EFAULT;
2622
2623                 if (eeprom.offset > eeprom.offset+eeprom.len)
2624                         return -EINVAL;
2625
2626                 if ((eeprom.offset+eeprom.len) > NATSEMI_EEPROM_SIZE) {
2627                         eeprom.len = NATSEMI_EEPROM_SIZE-eeprom.offset;
2628                 }
2629                 eeprom.magic = PCI_VENDOR_ID_NS | (PCI_DEVICE_ID_NS_83815<<16);
2630                 if (copy_to_user(useraddr, &eeprom, sizeof(eeprom)))
2631                         return -EFAULT;
2632
2633                 useraddr += offsetof(struct ethtool_eeprom, data);
2634
2635                 spin_lock_irq(&np->lock);
2636                 r = netdev_get_eeprom(dev, eebuf);
2637                 spin_unlock_irq(&np->lock);
2638
2639                 if (r)
2640                         return r;
2641                 if (copy_to_user(useraddr, eebuf+eeprom.offset, eeprom.len))
2642                         return -EFAULT;
2643                 return 0;
2644         }
2645
2646         }
2647
2648         return -EOPNOTSUPP;
2649 }
2650
2651 static int netdev_set_wol(struct net_device *dev, u32 newval)
2652 {
2653         struct netdev_private *np = netdev_priv(dev);
2654         void __iomem * ioaddr = ns_ioaddr(dev);
2655         u32 data = readl(ioaddr + WOLCmd) & ~WakeOptsSummary;
2656
2657         /* translate to bitmasks this chip understands */
2658         if (newval & WAKE_PHY)
2659                 data |= WakePhy;
2660         if (newval & WAKE_UCAST)
2661                 data |= WakeUnicast;
2662         if (newval & WAKE_MCAST)
2663                 data |= WakeMulticast;
2664         if (newval & WAKE_BCAST)
2665                 data |= WakeBroadcast;
2666         if (newval & WAKE_ARP)
2667                 data |= WakeArp;
2668         if (newval & WAKE_MAGIC)
2669                 data |= WakeMagic;
2670         if (np->srr >= SRR_DP83815_D) {
2671                 if (newval & WAKE_MAGICSECURE) {
2672                         data |= WakeMagicSecure;
2673                 }
2674         }
2675
2676         writel(data, ioaddr + WOLCmd);
2677
2678         return 0;
2679 }
2680
2681 static int netdev_get_wol(struct net_device *dev, u32 *supported, u32 *cur)
2682 {
2683         struct netdev_private *np = netdev_priv(dev);
2684         void __iomem * ioaddr = ns_ioaddr(dev);
2685         u32 regval = readl(ioaddr + WOLCmd);
2686
2687         *supported = (WAKE_PHY | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST
2688                         | WAKE_ARP | WAKE_MAGIC);
2689
2690         if (np->srr >= SRR_DP83815_D) {
2691                 /* SOPASS works on revD and higher */
2692                 *supported |= WAKE_MAGICSECURE;
2693         }
2694         *cur = 0;
2695
2696         /* translate from chip bitmasks */
2697         if (regval & WakePhy)
2698                 *cur |= WAKE_PHY;
2699         if (regval & WakeUnicast)
2700                 *cur |= WAKE_UCAST;
2701         if (regval & WakeMulticast)
2702                 *cur |= WAKE_MCAST;
2703         if (regval & WakeBroadcast)
2704                 *cur |= WAKE_BCAST;
2705         if (regval & WakeArp)
2706                 *cur |= WAKE_ARP;
2707         if (regval & WakeMagic)
2708                 *cur |= WAKE_MAGIC;
2709         if (regval & WakeMagicSecure) {
2710                 /* this can be on in revC, but it's broken */
2711                 *cur |= WAKE_MAGICSECURE;
2712         }
2713
2714         return 0;
2715 }
2716
2717 static int netdev_set_sopass(struct net_device *dev, u8 *newval)
2718 {
2719         struct netdev_private *np = netdev_priv(dev);
2720         void __iomem * ioaddr = ns_ioaddr(dev);
2721         u16 *sval = (u16 *)newval;
2722         u32 addr;
2723
2724         if (np->srr < SRR_DP83815_D) {
2725                 return 0;
2726         }
2727
2728         /* enable writing to these registers by disabling the RX filter */
2729         addr = readl(ioaddr + RxFilterAddr) & ~RFCRAddressMask;
2730         addr &= ~RxFilterEnable;
2731         writel(addr, ioaddr + RxFilterAddr);
2732
2733         /* write the three words to (undocumented) RFCR vals 0xa, 0xc, 0xe */
2734         writel(addr | 0xa, ioaddr + RxFilterAddr);
2735         writew(sval[0], ioaddr + RxFilterData);
2736
2737         writel(addr | 0xc, ioaddr + RxFilterAddr);
2738         writew(sval[1], ioaddr + RxFilterData);
2739
2740         writel(addr | 0xe, ioaddr + RxFilterAddr);
2741         writew(sval[2], ioaddr + RxFilterData);
2742
2743         /* re-enable the RX filter */
2744         writel(addr | RxFilterEnable, ioaddr + RxFilterAddr);
2745
2746         return 0;
2747 }
2748
2749 static int netdev_get_sopass(struct net_device *dev, u8 *data)
2750 {
2751         struct netdev_private *np = netdev_priv(dev);
2752         void __iomem * ioaddr = ns_ioaddr(dev);
2753         u16 *sval = (u16 *)data;
2754         u32 addr;
2755
2756         if (np->srr < SRR_DP83815_D) {
2757                 sval[0] = sval[1] = sval[2] = 0;
2758                 return 0;
2759         }
2760
2761         /* read the three words from (undocumented) RFCR vals 0xa, 0xc, 0xe */
2762         addr = readl(ioaddr + RxFilterAddr) & ~RFCRAddressMask;
2763
2764         writel(addr | 0xa, ioaddr + RxFilterAddr);
2765         sval[0] = readw(ioaddr + RxFilterData);
2766
2767         writel(addr | 0xc, ioaddr + RxFilterAddr);
2768         sval[1] = readw(ioaddr + RxFilterData);
2769
2770         writel(addr | 0xe, ioaddr + RxFilterAddr);
2771         sval[2] = readw(ioaddr + RxFilterData);
2772
2773         writel(addr, ioaddr + RxFilterAddr);
2774
2775         return 0;
2776 }
2777
2778 static int netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
2779 {
2780         struct netdev_private *np = netdev_priv(dev);
2781         u32 tmp;
2782
2783         ecmd->port        = dev->if_port;
2784         ecmd->speed       = np->speed;
2785         ecmd->duplex      = np->duplex;
2786         ecmd->autoneg     = np->autoneg;
2787         ecmd->advertising = 0;
2788         if (np->advertising & ADVERTISE_10HALF)
2789                 ecmd->advertising |= ADVERTISED_10baseT_Half;
2790         if (np->advertising & ADVERTISE_10FULL)
2791                 ecmd->advertising |= ADVERTISED_10baseT_Full;
2792         if (np->advertising & ADVERTISE_100HALF)
2793                 ecmd->advertising |= ADVERTISED_100baseT_Half;
2794         if (np->advertising & ADVERTISE_100FULL)
2795                 ecmd->advertising |= ADVERTISED_100baseT_Full;
2796         ecmd->supported   = (SUPPORTED_Autoneg |
2797                 SUPPORTED_10baseT_Half  | SUPPORTED_10baseT_Full  |
2798                 SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
2799                 SUPPORTED_TP | SUPPORTED_MII | SUPPORTED_FIBRE);
2800         ecmd->phy_address = np->phy_addr_external;
2801         /*
2802          * We intentionally report the phy address of the external
2803          * phy, even if the internal phy is used. This is necessary
2804          * to work around a deficiency of the ethtool interface:
2805          * It's only possible to query the settings of the active
2806          * port. Therefore 
2807          * # ethtool -s ethX port mii
2808          * actually sends an ioctl to switch to port mii with the
2809          * settings that are used for the current active port.
2810          * If we would report a different phy address in this
2811          * command, then
2812          * # ethtool -s ethX port tp;ethtool -s ethX port mii
2813          * would unintentionally change the phy address.
2814          *
2815          * Fortunately the phy address doesn't matter with the
2816          * internal phy...
2817          */
2818
2819         /* set information based on active port type */
2820         switch (ecmd->port) {
2821         default:
2822         case PORT_TP:
2823                 ecmd->advertising |= ADVERTISED_TP;
2824                 ecmd->transceiver = XCVR_INTERNAL;
2825                 break;
2826         case PORT_MII:
2827                 ecmd->advertising |= ADVERTISED_MII;
2828                 ecmd->transceiver = XCVR_EXTERNAL;
2829                 break;
2830         case PORT_FIBRE:
2831                 ecmd->advertising |= ADVERTISED_FIBRE;
2832                 ecmd->transceiver = XCVR_EXTERNAL;
2833                 break;
2834         }
2835
2836         /* if autonegotiation is on, try to return the active speed/duplex */
2837         if (ecmd->autoneg == AUTONEG_ENABLE) {
2838                 ecmd->advertising |= ADVERTISED_Autoneg;
2839                 tmp = mii_nway_result(
2840                         np->advertising & mdio_read(dev, MII_LPA));
2841                 if (tmp == LPA_100FULL || tmp == LPA_100HALF)
2842                         ecmd->speed  = SPEED_100;
2843                 else
2844                         ecmd->speed  = SPEED_10;
2845                 if (tmp == LPA_100FULL || tmp == LPA_10FULL)
2846                         ecmd->duplex = DUPLEX_FULL;
2847                 else
2848                         ecmd->duplex = DUPLEX_HALF;
2849         }
2850
2851         /* ignore maxtxpkt, maxrxpkt for now */
2852
2853         return 0;
2854 }
2855
2856 static int netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
2857 {
2858         struct netdev_private *np = netdev_priv(dev);
2859
2860         if (ecmd->port != PORT_TP && ecmd->port != PORT_MII && ecmd->port != PORT_FIBRE)
2861                 return -EINVAL;
2862         if (ecmd->transceiver != XCVR_INTERNAL && ecmd->transceiver != XCVR_EXTERNAL)
2863                 return -EINVAL;
2864         if (ecmd->autoneg == AUTONEG_ENABLE) {
2865                 if ((ecmd->advertising & (ADVERTISED_10baseT_Half |
2866                                           ADVERTISED_10baseT_Full |
2867                                           ADVERTISED_100baseT_Half |
2868                                           ADVERTISED_100baseT_Full)) == 0) {
2869                         return -EINVAL;
2870                 }
2871         } else if (ecmd->autoneg == AUTONEG_DISABLE) {
2872                 if (ecmd->speed != SPEED_10 && ecmd->speed != SPEED_100)
2873                         return -EINVAL;
2874                 if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL)
2875                         return -EINVAL;
2876         } else {
2877                 return -EINVAL;
2878         }
2879
2880         /*
2881          * maxtxpkt, maxrxpkt: ignored for now.
2882          *
2883          * transceiver:
2884          * PORT_TP is always XCVR_INTERNAL, PORT_MII and PORT_FIBRE are always
2885          * XCVR_EXTERNAL. The implementation thus ignores ecmd->transceiver and
2886          * selects based on ecmd->port.
2887          *
2888          * Actually PORT_FIBRE is nearly identical to PORT_MII: it's for fibre
2889          * phys that are connected to the mii bus. It's used to apply fibre
2890          * specific updates.
2891          */
2892
2893         /* WHEW! now lets bang some bits */
2894
2895         /* save the parms */
2896         dev->if_port          = ecmd->port;
2897         np->autoneg           = ecmd->autoneg;
2898         np->phy_addr_external = ecmd->phy_address & PhyAddrMask;
2899         if (np->autoneg == AUTONEG_ENABLE) {
2900                 /* advertise only what has been requested */
2901                 np->advertising &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4);
2902                 if (ecmd->advertising & ADVERTISED_10baseT_Half)
2903                         np->advertising |= ADVERTISE_10HALF;
2904                 if (ecmd->advertising & ADVERTISED_10baseT_Full)
2905                         np->advertising |= ADVERTISE_10FULL;
2906                 if (ecmd->advertising & ADVERTISED_100baseT_Half)
2907                         np->advertising |= ADVERTISE_100HALF;
2908                 if (ecmd->advertising & ADVERTISED_100baseT_Full)
2909                         np->advertising |= ADVERTISE_100FULL;
2910         } else {
2911                 np->speed  = ecmd->speed;
2912                 np->duplex = ecmd->duplex;
2913                 /* user overriding the initial full duplex parm? */
2914                 if (np->duplex == DUPLEX_HALF)
2915                         np->full_duplex = 0;
2916         }
2917
2918         /* get the right phy enabled */
2919         if (ecmd->port == PORT_TP)
2920                 switch_port_internal(dev);
2921         else
2922                 switch_port_external(dev);
2923
2924         /* set parms and see how this affected our link status */
2925         init_phy_fixup(dev);
2926         check_link(dev);
2927         return 0;
2928 }
2929
2930 static int netdev_get_regs(struct net_device *dev, u8 *buf)
2931 {
2932         int i;
2933         int j;
2934         u32 rfcr;
2935         u32 *rbuf = (u32 *)buf;
2936         void __iomem * ioaddr = ns_ioaddr(dev);
2937
2938         /* read non-mii page 0 of registers */
2939         for (i = 0; i < NATSEMI_PG0_NREGS/2; i++) {
2940                 rbuf[i] = readl(ioaddr + i*4);
2941         }
2942
2943         /* read current mii registers */
2944         for (i = NATSEMI_PG0_NREGS/2; i < NATSEMI_PG0_NREGS; i++)
2945                 rbuf[i] = mdio_read(dev, i & 0x1f);
2946
2947         /* read only the 'magic' registers from page 1 */
2948         writew(1, ioaddr + PGSEL);
2949         rbuf[i++] = readw(ioaddr + PMDCSR);
2950         rbuf[i++] = readw(ioaddr + TSTDAT);
2951         rbuf[i++] = readw(ioaddr + DSPCFG);
2952         rbuf[i++] = readw(ioaddr + SDCFG);
2953         writew(0, ioaddr + PGSEL);
2954
2955         /* read RFCR indexed registers */
2956         rfcr = readl(ioaddr + RxFilterAddr);
2957         for (j = 0; j < NATSEMI_RFDR_NREGS; j++) {
2958                 writel(j*2, ioaddr + RxFilterAddr);
2959                 rbuf[i++] = readw(ioaddr + RxFilterData);
2960         }
2961         writel(rfcr, ioaddr + RxFilterAddr);
2962
2963         /* the interrupt status is clear-on-read - see if we missed any */
2964         if (rbuf[4] & rbuf[5]) {
2965                 printk(KERN_WARNING
2966                         "%s: shoot, we dropped an interrupt (%#08x)\n",
2967                         dev->name, rbuf[4] & rbuf[5]);
2968         }
2969
2970         return 0;
2971 }
2972
2973 #define SWAP_BITS(x)    ( (((x) & 0x0001) << 15) | (((x) & 0x0002) << 13) \
2974                         | (((x) & 0x0004) << 11) | (((x) & 0x0008) << 9)  \
2975                         | (((x) & 0x0010) << 7)  | (((x) & 0x0020) << 5)  \
2976                         | (((x) & 0x0040) << 3)  | (((x) & 0x0080) << 1)  \
2977                         | (((x) & 0x0100) >> 1)  | (((x) & 0x0200) >> 3)  \
2978                         | (((x) & 0x0400) >> 5)  | (((x) & 0x0800) >> 7)  \
2979                         | (((x) & 0x1000) >> 9)  | (((x) & 0x2000) >> 11) \
2980                         | (((x) & 0x4000) >> 13) | (((x) & 0x8000) >> 15) )
2981
2982 static int netdev_get_eeprom(struct net_device *dev, u8 *buf)
2983 {
2984         int i;
2985         u16 *ebuf = (u16 *)buf;
2986         void __iomem * ioaddr = ns_ioaddr(dev);
2987
2988         /* eeprom_read reads 16 bits, and indexes by 16 bits */
2989         for (i = 0; i < NATSEMI_EEPROM_SIZE/2; i++) {
2990                 ebuf[i] = eeprom_read(ioaddr, i);
2991                 /* The EEPROM itself stores data bit-swapped, but eeprom_read
2992                  * reads it back "sanely". So we swap it back here in order to
2993                  * present it to userland as it is stored. */
2994                 ebuf[i] = SWAP_BITS(ebuf[i]);
2995         }
2996         return 0;
2997 }
2998
2999 static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
3000 {
3001         struct mii_ioctl_data *data = if_mii(rq);
3002         struct netdev_private *np = netdev_priv(dev);
3003
3004         switch(cmd) {
3005         case SIOCETHTOOL:
3006                 return netdev_ethtool_ioctl(dev, rq->ifr_data);
3007         case SIOCGMIIPHY:               /* Get address of MII PHY in use. */
3008         case SIOCDEVPRIVATE:            /* for binary compat, remove in 2.5 */
3009                 data->phy_id = np->phy_addr_external;
3010                 /* Fall Through */
3011
3012         case SIOCGMIIREG:               /* Read MII PHY register. */
3013         case SIOCDEVPRIVATE+1:          /* for binary compat, remove in 2.5 */
3014                 /* The phy_id is not enough to uniquely identify
3015                  * the intended target. Therefore the command is sent to
3016                  * the given mii on the current port.
3017                  */
3018                 if (dev->if_port == PORT_TP) {
3019                         if ((data->phy_id & 0x1f) == np->phy_addr_external)
3020                                 data->val_out = mdio_read(dev,
3021                                                         data->reg_num & 0x1f);
3022                         else
3023                                 data->val_out = 0;
3024                 } else {
3025                         move_int_phy(dev, data->phy_id & 0x1f);
3026                         data->val_out = miiport_read(dev, data->phy_id & 0x1f,
3027                                                         data->reg_num & 0x1f);
3028                 }
3029                 return 0;
3030
3031         case SIOCSMIIREG:               /* Write MII PHY register. */
3032         case SIOCDEVPRIVATE+2:          /* for binary compat, remove in 2.5 */
3033                 if (!capable(CAP_NET_ADMIN))
3034                         return -EPERM;
3035                 if (dev->if_port == PORT_TP) {
3036                         if ((data->phy_id & 0x1f) == np->phy_addr_external) {
3037                                 if ((data->reg_num & 0x1f) == MII_ADVERTISE)
3038                                         np->advertising = data->val_in;
3039                                 mdio_write(dev, data->reg_num & 0x1f,
3040                                                         data->val_in);
3041                         }
3042                 } else {
3043                         if ((data->phy_id & 0x1f) == np->phy_addr_external) {
3044                                 if ((data->reg_num & 0x1f) == MII_ADVERTISE)
3045                                         np->advertising = data->val_in;
3046                         }
3047                         move_int_phy(dev, data->phy_id & 0x1f);
3048                         miiport_write(dev, data->phy_id & 0x1f,
3049                                                 data->reg_num & 0x1f,
3050                                                 data->val_in);
3051                 }
3052                 return 0;
3053         default:
3054                 return -EOPNOTSUPP;
3055         }
3056 }
3057
3058 static void enable_wol_mode(struct net_device *dev, int enable_intr)
3059 {
3060         void __iomem * ioaddr = ns_ioaddr(dev);
3061         struct netdev_private *np = netdev_priv(dev);
3062
3063         if (netif_msg_wol(np))
3064                 printk(KERN_INFO "%s: remaining active for wake-on-lan\n",
3065                         dev->name);
3066
3067         /* For WOL we must restart the rx process in silent mode.
3068          * Write NULL to the RxRingPtr. Only possible if
3069          * rx process is stopped
3070          */
3071         writel(0, ioaddr + RxRingPtr);
3072
3073         /* read WoL status to clear */
3074         readl(ioaddr + WOLCmd);
3075
3076         /* PME on, clear status */
3077         writel(np->SavedClkRun | PMEEnable | PMEStatus, ioaddr + ClkRun);
3078
3079         /* and restart the rx process */
3080         writel(RxOn, ioaddr + ChipCmd);
3081
3082         if (enable_intr) {
3083                 /* enable the WOL interrupt.
3084                  * Could be used to send a netlink message.
3085                  */
3086                 writel(WOLPkt | LinkChange, ioaddr + IntrMask);
3087                 writel(1, ioaddr + IntrEnable);
3088         }
3089 }
3090
3091 static int netdev_close(struct net_device *dev)
3092 {
3093         void __iomem * ioaddr = ns_ioaddr(dev);
3094         struct netdev_private *np = netdev_priv(dev);
3095
3096         if (netif_msg_ifdown(np))
3097                 printk(KERN_DEBUG
3098                         "%s: Shutting down ethercard, status was %#04x.\n",
3099                         dev->name, (int)readl(ioaddr + ChipCmd));
3100         if (netif_msg_pktdata(np))
3101                 printk(KERN_DEBUG
3102                         "%s: Queue pointers were Tx %d / %d,  Rx %d / %d.\n",
3103                         dev->name, np->cur_tx, np->dirty_tx,
3104                         np->cur_rx, np->dirty_rx);
3105
3106         /*
3107          * FIXME: what if someone tries to close a device
3108          * that is suspended?
3109          * Should we reenable the nic to switch to
3110          * the final WOL settings?
3111          */
3112
3113         del_timer_sync(&np->timer);
3114         disable_irq(dev->irq);
3115         spin_lock_irq(&np->lock);
3116         /* Disable interrupts, and flush posted writes */
3117         writel(0, ioaddr + IntrEnable);
3118         readl(ioaddr + IntrEnable);
3119         np->hands_off = 1;
3120         spin_unlock_irq(&np->lock);
3121         enable_irq(dev->irq);
3122
3123         free_irq(dev->irq, dev);
3124
3125         /* Interrupt disabled, interrupt handler released,
3126          * queue stopped, timer deleted, rtnl_lock held
3127          * All async codepaths that access the driver are disabled.
3128          */
3129         spin_lock_irq(&np->lock);
3130         np->hands_off = 0;
3131         readl(ioaddr + IntrMask);
3132         readw(ioaddr + MIntrStatus);
3133
3134         /* Freeze Stats */
3135         writel(StatsFreeze, ioaddr + StatsCtrl);
3136
3137         /* Stop the chip's Tx and Rx processes. */
3138         natsemi_stop_rxtx(dev);
3139
3140         __get_stats(dev);
3141         spin_unlock_irq(&np->lock);
3142
3143         /* clear the carrier last - an interrupt could reenable it otherwise */
3144         netif_carrier_off(dev);
3145         netif_stop_queue(dev);
3146
3147         dump_ring(dev);
3148         drain_ring(dev);
3149         free_ring(dev);
3150
3151         {
3152                 u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
3153                 if (wol) {
3154                         /* restart the NIC in WOL mode.
3155                          * The nic must be stopped for this.
3156                          */
3157                         enable_wol_mode(dev, 0);
3158                 } else {
3159                         /* Restore PME enable bit unmolested */
3160                         writel(np->SavedClkRun, ioaddr + ClkRun);
3161                 }
3162         }
3163         return 0;
3164 }
3165
3166
3167 static void __devexit natsemi_remove1 (struct pci_dev *pdev)
3168 {
3169         struct net_device *dev = pci_get_drvdata(pdev);
3170         void __iomem * ioaddr = ns_ioaddr(dev);
3171
3172         unregister_netdev (dev);
3173         pci_release_regions (pdev);
3174         iounmap(ioaddr);
3175         free_netdev (dev);
3176         pci_set_drvdata(pdev, NULL);
3177 }
3178
3179 #ifdef CONFIG_PM
3180
3181 /*
3182  * The ns83815 chip doesn't have explicit RxStop bits.
3183  * Kicking the Rx or Tx process for a new packet reenables the Rx process
3184  * of the nic, thus this function must be very careful:
3185  *
3186  * suspend/resume synchronization:
3187  * entry points:
3188  *   netdev_open, netdev_close, netdev_ioctl, set_rx_mode, intr_handler,
3189  *   start_tx, tx_timeout
3190  *
3191  * No function accesses the hardware without checking np->hands_off.
3192  *      the check occurs under spin_lock_irq(&np->lock);
3193  * exceptions:
3194  *      * netdev_ioctl: noncritical access.
3195  *      * netdev_open: cannot happen due to the device_detach
3196  *      * netdev_close: doesn't hurt.
3197  *      * netdev_timer: timer stopped by natsemi_suspend.
3198  *      * intr_handler: doesn't acquire the spinlock. suspend calls
3199  *              disable_irq() to enforce synchronization.
3200  *
3201  * Interrupts must be disabled, otherwise hands_off can cause irq storms.
3202  */
3203
3204 static int natsemi_suspend (struct pci_dev *pdev, u32 state)
3205 {
3206         struct net_device *dev = pci_get_drvdata (pdev);
3207         struct netdev_private *np = netdev_priv(dev);
3208         void __iomem * ioaddr = ns_ioaddr(dev);
3209
3210         rtnl_lock();
3211         if (netif_running (dev)) {
3212                 del_timer_sync(&np->timer);
3213
3214                 disable_irq(dev->irq);
3215                 spin_lock_irq(&np->lock);
3216
3217                 writel(0, ioaddr + IntrEnable);
3218                 np->hands_off = 1;
3219                 natsemi_stop_rxtx(dev);
3220                 netif_stop_queue(dev);
3221
3222                 spin_unlock_irq(&np->lock);
3223                 enable_irq(dev->irq);
3224
3225                 /* Update the error counts. */
3226                 __get_stats(dev);
3227
3228                 /* pci_power_off(pdev, -1); */
3229                 drain_ring(dev);
3230                 {
3231                         u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
3232                         /* Restore PME enable bit */
3233                         if (wol) {
3234                                 /* restart the NIC in WOL mode.
3235                                  * The nic must be stopped for this.
3236                                  * FIXME: use the WOL interrupt
3237                                  */
3238                                 enable_wol_mode(dev, 0);
3239                         } else {
3240                                 /* Restore PME enable bit unmolested */
3241                                 writel(np->SavedClkRun, ioaddr + ClkRun);
3242                         }
3243                 }
3244         }
3245         netif_device_detach(dev);
3246         rtnl_unlock();
3247         return 0;
3248 }
3249
3250
3251 static int natsemi_resume (struct pci_dev *pdev)
3252 {
3253         struct net_device *dev = pci_get_drvdata (pdev);
3254         struct netdev_private *np = netdev_priv(dev);
3255
3256         rtnl_lock();
3257         if (netif_device_present(dev))
3258                 goto out;
3259         if (netif_running(dev)) {
3260                 BUG_ON(!np->hands_off);
3261                 pci_enable_device(pdev);
3262         /*      pci_power_on(pdev); */
3263
3264                 natsemi_reset(dev);
3265                 init_ring(dev);
3266                 disable_irq(dev->irq);
3267                 spin_lock_irq(&np->lock);
3268                 np->hands_off = 0;
3269                 init_registers(dev);
3270                 netif_device_attach(dev);
3271                 spin_unlock_irq(&np->lock);
3272                 enable_irq(dev->irq);
3273
3274                 mod_timer(&np->timer, jiffies + 1*HZ);
3275         }
3276         netif_device_attach(dev);
3277 out:
3278         rtnl_unlock();
3279         return 0;
3280 }
3281
3282 #endif /* CONFIG_PM */
3283
3284 static struct pci_driver natsemi_driver = {
3285         .name           = DRV_NAME,
3286         .id_table       = natsemi_pci_tbl,
3287         .probe          = natsemi_probe1,
3288         .remove         = __devexit_p(natsemi_remove1),
3289 #ifdef CONFIG_PM
3290         .suspend        = natsemi_suspend,
3291         .resume         = natsemi_resume,
3292 #endif
3293 };
3294
3295 static int __init natsemi_init_mod (void)
3296 {
3297 /* when a module, this is printed whether or not devices are found in probe */
3298 #ifdef MODULE
3299         printk(version);
3300 #endif
3301
3302         return pci_module_init (&natsemi_driver);
3303 }
3304
3305 static void __exit natsemi_exit_mod (void)
3306 {
3307         pci_unregister_driver (&natsemi_driver);
3308 }
3309
3310 module_init(natsemi_init_mod);
3311 module_exit(natsemi_exit_mod);
3312