File: /usr/src/linux/drivers/net/sundance.c

1     /* sundance.c: A Linux device driver for the Sundance ST201 "Alta". */
2     /*
3     	Written 1999-2000 by Donald Becker.
4     
5     	This software may be used and distributed according to the terms of
6     	the GNU General Public License (GPL), incorporated herein by reference.
7     	Drivers based on or derived from this code fall under the GPL and must
8     	retain the authorship, copyright and license notice.  This file is not
9     	a complete program and may only be used when the entire operating
10     	system is licensed under the GPL.
11     
12     	The author may be reached as becker@scyld.com, or C/O
13     	Scyld Computing Corporation
14     	410 Severn Ave., Suite 210
15     	Annapolis MD 21403
16     
17     	Support and updates available at
18     	http://www.scyld.com/network/sundance.html
19     */
20     
21     #define DRV_NAME	"sundance"
22     #define DRV_VERSION	"1.01"
23     #define DRV_RELDATE	"4/09/00"
24     
25     
26     /* The user-configurable values.
27        These may be modified when a driver module is loaded.*/
28     
29     static int debug = 1;			/* 1 normal messages, 0 quiet .. 7 verbose. */
30     /* Maximum events (Rx packets, etc.) to handle at each interrupt. */
31     static int max_interrupt_work = 20;
32     static int mtu;
33     /* Maximum number of multicast addresses to filter (vs. rx-all-multicast).
34        Typical is a 64 element hash table based on the Ethernet CRC.  */
35     static int multicast_filter_limit = 32;
36     
37     /* Set the copy breakpoint for the copy-only-tiny-frames scheme.
38        Setting to > 1518 effectively disables this feature.
39        This chip can receive into offset buffers, so the Alpha does not
40        need a copy-align. */
41     static int rx_copybreak;
42     
43     /* Used to pass the media type, etc.
44        Both 'options[]' and 'full_duplex[]' should exist for driver
45        interoperability.
46        The media type is usually passed in 'options[]'.
47     */
48     #define MAX_UNITS 8		/* More are supported, limit only on options */
49     static int options[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
50     static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
51     
52     /* Operational parameters that are set at compile time. */
53     
54     /* Keep the ring sizes a power of two for compile efficiency.
55        The compiler will convert <unsigned>'%'<2^N> into a bit mask.
56        Making the Tx ring too large decreases the effectiveness of channel
57        bonding and packet priority, and more than 128 requires modifying the
58        Tx error recovery.
59        Large receive rings merely waste memory. */
60     #define TX_RING_SIZE	16
61     #define TX_QUEUE_LEN	10		/* Limit ring entries actually used.  */
62     #define RX_RING_SIZE	32
63     #define TX_TOTAL_SIZE	TX_RING_SIZE*sizeof(struct netdev_desc)
64     #define RX_TOTAL_SIZE	RX_RING_SIZE*sizeof(struct netdev_desc)
65     
66     /* Operational parameters that usually are not changed. */
67     /* Time in jiffies before concluding the transmitter is hung. */
68     #define TX_TIMEOUT  (2*HZ)
69     
70     #define PKT_BUF_SZ		1536			/* Size of each temporary Rx buffer.*/
71     
72     #ifndef __KERNEL__
73     #define __KERNEL__
74     #endif
75     #if !defined(__OPTIMIZE__)
76     #warning  You must compile this file with the correct options!
77     #warning  See the last lines of the source file.
78     #error You must compile this driver with "-O".
79     #endif
80     
81     /* Include files, designed to support most kernel versions 2.0.0 and later. */
82     #include <linux/module.h>
83     #include <linux/kernel.h>
84     #include <linux/string.h>
85     #include <linux/timer.h>
86     #include <linux/errno.h>
87     #include <linux/ioport.h>
88     #include <linux/slab.h>
89     #include <linux/interrupt.h>
90     #include <linux/pci.h>
91     #include <linux/netdevice.h>
92     #include <linux/etherdevice.h>
93     #include <linux/skbuff.h>
94     #include <linux/init.h>
95     #include <linux/ethtool.h>
96     #include <linux/mii.h>
97     #include <asm/uaccess.h>
98     #include <asm/processor.h>		/* Processor type for cache alignment. */
99     #include <asm/bitops.h>
100     #include <asm/io.h>
101     
102     #include <linux/spinlock.h>
103     
104     /* These identify the driver base version and may not be removed. */
105     static char version[] __devinitdata =
106     KERN_INFO DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE "  Written by Donald Becker\n"
107     KERN_INFO "  http://www.scyld.com/network/sundance.html\n";
108     
109     MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
110     MODULE_DESCRIPTION("Sundance Alta Ethernet driver");
111     MODULE_PARM(max_interrupt_work, "i");
112     MODULE_PARM(mtu, "i");
113     MODULE_PARM(debug, "i");
114     MODULE_PARM(rx_copybreak, "i");
115     MODULE_PARM(options, "1-" __MODULE_STRING(MAX_UNITS) "i");
116     MODULE_PARM(full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
117     MODULE_PARM_DESC(max_interrupt_work, "Sundance Alta maximum events handled per interrupt");
118     MODULE_PARM_DESC(mtu, "Sundance Alta MTU (all boards)");
119     MODULE_PARM_DESC(debug, "Sundance Alta debug level (0-5)");
120     MODULE_PARM_DESC(rx_copybreak, "Sundance Alta copy breakpoint for copy-only-tiny-frames");
121     MODULE_PARM_DESC(options, "Sundance Alta: Bits 0-3: media type, bit 17: full duplex");
122     MODULE_PARM_DESC(full_duplex, "Sundance Alta full duplex setting(s) (1)");
123     
124     /*
125     				Theory of Operation
126     
127     I. Board Compatibility
128     
129     This driver is designed for the Sundance Technologies "Alta" ST201 chip.
130     
131     II. Board-specific settings
132     
133     III. Driver operation
134     
135     IIIa. Ring buffers
136     
137     This driver uses two statically allocated fixed-size descriptor lists
138     formed into rings by a branch from the final descriptor to the beginning of
139     the list.  The ring sizes are set at compile time by RX/TX_RING_SIZE.
140     Some chips explicitly use only 2^N sized rings, while others use a
141     'next descriptor' pointer that the driver forms into rings.
142     
143     IIIb/c. Transmit/Receive Structure
144     
145     This driver uses a zero-copy receive and transmit scheme.
146     The driver allocates full frame size skbuffs for the Rx ring buffers at
147     open() time and passes the skb->data field to the chip as receive data
148     buffers.  When an incoming frame is less than RX_COPYBREAK bytes long,
149     a fresh skbuff is allocated and the frame is copied to the new skbuff.
150     When the incoming frame is larger, the skbuff is passed directly up the
151     protocol stack.  Buffers consumed this way are replaced by newly allocated
152     skbuffs in a later phase of receives.
153     
154     The RX_COPYBREAK value is chosen to trade-off the memory wasted by
155     using a full-sized skbuff for small frames vs. the copying costs of larger
156     frames.  New boards are typically used in generously configured machines
157     and the underfilled buffers have negligible impact compared to the benefit of
158     a single allocation size, so the default value of zero results in never
159     copying packets.  When copying is done, the cost is usually mitigated by using
160     a combined copy/checksum routine.  Copying also preloads the cache, which is
161     most useful with small frames.
162     
163     A subtle aspect of the operation is that the IP header at offset 14 in an
164     ethernet frame isn't longword aligned for further processing.
165     Unaligned buffers are permitted by the Sundance hardware, so
166     frames are received into the skbuff at an offset of "+2", 16-byte aligning
167     the IP header.
168     
169     IIId. Synchronization
170     
171     The driver runs as two independent, single-threaded flows of control.  One
172     is the send-packet routine, which enforces single-threaded use by the
173     dev->tbusy flag.  The other thread is the interrupt handler, which is single
174     threaded by the hardware and interrupt handling software.
175     
176     The send packet thread has partial control over the Tx ring and 'dev->tbusy'
177     flag.  It sets the tbusy flag whenever it's queuing a Tx packet. If the next
178     queue slot is empty, it clears the tbusy flag when finished otherwise it sets
179     the 'lp->tx_full' flag.
180     
181     The interrupt handler has exclusive control over the Rx ring and records stats
182     from the Tx ring.  After reaping the stats, it marks the Tx queue entry as
183     empty by incrementing the dirty_tx mark. Iff the 'lp->tx_full' flag is set, it
184     clears both the tx_full and tbusy flags.
185     
186     IV. Notes
187     
188     IVb. References
189     
190     The Sundance ST201 datasheet, preliminary version.
191     http://cesdis.gsfc.nasa.gov/linux/misc/100mbps.html
192     http://cesdis.gsfc.nasa.gov/linux/misc/NWay.html
193     
194     IVc. Errata
195     
196     */
197     
198     
199     
200     enum pci_id_flags_bits {
201             /* Set PCI command register bits before calling probe1(). */
202             PCI_USES_IO=1, PCI_USES_MEM=2, PCI_USES_MASTER=4,
203             /* Read and map the single following PCI BAR. */
204             PCI_ADDR0=0<<4, PCI_ADDR1=1<<4, PCI_ADDR2=2<<4, PCI_ADDR3=3<<4,
205             PCI_ADDR_64BITS=0x100, PCI_NO_ACPI_WAKE=0x200, PCI_NO_MIN_LATENCY=0x400,
206     };
207     enum chip_capability_flags {CanHaveMII=1, };
208     #ifdef USE_IO_OPS
209     #define PCI_IOTYPE (PCI_USES_MASTER | PCI_USES_IO  | PCI_ADDR0)
210     #else
211     #define PCI_IOTYPE (PCI_USES_MASTER | PCI_USES_MEM | PCI_ADDR1)
212     #endif
213     
214     static struct pci_device_id sundance_pci_tbl[] __devinitdata = {
215     	{ 0x1186, 0x1002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
216     	{ 0x13F0, 0x0201, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 1 },
217     	{ 0, }
218     };
219     MODULE_DEVICE_TABLE(pci, sundance_pci_tbl);
220     
221     struct pci_id_info {
222             const char *name;
223             struct match_info {
224                     int     pci, pci_mask, subsystem, subsystem_mask;
225                     int revision, revision_mask;                            /* Only 8 bits. */
226             } id;
227             enum pci_id_flags_bits pci_flags;
228             int io_size;                            /* Needed for I/O region check or ioremap(). */
229             int drv_flags;                          /* Driver use, intended as capability flags. */
230     };
231     static struct pci_id_info pci_id_tbl[] = {
232     	{"OEM Sundance Technology ST201", {0x10021186, 0xffffffff, },
233     	 PCI_IOTYPE, 128, CanHaveMII},
234     	{"Sundance Technology Alta", {0x020113F0, 0xffffffff, },
235     	 PCI_IOTYPE, 128, CanHaveMII},
236     	{0,},						/* 0 terminated list. */
237     };
238     
239     /* This driver was written to use PCI memory space, however x86-oriented
240        hardware often uses I/O space accesses. */
241     #ifdef USE_IO_OPS
242     #undef readb
243     #undef readw
244     #undef readl
245     #undef writeb
246     #undef writew
247     #undef writel
248     #define readb inb
249     #define readw inw
250     #define readl inl
251     #define writeb outb
252     #define writew outw
253     #define writel outl
254     #endif
255     
256     /* Offsets to the device registers.
257        Unlike software-only systems, device drivers interact with complex hardware.
258        It's not useful to define symbolic names for every register bit in the
259        device.  The name can only partially document the semantics and make
260        the driver longer and more difficult to read.
261        In general, only the important configuration values or bits changed
262        multiple times should be defined symbolically.
263     */
264     enum alta_offsets {
265     	DMACtrl = 0x00,
266     	TxListPtr = 0x04,
267     	TxDMACtrl = 0x08,
268     	TxDescPoll = 0x0a,
269     	RxDMAStatus = 0x0c,
270     	RxListPtr = 0x10,
271     	RxDMACtrl = 0x14,
272     	RxDescPoll = 0x16,
273     	LEDCtrl = 0x1a,
274     	ASICCtrl = 0x30,
275     	EEData = 0x34,
276     	EECtrl = 0x36,
277     	TxThreshold = 0x3c,
278     	FlashAddr = 0x40,
279     	FlashData = 0x44,
280     	TxStatus = 0x46,
281     	DownCounter = 0x18,
282     	IntrClear = 0x4a,
283     	IntrEnable = 0x4c,
284     	IntrStatus = 0x4e,
285     	MACCtrl0 = 0x50,
286     	MACCtrl1 = 0x52,
287     	StationAddr = 0x54,
288     	MaxTxSize = 0x5A,
289     	RxMode = 0x5c,
290     	MIICtrl = 0x5e,
291     	MulticastFilter0 = 0x60,
292     	MulticastFilter1 = 0x64,
293     	RxOctetsLow = 0x68,
294     	RxOctetsHigh = 0x6a,
295     	TxOctetsLow = 0x6c,
296     	TxOctetsHigh = 0x6e,
297     	TxFramesOK = 0x70,
298     	RxFramesOK = 0x72,
299     	StatsCarrierError = 0x74,
300     	StatsLateColl = 0x75,
301     	StatsMultiColl = 0x76,
302     	StatsOneColl = 0x77,
303     	StatsTxDefer = 0x78,
304     	RxMissed = 0x79,
305     	StatsTxXSDefer = 0x7a,
306     	StatsTxAbort = 0x7b,
307     	StatsBcastTx = 0x7c,
308     	StatsBcastRx = 0x7d,
309     	StatsMcastTx = 0x7e,
310     	StatsMcastRx = 0x7f,
311     	/* Aliased and bogus values! */
312     	RxStatus = 0x0c,
313     };
314     
315     /* Bits in the interrupt status/mask registers. */
316     enum intr_status_bits {
317     	IntrSummary=0x0001, IntrPCIErr=0x0002, IntrMACCtrl=0x0008,
318     	IntrTxDone=0x0004, IntrRxDone=0x0010, IntrRxStart=0x0020,
319     	IntrDrvRqst=0x0040,
320     	StatsMax=0x0080, LinkChange=0x0100,
321     	IntrTxDMADone=0x0200, IntrRxDMADone=0x0400,
322     };
323     
324     /* Bits in the RxMode register. */
325     enum rx_mode_bits {
326     	AcceptAllIPMulti=0x20, AcceptMultiHash=0x10, AcceptAll=0x08,
327     	AcceptBroadcast=0x04, AcceptMulticast=0x02, AcceptMyPhys=0x01,
328     };
329     /* Bits in MACCtrl. */
330     enum mac_ctrl0_bits {
331     	EnbFullDuplex=0x20, EnbRcvLargeFrame=0x40,
332     	EnbFlowCtrl=0x100, EnbPassRxCRC=0x200,
333     };
334     enum mac_ctrl1_bits {
335     	StatsEnable=0x0020,	StatsDisable=0x0040, StatsEnabled=0x0080,
336     	TxEnable=0x0100, TxDisable=0x0200, TxEnabled=0x0400,
337     	RxEnable=0x0800, RxDisable=0x1000, RxEnabled=0x2000,
338     };
339     
340     /* The Rx and Tx buffer descriptors. */
341     /* Note that using only 32 bit fields simplifies conversion to big-endian
342        architectures. */
343     struct netdev_desc {
344     	u32 next_desc;
345     	u32 status;
346     	struct desc_frag { u32 addr, length; } frag[1];
347     };
348     
349     /* Bits in netdev_desc.status */
350     enum desc_status_bits {
351     	DescOwn=0x8000,
352     	DescEndPacket=0x4000,
353     	DescEndRing=0x2000,
354     	LastFrag=0x80000000,
355     	DescIntrOnTx=0x8000,
356     	DescIntrOnDMADone=0x80000000,
357     	DisableAlign = 0x00000001,
358     };
359     
360     #define PRIV_ALIGN	15 	/* Required alignment mask */
361     /* Use  __attribute__((aligned (L1_CACHE_BYTES)))  to maintain alignment
362        within the structure. */
363     #define MII_CNT		4
364     struct netdev_private {
365     	/* Descriptor rings first for alignment. */
366     	struct netdev_desc *rx_ring;
367     	struct netdev_desc *tx_ring;
368     	struct sk_buff* rx_skbuff[RX_RING_SIZE];
369     	struct sk_buff* tx_skbuff[TX_RING_SIZE];
370             dma_addr_t tx_ring_dma;
371             dma_addr_t rx_ring_dma;
372     	struct net_device_stats stats;
373     	struct timer_list timer;	/* Media monitoring timer. */
374     	/* Frequently used values: keep some adjacent for cache effect. */
375     	spinlock_t lock;
376     	int chip_id, drv_flags;
377     	unsigned int cur_rx, dirty_rx;		/* Producer/consumer ring indices */
378     	unsigned int rx_buf_sz;				/* Based on MTU+slack. */
379     	spinlock_t txlock;					/* Group with Tx control cache line. */
380     	struct netdev_desc *last_tx;		/* Last Tx descriptor used. */
381     	unsigned int cur_tx, dirty_tx;
382     	unsigned int tx_full:1;				/* The Tx queue is full. */
383     	/* These values are keep track of the transceiver/media in use. */
384     	unsigned int full_duplex:1;			/* Full-duplex operation requested. */
385     	unsigned int duplex_lock:1;
386     	unsigned int medialock:1;			/* Do not sense media. */
387     	unsigned int default_port:4;		/* Last dev->if_port value. */
388     	/* Multicast and receive mode. */
389     	spinlock_t mcastlock;				/* SMP lock multicast updates. */
390     	u16 mcast_filter[4];
391     	/* MII transceiver section. */
392     	int mii_cnt;						/* MII device addresses. */
393     	u16 advertising;					/* NWay media advertisement */
394     	unsigned char phys[MII_CNT];		/* MII device addresses, only first one used. */
395     	struct pci_dev *pci_dev;
396     };
397     
398     /* The station address location in the EEPROM. */
399     #define EEPROM_SA_OFFSET	0x10
400     
401     static int  eeprom_read(long ioaddr, int location);
402     static int  mdio_read(struct net_device *dev, int phy_id, int location);
403     static void mdio_write(struct net_device *dev, int phy_id, int location, int value);
404     static int  netdev_open(struct net_device *dev);
405     static void check_duplex(struct net_device *dev);
406     static void netdev_timer(unsigned long data);
407     static void tx_timeout(struct net_device *dev);
408     static void init_ring(struct net_device *dev);
409     static int  start_tx(struct sk_buff *skb, struct net_device *dev);
410     static void intr_handler(int irq, void *dev_instance, struct pt_regs *regs);
411     static void netdev_error(struct net_device *dev, int intr_status);
412     static int  netdev_rx(struct net_device *dev);
413     static void netdev_error(struct net_device *dev, int intr_status);
414     static void set_rx_mode(struct net_device *dev);
415     static struct net_device_stats *get_stats(struct net_device *dev);
416     static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
417     static int  netdev_close(struct net_device *dev);
418     
419     
420     
421     static int __devinit sundance_probe1 (struct pci_dev *pdev,
422     				      const struct pci_device_id *ent)
423     {
424     	struct net_device *dev;
425     	struct netdev_private *np;
426     	static int card_idx;
427     	int chip_idx = ent->driver_data;
428     	int irq;
429     	int i, option = card_idx < MAX_UNITS ? options[card_idx] : 0;
430     	long ioaddr;
431     	void *ring_space;
432     	dma_addr_t ring_dma;
433     
434     
435     /* when built into the kernel, we only print version if device is found */
436     #ifndef MODULE
437     	static int printed_version;
438     	if (!printed_version++)
439     		printk(version);
440     #endif
441     
442     	if (pci_enable_device(pdev))
443     		return -EIO;
444     	pci_set_master(pdev);
445     
446     	irq = pdev->irq;
447     
448     	dev = alloc_etherdev(sizeof(*np));
449     	if (!dev)
450     		return -ENOMEM;
451     	SET_MODULE_OWNER(dev);
452     
453     	if (pci_request_regions(pdev, DRV_NAME))
454     		goto err_out_netdev;
455     
456     #ifdef USE_IO_OPS
457     	ioaddr = pci_resource_start(pdev, 0);
458     #else
459     	ioaddr = pci_resource_start(pdev, 1);
460     	ioaddr = (long) ioremap (ioaddr, pci_id_tbl[chip_idx].io_size);
461     	if (!ioaddr)
462     		goto err_out_res;
463     #endif
464     
465     	for (i = 0; i < 3; i++)
466     		((u16 *)dev->dev_addr)[i] =
467     			le16_to_cpu(eeprom_read(ioaddr, i + EEPROM_SA_OFFSET));
468     
469     	dev->base_addr = ioaddr;
470     	dev->irq = irq;
471     
472     	np = dev->priv;
473     	np->chip_id = chip_idx;
474     	np->drv_flags = pci_id_tbl[chip_idx].drv_flags;
475     	np->pci_dev = pdev;
476     	spin_lock_init(&np->lock);
477     
478     	ring_space = pci_alloc_consistent(pdev, TX_TOTAL_SIZE, &ring_dma);
479     	if (!ring_space)
480     		goto err_out_cleardev;
481     	np->tx_ring = (struct netdev_desc *)ring_space;
482     	np->tx_ring_dma = ring_dma;
483     
484     	ring_space = pci_alloc_consistent(pdev, RX_TOTAL_SIZE, &ring_dma);
485     	if (!ring_space)
486     		goto err_out_unmap_tx;
487     	np->rx_ring = (struct netdev_desc *)ring_space;
488     	np->rx_ring_dma = ring_dma;
489     
490     	if (dev->mem_start)
491     		option = dev->mem_start;
492     
493     	/* The lower four bits are the media type. */
494     	if (option > 0) {
495     		if (option & 0x200)
496     			np->full_duplex = 1;
497     		np->default_port = option & 15;
498     		if (np->default_port)
499     			np->medialock = 1;
500     	}
501     	if (card_idx < MAX_UNITS  &&  full_duplex[card_idx] > 0)
502     		np->full_duplex = 1;
503     
504     	if (np->full_duplex)
505     		np->duplex_lock = 1;
506     
507     	/* The chip-specific entries in the device structure. */
508     	dev->open = &netdev_open;
509     	dev->hard_start_xmit = &start_tx;
510     	dev->stop = &netdev_close;
511     	dev->get_stats = &get_stats;
512     	dev->set_multicast_list = &set_rx_mode;
513     	dev->do_ioctl = &netdev_ioctl;
514     	dev->tx_timeout = &tx_timeout;
515     	dev->watchdog_timeo = TX_TIMEOUT;
516     	pci_set_drvdata(pdev, dev);
517     
518     	if (mtu)
519     		dev->mtu = mtu;
520     
521     	i = register_netdev(dev);
522     	if (i)
523     		goto err_out_unmap_rx;
524     
525     	printk(KERN_INFO "%s: %s at 0x%lx, ",
526     		   dev->name, pci_id_tbl[chip_idx].name, ioaddr);
527     	for (i = 0; i < 5; i++)
528     			printk("%2.2x:", dev->dev_addr[i]);
529     	printk("%2.2x, IRQ %d.\n", dev->dev_addr[i], irq);
530     
531     	if (1) {
532     		int phy, phy_idx = 0;
533     		np->phys[0] = 1;		/* Default setting */
534     		for (phy = 0; phy < 32 && phy_idx < MII_CNT; phy++) {
535     			int mii_status = mdio_read(dev, phy, 1);
536     			if (mii_status != 0xffff  &&  mii_status != 0x0000) {
537     				np->phys[phy_idx++] = phy;
538     				np->advertising = mdio_read(dev, phy, 4);
539     				printk(KERN_INFO "%s: MII PHY found at address %d, status "
540     					   "0x%4.4x advertising %4.4x.\n",
541     					   dev->name, phy, mii_status, np->advertising);
542     			}
543     		}
544     		np->mii_cnt = phy_idx;
545     		if (phy_idx == 0)
546     			printk(KERN_INFO "%s: No MII transceiver found!, ASIC status %x\n",
547     				   dev->name, readl(ioaddr + ASICCtrl));
548     	}
549     
550     	/* Perhaps move the reset here? */
551     	/* Reset the chip to erase previous misconfiguration. */
552     	if (debug > 1)
553     		printk("ASIC Control is %x.\n", readl(ioaddr + ASICCtrl));
554     	writew(0x007f, ioaddr + ASICCtrl + 2);
555     	if (debug > 1)
556     		printk("ASIC Control is now %x.\n", readl(ioaddr + ASICCtrl));
557     
558     	card_idx++;
559     	return 0;
560     
561     err_out_unmap_rx:
562             pci_free_consistent(pdev, RX_TOTAL_SIZE, np->rx_ring, np->rx_ring_dma);
563     err_out_unmap_tx:
564             pci_free_consistent(pdev, TX_TOTAL_SIZE, np->tx_ring, np->tx_ring_dma);
565     err_out_cleardev:
566     	pci_set_drvdata(pdev, NULL);
567     #ifndef USE_IO_OPS
568     	iounmap((void *)ioaddr);
569     err_out_res:
570     #endif
571     	pci_release_regions(pdev);
572     err_out_netdev:
573     	kfree (dev);
574     	return -ENODEV;
575     }
576     
577     
578     /* Read the EEPROM and MII Management Data I/O (MDIO) interfaces. */
579     static int eeprom_read(long ioaddr, int location)
580     {
581     	int boguscnt = 1000;		/* Typical 190 ticks. */
582     	writew(0x0200 | (location & 0xff), ioaddr + EECtrl);
583     	do {
584     		if (! (readw(ioaddr + EECtrl) & 0x8000)) {
585     			return readw(ioaddr + EEData);
586     		}
587     	} while (--boguscnt > 0);
588     	return 0;
589     }
590     
591     /*  MII transceiver control section.
592     	Read and write the MII registers using software-generated serial
593     	MDIO protocol.  See the MII specifications or DP83840A data sheet
594     	for details.
595     
596     	The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
597     	met by back-to-back 33Mhz PCI cycles. */
598     #define mdio_delay() readb(mdio_addr)
599     
600     /* Set iff a MII transceiver on any interface requires mdio preamble.
601        This only set with older tranceivers, so the extra
602        code size of a per-interface flag is not worthwhile. */
603     static const char mii_preamble_required = 1;
604     
605     enum mii_reg_bits {
606     	MDIO_ShiftClk=0x0001, MDIO_Data=0x0002, MDIO_EnbOutput=0x0004,
607     };
608     #define MDIO_EnbIn  (0)
609     #define MDIO_WRITE0 (MDIO_EnbOutput)
610     #define MDIO_WRITE1 (MDIO_Data | MDIO_EnbOutput)
611     
612     /* Generate the preamble required for initial synchronization and
613        a few older transceivers. */
614     static void mdio_sync(long mdio_addr)
615     {
616     	int bits = 32;
617     
618     	/* Establish sync by sending at least 32 logic ones. */
619     	while (--bits >= 0) {
620     		writeb(MDIO_WRITE1, mdio_addr);
621     		mdio_delay();
622     		writeb(MDIO_WRITE1 | MDIO_ShiftClk, mdio_addr);
623     		mdio_delay();
624     	}
625     }
626     
627     static int mdio_read(struct net_device *dev, int phy_id, int location)
628     {
629     	long mdio_addr = dev->base_addr + MIICtrl;
630     	int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
631     	int i, retval = 0;
632     
633     	if (mii_preamble_required)
634     		mdio_sync(mdio_addr);
635     
636     	/* Shift the read command bits out. */
637     	for (i = 15; i >= 0; i--) {
638     		int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
639     
640     		writeb(dataval, mdio_addr);
641     		mdio_delay();
642     		writeb(dataval | MDIO_ShiftClk, mdio_addr);
643     		mdio_delay();
644     	}
645     	/* Read the two transition, 16 data, and wire-idle bits. */
646     	for (i = 19; i > 0; i--) {
647     		writeb(MDIO_EnbIn, mdio_addr);
648     		mdio_delay();
649     		retval = (retval << 1) | ((readb(mdio_addr) & MDIO_Data) ? 1 : 0);
650     		writeb(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
651     		mdio_delay();
652     	}
653     	return (retval>>1) & 0xffff;
654     }
655     
656     static void mdio_write(struct net_device *dev, int phy_id, int location, int value)
657     {
658     	long mdio_addr = dev->base_addr + MIICtrl;
659     	int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location<<18) | value;
660     	int i;
661     
662     	if (mii_preamble_required)
663     		mdio_sync(mdio_addr);
664     
665     	/* Shift the command bits out. */
666     	for (i = 31; i >= 0; i--) {
667     		int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
668     
669     		writeb(dataval, mdio_addr);
670     		mdio_delay();
671     		writeb(dataval | MDIO_ShiftClk, mdio_addr);
672     		mdio_delay();
673     	}
674     	/* Clear out extra bits. */
675     	for (i = 2; i > 0; i--) {
676     		writeb(MDIO_EnbIn, mdio_addr);
677     		mdio_delay();
678     		writeb(MDIO_EnbIn | MDIO_ShiftClk, mdio_addr);
679     		mdio_delay();
680     	}
681     	return;
682     }
683     
684     
685     static int netdev_open(struct net_device *dev)
686     {
687     	struct netdev_private *np = dev->priv;
688     	long ioaddr = dev->base_addr;
689     	int i;
690     
691     	/* Do we need to reset the chip??? */
692     
693     	i = request_irq(dev->irq, &intr_handler, SA_SHIRQ, dev->name, dev);
694     	if (i)
695     		return i;
696     
697     	if (debug > 1)
698     		printk(KERN_DEBUG "%s: netdev_open() irq %d.\n",
699     			   dev->name, dev->irq);
700     
701     	init_ring(dev);
702     
703     	writel(np->rx_ring_dma, ioaddr + RxListPtr);
704     	/* The Tx list pointer is written as packets are queued. */
705     
706     	for (i = 0; i < 6; i++)
707     		writeb(dev->dev_addr[i], ioaddr + StationAddr + i);
708     
709     	/* Initialize other registers. */
710     	/* Configure the PCI bus bursts and FIFO thresholds. */
711     
712     	if (dev->if_port == 0)
713     		dev->if_port = np->default_port;
714     
715     	np->full_duplex = np->duplex_lock;
716     	np->mcastlock = (spinlock_t) SPIN_LOCK_UNLOCKED;
717     
718     	set_rx_mode(dev);
719     	writew(0, ioaddr + IntrEnable);
720     	writew(0, ioaddr + DownCounter);
721     	/* Set the chip to poll every N*320nsec. */
722     	writeb(100, ioaddr + RxDescPoll);
723     	writeb(127, ioaddr + TxDescPoll);
724     	netif_start_queue(dev);
725     
726     	/* Enable interrupts by setting the interrupt mask. */
727     	writew(IntrRxDone | IntrRxDMADone | IntrPCIErr | IntrDrvRqst | IntrTxDone
728     		   | StatsMax | LinkChange, ioaddr + IntrEnable);
729     
730     	writew(StatsEnable | RxEnable | TxEnable, ioaddr + MACCtrl1);
731     
732     	if (debug > 2)
733     		printk(KERN_DEBUG "%s: Done netdev_open(), status: Rx %x Tx %x "
734     			   "MAC Control %x, %4.4x %4.4x.\n",
735     			   dev->name, readl(ioaddr + RxStatus), readb(ioaddr + TxStatus),
736     			   readl(ioaddr + MACCtrl0),
737     			   readw(ioaddr + MACCtrl1), readw(ioaddr + MACCtrl0));
738     
739     	/* Set the timer to check for link beat. */
740     	init_timer(&np->timer);
741     	np->timer.expires = jiffies + 3*HZ;
742     	np->timer.data = (unsigned long)dev;
743     	np->timer.function = &netdev_timer;				/* timer handler */
744     	add_timer(&np->timer);
745     
746     	return 0;
747     }
748     
749     static void check_duplex(struct net_device *dev)
750     {
751     	struct netdev_private *np = dev->priv;
752     	long ioaddr = dev->base_addr;
753     	int mii_reg5 = mdio_read(dev, np->phys[0], 5);
754     	int negotiated = mii_reg5 & np->advertising;
755     	int duplex;
756     
757     	if (np->duplex_lock  ||  mii_reg5 == 0xffff)
758     		return;
759     	duplex = (negotiated & 0x0100) || (negotiated & 0x01C0) == 0x0040;
760     	if (np->full_duplex != duplex) {
761     		np->full_duplex = duplex;
762     		if (debug)
763     			printk(KERN_INFO "%s: Setting %s-duplex based on MII #%d "
764     				   "negotiated capability %4.4x.\n", dev->name,
765     				   duplex ? "full" : "half", np->phys[0], negotiated);
766     		writew(duplex ? 0x20 : 0, ioaddr + MACCtrl0);
767     	}
768     }
769     
770     static void netdev_timer(unsigned long data)
771     {
772     	struct net_device *dev = (struct net_device *)data;
773     	struct netdev_private *np = dev->priv;
774     	long ioaddr = dev->base_addr;
775     	int next_tick = 10*HZ;
776     
777     	if (debug > 3) {
778     		printk(KERN_DEBUG "%s: Media selection timer tick, intr status %4.4x, "
779     			   "Tx %x Rx %x.\n",
780     			   dev->name, readw(ioaddr + IntrEnable),
781     			   readb(ioaddr + TxStatus), readl(ioaddr + RxStatus));
782     	}
783     	check_duplex(dev);
784     	np->timer.expires = jiffies + next_tick;
785     	add_timer(&np->timer);
786     }
787     
788     static void tx_timeout(struct net_device *dev)
789     {
790     	struct netdev_private *np = dev->priv;
791     	long ioaddr = dev->base_addr;
792     
793     	printk(KERN_WARNING "%s: Transmit timed out, status %2.2x,"
794     		   " resetting...\n", dev->name, readb(ioaddr + TxStatus));
795     
796     	{
797     		int i;
798     		printk(KERN_DEBUG "  Rx ring %p: ", np->rx_ring);
799     		for (i = 0; i < RX_RING_SIZE; i++)
800     			printk(" %8.8x", (unsigned int)np->rx_ring[i].status);
801     		printk("\n"KERN_DEBUG"  Tx ring %p: ", np->tx_ring);
802     		for (i = 0; i < TX_RING_SIZE; i++)
803     			printk(" %4.4x", np->tx_ring[i].status);
804     		printk("\n");
805     	}
806     
807     	/* Perhaps we should reinitialize the hardware here. */
808     	dev->if_port = 0;
809     	/* Stop and restart the chip's Tx processes . */
810     
811     	/* Trigger an immediate transmit demand. */
812     	writew(IntrRxDone | IntrRxDMADone | IntrPCIErr | IntrDrvRqst | IntrTxDone
813     		   | StatsMax | LinkChange, ioaddr + IntrEnable);
814     
815     	dev->trans_start = jiffies;
816     	np->stats.tx_errors++;
817     
818     	if (!np->tx_full)
819     		netif_wake_queue(dev);
820     }
821     
822     
823     /* Initialize the Rx and Tx rings, along with various 'dev' bits. */
824     static void init_ring(struct net_device *dev)
825     {
826     	struct netdev_private *np = dev->priv;
827     	int i;
828     
829     	np->tx_full = 0;
830     	np->cur_rx = np->cur_tx = 0;
831     	np->dirty_rx = np->dirty_tx = 0;
832     
833     	np->rx_buf_sz = (dev->mtu <= 1500 ? PKT_BUF_SZ : dev->mtu + 32);
834     
835     	/* Initialize all Rx descriptors. */
836     	for (i = 0; i < RX_RING_SIZE; i++) {
837     		np->rx_ring[i].next_desc = cpu_to_le32(np->rx_ring_dma + 
838     			((i+1)%RX_RING_SIZE)*sizeof(*np->rx_ring));
839     		np->rx_ring[i].status = 0;
840     		np->rx_ring[i].frag[0].length = 0;
841     		np->rx_skbuff[i] = 0;
842     	}
843     
844     	/* Fill in the Rx buffers.  Handle allocation failure gracefully. */
845     	for (i = 0; i < RX_RING_SIZE; i++) {
846     		struct sk_buff *skb = dev_alloc_skb(np->rx_buf_sz);
847     		np->rx_skbuff[i] = skb;
848     		if (skb == NULL)
849     			break;
850     		skb->dev = dev;		/* Mark as being used by this device. */
851     		skb_reserve(skb, 2);	/* 16 byte align the IP header. */
852     		np->rx_ring[i].frag[0].addr = cpu_to_le32(
853     			pci_map_single(np->pci_dev, skb->tail, np->rx_buf_sz, 
854     				PCI_DMA_FROMDEVICE));
855     		np->rx_ring[i].frag[0].length = cpu_to_le32(np->rx_buf_sz | LastFrag);
856     	}
857     	np->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
858     
859     	for (i = 0; i < TX_RING_SIZE; i++) {
860     		np->tx_skbuff[i] = 0;
861     		np->tx_ring[i].status = 0;
862     	}
863     	return;
864     }
865     
866     static int start_tx(struct sk_buff *skb, struct net_device *dev)
867     {
868     	struct netdev_private *np = dev->priv;
869     	struct netdev_desc *txdesc;
870     	unsigned entry;
871     
872     	/* Note: Ordering is important here, set the field with the
873     	   "ownership" bit last, and only then increment cur_tx. */
874     
875     	/* Calculate the next Tx descriptor entry. */
876     	entry = np->cur_tx % TX_RING_SIZE;
877     	np->tx_skbuff[entry] = skb;
878     	txdesc = &np->tx_ring[entry];
879     
880     	txdesc->next_desc = 0;
881     	/* Note: disable the interrupt generation here before releasing. */
882     	txdesc->status =
883     		cpu_to_le32((entry<<2) | DescIntrOnDMADone | DescIntrOnTx | DisableAlign);
884     	txdesc->frag[0].addr = cpu_to_le32(pci_map_single(np->pci_dev, 
885     		skb->data, skb->len, PCI_DMA_TODEVICE));
886     	txdesc->frag[0].length = cpu_to_le32(skb->len | LastFrag);
887     	if (np->last_tx)
888     		np->last_tx->next_desc = cpu_to_le32(np->tx_ring_dma +
889     			entry*sizeof(struct netdev_desc));
890     	np->last_tx = txdesc;
891     	np->cur_tx++;
892     
893     	/* On some architectures: explicitly flush cache lines here. */
894     
895     	if (np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 1) {
896     		/* do nothing */
897     	} else {
898     		np->tx_full = 1;
899     		netif_stop_queue(dev);
900     	}
901     	/* Side effect: The read wakes the potentially-idle transmit channel. */
902     	if (readl(dev->base_addr + TxListPtr) == 0)
903     		writel(np->tx_ring_dma + entry*sizeof(*np->tx_ring),
904     			dev->base_addr + TxListPtr);
905     
906     	dev->trans_start = jiffies;
907     
908     	if (debug > 4) {
909     		printk(KERN_DEBUG "%s: Transmit frame #%d queued in slot %d.\n",
910     			   dev->name, np->cur_tx, entry);
911     	}
912     	return 0;
913     }
914     
915     /* The interrupt handler does all of the Rx thread work and cleans up
916        after the Tx thread. */
917     static void intr_handler(int irq, void *dev_instance, struct pt_regs *rgs)
918     {
919     	struct net_device *dev = (struct net_device *)dev_instance;
920     	struct netdev_private *np;
921     	long ioaddr;
922     	int boguscnt = max_interrupt_work;
923     
924     	ioaddr = dev->base_addr;
925     	np = dev->priv;
926     	spin_lock(&np->lock);
927     
928     	do {
929     		int intr_status = readw(ioaddr + IntrStatus);
930     		writew(intr_status & (IntrRxDone | IntrRxDMADone | IntrPCIErr |
931     			IntrDrvRqst | IntrTxDone | IntrTxDMADone | StatsMax | 
932     			LinkChange), ioaddr + IntrStatus);
933     
934     		if (debug > 4)
935     			printk(KERN_DEBUG "%s: Interrupt, status %4.4x.\n",
936     				   dev->name, intr_status);
937     
938     		if (intr_status == 0)
939     			break;
940     
941     		if (intr_status & (IntrRxDone|IntrRxDMADone))
942     			netdev_rx(dev);
943     
944     		if (intr_status & IntrTxDone) {
945     			int boguscnt = 32;
946     			int tx_status = readw(ioaddr + TxStatus);
947     			while (tx_status & 0x80) {
948     				if (debug > 4)
949     					printk("%s: Transmit status is %2.2x.\n",
950     						   dev->name, tx_status);
951     				if (tx_status & 0x1e) {
952     					np->stats.tx_errors++;
953     					if (tx_status & 0x10)  np->stats.tx_fifo_errors++;
954     #ifdef ETHER_STATS
955     					if (tx_status & 0x08)  np->stats.collisions16++;
956     #else
957     					if (tx_status & 0x08)  np->stats.collisions++;
958     #endif
959     					if (tx_status & 0x04)  np->stats.tx_fifo_errors++;
960     					if (tx_status & 0x02)  np->stats.tx_window_errors++;
961     					/* This reset has not been verified!. */
962     					if (tx_status & 0x10) {			/* Reset the Tx. */
963     						writew(0x001c, ioaddr + ASICCtrl + 2);
964     #if 0					/* Do we need to reset the Tx pointer here? */
965     						writel(np->tx_ring_dma
966     							+ np->dirty_tx*sizeof(*np->tx_ring),
967     							dev->base_addr + TxListPtr);
968     #endif
969     					}
970     					if (tx_status & 0x1e) 		/* Restart the Tx. */
971     						writew(TxEnable, ioaddr + MACCtrl1);
972     				}
973     				/* Yup, this is a documentation bug.  It cost me *hours*. */
974     				writew(0, ioaddr + TxStatus);
975     				tx_status = readb(ioaddr + TxStatus);
976     				if (--boguscnt < 0)
977     					break;
978     			}
979     		}
980     		for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
981     			int entry = np->dirty_tx % TX_RING_SIZE;
982     			struct sk_buff *skb;
983     
984     			if ( ! (np->tx_ring[entry].status & 0x00010000))
985     				break;
986     			skb = np->tx_skbuff[entry];
987     			/* Free the original skb. */
988     			pci_unmap_single(np->pci_dev, 
989     				np->tx_ring[entry].frag[0].addr, 
990     				skb->len, PCI_DMA_TODEVICE);
991     			dev_kfree_skb_irq(skb);
992     			np->tx_skbuff[entry] = 0;
993     		}
994     		if (np->tx_full
995     			&& np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
996     			/* The ring is no longer full, clear tbusy. */
997     			np->tx_full = 0;
998     			netif_wake_queue(dev);
999     		}
1000     
1001     		/* Abnormal error summary/uncommon events handlers. */
1002     		if (intr_status & (IntrDrvRqst | IntrPCIErr | LinkChange | StatsMax))
1003     			netdev_error(dev, intr_status);
1004     
1005     		if (--boguscnt < 0) {
1006     			get_stats(dev);
1007     			printk(KERN_WARNING "%s: Too much work at interrupt, "
1008     				   "status=0x%4.4x / 0x%4.4x.\n",
1009     				   dev->name, intr_status, readw(ioaddr + IntrClear));
1010     			/* Re-enable us in 3.2msec. */
1011     			writew(0, ioaddr + IntrEnable);
1012     			writew(1000, ioaddr + DownCounter);
1013     			writew(IntrDrvRqst, ioaddr + IntrEnable);
1014     			break;
1015     		}
1016     	} while (1);
1017     
1018     	if (debug > 3)
1019     		printk(KERN_DEBUG "%s: exiting interrupt, status=%#4.4x.\n",
1020     			   dev->name, readw(ioaddr + IntrStatus));
1021     
1022     	spin_unlock(&np->lock);
1023     }
1024     
1025     /* This routine is logically part of the interrupt handler, but separated
1026        for clarity and better register allocation. */
1027     static int netdev_rx(struct net_device *dev)
1028     {
1029     	struct netdev_private *np = dev->priv;
1030     	int entry = np->cur_rx % RX_RING_SIZE;
1031     	int boguscnt = np->dirty_rx + RX_RING_SIZE - np->cur_rx;
1032     
1033     	if (debug > 4) {
1034     		printk(KERN_DEBUG " In netdev_rx(), entry %d status %4.4x.\n",
1035     			   entry, np->rx_ring[entry].status);
1036     	}
1037     
1038     	/* If EOP is set on the next entry, it's a new packet. Send it up. */
1039     	while (1) {
1040     		struct netdev_desc *desc = &(np->rx_ring[entry]);
1041     		u32 frame_status;
1042     		int pkt_len;
1043     
1044     		if (!(desc->status & DescOwn))
1045     			break;
1046     		frame_status = le32_to_cpu(desc->status);
1047     		pkt_len = frame_status & 0x1fff;	/* Chip omits the CRC. */
1048     		if (debug > 4)
1049     			printk(KERN_DEBUG "  netdev_rx() status was %8.8x.\n",
1050     				   frame_status);
1051     		if (--boguscnt < 0)
1052     			break;
1053     		pci_dma_sync_single(np->pci_dev, desc->frag[0].addr,
1054     			np->rx_buf_sz, PCI_DMA_FROMDEVICE);
1055     		
1056     		if (frame_status & 0x001f4000) {
1057     			/* There was a error. */
1058     			if (debug > 2)
1059     				printk(KERN_DEBUG "  netdev_rx() Rx error was %8.8x.\n",
1060     					   frame_status);
1061     			np->stats.rx_errors++;
1062     			if (frame_status & 0x00100000) np->stats.rx_length_errors++;
1063     			if (frame_status & 0x00010000) np->stats.rx_fifo_errors++;
1064     			if (frame_status & 0x00060000) np->stats.rx_frame_errors++;
1065     			if (frame_status & 0x00080000) np->stats.rx_crc_errors++;
1066     			if (frame_status & 0x00100000) {
1067     				printk(KERN_WARNING "%s: Oversized Ethernet frame,"
1068     					   " status %8.8x.\n",
1069     					   dev->name, frame_status);
1070     			}
1071     		} else {
1072     			struct sk_buff *skb;
1073     
1074     #ifndef final_version
1075     			if (debug > 4)
1076     				printk(KERN_DEBUG "  netdev_rx() normal Rx pkt length %d"
1077     					   ", bogus_cnt %d.\n",
1078     					   pkt_len, boguscnt);
1079     #endif
1080     			/* Check if the packet is long enough to accept without copying
1081     			   to a minimally-sized skbuff. */
1082     			if (pkt_len < rx_copybreak
1083     				&& (skb = dev_alloc_skb(pkt_len + 2)) != NULL) {
1084     				skb->dev = dev;
1085     				skb_reserve(skb, 2);	/* 16 byte align the IP header */
1086     				eth_copy_and_sum(skb, np->rx_skbuff[entry]->tail, pkt_len, 0);
1087     				skb_put(skb, pkt_len);
1088     			} else {
1089     				pci_unmap_single(np->pci_dev, 
1090     					desc->frag[0].addr,
1091     					np->rx_buf_sz, 
1092     					PCI_DMA_FROMDEVICE);
1093     				skb_put(skb = np->rx_skbuff[entry], pkt_len);
1094     				np->rx_skbuff[entry] = NULL;
1095     			}
1096     			skb->protocol = eth_type_trans(skb, dev);
1097     			/* Note: checksum -> skb->ip_summed = CHECKSUM_UNNECESSARY; */
1098     			netif_rx(skb);
1099     			dev->last_rx = jiffies;
1100     		}
1101     		entry = (++np->cur_rx) % RX_RING_SIZE;
1102     	}
1103     
1104     	/* Refill the Rx ring buffers. */
1105     	for (; np->cur_rx - np->dirty_rx > 0; np->dirty_rx++) {
1106     		struct sk_buff *skb;
1107     		entry = np->dirty_rx % RX_RING_SIZE;
1108     		if (np->rx_skbuff[entry] == NULL) {
1109     			skb = dev_alloc_skb(np->rx_buf_sz);
1110     			np->rx_skbuff[entry] = skb;
1111     			if (skb == NULL)
1112     				break;		/* Better luck next round. */
1113     			skb->dev = dev;		/* Mark as being used by this device. */
1114     			skb_reserve(skb, 2);	/* Align IP on 16 byte boundaries */
1115     			np->rx_ring[entry].frag[0].addr = cpu_to_le32(
1116     				pci_map_single(np->pci_dev, skb->tail, 
1117     					np->rx_buf_sz, PCI_DMA_FROMDEVICE));
1118     		}
1119     		/* Perhaps we need not reset this field. */
1120     		np->rx_ring[entry].frag[0].length =
1121     			cpu_to_le32(np->rx_buf_sz | LastFrag);
1122     		np->rx_ring[entry].status = 0;
1123     	}
1124     
1125     	/* No need to restart Rx engine, it will poll. */
1126     	return 0;
1127     }
1128     
1129     static void netdev_error(struct net_device *dev, int intr_status)
1130     {
1131     	long ioaddr = dev->base_addr;
1132     	struct netdev_private *np = dev->priv;
1133     
1134     	if (intr_status & IntrDrvRqst) {
1135     		/* Stop the down counter and turn interrupts back on. */
1136     		printk("%s: Turning interrupts back on.\n", dev->name);
1137     		writew(0, ioaddr + IntrEnable);
1138     		writew(0, ioaddr + DownCounter);
1139     		writew(IntrRxDone | IntrRxDMADone | IntrPCIErr | IntrDrvRqst |
1140     			   IntrTxDone | StatsMax | LinkChange, ioaddr + IntrEnable);
1141     	}
1142     	if (intr_status & LinkChange) {
1143     		printk(KERN_ERR "%s: Link changed: Autonegotiation advertising"
1144     			   " %4.4x  partner %4.4x.\n", dev->name,
1145     			   mdio_read(dev, np->phys[0], 4),
1146     			   mdio_read(dev, np->phys[0], 5));
1147     		check_duplex(dev);
1148     	}
1149     	if (intr_status & StatsMax) {
1150     		get_stats(dev);
1151     	}
1152     	if (intr_status & IntrPCIErr) {
1153     		printk(KERN_ERR "%s: Something Wicked happened! %4.4x.\n",
1154     			   dev->name, intr_status);
1155     		/* We must do a global reset of DMA to continue. */
1156     	}
1157     }
1158     
1159     static struct net_device_stats *get_stats(struct net_device *dev)
1160     {
1161     	long ioaddr = dev->base_addr;
1162     	struct netdev_private *np = dev->priv;
1163     	int i;
1164     
1165     	/* We should lock this segment of code for SMP eventually, although
1166     	   the vulnerability window is very small and statistics are
1167     	   non-critical. */
1168     	/* The chip only need report frame silently dropped. */
1169     	np->stats.rx_missed_errors	+= readb(ioaddr + RxMissed);
1170     	np->stats.tx_packets += readw(ioaddr + TxFramesOK);
1171     	np->stats.rx_packets += readw(ioaddr + RxFramesOK);
1172     	np->stats.collisions += readb(ioaddr + StatsLateColl);
1173     	np->stats.collisions += readb(ioaddr + StatsMultiColl);
1174     	np->stats.collisions += readb(ioaddr + StatsOneColl);
1175     	readb(ioaddr + StatsCarrierError);
1176     	readb(ioaddr + StatsTxDefer);
1177     	for (i = StatsTxDefer; i <= StatsMcastRx; i++)
1178     		readb(ioaddr + i);
1179     	np->stats.tx_bytes += readw(ioaddr + TxOctetsLow);
1180     	np->stats.tx_bytes += readw(ioaddr + TxOctetsHigh) << 16;
1181     	np->stats.rx_bytes += readw(ioaddr + RxOctetsLow);
1182     	np->stats.rx_bytes += readw(ioaddr + RxOctetsHigh) << 16;
1183     
1184     	return &np->stats;
1185     }
1186     
1187     /* The little-endian AUTODIN II ethernet CRC calculations.
1188        A big-endian version is also available.
1189        This is slow but compact code.  Do not use this routine for bulk data,
1190        use a table-based routine instead.
1191        This is common code and should be moved to net/core/crc.c.
1192        Chips may use the upper or lower CRC bits, and may reverse and/or invert
1193        them.  Select the endian-ness that results in minimal calculations.
1194     */
1195     static unsigned const ethernet_polynomial_le = 0xedb88320U;
1196     static inline unsigned ether_crc_le(int length, unsigned char *data)
1197     {
1198     	unsigned int crc = 0xffffffff;	/* Initial value. */
1199     	while(--length >= 0) {
1200     		unsigned char current_octet = *data++;
1201     		int bit;
1202     		for (bit = 8; --bit >= 0; current_octet >>= 1) {
1203     			if ((crc ^ current_octet) & 1) {
1204     				crc >>= 1;
1205     				crc ^= ethernet_polynomial_le;
1206     			} else
1207     				crc >>= 1;
1208     		}
1209     	}
1210     	return crc;
1211     }
1212     
1213     static void set_rx_mode(struct net_device *dev)
1214     {
1215     	long ioaddr = dev->base_addr;
1216     	u16 mc_filter[4];			/* Multicast hash filter */
1217     	u32 rx_mode;
1218     	int i;
1219     
1220     	if (dev->flags & IFF_PROMISC) {			/* Set promiscuous. */
1221     		/* Unconditionally log net taps. */
1222     		printk(KERN_NOTICE "%s: Promiscuous mode enabled.\n", dev->name);
1223     		memset(mc_filter, 0xff, sizeof(mc_filter));
1224     		rx_mode = AcceptBroadcast | AcceptMulticast | AcceptAll | AcceptMyPhys;
1225     	} else if ((dev->mc_count > multicast_filter_limit)
1226     			   ||  (dev->flags & IFF_ALLMULTI)) {
1227     		/* Too many to match, or accept all multicasts. */
1228     		memset(mc_filter, 0xff, sizeof(mc_filter));
1229     		rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
1230     	} else if (dev->mc_count) {
1231     		struct dev_mc_list *mclist;
1232     		memset(mc_filter, 0, sizeof(mc_filter));
1233     		for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
1234     			 i++, mclist = mclist->next) {
1235     			set_bit(ether_crc_le(ETH_ALEN, mclist->dmi_addr) & 0x3f,
1236     					mc_filter);
1237     		}
1238     		rx_mode = AcceptBroadcast | AcceptMultiHash | AcceptMyPhys;
1239     	} else {
1240     		writeb(AcceptBroadcast | AcceptMyPhys, ioaddr + RxMode);
1241     		return;
1242     	}
1243     	for (i = 0; i < 4; i++)
1244     		writew(mc_filter[i], ioaddr + MulticastFilter0 + i*2);
1245     	writeb(rx_mode, ioaddr + RxMode);
1246     }
1247     
1248     static int netdev_ethtool_ioctl(struct net_device *dev, void *useraddr)
1249     {
1250     	struct netdev_private *np = dev->priv;
1251     	u32 ethcmd;
1252     		
1253     	if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd)))
1254     		return -EFAULT;
1255     
1256             switch (ethcmd) {
1257             case ETHTOOL_GDRVINFO: {
1258     		struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
1259     		strcpy(info.driver, DRV_NAME);
1260     		strcpy(info.version, DRV_VERSION);
1261     		strcpy(info.bus_info, np->pci_dev->slot_name);
1262     		if (copy_to_user(useraddr, &info, sizeof(info)))
1263     			return -EFAULT;
1264     		return 0;
1265     	}
1266     
1267             }
1268     	
1269     	return -EOPNOTSUPP;
1270     }
1271     
1272     static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
1273     {
1274     	struct mii_ioctl_data *data = (struct mii_ioctl_data *)&rq->ifr_data;
1275     
1276     	switch(cmd) {
1277     	case SIOCETHTOOL:
1278     		return netdev_ethtool_ioctl(dev, (void *) rq->ifr_data);
1279     	case SIOCGMIIPHY:		/* Get address of MII PHY in use. */
1280     	case SIOCDEVPRIVATE:		/* for binary compat, remove in 2.5 */
1281     		data->phy_id = ((struct netdev_private *)dev->priv)->phys[0] & 0x1f;
1282     		/* Fall Through */
1283     
1284     	case SIOCGMIIREG:		/* Read MII PHY register. */
1285     	case SIOCDEVPRIVATE+1:		/* for binary compat, remove in 2.5 */
1286     		data->val_out = mdio_read(dev, data->phy_id & 0x1f, data->reg_num & 0x1f);
1287     		return 0;
1288     
1289     	case SIOCSMIIREG:		/* Write MII PHY register. */
1290     	case SIOCDEVPRIVATE+2:		/* for binary compat, remove in 2.5 */
1291     		if (!capable(CAP_NET_ADMIN))
1292     			return -EPERM;
1293     		mdio_write(dev, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in);
1294     		return 0;
1295     	default:
1296     		return -EOPNOTSUPP;
1297     	}
1298     }
1299     
1300     static int netdev_close(struct net_device *dev)
1301     {
1302     	long ioaddr = dev->base_addr;
1303     	struct netdev_private *np = dev->priv;
1304     	struct sk_buff *skb;
1305     	int i;
1306     
1307     	netif_stop_queue(dev);
1308     
1309     	if (debug > 1) {
1310     		printk(KERN_DEBUG "%s: Shutting down ethercard, status was Tx %2.2x "
1311     			   "Rx %4.4x Int %2.2x.\n",
1312     			   dev->name, readb(ioaddr + TxStatus),
1313     			   readl(ioaddr + RxStatus), readw(ioaddr + IntrStatus));
1314     		printk(KERN_DEBUG "%s: Queue pointers were Tx %d / %d,  Rx %d / %d.\n",
1315     			   dev->name, np->cur_tx, np->dirty_tx, np->cur_rx, np->dirty_rx);
1316     	}
1317     
1318     	/* Disable interrupts by clearing the interrupt mask. */
1319     	writew(0x0000, ioaddr + IntrEnable);
1320     
1321     	/* Stop the chip's Tx and Rx processes. */
1322     	writew(TxDisable | RxDisable | StatsDisable, ioaddr + MACCtrl1);
1323     
1324     #ifdef __i386__
1325     	if (debug > 2) {
1326     		printk("\n"KERN_DEBUG"  Tx ring at %8.8x:\n",
1327     			   (int)(np->tx_ring_dma));
1328     		for (i = 0; i < TX_RING_SIZE; i++)
1329     			printk(" #%d desc. %4.4x %8.8x %8.8x.\n",
1330     				   i, np->tx_ring[i].status, np->tx_ring[i].frag[0].addr,
1331     				   np->tx_ring[i].frag[0].length);
1332     		printk("\n"KERN_DEBUG "  Rx ring %8.8x:\n",
1333     			   (int)(np->rx_ring_dma));
1334     		for (i = 0; i < /*RX_RING_SIZE*/4 ; i++) {
1335     			printk(KERN_DEBUG " #%d desc. %4.4x %4.4x %8.8x\n",
1336     				   i, np->rx_ring[i].status, np->rx_ring[i].frag[0].addr,
1337     				   np->rx_ring[i].frag[0].length);
1338     		}
1339     	}
1340     #endif /* __i386__ debugging only */
1341     
1342     	free_irq(dev->irq, dev);
1343     
1344     	del_timer_sync(&np->timer);
1345     
1346     	/* Free all the skbuffs in the Rx queue. */
1347     	for (i = 0; i < RX_RING_SIZE; i++) {
1348     		np->rx_ring[i].status = 0;
1349     		np->rx_ring[i].frag[0].addr = 0xBADF00D0; /* An invalid address. */
1350     		skb = np->rx_skbuff[i];
1351     		if (skb) {
1352     			pci_unmap_single(np->pci_dev, 
1353     				np->rx_ring[i].frag[0].addr, np->rx_buf_sz, 
1354     				PCI_DMA_FROMDEVICE);
1355     			dev_kfree_skb(skb);
1356     			np->rx_skbuff[i] = 0;
1357     		}
1358     	}
1359     	for (i = 0; i < TX_RING_SIZE; i++) {
1360     		skb = np->tx_skbuff[i];
1361     		if (skb) {
1362     			pci_unmap_single(np->pci_dev, 
1363     				np->tx_ring[i].frag[0].addr, skb->len,
1364     				PCI_DMA_TODEVICE);
1365     			dev_kfree_skb(skb);
1366     			np->tx_skbuff[i] = 0;
1367     		}
1368     	}
1369     
1370     	return 0;
1371     }
1372     
1373     static void __devexit sundance_remove1 (struct pci_dev *pdev)
1374     {
1375     	struct net_device *dev = pci_get_drvdata(pdev);
1376     	
1377     	/* No need to check MOD_IN_USE, as sys_delete_module() checks. */
1378     	if (dev) {
1379     		struct netdev_private *np = dev->priv;
1380     
1381     		unregister_netdev(dev);
1382             	pci_free_consistent(pdev, RX_TOTAL_SIZE, np->rx_ring, 
1383     			np->rx_ring_dma);
1384     	        pci_free_consistent(pdev, TX_TOTAL_SIZE, np->tx_ring, 
1385     			np->tx_ring_dma);
1386     		pci_release_regions(pdev);
1387     #ifndef USE_IO_OPS
1388     		iounmap((char *)(dev->base_addr));
1389     #endif
1390     		kfree(dev);
1391     		pci_set_drvdata(pdev, NULL);
1392     	}
1393     }
1394     
1395     static struct pci_driver sundance_driver = {
1396     	name:		DRV_NAME,
1397     	id_table:	sundance_pci_tbl,
1398     	probe:		sundance_probe1,
1399     	remove:		sundance_remove1,
1400     };
1401     
1402     static int __init sundance_init(void)
1403     {
1404     /* when a module, this is printed whether or not devices are found in probe */
1405     #ifdef MODULE
1406     	printk(version);
1407     #endif
1408     	return pci_module_init(&sundance_driver);
1409     }
1410     
1411     static void __exit sundance_exit(void)
1412     {
1413     	pci_unregister_driver(&sundance_driver);
1414     }
1415     
1416     module_init(sundance_init);
1417     module_exit(sundance_exit);
1418