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