upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / net / eepro100.c
1 /* drivers/net/eepro100.c: An Intel i82557-559 Ethernet driver for Linux. */
2 /*
3         Written 1996-1999 by Donald Becker.
4
5         The driver also contains updates by different kernel developers
6         (see incomplete list below).
7         Current maintainer is Andrey V. Savochkin <saw@saw.sw.com.sg>.
8         Please use this email address and linux-kernel mailing list for bug reports.
9
10         This software may be used and distributed according to the terms
11         of the GNU General Public License, incorporated herein by reference.
12
13         This driver is for the Intel EtherExpress Pro100 (Speedo3) design.
14         It should work with all i82557/558/559 boards.
15
16         Version history:
17         1998 Apr - 2000 Feb  Andrey V. Savochkin <saw@saw.sw.com.sg>
18                 Serious fixes for multicast filter list setting, TX timeout routine;
19                 RX ring refilling logic;  other stuff
20         2000 Feb  Jeff Garzik <jgarzik@pobox.com>
21                 Convert to new PCI driver interface
22         2000 Mar 24  Dragan Stancevic <visitor@valinux.com>
23                 Disabled FC and ER, to avoid lockups when when we get FCP interrupts.
24         2000 Jul 17 Goutham Rao <goutham.rao@intel.com>
25                 PCI DMA API fixes, adding pci_dma_sync_single calls where neccesary
26         2000 Aug 31 David Mosberger <davidm@hpl.hp.com>
27                 rx_align support: enables rx DMA without causing unaligned accesses.
28 */
29
30 static const char *version =
31 "eepro100.c:v1.09j-t 9/29/99 Donald Becker http://www.scyld.com/network/eepro100.html\n"
32 "eepro100.c: $Revision: 1.36 $ 2000/11/17 Modified by Andrey V. Savochkin <saw@saw.sw.com.sg> and others\n";
33
34 /* A few user-configurable values that apply to all boards.
35    First set is undocumented and spelled per Intel recommendations. */
36
37 static int congenb /* = 0 */; /* Enable congestion control in the DP83840. */
38 static int txfifo = 8;          /* Tx FIFO threshold in 4 byte units, 0-15 */
39 static int rxfifo = 8;          /* Rx FIFO threshold, default 32 bytes. */
40 /* Tx/Rx DMA burst length, 0-127, 0 == no preemption, tx==128 -> disabled. */
41 static int txdmacount = 128;
42 static int rxdmacount /* = 0 */;
43
44 #if defined(__ia64__) || defined(__alpha__) || defined(__sparc__) || defined(__mips__) || \
45         defined(__arm__)
46   /* align rx buffers to 2 bytes so that IP header is aligned */
47 # define rx_align(skb)          skb_reserve((skb), 2)
48 # define RxFD_ALIGNMENT         __attribute__ ((aligned (2), packed))
49 #else
50 # define rx_align(skb)
51 # define RxFD_ALIGNMENT
52 #endif
53
54 /* Set the copy breakpoint for the copy-only-tiny-buffer Rx method.
55    Lower values use more memory, but are faster. */
56 static int rx_copybreak = 200;
57
58 /* Maximum events (Rx packets, etc.) to handle at each interrupt. */
59 static int max_interrupt_work = 20;
60
61 /* Maximum number of multicast addresses to filter (vs. rx-all-multicast) */
62 static int multicast_filter_limit = 64;
63
64 /* 'options' is used to pass a transceiver override or full-duplex flag
65    e.g. "options=16" for FD, "options=32" for 100mbps-only. */
66 static int full_duplex[] = {-1, -1, -1, -1, -1, -1, -1, -1};
67 static int options[] = {-1, -1, -1, -1, -1, -1, -1, -1};
68
69 /* A few values that may be tweaked. */
70 /* The ring sizes should be a power of two for efficiency. */
71 #define TX_RING_SIZE    64
72 #define RX_RING_SIZE    64
73 /* How much slots multicast filter setup may take.
74    Do not descrease without changing set_rx_mode() implementaion. */
75 #define TX_MULTICAST_SIZE   2
76 #define TX_MULTICAST_RESERV (TX_MULTICAST_SIZE*2)
77 /* Actual number of TX packets queued, must be
78    <= TX_RING_SIZE-TX_MULTICAST_RESERV. */
79 #define TX_QUEUE_LIMIT  (TX_RING_SIZE-TX_MULTICAST_RESERV)
80 /* Hysteresis marking queue as no longer full. */
81 #define TX_QUEUE_UNFULL (TX_QUEUE_LIMIT-4)
82
83 /* Operational parameters that usually are not changed. */
84
85 /* Time in jiffies before concluding the transmitter is hung. */
86 #define TX_TIMEOUT              (2*HZ)
87 /* Size of an pre-allocated Rx buffer: <Ethernet MTU> + slack.*/
88 #define PKT_BUF_SZ              1536
89
90 #include <linux/config.h>
91 #include <linux/module.h>
92
93 #include <linux/kernel.h>
94 #include <linux/string.h>
95 #include <linux/errno.h>
96 #include <linux/ioport.h>
97 #include <linux/slab.h>
98 #include <linux/interrupt.h>
99 #include <linux/timer.h>
100 #include <linux/pci.h>
101 #include <linux/spinlock.h>
102 #include <linux/init.h>
103 #include <linux/mii.h>
104 #include <linux/delay.h>
105 #include <linux/bitops.h>
106
107 #include <asm/io.h>
108 #include <asm/uaccess.h>
109 #include <asm/irq.h>
110
111 #include <linux/netdevice.h>
112 #include <linux/etherdevice.h>
113 #include <linux/rtnetlink.h>
114 #include <linux/skbuff.h>
115 #include <linux/ethtool.h>
116
117 /* enable PIO instead of MMIO, if CONFIG_EEPRO100_PIO is selected */
118 #ifdef CONFIG_EEPRO100_PIO
119 #define USE_IO 1
120 #endif
121
122 static int debug = -1;
123 #define DEBUG_DEFAULT           (NETIF_MSG_DRV          | \
124                                  NETIF_MSG_HW           | \
125                                  NETIF_MSG_RX_ERR       | \
126                                  NETIF_MSG_TX_ERR)
127 #define DEBUG                   ((debug >= 0) ? (1<<debug)-1 : DEBUG_DEFAULT)
128
129
130 MODULE_AUTHOR("Maintainer: Andrey V. Savochkin <saw@saw.sw.com.sg>");
131 MODULE_DESCRIPTION("Intel i82557/i82558/i82559 PCI EtherExpressPro driver");
132 MODULE_LICENSE("GPL");
133 MODULE_PARM(debug, "i");
134 MODULE_PARM(options, "1-" __MODULE_STRING(8) "i");
135 MODULE_PARM(full_duplex, "1-" __MODULE_STRING(8) "i");
136 MODULE_PARM(congenb, "i");
137 MODULE_PARM(txfifo, "i");
138 MODULE_PARM(rxfifo, "i");
139 MODULE_PARM(txdmacount, "i");
140 MODULE_PARM(rxdmacount, "i");
141 MODULE_PARM(rx_copybreak, "i");
142 MODULE_PARM(max_interrupt_work, "i");
143 MODULE_PARM(multicast_filter_limit, "i");
144 MODULE_PARM_DESC(debug, "debug level (0-6)");
145 MODULE_PARM_DESC(options, "Bits 0-3: transceiver type, bit 4: full duplex, bit 5: 100Mbps");
146 MODULE_PARM_DESC(full_duplex, "full duplex setting(s) (1)");
147 MODULE_PARM_DESC(congenb, "Enable congestion control (1)");
148 MODULE_PARM_DESC(txfifo, "Tx FIFO threshold in 4 byte units, (0-15)");
149 MODULE_PARM_DESC(rxfifo, "Rx FIFO threshold in 4 byte units, (0-15)");
150 MODULE_PARM_DESC(txdmaccount, "Tx DMA burst length; 128 - disable (0-128)");
151 MODULE_PARM_DESC(rxdmaccount, "Rx DMA burst length; 128 - disable (0-128)");
152 MODULE_PARM_DESC(rx_copybreak, "copy breakpoint for copy-only-tiny-frames");
153 MODULE_PARM_DESC(max_interrupt_work, "maximum events handled per interrupt");
154 MODULE_PARM_DESC(multicast_filter_limit, "maximum number of filtered multicast addresses");
155
156 #define RUN_AT(x) (jiffies + (x))
157
158 /* ACPI power states don't universally work (yet) */
159 #ifndef CONFIG_PM
160 #undef pci_set_power_state
161 #define pci_set_power_state null_set_power_state
162 static inline int null_set_power_state(struct pci_dev *dev, int state)
163 {
164         return 0;
165 }
166 #endif /* CONFIG_PM */
167
168 #define netdevice_start(dev)
169 #define netdevice_stop(dev)
170 #define netif_set_tx_timeout(dev, tf, tm) \
171                                                                 do { \
172                                                                         (dev)->tx_timeout = (tf); \
173                                                                         (dev)->watchdog_timeo = (tm); \
174                                                                 } while(0)
175
176
177
178 /*
179                                 Theory of Operation
180
181 I. Board Compatibility
182
183 This device driver is designed for the Intel i82557 "Speedo3" chip, Intel's
184 single-chip fast Ethernet controller for PCI, as used on the Intel
185 EtherExpress Pro 100 adapter.
186
187 II. Board-specific settings
188
189 PCI bus devices are configured by the system at boot time, so no jumpers
190 need to be set on the board.  The system BIOS should be set to assign the
191 PCI INTA signal to an otherwise unused system IRQ line.  While it's
192 possible to share PCI interrupt lines, it negatively impacts performance and
193 only recent kernels support it.
194
195 III. Driver operation
196
197 IIIA. General
198 The Speedo3 is very similar to other Intel network chips, that is to say
199 "apparently designed on a different planet".  This chips retains the complex
200 Rx and Tx descriptors and multiple buffers pointers as previous chips, but
201 also has simplified Tx and Rx buffer modes.  This driver uses the "flexible"
202 Tx mode, but in a simplified lower-overhead manner: it associates only a
203 single buffer descriptor with each frame descriptor.
204
205 Despite the extra space overhead in each receive skbuff, the driver must use
206 the simplified Rx buffer mode to assure that only a single data buffer is
207 associated with each RxFD. The driver implements this by reserving space
208 for the Rx descriptor at the head of each Rx skbuff.
209
210 The Speedo-3 has receive and command unit base addresses that are added to
211 almost all descriptor pointers.  The driver sets these to zero, so that all
212 pointer fields are absolute addresses.
213
214 The System Control Block (SCB) of some previous Intel chips exists on the
215 chip in both PCI I/O and memory space.  This driver uses the I/O space
216 registers, but might switch to memory mapped mode to better support non-x86
217 processors.
218
219 IIIB. Transmit structure
220
221 The driver must use the complex Tx command+descriptor mode in order to
222 have a indirect pointer to the skbuff data section.  Each Tx command block
223 (TxCB) is associated with two immediately appended Tx Buffer Descriptor
224 (TxBD).  A fixed ring of these TxCB+TxBD pairs are kept as part of the
225 speedo_private data structure for each adapter instance.
226
227 The newer i82558 explicitly supports this structure, and can read the two
228 TxBDs in the same PCI burst as the TxCB.
229
230 This ring structure is used for all normal transmit packets, but the
231 transmit packet descriptors aren't long enough for most non-Tx commands such
232 as CmdConfigure.  This is complicated by the possibility that the chip has
233 already loaded the link address in the previous descriptor.  So for these
234 commands we convert the next free descriptor on the ring to a NoOp, and point
235 that descriptor's link to the complex command.
236
237 An additional complexity of these non-transmit commands are that they may be
238 added asynchronous to the normal transmit queue, so we disable interrupts
239 whenever the Tx descriptor ring is manipulated.
240
241 A notable aspect of these special configure commands is that they do
242 work with the normal Tx ring entry scavenge method.  The Tx ring scavenge
243 is done at interrupt time using the 'dirty_tx' index, and checking for the
244 command-complete bit.  While the setup frames may have the NoOp command on the
245 Tx ring marked as complete, but not have completed the setup command, this
246 is not a problem.  The tx_ring entry can be still safely reused, as the
247 tx_skbuff[] entry is always empty for config_cmd and mc_setup frames.
248
249 Commands may have bits set e.g. CmdSuspend in the command word to either
250 suspend or stop the transmit/command unit.  This driver always flags the last
251 command with CmdSuspend, erases the CmdSuspend in the previous command, and
252 then issues a CU_RESUME.
253 Note: Watch out for the potential race condition here: imagine
254         erasing the previous suspend
255                 the chip processes the previous command
256                 the chip processes the final command, and suspends
257         doing the CU_RESUME
258                 the chip processes the next-yet-valid post-final-command.
259 So blindly sending a CU_RESUME is only safe if we do it immediately after
260 after erasing the previous CmdSuspend, without the possibility of an
261 intervening delay.  Thus the resume command is always within the
262 interrupts-disabled region.  This is a timing dependence, but handling this
263 condition in a timing-independent way would considerably complicate the code.
264
265 Note: In previous generation Intel chips, restarting the command unit was a
266 notoriously slow process.  This is presumably no longer true.
267
268 IIIC. Receive structure
269
270 Because of the bus-master support on the Speedo3 this driver uses the new
271 SKBUFF_RX_COPYBREAK scheme, rather than a fixed intermediate receive buffer.
272 This scheme allocates full-sized skbuffs as receive buffers.  The value
273 SKBUFF_RX_COPYBREAK is used as the copying breakpoint: it is chosen to
274 trade-off the memory wasted by passing the full-sized skbuff to the queue
275 layer for all frames vs. the copying cost of copying a frame to a
276 correctly-sized skbuff.
277
278 For small frames the copying cost is negligible (esp. considering that we
279 are pre-loading the cache with immediately useful header information), so we
280 allocate a new, minimally-sized skbuff.  For large frames the copying cost
281 is non-trivial, and the larger copy might flush the cache of useful data, so
282 we pass up the skbuff the packet was received into.
283
284 IV. Notes
285
286 Thanks to Steve Williams of Intel for arranging the non-disclosure agreement
287 that stated that I could disclose the information.  But I still resent
288 having to sign an Intel NDA when I'm helping Intel sell their own product!
289
290 */
291
292 static int speedo_found1(struct pci_dev *pdev, long ioaddr, int fnd_cnt, int acpi_idle_state);
293
294 enum pci_flags_bit {
295         PCI_USES_IO=1, PCI_USES_MEM=2, PCI_USES_MASTER=4,
296         PCI_ADDR0=0x10<<0, PCI_ADDR1=0x10<<1, PCI_ADDR2=0x10<<2, PCI_ADDR3=0x10<<3,
297 };
298
299 static inline unsigned int io_inw(unsigned long port)
300 {
301         return inw(port);
302 }
303 static inline void io_outw(unsigned int val, unsigned long port)
304 {
305         outw(val, port);
306 }
307
308 #ifndef USE_IO
309 /* Currently alpha headers define in/out macros.
310    Undefine them.  2000/03/30  SAW */
311 #undef inb
312 #undef inw
313 #undef inl
314 #undef outb
315 #undef outw
316 #undef outl
317 #define inb readb
318 #define inw readw
319 #define inl readl
320 #define outb writeb
321 #define outw writew
322 #define outl writel
323 #endif
324
325 /* Offsets to the various registers.
326    All accesses need not be longword aligned. */
327 enum speedo_offsets {
328         SCBStatus = 0, SCBCmd = 2,      /* Rx/Command Unit command and status. */
329         SCBIntmask = 3,
330         SCBPointer = 4,                         /* General purpose pointer. */
331         SCBPort = 8,                            /* Misc. commands and operands.  */
332         SCBflash = 12, SCBeeprom = 14, /* EEPROM and flash memory control. */
333         SCBCtrlMDI = 16,                        /* MDI interface control. */
334         SCBEarlyRx = 20,                        /* Early receive byte count. */
335 };
336 /* Commands that can be put in a command list entry. */
337 enum commands {
338         CmdNOp = 0, CmdIASetup = 0x10000, CmdConfigure = 0x20000,
339         CmdMulticastList = 0x30000, CmdTx = 0x40000, CmdTDR = 0x50000,
340         CmdDump = 0x60000, CmdDiagnose = 0x70000,
341         CmdSuspend = 0x40000000,        /* Suspend after completion. */
342         CmdIntr = 0x20000000,           /* Interrupt after completion. */
343         CmdTxFlex = 0x00080000,         /* Use "Flexible mode" for CmdTx command. */
344 };
345 /* Clear CmdSuspend (1<<30) avoiding interference with the card access to the
346    status bits.  Previous driver versions used separate 16 bit fields for
347    commands and statuses.  --SAW
348  */
349 #if defined(__alpha__)
350 # define clear_suspend(cmd)  clear_bit(30, &(cmd)->cmd_status);
351 #else
352 # if defined(__LITTLE_ENDIAN)
353 #  define clear_suspend(cmd)  ((__u16 *)&(cmd)->cmd_status)[1] &= ~0x4000
354 # elif defined(__BIG_ENDIAN)
355 #  define clear_suspend(cmd)  ((__u16 *)&(cmd)->cmd_status)[1] &= ~0x0040
356 # else
357 #  error Unsupported byteorder
358 # endif
359 #endif
360
361 enum SCBCmdBits {
362         SCBMaskCmdDone=0x8000, SCBMaskRxDone=0x4000, SCBMaskCmdIdle=0x2000,
363         SCBMaskRxSuspend=0x1000, SCBMaskEarlyRx=0x0800, SCBMaskFlowCtl=0x0400,
364         SCBTriggerIntr=0x0200, SCBMaskAll=0x0100,
365         /* The rest are Rx and Tx commands. */
366         CUStart=0x0010, CUResume=0x0020, CUStatsAddr=0x0040, CUShowStats=0x0050,
367         CUCmdBase=0x0060,       /* CU Base address (set to zero) . */
368         CUDumpStats=0x0070, /* Dump then reset stats counters. */
369         RxStart=0x0001, RxResume=0x0002, RxAbort=0x0004, RxAddrLoad=0x0006,
370         RxResumeNoResources=0x0007,
371 };
372
373 enum SCBPort_cmds {
374         PortReset=0, PortSelfTest=1, PortPartialReset=2, PortDump=3,
375 };
376
377 /* The Speedo3 Rx and Tx frame/buffer descriptors. */
378 struct descriptor {                         /* A generic descriptor. */
379         volatile s32 cmd_status;        /* All command and status fields. */
380         u32 link;                                   /* struct descriptor *  */
381         unsigned char params[0];
382 };
383
384 /* The Speedo3 Rx and Tx buffer descriptors. */
385 struct RxFD {                                   /* Receive frame descriptor. */
386         volatile s32 status;
387         u32 link;                                       /* struct RxFD * */
388         u32 rx_buf_addr;                        /* void * */
389         u32 count;
390 } RxFD_ALIGNMENT;
391
392 /* Selected elements of the Tx/RxFD.status word. */
393 enum RxFD_bits {
394         RxComplete=0x8000, RxOK=0x2000,
395         RxErrCRC=0x0800, RxErrAlign=0x0400, RxErrTooBig=0x0200, RxErrSymbol=0x0010,
396         RxEth2Type=0x0020, RxNoMatch=0x0004, RxNoIAMatch=0x0002,
397         TxUnderrun=0x1000,  StatusComplete=0x8000,
398 };
399
400 #define CONFIG_DATA_SIZE 22
401 struct TxFD {                                   /* Transmit frame descriptor set. */
402         s32 status;
403         u32 link;                                       /* void * */
404         u32 tx_desc_addr;                       /* Always points to the tx_buf_addr element. */
405         s32 count;                                      /* # of TBD (=1), Tx start thresh., etc. */
406         /* This constitutes two "TBD" entries -- we only use one. */
407 #define TX_DESCR_BUF_OFFSET 16
408         u32 tx_buf_addr0;                       /* void *, frame to be transmitted.  */
409         s32 tx_buf_size0;                       /* Length of Tx frame. */
410         u32 tx_buf_addr1;                       /* void *, frame to be transmitted.  */
411         s32 tx_buf_size1;                       /* Length of Tx frame. */
412         /* the structure must have space for at least CONFIG_DATA_SIZE starting
413          * from tx_desc_addr field */
414 };
415
416 /* Multicast filter setting block.  --SAW */
417 struct speedo_mc_block {
418         struct speedo_mc_block *next;
419         unsigned int tx;
420         dma_addr_t frame_dma;
421         unsigned int len;
422         struct descriptor frame __attribute__ ((__aligned__(16)));
423 };
424
425 /* Elements of the dump_statistics block. This block must be lword aligned. */
426 struct speedo_stats {
427         u32 tx_good_frames;
428         u32 tx_coll16_errs;
429         u32 tx_late_colls;
430         u32 tx_underruns;
431         u32 tx_lost_carrier;
432         u32 tx_deferred;
433         u32 tx_one_colls;
434         u32 tx_multi_colls;
435         u32 tx_total_colls;
436         u32 rx_good_frames;
437         u32 rx_crc_errs;
438         u32 rx_align_errs;
439         u32 rx_resource_errs;
440         u32 rx_overrun_errs;
441         u32 rx_colls_errs;
442         u32 rx_runt_errs;
443         u32 done_marker;
444 };
445
446 enum Rx_ring_state_bits {
447         RrNoMem=1, RrPostponed=2, RrNoResources=4, RrOOMReported=8,
448 };
449
450 /* Do not change the position (alignment) of the first few elements!
451    The later elements are grouped for cache locality.
452
453    Unfortunately, all the positions have been shifted since there.
454    A new re-alignment is required.  2000/03/06  SAW */
455 struct speedo_private {
456         struct TxFD     *tx_ring;               /* Commands (usually CmdTxPacket). */
457         struct RxFD *rx_ringp[RX_RING_SIZE];    /* Rx descriptor, used as ring. */
458         /* The addresses of a Tx/Rx-in-place packets/buffers. */
459         struct sk_buff *tx_skbuff[TX_RING_SIZE];
460         struct sk_buff *rx_skbuff[RX_RING_SIZE];
461         /* Mapped addresses of the rings. */
462         dma_addr_t tx_ring_dma;
463 #define TX_RING_ELEM_DMA(sp, n) ((sp)->tx_ring_dma + (n)*sizeof(struct TxFD))
464         dma_addr_t rx_ring_dma[RX_RING_SIZE];
465         struct descriptor *last_cmd;            /* Last command sent. */
466         unsigned int cur_tx, dirty_tx;          /* The ring entries to be free()ed. */
467         spinlock_t lock;                        /* Group with Tx control cache line. */
468         u32 tx_threshold;                       /* The value for txdesc.count. */
469         struct RxFD *last_rxf;                  /* Last filled RX buffer. */
470         dma_addr_t last_rxf_dma;
471         unsigned int cur_rx, dirty_rx;          /* The next free ring entry */
472         long last_rx_time;                      /* Last Rx, in jiffies, to handle Rx hang. */
473         struct net_device_stats stats;
474         struct speedo_stats *lstats;
475         dma_addr_t lstats_dma;
476         int chip_id;
477         struct pci_dev *pdev;
478         struct timer_list timer;                /* Media selection timer. */
479         struct speedo_mc_block *mc_setup_head;  /* Multicast setup frame list head. */
480         struct speedo_mc_block *mc_setup_tail;  /* Multicast setup frame list tail. */
481         long in_interrupt;                      /* Word-aligned dev->interrupt */
482         unsigned char acpi_pwr;
483         signed char rx_mode;                    /* Current PROMISC/ALLMULTI setting. */
484         unsigned int tx_full:1;                 /* The Tx queue is full. */
485         unsigned int flow_ctrl:1;               /* Use 802.3x flow control. */
486         unsigned int rx_bug:1;                  /* Work around receiver hang errata. */
487         unsigned char default_port:8;           /* Last dev->if_port value. */
488         unsigned char rx_ring_state;            /* RX ring status flags. */
489         unsigned short phy[2];                  /* PHY media interfaces available. */
490         unsigned short partner;                 /* Link partner caps. */
491         struct mii_if_info mii_if;              /* MII API hooks, info */
492         u32 msg_enable;                         /* debug message level */
493 };
494
495 /* The parameters for a CmdConfigure operation.
496    There are so many options that it would be difficult to document each bit.
497    We mostly use the default or recommended settings. */
498 static const char i82557_config_cmd[CONFIG_DATA_SIZE] = {
499         22, 0x08, 0, 0,  0, 0, 0x32, 0x03,  1, /* 1=Use MII  0=Use AUI */
500         0, 0x2E, 0,  0x60, 0,
501         0xf2, 0x48,   0, 0x40, 0xf2, 0x80,              /* 0x40=Force full-duplex */
502         0x3f, 0x05, };
503 static const char i82558_config_cmd[CONFIG_DATA_SIZE] = {
504         22, 0x08, 0, 1,  0, 0, 0x22, 0x03,  1, /* 1=Use MII  0=Use AUI */
505         0, 0x2E, 0,  0x60, 0x08, 0x88,
506         0x68, 0, 0x40, 0xf2, 0x84,              /* Disable FC */
507         0x31, 0x05, };
508
509 /* PHY media interface chips. */
510 static const char *phys[] = {
511         "None", "i82553-A/B", "i82553-C", "i82503",
512         "DP83840", "80c240", "80c24", "i82555",
513         "unknown-8", "unknown-9", "DP83840A", "unknown-11",
514         "unknown-12", "unknown-13", "unknown-14", "unknown-15", };
515 enum phy_chips { NonSuchPhy=0, I82553AB, I82553C, I82503, DP83840, S80C240,
516                                          S80C24, I82555, DP83840A=10, };
517 static const char is_mii[] = { 0, 1, 1, 0, 1, 1, 0, 1 };
518 #define EE_READ_CMD             (6)
519
520 static int eepro100_init_one(struct pci_dev *pdev,
521                 const struct pci_device_id *ent);
522
523 static int do_eeprom_cmd(long ioaddr, int cmd, int cmd_len);
524 static int mdio_read(struct net_device *dev, int phy_id, int location);
525 static void mdio_write(struct net_device *dev, int phy_id, int location, int value);
526 static int speedo_open(struct net_device *dev);
527 static void speedo_resume(struct net_device *dev);
528 static void speedo_timer(unsigned long data);
529 static void speedo_init_rx_ring(struct net_device *dev);
530 static void speedo_tx_timeout(struct net_device *dev);
531 static int speedo_start_xmit(struct sk_buff *skb, struct net_device *dev);
532 static void speedo_refill_rx_buffers(struct net_device *dev, int force);
533 static int speedo_rx(struct net_device *dev);
534 static void speedo_tx_buffer_gc(struct net_device *dev);
535 static irqreturn_t speedo_interrupt(int irq, void *dev_instance, struct pt_regs *regs);
536 static int speedo_close(struct net_device *dev);
537 static struct net_device_stats *speedo_get_stats(struct net_device *dev);
538 static int speedo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
539 static void set_rx_mode(struct net_device *dev);
540 static void speedo_show_state(struct net_device *dev);
541 static struct ethtool_ops ethtool_ops;
542
543 \f
544
545 #ifdef honor_default_port
546 /* Optional driver feature to allow forcing the transceiver setting.
547    Not recommended. */
548 static int mii_ctrl[8] = { 0x3300, 0x3100, 0x0000, 0x0100,
549                                                    0x2000, 0x2100, 0x0400, 0x3100};
550 #endif
551
552 /* How to wait for the command unit to accept a command.
553    Typically this takes 0 ticks. */
554 static inline unsigned char wait_for_cmd_done(struct net_device *dev)
555 {
556         int wait = 1000;
557         long cmd_ioaddr = dev->base_addr + SCBCmd;
558         unsigned char r;
559
560         do  {
561                 udelay(1);
562                 r = inb(cmd_ioaddr);
563         } while(r && --wait >= 0);
564
565         if (wait < 0)
566                 printk(KERN_ALERT "%s: wait_for_cmd_done timeout!\n", dev->name);
567         return r;
568 }
569
570 static int __devinit eepro100_init_one (struct pci_dev *pdev,
571                 const struct pci_device_id *ent)
572 {
573         unsigned long ioaddr;
574         int irq;
575         int acpi_idle_state = 0, pm;
576         static int cards_found /* = 0 */;
577
578 #ifndef MODULE
579         /* when built-in, we only print version if device is found */
580         static int did_version;
581         if (did_version++ == 0)
582                 printk(version);
583 #endif
584
585         /* save power state before pci_enable_device overwrites it */
586         pm = pci_find_capability(pdev, PCI_CAP_ID_PM);
587         if (pm) {
588                 u16 pwr_command;
589                 pci_read_config_word(pdev, pm + PCI_PM_CTRL, &pwr_command);
590                 acpi_idle_state = pwr_command & PCI_PM_CTRL_STATE_MASK;
591         }
592
593         if (pci_enable_device(pdev))
594                 goto err_out_free_mmio_region;
595
596         pci_set_master(pdev);
597
598         if (!request_region(pci_resource_start(pdev, 1),
599                         pci_resource_len(pdev, 1), "eepro100")) {
600                 printk (KERN_ERR "eepro100: cannot reserve I/O ports\n");
601                 goto err_out_none;
602         }
603         if (!request_mem_region(pci_resource_start(pdev, 0),
604                         pci_resource_len(pdev, 0), "eepro100")) {
605                 printk (KERN_ERR "eepro100: cannot reserve MMIO region\n");
606                 goto err_out_free_pio_region;
607         }
608
609         irq = pdev->irq;
610 #ifdef USE_IO
611         ioaddr = pci_resource_start(pdev, 1);
612         if (DEBUG & NETIF_MSG_PROBE)
613                 printk("Found Intel i82557 PCI Speedo at I/O %#lx, IRQ %d.\n",
614                            ioaddr, irq);
615 #else
616         ioaddr = (unsigned long)ioremap(pci_resource_start(pdev, 0),
617                                                                         pci_resource_len(pdev, 0));
618         if (!ioaddr) {
619                 printk (KERN_ERR "eepro100: cannot remap MMIO region %lx @ %lx\n",
620                                 pci_resource_len(pdev, 0), pci_resource_start(pdev, 0));
621                 goto err_out_free_mmio_region;
622         }
623         if (DEBUG & NETIF_MSG_PROBE)
624                 printk("Found Intel i82557 PCI Speedo, MMIO at %#lx, IRQ %d.\n",
625                            pci_resource_start(pdev, 0), irq);
626 #endif
627
628
629         if (speedo_found1(pdev, ioaddr, cards_found, acpi_idle_state) == 0)
630                 cards_found++;
631         else
632                 goto err_out_iounmap;
633
634         return 0;
635
636 err_out_iounmap: ;
637 #ifndef USE_IO
638         iounmap ((void *)ioaddr);
639 #endif
640 err_out_free_mmio_region:
641         release_mem_region(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
642 err_out_free_pio_region:
643         release_region(pci_resource_start(pdev, 1), pci_resource_len(pdev, 1));
644 err_out_none:
645         return -ENODEV;
646 }
647
648 #ifdef CONFIG_NET_POLL_CONTROLLER
649 /*
650  * Polling 'interrupt' - used by things like netconsole to send skbs
651  * without having to re-enable interrupts. It's not called while
652  * the interrupt routine is executing.
653  */
654
655 static void poll_speedo (struct net_device *dev)
656 {
657         /* disable_irq is not very nice, but with the funny lockless design
658            we have no other choice. */
659         disable_irq(dev->irq);
660         speedo_interrupt (dev->irq, dev, NULL);
661         enable_irq(dev->irq);
662 }
663 #endif
664
665 static int __devinit speedo_found1(struct pci_dev *pdev,
666                 long ioaddr, int card_idx, int acpi_idle_state)
667 {
668         struct net_device *dev;
669         struct speedo_private *sp;
670         const char *product;
671         int i, option;
672         u16 eeprom[0x100];
673         int size;
674         void *tx_ring_space;
675         dma_addr_t tx_ring_dma;
676
677         size = TX_RING_SIZE * sizeof(struct TxFD) + sizeof(struct speedo_stats);
678         tx_ring_space = pci_alloc_consistent(pdev, size, &tx_ring_dma);
679         if (tx_ring_space == NULL)
680                 return -1;
681
682         dev = alloc_etherdev(sizeof(struct speedo_private));
683         if (dev == NULL) {
684                 printk(KERN_ERR "eepro100: Could not allocate ethernet device.\n");
685                 pci_free_consistent(pdev, size, tx_ring_space, tx_ring_dma);
686                 return -1;
687         }
688
689         SET_MODULE_OWNER(dev);
690         SET_NETDEV_DEV(dev, &pdev->dev);
691
692         if (dev->mem_start > 0)
693                 option = dev->mem_start;
694         else if (card_idx >= 0  &&  options[card_idx] >= 0)
695                 option = options[card_idx];
696         else
697                 option = 0;
698
699         rtnl_lock();
700         if (dev_alloc_name(dev, dev->name) < 0) 
701                 goto err_free_unlock;
702
703         /* Read the station address EEPROM before doing the reset.
704            Nominally his should even be done before accepting the device, but
705            then we wouldn't have a device name with which to report the error.
706            The size test is for 6 bit vs. 8 bit address serial EEPROMs.
707         */
708         {
709                 unsigned long iobase;
710                 int read_cmd, ee_size;
711                 u16 sum;
712                 int j;
713
714                 /* Use IO only to avoid postponed writes and satisfy EEPROM timing
715                    requirements. */
716                 iobase = pci_resource_start(pdev, 1);
717                 if ((do_eeprom_cmd(iobase, EE_READ_CMD << 24, 27) & 0xffe0000)
718                         == 0xffe0000) {
719                         ee_size = 0x100;
720                         read_cmd = EE_READ_CMD << 24;
721                 } else {
722                         ee_size = 0x40;
723                         read_cmd = EE_READ_CMD << 22;
724                 }
725
726                 for (j = 0, i = 0, sum = 0; i < ee_size; i++) {
727                         u16 value = do_eeprom_cmd(iobase, read_cmd | (i << 16), 27);
728                         eeprom[i] = value;
729                         sum += value;
730                         if (i < 3) {
731                                 dev->dev_addr[j++] = value;
732                                 dev->dev_addr[j++] = value >> 8;
733                         }
734                 }
735                 if (sum != 0xBABA)
736                         printk(KERN_WARNING "%s: Invalid EEPROM checksum %#4.4x, "
737                                    "check settings before activating this device!\n",
738                                    dev->name, sum);
739                 /* Don't  unregister_netdev(dev);  as the EEPro may actually be
740                    usable, especially if the MAC address is set later.
741                    On the other hand, it may be unusable if MDI data is corrupted. */
742         }
743
744         /* Reset the chip: stop Tx and Rx processes and clear counters.
745            This takes less than 10usec and will easily finish before the next
746            action. */
747         outl(PortReset, ioaddr + SCBPort);
748         inl(ioaddr + SCBPort);
749         udelay(10);
750
751         if (eeprom[3] & 0x0100)
752                 product = "OEM i82557/i82558 10/100 Ethernet";
753         else
754                 product = pci_name(pdev);
755
756         printk(KERN_INFO "%s: %s, ", dev->name, product);
757
758         for (i = 0; i < 5; i++)
759                 printk("%2.2X:", dev->dev_addr[i]);
760         printk("%2.2X, ", dev->dev_addr[i]);
761 #ifdef USE_IO
762         printk("I/O at %#3lx, ", ioaddr);
763 #endif
764         printk("IRQ %d.\n", pdev->irq);
765
766         /* we must initialize base_addr early, for mdio_{read,write} */
767         dev->base_addr = ioaddr;
768
769 #if 1 || defined(kernel_bloat)
770         /* OK, this is pure kernel bloat.  I don't like it when other drivers
771            waste non-pageable kernel space to emit similar messages, but I need
772            them for bug reports. */
773         {
774                 const char *connectors[] = {" RJ45", " BNC", " AUI", " MII"};
775                 /* The self-test results must be paragraph aligned. */
776                 volatile s32 *self_test_results;
777                 int boguscnt = 16000;   /* Timeout for set-test. */
778                 if ((eeprom[3] & 0x03) != 0x03)
779                         printk(KERN_INFO "  Receiver lock-up bug exists -- enabling"
780                                    " work-around.\n");
781                 printk(KERN_INFO "  Board assembly %4.4x%2.2x-%3.3d, Physical"
782                            " connectors present:",
783                            eeprom[8], eeprom[9]>>8, eeprom[9] & 0xff);
784                 for (i = 0; i < 4; i++)
785                         if (eeprom[5] & (1<<i))
786                                 printk(connectors[i]);
787                 printk("\n"KERN_INFO"  Primary interface chip %s PHY #%d.\n",
788                            phys[(eeprom[6]>>8)&15], eeprom[6] & 0x1f);
789                 if (eeprom[7] & 0x0700)
790                         printk(KERN_INFO "    Secondary interface chip %s.\n",
791                                    phys[(eeprom[7]>>8)&7]);
792                 if (((eeprom[6]>>8) & 0x3f) == DP83840
793                         ||  ((eeprom[6]>>8) & 0x3f) == DP83840A) {
794                         int mdi_reg23 = mdio_read(dev, eeprom[6] & 0x1f, 23) | 0x0422;
795                         if (congenb)
796                           mdi_reg23 |= 0x0100;
797                         printk(KERN_INFO"  DP83840 specific setup, setting register 23 to %4.4x.\n",
798                                    mdi_reg23);
799                         mdio_write(dev, eeprom[6] & 0x1f, 23, mdi_reg23);
800                 }
801                 if ((option >= 0) && (option & 0x70)) {
802                         printk(KERN_INFO "  Forcing %dMbs %s-duplex operation.\n",
803                                    (option & 0x20 ? 100 : 10),
804                                    (option & 0x10 ? "full" : "half"));
805                         mdio_write(dev, eeprom[6] & 0x1f, MII_BMCR,
806                                            ((option & 0x20) ? 0x2000 : 0) |     /* 100mbps? */
807                                            ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
808                 }
809
810                 /* Perform a system self-test. */
811                 self_test_results = (s32*) ((((long) tx_ring_space) + 15) & ~0xf);
812                 self_test_results[0] = 0;
813                 self_test_results[1] = -1;
814                 outl(tx_ring_dma | PortSelfTest, ioaddr + SCBPort);
815                 do {
816                         udelay(10);
817                 } while (self_test_results[1] == -1  &&  --boguscnt >= 0);
818
819                 if (boguscnt < 0) {             /* Test optimized out. */
820                         printk(KERN_ERR "Self test failed, status %8.8x:\n"
821                                    KERN_ERR " Failure to initialize the i82557.\n"
822                                    KERN_ERR " Verify that the card is a bus-master"
823                                    " capable slot.\n",
824                                    self_test_results[1]);
825                 } else
826                         printk(KERN_INFO "  General self-test: %s.\n"
827                                    KERN_INFO "  Serial sub-system self-test: %s.\n"
828                                    KERN_INFO "  Internal registers self-test: %s.\n"
829                                    KERN_INFO "  ROM checksum self-test: %s (%#8.8x).\n",
830                                    self_test_results[1] & 0x1000 ? "failed" : "passed",
831                                    self_test_results[1] & 0x0020 ? "failed" : "passed",
832                                    self_test_results[1] & 0x0008 ? "failed" : "passed",
833                                    self_test_results[1] & 0x0004 ? "failed" : "passed",
834                                    self_test_results[0]);
835         }
836 #endif  /* kernel_bloat */
837
838         outl(PortReset, ioaddr + SCBPort);
839         inl(ioaddr + SCBPort);
840         udelay(10);
841
842         /* Return the chip to its original power state. */
843         pci_set_power_state(pdev, acpi_idle_state);
844
845         pci_set_drvdata (pdev, dev);
846         SET_NETDEV_DEV(dev, &pdev->dev);
847
848         dev->irq = pdev->irq;
849
850         sp = netdev_priv(dev);
851         sp->pdev = pdev;
852         sp->msg_enable = DEBUG;
853         sp->acpi_pwr = acpi_idle_state;
854         sp->tx_ring = tx_ring_space;
855         sp->tx_ring_dma = tx_ring_dma;
856         sp->lstats = (struct speedo_stats *)(sp->tx_ring + TX_RING_SIZE);
857         sp->lstats_dma = TX_RING_ELEM_DMA(sp, TX_RING_SIZE);
858         init_timer(&sp->timer); /* used in ioctl() */
859         spin_lock_init(&sp->lock);
860
861         sp->mii_if.full_duplex = option >= 0 && (option & 0x10) ? 1 : 0;
862         if (card_idx >= 0) {
863                 if (full_duplex[card_idx] >= 0)
864                         sp->mii_if.full_duplex = full_duplex[card_idx];
865         }
866         sp->default_port = option >= 0 ? (option & 0x0f) : 0;
867
868         sp->phy[0] = eeprom[6];
869         sp->phy[1] = eeprom[7];
870
871         sp->mii_if.phy_id = eeprom[6] & 0x1f;
872         sp->mii_if.phy_id_mask = 0x1f;
873         sp->mii_if.reg_num_mask = 0x1f;
874         sp->mii_if.dev = dev;
875         sp->mii_if.mdio_read = mdio_read;
876         sp->mii_if.mdio_write = mdio_write;
877         
878         sp->rx_bug = (eeprom[3] & 0x03) == 3 ? 0 : 1;
879         if (((pdev->device > 0x1030 && (pdev->device < 0x103F))) 
880             || (pdev->device == 0x2449) || (pdev->device == 0x2459) 
881             || (pdev->device == 0x245D)) {
882                 sp->chip_id = 1;
883         }
884
885         if (sp->rx_bug)
886                 printk(KERN_INFO "  Receiver lock-up workaround activated.\n");
887
888         /* The Speedo-specific entries in the device structure. */
889         dev->open = &speedo_open;
890         dev->hard_start_xmit = &speedo_start_xmit;
891         netif_set_tx_timeout(dev, &speedo_tx_timeout, TX_TIMEOUT);
892         dev->stop = &speedo_close;
893         dev->get_stats = &speedo_get_stats;
894         dev->set_multicast_list = &set_rx_mode;
895         dev->do_ioctl = &speedo_ioctl;
896         SET_ETHTOOL_OPS(dev, &ethtool_ops);
897 #ifdef CONFIG_NET_POLL_CONTROLLER
898         dev->poll_controller = &poll_speedo;
899 #endif
900
901         if (register_netdevice(dev))
902                 goto err_free_unlock;
903         rtnl_unlock();
904
905         return 0;
906
907  err_free_unlock:
908         rtnl_unlock();
909         free_netdev(dev);
910         return -1;
911 }
912
913 static void do_slow_command(struct net_device *dev, int cmd)
914 {
915         long cmd_ioaddr = dev->base_addr + SCBCmd;
916         int wait = 0;
917         do
918                 if (inb(cmd_ioaddr) == 0) break;
919         while(++wait <= 200);
920         if (wait > 100)
921                 printk(KERN_ERR "Command %4.4x never accepted (%d polls)!\n",
922                        inb(cmd_ioaddr), wait);
923
924         outb(cmd, cmd_ioaddr);
925
926         for (wait = 0; wait <= 100; wait++)
927                 if (inb(cmd_ioaddr) == 0) return;
928         for (; wait <= 20000; wait++)
929                 if (inb(cmd_ioaddr) == 0) return;
930                 else udelay(1);
931         printk(KERN_ERR "Command %4.4x was not accepted after %d polls!"
932                "  Current status %8.8x.\n",
933                cmd, wait, inl(dev->base_addr + SCBStatus));
934 }
935
936 /* Serial EEPROM section.
937    A "bit" grungy, but we work our way through bit-by-bit :->. */
938 /*  EEPROM_Ctrl bits. */
939 #define EE_SHIFT_CLK    0x01    /* EEPROM shift clock. */
940 #define EE_CS                   0x02    /* EEPROM chip select. */
941 #define EE_DATA_WRITE   0x04    /* EEPROM chip data in. */
942 #define EE_DATA_READ    0x08    /* EEPROM chip data out. */
943 #define EE_ENB                  (0x4800 | EE_CS)
944 #define EE_WRITE_0              0x4802
945 #define EE_WRITE_1              0x4806
946 #define EE_OFFSET               SCBeeprom
947
948 /* The fixes for the code were kindly provided by Dragan Stancevic
949    <visitor@valinux.com> to strictly follow Intel specifications of EEPROM
950    access timing.
951    The publicly available sheet 64486302 (sec. 3.1) specifies 1us access
952    interval for serial EEPROM.  However, it looks like that there is an
953    additional requirement dictating larger udelay's in the code below.
954    2000/05/24  SAW */
955 static int __devinit do_eeprom_cmd(long ioaddr, int cmd, int cmd_len)
956 {
957         unsigned retval = 0;
958         long ee_addr = ioaddr + SCBeeprom;
959
960         io_outw(EE_ENB, ee_addr); udelay(2);
961         io_outw(EE_ENB | EE_SHIFT_CLK, ee_addr); udelay(2);
962
963         /* Shift the command bits out. */
964         do {
965                 short dataval = (cmd & (1 << cmd_len)) ? EE_WRITE_1 : EE_WRITE_0;
966                 io_outw(dataval, ee_addr); udelay(2);
967                 io_outw(dataval | EE_SHIFT_CLK, ee_addr); udelay(2);
968                 retval = (retval << 1) | ((io_inw(ee_addr) & EE_DATA_READ) ? 1 : 0);
969         } while (--cmd_len >= 0);
970         io_outw(EE_ENB, ee_addr); udelay(2);
971
972         /* Terminate the EEPROM access. */
973         io_outw(EE_ENB & ~EE_CS, ee_addr);
974         return retval;
975 }
976
977 static int mdio_read(struct net_device *dev, int phy_id, int location)
978 {
979         long ioaddr = dev->base_addr;
980         int val, boguscnt = 64*10;              /* <64 usec. to complete, typ 27 ticks */
981         outl(0x08000000 | (location<<16) | (phy_id<<21), ioaddr + SCBCtrlMDI);
982         do {
983                 val = inl(ioaddr + SCBCtrlMDI);
984                 if (--boguscnt < 0) {
985                         printk(KERN_ERR " mdio_read() timed out with val = %8.8x.\n", val);
986                         break;
987                 }
988         } while (! (val & 0x10000000));
989         return val & 0xffff;
990 }
991
992 static void mdio_write(struct net_device *dev, int phy_id, int location, int value)
993 {
994         long ioaddr = dev->base_addr;
995         int val, boguscnt = 64*10;              /* <64 usec. to complete, typ 27 ticks */
996         outl(0x04000000 | (location<<16) | (phy_id<<21) | value,
997                  ioaddr + SCBCtrlMDI);
998         do {
999                 val = inl(ioaddr + SCBCtrlMDI);
1000                 if (--boguscnt < 0) {
1001                         printk(KERN_ERR" mdio_write() timed out with val = %8.8x.\n", val);
1002                         break;
1003                 }
1004         } while (! (val & 0x10000000));
1005 }
1006
1007 static int
1008 speedo_open(struct net_device *dev)
1009 {
1010         struct speedo_private *sp = netdev_priv(dev);
1011         long ioaddr = dev->base_addr;
1012         int retval;
1013
1014         if (netif_msg_ifup(sp))
1015                 printk(KERN_DEBUG "%s: speedo_open() irq %d.\n", dev->name, dev->irq);
1016
1017         pci_set_power_state(sp->pdev, 0);
1018
1019         /* Set up the Tx queue early.. */
1020         sp->cur_tx = 0;
1021         sp->dirty_tx = 0;
1022         sp->last_cmd = NULL;
1023         sp->tx_full = 0;
1024         sp->in_interrupt = 0;
1025
1026         /* .. we can safely take handler calls during init. */
1027         retval = request_irq(dev->irq, &speedo_interrupt, SA_SHIRQ, dev->name, dev);
1028         if (retval) {
1029                 return retval;
1030         }
1031
1032         dev->if_port = sp->default_port;
1033
1034 #ifdef oh_no_you_dont_unless_you_honour_the_options_passed_in_to_us
1035         /* Retrigger negotiation to reset previous errors. */
1036         if ((sp->phy[0] & 0x8000) == 0) {
1037                 int phy_addr = sp->phy[0] & 0x1f ;
1038                 /* Use 0x3300 for restarting NWay, other values to force xcvr:
1039                    0x0000 10-HD
1040                    0x0100 10-FD
1041                    0x2000 100-HD
1042                    0x2100 100-FD
1043                 */
1044 #ifdef honor_default_port
1045                 mdio_write(dev, phy_addr, MII_BMCR, mii_ctrl[dev->default_port & 7]);
1046 #else
1047                 mdio_write(dev, phy_addr, MII_BMCR, 0x3300);
1048 #endif
1049         }
1050 #endif
1051
1052         speedo_init_rx_ring(dev);
1053
1054         /* Fire up the hardware. */
1055         outw(SCBMaskAll, ioaddr + SCBCmd);
1056         speedo_resume(dev);
1057
1058         netdevice_start(dev);
1059         netif_start_queue(dev);
1060
1061         /* Setup the chip and configure the multicast list. */
1062         sp->mc_setup_head = NULL;
1063         sp->mc_setup_tail = NULL;
1064         sp->flow_ctrl = sp->partner = 0;
1065         sp->rx_mode = -1;                       /* Invalid -> always reset the mode. */
1066         set_rx_mode(dev);
1067         if ((sp->phy[0] & 0x8000) == 0)
1068                 sp->mii_if.advertising = mdio_read(dev, sp->phy[0] & 0x1f, MII_ADVERTISE);
1069
1070         mii_check_link(&sp->mii_if);
1071
1072         if (netif_msg_ifup(sp)) {
1073                 printk(KERN_DEBUG "%s: Done speedo_open(), status %8.8x.\n",
1074                            dev->name, inw(ioaddr + SCBStatus));
1075         }
1076
1077         /* Set the timer.  The timer serves a dual purpose:
1078            1) to monitor the media interface (e.g. link beat) and perhaps switch
1079            to an alternate media type
1080            2) to monitor Rx activity, and restart the Rx process if the receiver
1081            hangs. */
1082         sp->timer.expires = RUN_AT((24*HZ)/10);                         /* 2.4 sec. */
1083         sp->timer.data = (unsigned long)dev;
1084         sp->timer.function = &speedo_timer;                                     /* timer handler */
1085         add_timer(&sp->timer);
1086
1087         /* No need to wait for the command unit to accept here. */
1088         if ((sp->phy[0] & 0x8000) == 0)
1089                 mdio_read(dev, sp->phy[0] & 0x1f, MII_BMCR);
1090
1091         return 0;
1092 }
1093
1094 /* Start the chip hardware after a full reset. */
1095 static void speedo_resume(struct net_device *dev)
1096 {
1097         struct speedo_private *sp = netdev_priv(dev);
1098         long ioaddr = dev->base_addr;
1099
1100         /* Start with a Tx threshold of 256 (0x..20.... 8 byte units). */
1101         sp->tx_threshold = 0x01208000;
1102
1103         /* Set the segment registers to '0'. */
1104         if (wait_for_cmd_done(dev) != 0) {
1105                 outl(PortPartialReset, ioaddr + SCBPort);
1106                 udelay(10);
1107         }
1108
1109         outl(0, ioaddr + SCBPointer);
1110         inl(ioaddr + SCBPointer);                       /* Flush to PCI. */
1111         udelay(10);                     /* Bogus, but it avoids the bug. */
1112
1113         /* Note: these next two operations can take a while. */
1114         do_slow_command(dev, RxAddrLoad);
1115         do_slow_command(dev, CUCmdBase);
1116
1117         /* Load the statistics block and rx ring addresses. */
1118         outl(sp->lstats_dma, ioaddr + SCBPointer);
1119         inl(ioaddr + SCBPointer);                       /* Flush to PCI */
1120
1121         outb(CUStatsAddr, ioaddr + SCBCmd);
1122         sp->lstats->done_marker = 0;
1123         wait_for_cmd_done(dev);
1124
1125         if (sp->rx_ringp[sp->cur_rx % RX_RING_SIZE] == NULL) {
1126                 if (netif_msg_rx_err(sp))
1127                         printk(KERN_DEBUG "%s: NULL cur_rx in speedo_resume().\n",
1128                                         dev->name);
1129         } else {
1130                 outl(sp->rx_ring_dma[sp->cur_rx % RX_RING_SIZE],
1131                          ioaddr + SCBPointer);
1132                 inl(ioaddr + SCBPointer);               /* Flush to PCI */
1133         }
1134
1135         /* Note: RxStart should complete instantly. */
1136         do_slow_command(dev, RxStart);
1137         do_slow_command(dev, CUDumpStats);
1138
1139         /* Fill the first command with our physical address. */
1140         {
1141                 struct descriptor *ias_cmd;
1142
1143                 ias_cmd =
1144                         (struct descriptor *)&sp->tx_ring[sp->cur_tx++ % TX_RING_SIZE];
1145                 /* Avoid a bug(?!) here by marking the command already completed. */
1146                 ias_cmd->cmd_status = cpu_to_le32((CmdSuspend | CmdIASetup) | 0xa000);
1147                 ias_cmd->link =
1148                         cpu_to_le32(TX_RING_ELEM_DMA(sp, sp->cur_tx % TX_RING_SIZE));
1149                 memcpy(ias_cmd->params, dev->dev_addr, 6);
1150                 if (sp->last_cmd)
1151                         clear_suspend(sp->last_cmd);
1152                 sp->last_cmd = ias_cmd;
1153         }
1154
1155         /* Start the chip's Tx process and unmask interrupts. */
1156         outl(TX_RING_ELEM_DMA(sp, sp->dirty_tx % TX_RING_SIZE),
1157                  ioaddr + SCBPointer);
1158         /* We are not ACK-ing FCP and ER in the interrupt handler yet so they should
1159            remain masked --Dragan */
1160         outw(CUStart | SCBMaskEarlyRx | SCBMaskFlowCtl, ioaddr + SCBCmd);
1161 }
1162
1163 /*
1164  * Sometimes the receiver stops making progress.  This routine knows how to
1165  * get it going again, without losing packets or being otherwise nasty like
1166  * a chip reset would be.  Previously the driver had a whole sequence
1167  * of if RxSuspended, if it's no buffers do one thing, if it's no resources,
1168  * do another, etc.  But those things don't really matter.  Separate logic
1169  * in the ISR provides for allocating buffers--the other half of operation
1170  * is just making sure the receiver is active.  speedo_rx_soft_reset does that.
1171  * This problem with the old, more involved algorithm is shown up under
1172  * ping floods on the order of 60K packets/second on a 100Mbps fdx network.
1173  */
1174 static void
1175 speedo_rx_soft_reset(struct net_device *dev)
1176 {
1177         struct speedo_private *sp = netdev_priv(dev);
1178         struct RxFD *rfd;
1179         long ioaddr;
1180
1181         ioaddr = dev->base_addr;
1182         if (wait_for_cmd_done(dev) != 0) {
1183                 printk("%s: previous command stalled\n", dev->name);
1184                 return;
1185         }
1186         /*
1187         * Put the hardware into a known state.
1188         */
1189         outb(RxAbort, ioaddr + SCBCmd);
1190
1191         rfd = sp->rx_ringp[sp->cur_rx % RX_RING_SIZE];
1192
1193         rfd->rx_buf_addr = 0xffffffff;
1194
1195         if (wait_for_cmd_done(dev) != 0) {
1196                 printk("%s: RxAbort command stalled\n", dev->name);
1197                 return;
1198         }
1199         outl(sp->rx_ring_dma[sp->cur_rx % RX_RING_SIZE],
1200                 ioaddr + SCBPointer);
1201         outb(RxStart, ioaddr + SCBCmd);
1202 }
1203
1204
1205 /* Media monitoring and control. */
1206 static void speedo_timer(unsigned long data)
1207 {
1208         struct net_device *dev = (struct net_device *)data;
1209         struct speedo_private *sp = netdev_priv(dev);
1210         long ioaddr = dev->base_addr;
1211         int phy_num = sp->phy[0] & 0x1f;
1212
1213         /* We have MII and lost link beat. */
1214         if ((sp->phy[0] & 0x8000) == 0) {
1215                 int partner = mdio_read(dev, phy_num, MII_LPA);
1216                 if (partner != sp->partner) {
1217                         int flow_ctrl = sp->mii_if.advertising & partner & 0x0400 ? 1 : 0;
1218                         if (netif_msg_link(sp)) {
1219                                 printk(KERN_DEBUG "%s: Link status change.\n", dev->name);
1220                                 printk(KERN_DEBUG "%s: Old partner %x, new %x, adv %x.\n",
1221                                            dev->name, sp->partner, partner, sp->mii_if.advertising);
1222                         }
1223                         sp->partner = partner;
1224                         if (flow_ctrl != sp->flow_ctrl) {
1225                                 sp->flow_ctrl = flow_ctrl;
1226                                 sp->rx_mode = -1;       /* Trigger a reload. */
1227                         }
1228                 }
1229         }
1230         mii_check_link(&sp->mii_if);
1231         if (netif_msg_timer(sp)) {
1232                 printk(KERN_DEBUG "%s: Media control tick, status %4.4x.\n",
1233                            dev->name, inw(ioaddr + SCBStatus));
1234         }
1235         if (sp->rx_mode < 0  ||
1236                 (sp->rx_bug  && jiffies - sp->last_rx_time > 2*HZ)) {
1237                 /* We haven't received a packet in a Long Time.  We might have been
1238                    bitten by the receiver hang bug.  This can be cleared by sending
1239                    a set multicast list command. */
1240                 if (netif_msg_timer(sp))
1241                         printk(KERN_DEBUG "%s: Sending a multicast list set command"
1242                                    " from a timer routine,"
1243                                    " m=%d, j=%ld, l=%ld.\n",
1244                                    dev->name, sp->rx_mode, jiffies, sp->last_rx_time);
1245                 set_rx_mode(dev);
1246         }
1247         /* We must continue to monitor the media. */
1248         sp->timer.expires = RUN_AT(2*HZ);                       /* 2.0 sec. */
1249         add_timer(&sp->timer);
1250 }
1251
1252 static void speedo_show_state(struct net_device *dev)
1253 {
1254         struct speedo_private *sp = netdev_priv(dev);
1255         int i;
1256
1257         if (netif_msg_pktdata(sp)) {
1258                 printk(KERN_DEBUG "%s: Tx ring dump,  Tx queue %u / %u:\n", 
1259                     dev->name, sp->cur_tx, sp->dirty_tx);
1260                 for (i = 0; i < TX_RING_SIZE; i++)
1261                         printk(KERN_DEBUG "%s:  %c%c%2d %8.8x.\n", dev->name,
1262                             i == sp->dirty_tx % TX_RING_SIZE ? '*' : ' ',
1263                             i == sp->cur_tx % TX_RING_SIZE ? '=' : ' ',
1264                             i, sp->tx_ring[i].status);
1265
1266                 printk(KERN_DEBUG "%s: Printing Rx ring"
1267                     " (next to receive into %u, dirty index %u).\n",
1268                     dev->name, sp->cur_rx, sp->dirty_rx);
1269                 for (i = 0; i < RX_RING_SIZE; i++)
1270                         printk(KERN_DEBUG "%s: %c%c%c%2d %8.8x.\n", dev->name,
1271                             sp->rx_ringp[i] == sp->last_rxf ? 'l' : ' ',
1272                             i == sp->dirty_rx % RX_RING_SIZE ? '*' : ' ',
1273                             i == sp->cur_rx % RX_RING_SIZE ? '=' : ' ',
1274                             i, (sp->rx_ringp[i] != NULL) ?
1275                             (unsigned)sp->rx_ringp[i]->status : 0);
1276         }
1277
1278 #if 0
1279         {
1280                 long ioaddr = dev->base_addr;
1281                 int phy_num = sp->phy[0] & 0x1f;
1282                 for (i = 0; i < 16; i++) {
1283                         /* FIXME: what does it mean?  --SAW */
1284                         if (i == 6) i = 21;
1285                         printk(KERN_DEBUG "%s:  PHY index %d register %d is %4.4x.\n",
1286                                    dev->name, phy_num, i, mdio_read(dev, phy_num, i));
1287                 }
1288         }
1289 #endif
1290
1291 }
1292
1293 /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
1294 static void
1295 speedo_init_rx_ring(struct net_device *dev)
1296 {
1297         struct speedo_private *sp = netdev_priv(dev);
1298         struct RxFD *rxf, *last_rxf = NULL;
1299         dma_addr_t last_rxf_dma = 0 /* to shut up the compiler */;
1300         int i;
1301
1302         sp->cur_rx = 0;
1303
1304         for (i = 0; i < RX_RING_SIZE; i++) {
1305                 struct sk_buff *skb;
1306                 skb = dev_alloc_skb(PKT_BUF_SZ + sizeof(struct RxFD));
1307                 /* XXX: do we really want to call this before the NULL check? --hch */
1308                 rx_align(skb);                  /* Align IP on 16 byte boundary */
1309                 sp->rx_skbuff[i] = skb;
1310                 if (skb == NULL)
1311                         break;                  /* OK.  Just initially short of Rx bufs. */
1312                 skb->dev = dev;                 /* Mark as being used by this device. */
1313                 rxf = (struct RxFD *)skb->tail;
1314                 sp->rx_ringp[i] = rxf;
1315                 sp->rx_ring_dma[i] =
1316                         pci_map_single(sp->pdev, rxf,
1317                                         PKT_BUF_SZ + sizeof(struct RxFD), PCI_DMA_BIDIRECTIONAL);
1318                 skb_reserve(skb, sizeof(struct RxFD));
1319                 if (last_rxf) {
1320                         last_rxf->link = cpu_to_le32(sp->rx_ring_dma[i]);
1321                         pci_dma_sync_single_for_device(sp->pdev, last_rxf_dma,
1322                                                                                    sizeof(struct RxFD), PCI_DMA_TODEVICE);
1323                 }
1324                 last_rxf = rxf;
1325                 last_rxf_dma = sp->rx_ring_dma[i];
1326                 rxf->status = cpu_to_le32(0x00000001);  /* '1' is flag value only. */
1327                 rxf->link = 0;                                          /* None yet. */
1328                 /* This field unused by i82557. */
1329                 rxf->rx_buf_addr = 0xffffffff;
1330                 rxf->count = cpu_to_le32(PKT_BUF_SZ << 16);
1331                 pci_dma_sync_single_for_device(sp->pdev, sp->rx_ring_dma[i],
1332                                                                            sizeof(struct RxFD), PCI_DMA_TODEVICE);
1333         }
1334         sp->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
1335         /* Mark the last entry as end-of-list. */
1336         last_rxf->status = cpu_to_le32(0xC0000002);     /* '2' is flag value only. */
1337         pci_dma_sync_single_for_device(sp->pdev, sp->rx_ring_dma[RX_RING_SIZE-1],
1338                                                                    sizeof(struct RxFD), PCI_DMA_TODEVICE);
1339         sp->last_rxf = last_rxf;
1340         sp->last_rxf_dma = last_rxf_dma;
1341 }
1342
1343 static void speedo_purge_tx(struct net_device *dev)
1344 {
1345         struct speedo_private *sp = netdev_priv(dev);
1346         int entry;
1347
1348         while ((int)(sp->cur_tx - sp->dirty_tx) > 0) {
1349                 entry = sp->dirty_tx % TX_RING_SIZE;
1350                 if (sp->tx_skbuff[entry]) {
1351                         sp->stats.tx_errors++;
1352                         pci_unmap_single(sp->pdev,
1353                                         le32_to_cpu(sp->tx_ring[entry].tx_buf_addr0),
1354                                         sp->tx_skbuff[entry]->len, PCI_DMA_TODEVICE);
1355                         dev_kfree_skb_irq(sp->tx_skbuff[entry]);
1356                         sp->tx_skbuff[entry] = NULL;
1357                 }
1358                 sp->dirty_tx++;
1359         }
1360         while (sp->mc_setup_head != NULL) {
1361                 struct speedo_mc_block *t;
1362                 if (netif_msg_tx_err(sp))
1363                         printk(KERN_DEBUG "%s: freeing mc frame.\n", dev->name);
1364                 pci_unmap_single(sp->pdev, sp->mc_setup_head->frame_dma,
1365                                 sp->mc_setup_head->len, PCI_DMA_TODEVICE);
1366                 t = sp->mc_setup_head->next;
1367                 kfree(sp->mc_setup_head);
1368                 sp->mc_setup_head = t;
1369         }
1370         sp->mc_setup_tail = NULL;
1371         sp->tx_full = 0;
1372         netif_wake_queue(dev);
1373 }
1374
1375 static void reset_mii(struct net_device *dev)
1376 {
1377         struct speedo_private *sp = netdev_priv(dev);
1378
1379         /* Reset the MII transceiver, suggested by Fred Young @ scalable.com. */
1380         if ((sp->phy[0] & 0x8000) == 0) {
1381                 int phy_addr = sp->phy[0] & 0x1f;
1382                 int advertising = mdio_read(dev, phy_addr, MII_ADVERTISE);
1383                 int mii_bmcr = mdio_read(dev, phy_addr, MII_BMCR);
1384                 mdio_write(dev, phy_addr, MII_BMCR, 0x0400);
1385                 mdio_write(dev, phy_addr, MII_BMSR, 0x0000);
1386                 mdio_write(dev, phy_addr, MII_ADVERTISE, 0x0000);
1387                 mdio_write(dev, phy_addr, MII_BMCR, 0x8000);
1388 #ifdef honor_default_port
1389                 mdio_write(dev, phy_addr, MII_BMCR, mii_ctrl[dev->default_port & 7]);
1390 #else
1391                 mdio_read(dev, phy_addr, MII_BMCR);
1392                 mdio_write(dev, phy_addr, MII_BMCR, mii_bmcr);
1393                 mdio_write(dev, phy_addr, MII_ADVERTISE, advertising);
1394 #endif
1395         }
1396 }
1397
1398 static void speedo_tx_timeout(struct net_device *dev)
1399 {
1400         struct speedo_private *sp = netdev_priv(dev);
1401         long ioaddr = dev->base_addr;
1402         int status = inw(ioaddr + SCBStatus);
1403         unsigned long flags;
1404
1405         if (netif_msg_tx_err(sp)) {
1406                 printk(KERN_WARNING "%s: Transmit timed out: status %4.4x "
1407                    " %4.4x at %d/%d command %8.8x.\n",
1408                    dev->name, status, inw(ioaddr + SCBCmd),
1409                    sp->dirty_tx, sp->cur_tx,
1410                    sp->tx_ring[sp->dirty_tx % TX_RING_SIZE].status);
1411
1412         }
1413         speedo_show_state(dev);
1414 #if 0
1415         if ((status & 0x00C0) != 0x0080
1416                 &&  (status & 0x003C) == 0x0010) {
1417                 /* Only the command unit has stopped. */
1418                 printk(KERN_WARNING "%s: Trying to restart the transmitter...\n",
1419                            dev->name);
1420                 outl(TX_RING_ELEM_DMA(sp, dirty_tx % TX_RING_SIZE]),
1421                          ioaddr + SCBPointer);
1422                 outw(CUStart, ioaddr + SCBCmd);
1423                 reset_mii(dev);
1424         } else {
1425 #else
1426         {
1427 #endif
1428                 del_timer_sync(&sp->timer);
1429                 /* Reset the Tx and Rx units. */
1430                 outl(PortReset, ioaddr + SCBPort);
1431                 /* We may get spurious interrupts here.  But I don't think that they
1432                    may do much harm.  1999/12/09 SAW */
1433                 udelay(10);
1434                 /* Disable interrupts. */
1435                 outw(SCBMaskAll, ioaddr + SCBCmd);
1436                 synchronize_irq(dev->irq);
1437                 speedo_tx_buffer_gc(dev);
1438                 /* Free as much as possible.
1439                    It helps to recover from a hang because of out-of-memory.
1440                    It also simplifies speedo_resume() in case TX ring is full or
1441                    close-to-be full. */
1442                 speedo_purge_tx(dev);
1443                 speedo_refill_rx_buffers(dev, 1);
1444                 spin_lock_irqsave(&sp->lock, flags);
1445                 speedo_resume(dev);
1446                 sp->rx_mode = -1;
1447                 dev->trans_start = jiffies;
1448                 spin_unlock_irqrestore(&sp->lock, flags);
1449                 set_rx_mode(dev); /* it takes the spinlock itself --SAW */
1450                 /* Reset MII transceiver.  Do it before starting the timer to serialize
1451                    mdio_xxx operations.  Yes, it's a paranoya :-)  2000/05/09 SAW */
1452                 reset_mii(dev);
1453                 sp->timer.expires = RUN_AT(2*HZ);
1454                 add_timer(&sp->timer);
1455         }
1456         return;
1457 }
1458
1459 static int
1460 speedo_start_xmit(struct sk_buff *skb, struct net_device *dev)
1461 {
1462         struct speedo_private *sp = netdev_priv(dev);
1463         long ioaddr = dev->base_addr;
1464         int entry;
1465
1466         /* Prevent interrupts from changing the Tx ring from underneath us. */
1467         unsigned long flags;
1468
1469         spin_lock_irqsave(&sp->lock, flags);
1470
1471         /* Check if there are enough space. */
1472         if ((int)(sp->cur_tx - sp->dirty_tx) >= TX_QUEUE_LIMIT) {
1473                 printk(KERN_ERR "%s: incorrect tbusy state, fixed.\n", dev->name);
1474                 netif_stop_queue(dev);
1475                 sp->tx_full = 1;
1476                 spin_unlock_irqrestore(&sp->lock, flags);
1477                 return 1;
1478         }
1479
1480         /* Calculate the Tx descriptor entry. */
1481         entry = sp->cur_tx++ % TX_RING_SIZE;
1482
1483         sp->tx_skbuff[entry] = skb;
1484         sp->tx_ring[entry].status =
1485                 cpu_to_le32(CmdSuspend | CmdTx | CmdTxFlex);
1486         if (!(entry & ((TX_RING_SIZE>>2)-1)))
1487                 sp->tx_ring[entry].status |= cpu_to_le32(CmdIntr);
1488         sp->tx_ring[entry].link =
1489                 cpu_to_le32(TX_RING_ELEM_DMA(sp, sp->cur_tx % TX_RING_SIZE));
1490         sp->tx_ring[entry].tx_desc_addr =
1491                 cpu_to_le32(TX_RING_ELEM_DMA(sp, entry) + TX_DESCR_BUF_OFFSET);
1492         /* The data region is always in one buffer descriptor. */
1493         sp->tx_ring[entry].count = cpu_to_le32(sp->tx_threshold);
1494         sp->tx_ring[entry].tx_buf_addr0 =
1495                 cpu_to_le32(pci_map_single(sp->pdev, skb->data,
1496                                            skb->len, PCI_DMA_TODEVICE));
1497         sp->tx_ring[entry].tx_buf_size0 = cpu_to_le32(skb->len);
1498
1499         /* workaround for hardware bug on 10 mbit half duplex */
1500
1501         if ((sp->partner == 0) && (sp->chip_id == 1)) {
1502                 wait_for_cmd_done(dev);
1503                 outb(0 , ioaddr + SCBCmd);
1504                 udelay(1);
1505         }
1506
1507         /* Trigger the command unit resume. */
1508         wait_for_cmd_done(dev);
1509         clear_suspend(sp->last_cmd);
1510         /* We want the time window between clearing suspend flag on the previous
1511            command and resuming CU to be as small as possible.
1512            Interrupts in between are very undesired.  --SAW */
1513         outb(CUResume, ioaddr + SCBCmd);
1514         sp->last_cmd = (struct descriptor *)&sp->tx_ring[entry];
1515
1516         /* Leave room for set_rx_mode(). If there is no more space than reserved
1517            for multicast filter mark the ring as full. */
1518         if ((int)(sp->cur_tx - sp->dirty_tx) >= TX_QUEUE_LIMIT) {
1519                 netif_stop_queue(dev);
1520                 sp->tx_full = 1;
1521         }
1522
1523         spin_unlock_irqrestore(&sp->lock, flags);
1524
1525         dev->trans_start = jiffies;
1526
1527         return 0;
1528 }
1529
1530 static void speedo_tx_buffer_gc(struct net_device *dev)
1531 {
1532         unsigned int dirty_tx;
1533         struct speedo_private *sp = netdev_priv(dev);
1534
1535         dirty_tx = sp->dirty_tx;
1536         while ((int)(sp->cur_tx - dirty_tx) > 0) {
1537                 int entry = dirty_tx % TX_RING_SIZE;
1538                 int status = le32_to_cpu(sp->tx_ring[entry].status);
1539
1540                 if (netif_msg_tx_done(sp))
1541                         printk(KERN_DEBUG " scavenge candidate %d status %4.4x.\n",
1542                                    entry, status);
1543                 if ((status & StatusComplete) == 0)
1544                         break;                  /* It still hasn't been processed. */
1545                 if (status & TxUnderrun)
1546                         if (sp->tx_threshold < 0x01e08000) {
1547                                 if (netif_msg_tx_err(sp))
1548                                         printk(KERN_DEBUG "%s: TX underrun, threshold adjusted.\n",
1549                                                    dev->name);
1550                                 sp->tx_threshold += 0x00040000;
1551                         }
1552                 /* Free the original skb. */
1553                 if (sp->tx_skbuff[entry]) {
1554                         sp->stats.tx_packets++; /* Count only user packets. */
1555                         sp->stats.tx_bytes += sp->tx_skbuff[entry]->len;
1556                         pci_unmap_single(sp->pdev,
1557                                         le32_to_cpu(sp->tx_ring[entry].tx_buf_addr0),
1558                                         sp->tx_skbuff[entry]->len, PCI_DMA_TODEVICE);
1559                         dev_kfree_skb_irq(sp->tx_skbuff[entry]);
1560                         sp->tx_skbuff[entry] = NULL;
1561                 }
1562                 dirty_tx++;
1563         }
1564
1565         if (netif_msg_tx_err(sp) && (int)(sp->cur_tx - dirty_tx) > TX_RING_SIZE) {
1566                 printk(KERN_ERR "out-of-sync dirty pointer, %d vs. %d,"
1567                            " full=%d.\n",
1568                            dirty_tx, sp->cur_tx, sp->tx_full);
1569                 dirty_tx += TX_RING_SIZE;
1570         }
1571
1572         while (sp->mc_setup_head != NULL
1573                    && (int)(dirty_tx - sp->mc_setup_head->tx - 1) > 0) {
1574                 struct speedo_mc_block *t;
1575                 if (netif_msg_tx_err(sp))
1576                         printk(KERN_DEBUG "%s: freeing mc frame.\n", dev->name);
1577                 pci_unmap_single(sp->pdev, sp->mc_setup_head->frame_dma,
1578                                 sp->mc_setup_head->len, PCI_DMA_TODEVICE);
1579                 t = sp->mc_setup_head->next;
1580                 kfree(sp->mc_setup_head);
1581                 sp->mc_setup_head = t;
1582         }
1583         if (sp->mc_setup_head == NULL)
1584                 sp->mc_setup_tail = NULL;
1585
1586         sp->dirty_tx = dirty_tx;
1587 }
1588
1589 /* The interrupt handler does all of the Rx thread work and cleans up
1590    after the Tx thread. */
1591 static irqreturn_t speedo_interrupt(int irq, void *dev_instance, struct pt_regs *regs)
1592 {
1593         struct net_device *dev = (struct net_device *)dev_instance;
1594         struct speedo_private *sp;
1595         long ioaddr, boguscnt = max_interrupt_work;
1596         unsigned short status;
1597         unsigned int handled = 0;
1598
1599         ioaddr = dev->base_addr;
1600         sp = netdev_priv(dev);
1601
1602 #ifndef final_version
1603         /* A lock to prevent simultaneous entry on SMP machines. */
1604         if (test_and_set_bit(0, (void*)&sp->in_interrupt)) {
1605                 printk(KERN_ERR"%s: SMP simultaneous entry of an interrupt handler.\n",
1606                            dev->name);
1607                 sp->in_interrupt = 0;   /* Avoid halting machine. */
1608                 return IRQ_NONE;
1609         }
1610 #endif
1611
1612         do {
1613                 status = inw(ioaddr + SCBStatus);
1614                 /* Acknowledge all of the current interrupt sources ASAP. */
1615                 /* Will change from 0xfc00 to 0xff00 when we start handling
1616                    FCP and ER interrupts --Dragan */
1617                 outw(status & 0xfc00, ioaddr + SCBStatus);
1618
1619                 if (netif_msg_intr(sp))
1620                         printk(KERN_DEBUG "%s: interrupt  status=%#4.4x.\n",
1621                                    dev->name, status);
1622
1623                 if ((status & 0xfc00) == 0)
1624                         break;
1625                 handled = 1;
1626
1627
1628                 if ((status & 0x5000) ||        /* Packet received, or Rx error. */
1629                         (sp->rx_ring_state&(RrNoMem|RrPostponed)) == RrPostponed)
1630                                                                         /* Need to gather the postponed packet. */
1631                         speedo_rx(dev);
1632
1633                 /* Always check if all rx buffers are allocated.  --SAW */
1634                 speedo_refill_rx_buffers(dev, 0);
1635                 
1636                 spin_lock(&sp->lock);
1637                 /*
1638                  * The chip may have suspended reception for various reasons.
1639                  * Check for that, and re-prime it should this be the case.
1640                  */
1641                 switch ((status >> 2) & 0xf) {
1642                 case 0: /* Idle */
1643                         break;
1644                 case 1: /* Suspended */
1645                 case 2: /* No resources (RxFDs) */
1646                 case 9: /* Suspended with no more RBDs */
1647                 case 10: /* No resources due to no RBDs */
1648                 case 12: /* Ready with no RBDs */
1649                         speedo_rx_soft_reset(dev);
1650                         break;
1651                 case 3:  case 5:  case 6:  case 7:  case 8:
1652                 case 11:  case 13:  case 14:  case 15:
1653                         /* these are all reserved values */
1654                         break;
1655                 }
1656                 
1657                 
1658                 /* User interrupt, Command/Tx unit interrupt or CU not active. */
1659                 if (status & 0xA400) {
1660                         speedo_tx_buffer_gc(dev);
1661                         if (sp->tx_full
1662                                 && (int)(sp->cur_tx - sp->dirty_tx) < TX_QUEUE_UNFULL) {
1663                                 /* The ring is no longer full. */
1664                                 sp->tx_full = 0;
1665                                 netif_wake_queue(dev); /* Attention: under a spinlock.  --SAW */
1666                         }
1667                 }
1668                 
1669                 spin_unlock(&sp->lock);
1670
1671                 if (--boguscnt < 0) {
1672                         printk(KERN_ERR "%s: Too much work at interrupt, status=0x%4.4x.\n",
1673                                    dev->name, status);
1674                         /* Clear all interrupt sources. */
1675                         /* Will change from 0xfc00 to 0xff00 when we start handling
1676                            FCP and ER interrupts --Dragan */
1677                         outw(0xfc00, ioaddr + SCBStatus);
1678                         break;
1679                 }
1680         } while (1);
1681
1682         if (netif_msg_intr(sp))
1683                 printk(KERN_DEBUG "%s: exiting interrupt, status=%#4.4x.\n",
1684                            dev->name, inw(ioaddr + SCBStatus));
1685
1686         clear_bit(0, (void*)&sp->in_interrupt);
1687         return IRQ_RETVAL(handled);
1688 }
1689
1690 static inline struct RxFD *speedo_rx_alloc(struct net_device *dev, int entry)
1691 {
1692         struct speedo_private *sp = netdev_priv(dev);
1693         struct RxFD *rxf;
1694         struct sk_buff *skb;
1695         /* Get a fresh skbuff to replace the consumed one. */
1696         skb = dev_alloc_skb(PKT_BUF_SZ + sizeof(struct RxFD));
1697         /* XXX: do we really want to call this before the NULL check? --hch */
1698         rx_align(skb);                          /* Align IP on 16 byte boundary */
1699         sp->rx_skbuff[entry] = skb;
1700         if (skb == NULL) {
1701                 sp->rx_ringp[entry] = NULL;
1702                 return NULL;
1703         }
1704         rxf = sp->rx_ringp[entry] = (struct RxFD *)skb->tail;
1705         sp->rx_ring_dma[entry] =
1706                 pci_map_single(sp->pdev, rxf,
1707                                            PKT_BUF_SZ + sizeof(struct RxFD), PCI_DMA_FROMDEVICE);
1708         skb->dev = dev;
1709         skb_reserve(skb, sizeof(struct RxFD));
1710         rxf->rx_buf_addr = 0xffffffff;
1711         pci_dma_sync_single_for_device(sp->pdev, sp->rx_ring_dma[entry],
1712                                                                    sizeof(struct RxFD), PCI_DMA_TODEVICE);
1713         return rxf;
1714 }
1715
1716 static inline void speedo_rx_link(struct net_device *dev, int entry,
1717                                                                   struct RxFD *rxf, dma_addr_t rxf_dma)
1718 {
1719         struct speedo_private *sp = netdev_priv(dev);
1720         rxf->status = cpu_to_le32(0xC0000001);  /* '1' for driver use only. */
1721         rxf->link = 0;                  /* None yet. */
1722         rxf->count = cpu_to_le32(PKT_BUF_SZ << 16);
1723         sp->last_rxf->link = cpu_to_le32(rxf_dma);
1724         sp->last_rxf->status &= cpu_to_le32(~0xC0000000);
1725         pci_dma_sync_single_for_device(sp->pdev, sp->last_rxf_dma,
1726                                                                    sizeof(struct RxFD), PCI_DMA_TODEVICE);
1727         sp->last_rxf = rxf;
1728         sp->last_rxf_dma = rxf_dma;
1729 }
1730
1731 static int speedo_refill_rx_buf(struct net_device *dev, int force)
1732 {
1733         struct speedo_private *sp = netdev_priv(dev);
1734         int entry;
1735         struct RxFD *rxf;
1736
1737         entry = sp->dirty_rx % RX_RING_SIZE;
1738         if (sp->rx_skbuff[entry] == NULL) {
1739                 rxf = speedo_rx_alloc(dev, entry);
1740                 if (rxf == NULL) {
1741                         unsigned int forw;
1742                         int forw_entry;
1743                         if (netif_msg_rx_err(sp) || !(sp->rx_ring_state & RrOOMReported)) {
1744                                 printk(KERN_WARNING "%s: can't fill rx buffer (force %d)!\n",
1745                                                 dev->name, force);
1746                                 sp->rx_ring_state |= RrOOMReported;
1747                         }
1748                         speedo_show_state(dev);
1749                         if (!force)
1750                                 return -1;      /* Better luck next time!  */
1751                         /* Borrow an skb from one of next entries. */
1752                         for (forw = sp->dirty_rx + 1; forw != sp->cur_rx; forw++)
1753                                 if (sp->rx_skbuff[forw % RX_RING_SIZE] != NULL)
1754                                         break;
1755                         if (forw == sp->cur_rx)
1756                                 return -1;
1757                         forw_entry = forw % RX_RING_SIZE;
1758                         sp->rx_skbuff[entry] = sp->rx_skbuff[forw_entry];
1759                         sp->rx_skbuff[forw_entry] = NULL;
1760                         rxf = sp->rx_ringp[forw_entry];
1761                         sp->rx_ringp[forw_entry] = NULL;
1762                         sp->rx_ringp[entry] = rxf;
1763                 }
1764         } else {
1765                 rxf = sp->rx_ringp[entry];
1766         }
1767         speedo_rx_link(dev, entry, rxf, sp->rx_ring_dma[entry]);
1768         sp->dirty_rx++;
1769         sp->rx_ring_state &= ~(RrNoMem|RrOOMReported); /* Mark the progress. */
1770         return 0;
1771 }
1772
1773 static void speedo_refill_rx_buffers(struct net_device *dev, int force)
1774 {
1775         struct speedo_private *sp = netdev_priv(dev);
1776
1777         /* Refill the RX ring. */
1778         while ((int)(sp->cur_rx - sp->dirty_rx) > 0 &&
1779                         speedo_refill_rx_buf(dev, force) != -1);
1780 }
1781
1782 static int
1783 speedo_rx(struct net_device *dev)
1784 {
1785         struct speedo_private *sp = netdev_priv(dev);
1786         int entry = sp->cur_rx % RX_RING_SIZE;
1787         int rx_work_limit = sp->dirty_rx + RX_RING_SIZE - sp->cur_rx;
1788         int alloc_ok = 1;
1789         int npkts = 0;
1790
1791         if (netif_msg_intr(sp))
1792                 printk(KERN_DEBUG " In speedo_rx().\n");
1793         /* If we own the next entry, it's a new packet. Send it up. */
1794         while (sp->rx_ringp[entry] != NULL) {
1795                 int status;
1796                 int pkt_len;
1797
1798                 pci_dma_sync_single_for_cpu(sp->pdev, sp->rx_ring_dma[entry],
1799                                                                         sizeof(struct RxFD), PCI_DMA_FROMDEVICE);
1800                 status = le32_to_cpu(sp->rx_ringp[entry]->status);
1801                 pkt_len = le32_to_cpu(sp->rx_ringp[entry]->count) & 0x3fff;
1802
1803                 if (!(status & RxComplete))
1804                         break;
1805
1806                 if (--rx_work_limit < 0)
1807                         break;
1808
1809                 /* Check for a rare out-of-memory case: the current buffer is
1810                    the last buffer allocated in the RX ring.  --SAW */
1811                 if (sp->last_rxf == sp->rx_ringp[entry]) {
1812                         /* Postpone the packet.  It'll be reaped at an interrupt when this
1813                            packet is no longer the last packet in the ring. */
1814                         if (netif_msg_rx_err(sp))
1815                                 printk(KERN_DEBUG "%s: RX packet postponed!\n",
1816                                            dev->name);
1817                         sp->rx_ring_state |= RrPostponed;
1818                         break;
1819                 }
1820
1821                 if (netif_msg_rx_status(sp))
1822                         printk(KERN_DEBUG "  speedo_rx() status %8.8x len %d.\n", status,
1823                                    pkt_len);
1824                 if ((status & (RxErrTooBig|RxOK|0x0f90)) != RxOK) {
1825                         if (status & RxErrTooBig)
1826                                 printk(KERN_ERR "%s: Ethernet frame overran the Rx buffer, "
1827                                            "status %8.8x!\n", dev->name, status);
1828                         else if (! (status & RxOK)) {
1829                                 /* There was a fatal error.  This *should* be impossible. */
1830                                 sp->stats.rx_errors++;
1831                                 printk(KERN_ERR "%s: Anomalous event in speedo_rx(), "
1832                                            "status %8.8x.\n",
1833                                            dev->name, status);
1834                         }
1835                 } else {
1836                         struct sk_buff *skb;
1837
1838                         /* Check if the packet is long enough to just accept without
1839                            copying to a properly sized skbuff. */
1840                         if (pkt_len < rx_copybreak
1841                                 && (skb = dev_alloc_skb(pkt_len + 2)) != 0) {
1842                                 skb->dev = dev;
1843                                 skb_reserve(skb, 2);    /* Align IP on 16 byte boundaries */
1844                                 /* 'skb_put()' points to the start of sk_buff data area. */
1845                                 pci_dma_sync_single_for_cpu(sp->pdev, sp->rx_ring_dma[entry],
1846                                                                                         sizeof(struct RxFD) + pkt_len,
1847                                                                                         PCI_DMA_FROMDEVICE);
1848
1849 #if 1 || USE_IP_CSUM
1850                                 /* Packet is in one chunk -- we can copy + cksum. */
1851                                 eth_copy_and_sum(skb, sp->rx_skbuff[entry]->tail, pkt_len, 0);
1852                                 skb_put(skb, pkt_len);
1853 #else
1854                                 memcpy(skb_put(skb, pkt_len), sp->rx_skbuff[entry]->tail,
1855                                            pkt_len);
1856 #endif
1857                                 pci_dma_sync_single_for_device(sp->pdev, sp->rx_ring_dma[entry],
1858                                                                                            sizeof(struct RxFD) + pkt_len,
1859                                                                                            PCI_DMA_FROMDEVICE);
1860                                 npkts++;
1861                         } else {
1862                                 /* Pass up the already-filled skbuff. */
1863                                 skb = sp->rx_skbuff[entry];
1864                                 if (skb == NULL) {
1865                                         printk(KERN_ERR "%s: Inconsistent Rx descriptor chain.\n",
1866                                                    dev->name);
1867                                         break;
1868                                 }
1869                                 sp->rx_skbuff[entry] = NULL;
1870                                 skb_put(skb, pkt_len);
1871                                 npkts++;
1872                                 sp->rx_ringp[entry] = NULL;
1873                                 pci_unmap_single(sp->pdev, sp->rx_ring_dma[entry],
1874                                                                  PKT_BUF_SZ + sizeof(struct RxFD),
1875                                                                  PCI_DMA_FROMDEVICE);
1876                         }
1877                         skb->protocol = eth_type_trans(skb, dev);
1878                         netif_rx(skb);
1879                         dev->last_rx = jiffies;
1880                         sp->stats.rx_packets++;
1881                         sp->stats.rx_bytes += pkt_len;
1882                 }
1883                 entry = (++sp->cur_rx) % RX_RING_SIZE;
1884                 sp->rx_ring_state &= ~RrPostponed;
1885                 /* Refill the recently taken buffers.
1886                    Do it one-by-one to handle traffic bursts better. */
1887                 if (alloc_ok && speedo_refill_rx_buf(dev, 0) == -1)
1888                         alloc_ok = 0;
1889         }
1890
1891         /* Try hard to refill the recently taken buffers. */
1892         speedo_refill_rx_buffers(dev, 1);
1893
1894         if (npkts)
1895                 sp->last_rx_time = jiffies;
1896
1897         return 0;
1898 }
1899
1900 static int
1901 speedo_close(struct net_device *dev)
1902 {
1903         long ioaddr = dev->base_addr;
1904         struct speedo_private *sp = netdev_priv(dev);
1905         int i;
1906
1907         netdevice_stop(dev);
1908         netif_stop_queue(dev);
1909
1910         if (netif_msg_ifdown(sp))
1911                 printk(KERN_DEBUG "%s: Shutting down ethercard, status was %4.4x.\n",
1912                            dev->name, inw(ioaddr + SCBStatus));
1913
1914         /* Shut off the media monitoring timer. */
1915         del_timer_sync(&sp->timer);
1916
1917         outw(SCBMaskAll, ioaddr + SCBCmd);
1918
1919         /* Shutting down the chip nicely fails to disable flow control. So.. */
1920         outl(PortPartialReset, ioaddr + SCBPort);
1921         inl(ioaddr + SCBPort); /* flush posted write */
1922         /*
1923          * The chip requires a 10 microsecond quiet period.  Wait here!
1924          */
1925         udelay(10);
1926
1927         free_irq(dev->irq, dev);
1928         speedo_show_state(dev);
1929
1930     /* Free all the skbuffs in the Rx and Tx queues. */
1931         for (i = 0; i < RX_RING_SIZE; i++) {
1932                 struct sk_buff *skb = sp->rx_skbuff[i];
1933                 sp->rx_skbuff[i] = NULL;
1934                 /* Clear the Rx descriptors. */
1935                 if (skb) {
1936                         pci_unmap_single(sp->pdev,
1937                                          sp->rx_ring_dma[i],
1938                                          PKT_BUF_SZ + sizeof(struct RxFD), PCI_DMA_FROMDEVICE);
1939                         dev_kfree_skb(skb);
1940                 }
1941         }
1942
1943         for (i = 0; i < TX_RING_SIZE; i++) {
1944                 struct sk_buff *skb = sp->tx_skbuff[i];
1945                 sp->tx_skbuff[i] = NULL;
1946                 /* Clear the Tx descriptors. */
1947                 if (skb) {
1948                         pci_unmap_single(sp->pdev,
1949                                          le32_to_cpu(sp->tx_ring[i].tx_buf_addr0),
1950                                          skb->len, PCI_DMA_TODEVICE);
1951                         dev_kfree_skb(skb);
1952                 }
1953         }
1954
1955         /* Free multicast setting blocks. */
1956         for (i = 0; sp->mc_setup_head != NULL; i++) {
1957                 struct speedo_mc_block *t;
1958                 t = sp->mc_setup_head->next;
1959                 kfree(sp->mc_setup_head);
1960                 sp->mc_setup_head = t;
1961         }
1962         sp->mc_setup_tail = NULL;
1963         if (netif_msg_ifdown(sp))
1964                 printk(KERN_DEBUG "%s: %d multicast blocks dropped.\n", dev->name, i);
1965
1966         pci_set_power_state(sp->pdev, 2);
1967
1968         return 0;
1969 }
1970
1971 /* The Speedo-3 has an especially awkward and unusable method of getting
1972    statistics out of the chip.  It takes an unpredictable length of time
1973    for the dump-stats command to complete.  To avoid a busy-wait loop we
1974    update the stats with the previous dump results, and then trigger a
1975    new dump.
1976
1977    Oh, and incoming frames are dropped while executing dump-stats!
1978    */
1979 static struct net_device_stats *
1980 speedo_get_stats(struct net_device *dev)
1981 {
1982         struct speedo_private *sp = netdev_priv(dev);
1983         long ioaddr = dev->base_addr;
1984
1985         /* Update only if the previous dump finished. */
1986         if (sp->lstats->done_marker == le32_to_cpu(0xA007)) {
1987                 sp->stats.tx_aborted_errors += le32_to_cpu(sp->lstats->tx_coll16_errs);
1988                 sp->stats.tx_window_errors += le32_to_cpu(sp->lstats->tx_late_colls);
1989                 sp->stats.tx_fifo_errors += le32_to_cpu(sp->lstats->tx_underruns);
1990                 sp->stats.tx_fifo_errors += le32_to_cpu(sp->lstats->tx_lost_carrier);
1991                 /*sp->stats.tx_deferred += le32_to_cpu(sp->lstats->tx_deferred);*/
1992                 sp->stats.collisions += le32_to_cpu(sp->lstats->tx_total_colls);
1993                 sp->stats.rx_crc_errors += le32_to_cpu(sp->lstats->rx_crc_errs);
1994                 sp->stats.rx_frame_errors += le32_to_cpu(sp->lstats->rx_align_errs);
1995                 sp->stats.rx_over_errors += le32_to_cpu(sp->lstats->rx_resource_errs);
1996                 sp->stats.rx_fifo_errors += le32_to_cpu(sp->lstats->rx_overrun_errs);
1997                 sp->stats.rx_length_errors += le32_to_cpu(sp->lstats->rx_runt_errs);
1998                 sp->lstats->done_marker = 0x0000;
1999                 if (netif_running(dev)) {
2000                         unsigned long flags;
2001                         /* Take a spinlock to make wait_for_cmd_done and sending the
2002                            command atomic.  --SAW */
2003                         spin_lock_irqsave(&sp->lock, flags);
2004                         wait_for_cmd_done(dev);
2005                         outb(CUDumpStats, ioaddr + SCBCmd);
2006                         spin_unlock_irqrestore(&sp->lock, flags);
2007                 }
2008         }
2009         return &sp->stats;
2010 }
2011
2012 static void speedo_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2013 {
2014         struct speedo_private *sp = netdev_priv(dev);
2015         strncpy(info->driver, "eepro100", sizeof(info->driver)-1);
2016         strncpy(info->version, version, sizeof(info->version)-1);
2017         if (sp->pdev)
2018                 strcpy(info->bus_info, pci_name(sp->pdev));
2019 }
2020
2021 static int speedo_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
2022 {
2023         struct speedo_private *sp = netdev_priv(dev);
2024         spin_lock_irq(&sp->lock);
2025         mii_ethtool_gset(&sp->mii_if, ecmd);
2026         spin_unlock_irq(&sp->lock);
2027         return 0;
2028 }
2029
2030 static int speedo_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
2031 {
2032         struct speedo_private *sp = netdev_priv(dev);
2033         int res;
2034         spin_lock_irq(&sp->lock);
2035         res = mii_ethtool_sset(&sp->mii_if, ecmd);
2036         spin_unlock_irq(&sp->lock);
2037         return res;
2038 }
2039
2040 static int speedo_nway_reset(struct net_device *dev)
2041 {
2042         struct speedo_private *sp = netdev_priv(dev);
2043         return mii_nway_restart(&sp->mii_if);
2044 }
2045
2046 static u32 speedo_get_link(struct net_device *dev)
2047 {
2048         struct speedo_private *sp = netdev_priv(dev);
2049         return mii_link_ok(&sp->mii_if);
2050 }
2051
2052 static u32 speedo_get_msglevel(struct net_device *dev)
2053 {
2054         struct speedo_private *sp = netdev_priv(dev);
2055         return sp->msg_enable;
2056 }
2057
2058 static void speedo_set_msglevel(struct net_device *dev, u32 v)
2059 {
2060         struct speedo_private *sp = netdev_priv(dev);
2061         sp->msg_enable = v;
2062 }
2063
2064 static struct ethtool_ops ethtool_ops = {
2065         .get_drvinfo = speedo_get_drvinfo,
2066         .get_settings = speedo_get_settings,
2067         .set_settings = speedo_set_settings,
2068         .nway_reset = speedo_nway_reset,
2069         .get_link = speedo_get_link,
2070         .get_msglevel = speedo_get_msglevel,
2071         .set_msglevel = speedo_set_msglevel,
2072 };
2073
2074 static int speedo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2075 {
2076         struct speedo_private *sp = netdev_priv(dev);
2077         struct mii_ioctl_data *data = if_mii(rq);
2078         int phy = sp->phy[0] & 0x1f;
2079         int saved_acpi;
2080         int t;
2081
2082     switch(cmd) {
2083         case SIOCGMIIPHY:               /* Get address of MII PHY in use. */
2084                 data->phy_id = phy;
2085
2086         case SIOCGMIIREG:               /* Read MII PHY register. */
2087                 /* FIXME: these operations need to be serialized with MDIO
2088                    access from the timeout handler.
2089                    They are currently serialized only with MDIO access from the
2090                    timer routine.  2000/05/09 SAW */
2091                 saved_acpi = pci_set_power_state(sp->pdev, 0);
2092                 t = del_timer_sync(&sp->timer);
2093                 data->val_out = mdio_read(dev, data->phy_id & 0x1f, data->reg_num & 0x1f);
2094                 if (t)
2095                         add_timer(&sp->timer); /* may be set to the past  --SAW */
2096                 pci_set_power_state(sp->pdev, saved_acpi);
2097                 return 0;
2098
2099         case SIOCSMIIREG:               /* Write MII PHY register. */
2100                 if (!capable(CAP_NET_ADMIN))
2101                         return -EPERM;
2102                 saved_acpi = pci_set_power_state(sp->pdev, 0);
2103                 t = del_timer_sync(&sp->timer);
2104                 mdio_write(dev, data->phy_id, data->reg_num, data->val_in);
2105                 if (t)
2106                         add_timer(&sp->timer); /* may be set to the past  --SAW */
2107                 pci_set_power_state(sp->pdev, saved_acpi);
2108                 return 0;
2109         default:
2110                 return -EOPNOTSUPP;
2111         }
2112 }
2113
2114 /* Set or clear the multicast filter for this adaptor.
2115    This is very ugly with Intel chips -- we usually have to execute an
2116    entire configuration command, plus process a multicast command.
2117    This is complicated.  We must put a large configuration command and
2118    an arbitrarily-sized multicast command in the transmit list.
2119    To minimize the disruption -- the previous command might have already
2120    loaded the link -- we convert the current command block, normally a Tx
2121    command, into a no-op and link it to the new command.
2122 */
2123 static void set_rx_mode(struct net_device *dev)
2124 {
2125         struct speedo_private *sp = netdev_priv(dev);
2126         long ioaddr = dev->base_addr;
2127         struct descriptor *last_cmd;
2128         char new_rx_mode;
2129         unsigned long flags;
2130         int entry, i;
2131
2132         if (dev->flags & IFF_PROMISC) {                 /* Set promiscuous. */
2133                 new_rx_mode = 3;
2134         } else if ((dev->flags & IFF_ALLMULTI)  ||
2135                            dev->mc_count > multicast_filter_limit) {
2136                 new_rx_mode = 1;
2137         } else
2138                 new_rx_mode = 0;
2139
2140         if (netif_msg_rx_status(sp))
2141                 printk(KERN_DEBUG "%s: set_rx_mode %d -> %d\n", dev->name,
2142                                 sp->rx_mode, new_rx_mode);
2143
2144         if ((int)(sp->cur_tx - sp->dirty_tx) > TX_RING_SIZE - TX_MULTICAST_SIZE) {
2145             /* The Tx ring is full -- don't add anything!  Hope the mode will be
2146                  * set again later. */
2147                 sp->rx_mode = -1;
2148                 return;
2149         }
2150
2151         if (new_rx_mode != sp->rx_mode) {
2152                 u8 *config_cmd_data;
2153
2154                 spin_lock_irqsave(&sp->lock, flags);
2155                 entry = sp->cur_tx++ % TX_RING_SIZE;
2156                 last_cmd = sp->last_cmd;
2157                 sp->last_cmd = (struct descriptor *)&sp->tx_ring[entry];
2158
2159                 sp->tx_skbuff[entry] = NULL;                    /* Redundant. */
2160                 sp->tx_ring[entry].status = cpu_to_le32(CmdSuspend | CmdConfigure);
2161                 sp->tx_ring[entry].link =
2162                         cpu_to_le32(TX_RING_ELEM_DMA(sp, (entry + 1) % TX_RING_SIZE));
2163                 config_cmd_data = (void *)&sp->tx_ring[entry].tx_desc_addr;
2164                 /* Construct a full CmdConfig frame. */
2165                 memcpy(config_cmd_data, i82558_config_cmd, CONFIG_DATA_SIZE);
2166                 config_cmd_data[1] = (txfifo << 4) | rxfifo;
2167                 config_cmd_data[4] = rxdmacount;
2168                 config_cmd_data[5] = txdmacount + 0x80;
2169                 config_cmd_data[15] |= (new_rx_mode & 2) ? 1 : 0;
2170                 /* 0x80 doesn't disable FC 0x84 does.
2171                    Disable Flow control since we are not ACK-ing any FC interrupts
2172                    for now. --Dragan */
2173                 config_cmd_data[19] = 0x84;
2174                 config_cmd_data[19] |= sp->mii_if.full_duplex ? 0x40 : 0;
2175                 config_cmd_data[21] = (new_rx_mode & 1) ? 0x0D : 0x05;
2176                 if (sp->phy[0] & 0x8000) {                      /* Use the AUI port instead. */
2177                         config_cmd_data[15] |= 0x80;
2178                         config_cmd_data[8] = 0;
2179                 }
2180                 /* Trigger the command unit resume. */
2181                 wait_for_cmd_done(dev);
2182                 clear_suspend(last_cmd);
2183                 outb(CUResume, ioaddr + SCBCmd);
2184                 if ((int)(sp->cur_tx - sp->dirty_tx) >= TX_QUEUE_LIMIT) {
2185                         netif_stop_queue(dev);
2186                         sp->tx_full = 1;
2187                 }
2188                 spin_unlock_irqrestore(&sp->lock, flags);
2189         }
2190
2191         if (new_rx_mode == 0  &&  dev->mc_count < 4) {
2192                 /* The simple case of 0-3 multicast list entries occurs often, and
2193                    fits within one tx_ring[] entry. */
2194                 struct dev_mc_list *mclist;
2195                 u16 *setup_params, *eaddrs;
2196
2197                 spin_lock_irqsave(&sp->lock, flags);
2198                 entry = sp->cur_tx++ % TX_RING_SIZE;
2199                 last_cmd = sp->last_cmd;
2200                 sp->last_cmd = (struct descriptor *)&sp->tx_ring[entry];
2201
2202                 sp->tx_skbuff[entry] = NULL;
2203                 sp->tx_ring[entry].status = cpu_to_le32(CmdSuspend | CmdMulticastList);
2204                 sp->tx_ring[entry].link =
2205                         cpu_to_le32(TX_RING_ELEM_DMA(sp, (entry + 1) % TX_RING_SIZE));
2206                 sp->tx_ring[entry].tx_desc_addr = 0; /* Really MC list count. */
2207                 setup_params = (u16 *)&sp->tx_ring[entry].tx_desc_addr;
2208                 *setup_params++ = cpu_to_le16(dev->mc_count*6);
2209                 /* Fill in the multicast addresses. */
2210                 for (i = 0, mclist = dev->mc_list; i < dev->mc_count;
2211                          i++, mclist = mclist->next) {
2212                         eaddrs = (u16 *)mclist->dmi_addr;
2213                         *setup_params++ = *eaddrs++;
2214                         *setup_params++ = *eaddrs++;
2215                         *setup_params++ = *eaddrs++;
2216                 }
2217
2218                 wait_for_cmd_done(dev);
2219                 clear_suspend(last_cmd);
2220                 /* Immediately trigger the command unit resume. */
2221                 outb(CUResume, ioaddr + SCBCmd);
2222
2223                 if ((int)(sp->cur_tx - sp->dirty_tx) >= TX_QUEUE_LIMIT) {
2224                         netif_stop_queue(dev);
2225                         sp->tx_full = 1;
2226                 }
2227                 spin_unlock_irqrestore(&sp->lock, flags);
2228         } else if (new_rx_mode == 0) {
2229                 struct dev_mc_list *mclist;
2230                 u16 *setup_params, *eaddrs;
2231                 struct speedo_mc_block *mc_blk;
2232                 struct descriptor *mc_setup_frm;
2233                 int i;
2234
2235                 mc_blk = kmalloc(sizeof(*mc_blk) + 2 + multicast_filter_limit*6,
2236                                                  GFP_ATOMIC);
2237                 if (mc_blk == NULL) {
2238                         printk(KERN_ERR "%s: Failed to allocate a setup frame.\n",
2239                                    dev->name);
2240                         sp->rx_mode = -1; /* We failed, try again. */
2241                         return;
2242                 }
2243                 mc_blk->next = NULL;
2244                 mc_blk->len = 2 + multicast_filter_limit*6;
2245                 mc_blk->frame_dma =
2246                         pci_map_single(sp->pdev, &mc_blk->frame, mc_blk->len,
2247                                         PCI_DMA_TODEVICE);
2248                 mc_setup_frm = &mc_blk->frame;
2249
2250                 /* Fill the setup frame. */
2251                 if (netif_msg_ifup(sp))
2252                         printk(KERN_DEBUG "%s: Constructing a setup frame at %p.\n",
2253                                    dev->name, mc_setup_frm);
2254                 mc_setup_frm->cmd_status =
2255                         cpu_to_le32(CmdSuspend | CmdIntr | CmdMulticastList);
2256                 /* Link set below. */
2257                 setup_params = (u16 *)&mc_setup_frm->params;
2258                 *setup_params++ = cpu_to_le16(dev->mc_count*6);
2259                 /* Fill in the multicast addresses. */
2260                 for (i = 0, mclist = dev->mc_list; i < dev->mc_count;
2261                          i++, mclist = mclist->next) {
2262                         eaddrs = (u16 *)mclist->dmi_addr;
2263                         *setup_params++ = *eaddrs++;
2264                         *setup_params++ = *eaddrs++;
2265                         *setup_params++ = *eaddrs++;
2266                 }
2267
2268                 /* Disable interrupts while playing with the Tx Cmd list. */
2269                 spin_lock_irqsave(&sp->lock, flags);
2270
2271                 if (sp->mc_setup_tail)
2272                         sp->mc_setup_tail->next = mc_blk;
2273                 else
2274                         sp->mc_setup_head = mc_blk;
2275                 sp->mc_setup_tail = mc_blk;
2276                 mc_blk->tx = sp->cur_tx;
2277
2278                 entry = sp->cur_tx++ % TX_RING_SIZE;
2279                 last_cmd = sp->last_cmd;
2280                 sp->last_cmd = mc_setup_frm;
2281
2282                 /* Change the command to a NoOp, pointing to the CmdMulti command. */
2283                 sp->tx_skbuff[entry] = NULL;
2284                 sp->tx_ring[entry].status = cpu_to_le32(CmdNOp);
2285                 sp->tx_ring[entry].link = cpu_to_le32(mc_blk->frame_dma);
2286
2287                 /* Set the link in the setup frame. */
2288                 mc_setup_frm->link =
2289                         cpu_to_le32(TX_RING_ELEM_DMA(sp, (entry + 1) % TX_RING_SIZE));
2290
2291                 pci_dma_sync_single_for_device(sp->pdev, mc_blk->frame_dma,
2292                                                                            mc_blk->len, PCI_DMA_TODEVICE);
2293
2294                 wait_for_cmd_done(dev);
2295                 clear_suspend(last_cmd);
2296                 /* Immediately trigger the command unit resume. */
2297                 outb(CUResume, ioaddr + SCBCmd);
2298
2299                 if ((int)(sp->cur_tx - sp->dirty_tx) >= TX_QUEUE_LIMIT) {
2300                         netif_stop_queue(dev);
2301                         sp->tx_full = 1;
2302                 }
2303                 spin_unlock_irqrestore(&sp->lock, flags);
2304
2305                 if (netif_msg_rx_status(sp))
2306                         printk(" CmdMCSetup frame length %d in entry %d.\n",
2307                                    dev->mc_count, entry);
2308         }
2309
2310         sp->rx_mode = new_rx_mode;
2311 }
2312 \f
2313 #ifdef CONFIG_PM
2314 static int eepro100_suspend(struct pci_dev *pdev, u32 state)
2315 {
2316         struct net_device *dev = pci_get_drvdata (pdev);
2317         struct speedo_private *sp = netdev_priv(dev);
2318         long ioaddr = dev->base_addr;
2319
2320         pci_save_state(pdev);
2321
2322         if (!netif_running(dev))
2323                 return 0;
2324                 
2325         del_timer_sync(&sp->timer);
2326
2327         netif_device_detach(dev);
2328         outl(PortPartialReset, ioaddr + SCBPort);
2329         
2330         /* XXX call pci_set_power_state ()? */
2331         pci_disable_device(pdev);
2332         pci_set_power_state (pdev, 3);
2333         return 0;
2334 }
2335
2336 static int eepro100_resume(struct pci_dev *pdev)
2337 {
2338         struct net_device *dev = pci_get_drvdata (pdev);
2339         struct speedo_private *sp = netdev_priv(dev);
2340         long ioaddr = dev->base_addr;
2341
2342         pci_set_power_state(pdev, 0);
2343         pci_restore_state(pdev);
2344         pci_enable_device(pdev);
2345         pci_set_master(pdev);
2346
2347         if (!netif_running(dev))
2348                 return 0;
2349
2350         /* I'm absolutely uncertain if this part of code may work.
2351            The problems are:
2352             - correct hardware reinitialization;
2353                 - correct driver behavior between different steps of the
2354                   reinitialization;
2355                 - serialization with other driver calls.
2356            2000/03/08  SAW */
2357         outw(SCBMaskAll, ioaddr + SCBCmd);
2358         speedo_resume(dev);
2359         netif_device_attach(dev);
2360         sp->rx_mode = -1;
2361         sp->flow_ctrl = sp->partner = 0;
2362         set_rx_mode(dev);
2363         sp->timer.expires = RUN_AT(2*HZ);
2364         add_timer(&sp->timer);
2365         return 0;
2366 }
2367 #endif /* CONFIG_PM */
2368
2369 static void __devexit eepro100_remove_one (struct pci_dev *pdev)
2370 {
2371         struct net_device *dev = pci_get_drvdata (pdev);
2372         struct speedo_private *sp = netdev_priv(dev);
2373         
2374         unregister_netdev(dev);
2375
2376         release_region(pci_resource_start(pdev, 1), pci_resource_len(pdev, 1));
2377         release_mem_region(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
2378
2379 #ifndef USE_IO
2380         iounmap((char *)dev->base_addr);
2381 #endif
2382
2383         pci_free_consistent(pdev, TX_RING_SIZE * sizeof(struct TxFD)
2384                                                                 + sizeof(struct speedo_stats),
2385                                                 sp->tx_ring, sp->tx_ring_dma);
2386         pci_disable_device(pdev);
2387         free_netdev(dev);
2388 }
2389 \f
2390 static struct pci_device_id eepro100_pci_tbl[] = {
2391         { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82557,
2392                 PCI_ANY_ID, PCI_ANY_ID, },
2393         { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82559ER,
2394                 PCI_ANY_ID, PCI_ANY_ID, },
2395         { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_7,
2396                 PCI_ANY_ID, PCI_ANY_ID, },
2397         { PCI_VENDOR_ID_INTEL, 0x1029, PCI_ANY_ID, PCI_ANY_ID, },
2398         { PCI_VENDOR_ID_INTEL, 0x1030, PCI_ANY_ID, PCI_ANY_ID, },
2399         { PCI_VENDOR_ID_INTEL, 0x1031, PCI_ANY_ID, PCI_ANY_ID, },
2400         { PCI_VENDOR_ID_INTEL, 0x1032, PCI_ANY_ID, PCI_ANY_ID, },
2401         { PCI_VENDOR_ID_INTEL, 0x1033, PCI_ANY_ID, PCI_ANY_ID, },
2402         { PCI_VENDOR_ID_INTEL, 0x1034, PCI_ANY_ID, PCI_ANY_ID, },
2403         { PCI_VENDOR_ID_INTEL, 0x1035, PCI_ANY_ID, PCI_ANY_ID, },
2404         { PCI_VENDOR_ID_INTEL, 0x1036, PCI_ANY_ID, PCI_ANY_ID, },
2405         { PCI_VENDOR_ID_INTEL, 0x1037, PCI_ANY_ID, PCI_ANY_ID, },
2406         { PCI_VENDOR_ID_INTEL, 0x1038, PCI_ANY_ID, PCI_ANY_ID, },
2407         { PCI_VENDOR_ID_INTEL, 0x1039, PCI_ANY_ID, PCI_ANY_ID, },
2408         { PCI_VENDOR_ID_INTEL, 0x103A, PCI_ANY_ID, PCI_ANY_ID, },
2409         { PCI_VENDOR_ID_INTEL, 0x103B, PCI_ANY_ID, PCI_ANY_ID, },
2410         { PCI_VENDOR_ID_INTEL, 0x103C, PCI_ANY_ID, PCI_ANY_ID, },
2411         { PCI_VENDOR_ID_INTEL, 0x103D, PCI_ANY_ID, PCI_ANY_ID, },
2412         { PCI_VENDOR_ID_INTEL, 0x103E, PCI_ANY_ID, PCI_ANY_ID, },
2413         { PCI_VENDOR_ID_INTEL, 0x1050, PCI_ANY_ID, PCI_ANY_ID, },
2414         { PCI_VENDOR_ID_INTEL, 0x1059, PCI_ANY_ID, PCI_ANY_ID, },
2415         { PCI_VENDOR_ID_INTEL, 0x1227, PCI_ANY_ID, PCI_ANY_ID, },
2416         { PCI_VENDOR_ID_INTEL, 0x1228, PCI_ANY_ID, PCI_ANY_ID, },
2417         { PCI_VENDOR_ID_INTEL, 0x2449, PCI_ANY_ID, PCI_ANY_ID, },
2418         { PCI_VENDOR_ID_INTEL, 0x2459, PCI_ANY_ID, PCI_ANY_ID, },
2419         { PCI_VENDOR_ID_INTEL, 0x245D, PCI_ANY_ID, PCI_ANY_ID, },
2420         { PCI_VENDOR_ID_INTEL, 0x5200, PCI_ANY_ID, PCI_ANY_ID, },
2421         { PCI_VENDOR_ID_INTEL, 0x5201, PCI_ANY_ID, PCI_ANY_ID, },
2422         { 0,}
2423 };
2424 MODULE_DEVICE_TABLE(pci, eepro100_pci_tbl);
2425         
2426 static struct pci_driver eepro100_driver = {
2427         .name           = "eepro100",
2428         .id_table       = eepro100_pci_tbl,
2429         .probe          = eepro100_init_one,
2430         .remove         = __devexit_p(eepro100_remove_one),
2431 #ifdef CONFIG_PM
2432         .suspend        = eepro100_suspend,
2433         .resume         = eepro100_resume,
2434 #endif /* CONFIG_PM */
2435 };
2436
2437 static int __init eepro100_init_module(void)
2438 {
2439 #ifdef MODULE
2440         printk(version);
2441 #endif
2442         return pci_module_init(&eepro100_driver);
2443 }
2444
2445 static void __exit eepro100_cleanup_module(void)
2446 {
2447         pci_unregister_driver(&eepro100_driver);
2448 }
2449
2450 module_init(eepro100_init_module);
2451 module_exit(eepro100_cleanup_module);
2452 \f
2453 /*
2454  * Local variables:
2455  *  compile-command: "gcc -DMODULE -D__KERNEL__ -I/usr/src/linux/net/inet -Wall -Wstrict-prototypes -O6 -c eepro100.c `[ -f /usr/include/linux/modversions.h ] && echo -DMODVERSIONS`"
2456  *  c-indent-level: 4
2457  *  c-basic-offset: 4
2458  *  tab-width: 4
2459  * End:
2460  */