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