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