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