⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myson803.c

📁 linux下网卡驱动实例,希望对大家有所帮助!
💻 C
📖 第 1 页 / 共 4 页
字号:
/* myson803.c: A Linux device driver for the Myson mtd803 Ethernet chip. */
/*
	Written 1998-2003 by Donald Becker.

	This software may be used and distributed according to the terms of
	the GNU General Public License (GPL), incorporated herein by reference.
	Drivers based on or derived from this code fall under the GPL and must
	retain the authorship, copyright and license notice.  This file is not
	a complete program and may only be used when the entire operating
	system is licensed under the GPL.

	The author may be reached as becker@scyld.com, or C/O
	Scyld Computing Corporation
	410 Severn Ave., Suite 210
	Annapolis MD 21403

	Support information and updates available at
	http://www.scyld.com/network/myson803.html
*/

/* These identify the driver base version and may not be removed. */
static const char version1[] =
"myson803.c:v1.05 3/10/2003 Written by Donald Becker <becker@scyld.com>\n";
static const char version2[] =
"  http://www.scyld.com/network/drivers.html\n";

/* Automatically extracted configuration info:
probe-func: myson803_probe
config-in: tristate 'Myson MTD803 series Ethernet support' CONFIG_MYSON_ETHER

c-help-name: Myson MTD803 PCI Ethernet support
c-help-symbol: CONFIG_MYSON_ETHER
c-help: This driver is for the Myson MTD803 Ethernet adapter series.
c-help: More specific information and updates are available from 
c-help: http://www.scyld.com/network/drivers.html
*/

/* The user-configurable values.
   These may be modified when a driver module is loaded.*/

/* Message enable level: 0..31 = no..all messages.  See NETIF_MSG docs. */
static int debug = 2;

/* Maximum events (Rx packets, etc.) to handle at each interrupt. */
static int max_interrupt_work = 40;

/* Maximum number of multicast addresses to filter (vs. rx-all-multicast).
   This chip uses a 64 element hash table based on the Ethernet CRC.  */
static int multicast_filter_limit = 32;

/* Set the copy breakpoint for the copy-only-tiny-frames scheme.
   Setting to > 1518 effectively disables this feature. */
static int rx_copybreak = 0;

/* Used to pass the media type, etc.
   Both 'options[]' and 'full_duplex[]' should exist for driver
   interoperability.
   The media type is usually passed in 'options[]'.
    The default is autonegotation for speed and duplex.
	This should rarely be overridden.
    Use option values 0x10/0x20 for 10Mbps, 0x100,0x200 for 100Mbps.
    Use option values 0x10 and 0x100 for forcing half duplex fixed speed.
    Use option values 0x20 and 0x200 for forcing full duplex operation.
*/
#define MAX_UNITS 8		/* More are supported, limit only on options */
static int options[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};

/* Operational parameters that are set at compile time. */

/* Keep the ring sizes a power of two for compile efficiency.
   The compiler will convert <unsigned>'%'<2^N> into a bit mask.
   Making the Tx ring too large decreases the effectiveness of channel
   bonding and packet priority.
   There are no ill effects from too-large receive rings. */
#define TX_RING_SIZE	16
#define TX_QUEUE_LEN	10		/* Limit Tx ring entries actually used.  */
#define RX_RING_SIZE	32

/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT  (6*HZ)

/* Allocation size of Rx buffers with normal sized Ethernet frames.
   Do not change this value without good reason.  This is not a limit,
   but a way to keep a consistent allocation size among drivers.
 */
#define PKT_BUF_SZ		1536

#ifndef __KERNEL__
#define __KERNEL__
#endif
#if !defined(__OPTIMIZE__)
#warning  You must compile this file with the correct options!
#warning  See the last lines of the source file.
#error You must compile this driver with "-O".
#endif

/* Include files, designed to support most kernel versions 2.0.0 and later. */
#include <linux/config.h>
#if defined(CONFIG_SMP) && ! defined(__SMP__)
#define __SMP__
#endif
#if defined(MODULE) && defined(CONFIG_MODVERSIONS) && ! defined(MODVERSIONS)
#define MODVERSIONS
#endif

#include <linux/version.h>
#if defined(MODVERSIONS)
#include <linux/modversions.h>
#endif
#include <linux/module.h>

#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#if LINUX_VERSION_CODE >= 0x20400
#include <linux/slab.h>
#else
#include <linux/malloc.h>
#endif
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <asm/processor.h>		/* Processor type for cache alignment. */
#include <asm/bitops.h>
#include <asm/io.h>
#include <asm/unaligned.h>

#ifdef INLINE_PCISCAN
#include "k_compat.h"
#else
#include "pci-scan.h"
#include "kern_compat.h"
#endif

/* Condensed operations for readability. */
#define virt_to_le32desc(addr)  cpu_to_le32(virt_to_bus(addr))
#define le32desc_to_virt(addr)  bus_to_virt(le32_to_cpu(addr))

#if (LINUX_VERSION_CODE >= 0x20100)  &&  defined(MODULE)
char kernel_version[] = UTS_RELEASE;
#endif

/* Kernels before 2.1.0 cannot map the high addrs assigned by some BIOSes. */
#if (LINUX_VERSION_CODE < 0x20100)  ||  ! defined(MODULE)
#define USE_IO_OPS
#endif

MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
MODULE_DESCRIPTION("Myson mtd803 Ethernet driver");
MODULE_LICENSE("GPL");
/* List in order of common use. */
MODULE_PARM(debug, "i");
MODULE_PARM(options, "1-" __MODULE_STRING(MAX_UNITS) "i");
MODULE_PARM(full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
MODULE_PARM(max_interrupt_work, "i");
MODULE_PARM(rx_copybreak, "i");
MODULE_PARM(multicast_filter_limit, "i");
MODULE_PARM_DESC(debug, "Driver message level (0-31)");
MODULE_PARM_DESC(options, "Force transceiver type or fixed speed+duplex");
MODULE_PARM_DESC(full_duplex, "Non-zero to force full duplex, "
				 "non-negotiated link (deprecated).");
MODULE_PARM_DESC(max_interrupt_work,
				 "Maximum events handled per interrupt");
MODULE_PARM_DESC(rx_copybreak,
				 "Breakpoint in bytes for copy-only-tiny-frames");
MODULE_PARM_DESC(multicast_filter_limit,
				 "Multicast addresses before switching to Rx-all-multicast");

/*
				Theory of Operation

I. Board Compatibility

This driver is for the Myson mtd803 chip.
It should work with other Myson 800 series chips.

II. Board-specific settings

None.

III. Driver operation

IIIa. Ring buffers

This driver uses two statically allocated fixed-size descriptor lists
formed into rings by a branch from the final descriptor to the beginning of
the list.  The ring sizes are set at compile time by RX/TX_RING_SIZE.
Some chips explicitly use only 2^N sized rings, while others use a
'next descriptor' pointer that the driver forms into rings.

IIIb/c. Transmit/Receive Structure

This driver uses a zero-copy receive and transmit scheme.
The driver allocates full frame size skbuffs for the Rx ring buffers at
open() time and passes the skb->data field to the chip as receive data
buffers.  When an incoming frame is less than RX_COPYBREAK bytes long,
a fresh skbuff is allocated and the frame is copied to the new skbuff.
When the incoming frame is larger, the skbuff is passed directly up the
protocol stack.  Buffers consumed this way are replaced by newly allocated
skbuffs in a later phase of receives.

The RX_COPYBREAK value is chosen to trade-off the memory wasted by
using a full-sized skbuff for small frames vs. the copying costs of larger
frames.  New boards are typically used in generously configured machines
and the underfilled buffers have negligible impact compared to the benefit of
a single allocation size, so the default value of zero results in never
copying packets.  When copying is done, the cost is usually mitigated by using
a combined copy/checksum routine.  Copying also preloads the cache, which is
most useful with small frames.

A subtle aspect of the operation is that the IP header at offset 14 in an
ethernet frame isn't longword aligned for further processing.
When unaligned buffers are permitted by the hardware (and always on copies)
frames are put into the skbuff at an offset of "+2", 16-byte aligning
the IP header.

IIId. Synchronization

The driver runs as two independent, single-threaded flows of control.  One
is the send-packet routine, which enforces single-threaded use by the
dev->tbusy flag.  The other thread is the interrupt handler, which is single
threaded by the hardware and interrupt handling software.

The send packet thread has partial control over the Tx ring and 'dev->tbusy'
flag.  It sets the tbusy flag whenever it's queuing a Tx packet. If the next
queue slot is empty, it clears the tbusy flag when finished otherwise it sets
the 'lp->tx_full' flag.

The interrupt handler has exclusive control over the Rx ring and records stats
from the Tx ring.  After reaping the stats, it marks the Tx queue entry as
empty by incrementing the dirty_tx mark. Iff the 'lp->tx_full' flag is set, it
clears both the tx_full and tbusy flags.

IIId. SMP semantics

The following are serialized with respect to each other via the "xmit_lock".
  dev->hard_start_xmit()	Transmit a packet
  dev->tx_timeout()			Transmit watchdog for stuck Tx
  dev->set_multicast_list()	Set the recieve filter.
Note: The Tx timeout watchdog code is implemented by the timer routine in
kernels up to 2.2.*.  In 2.4.* and later the timeout code is part of the
driver interface.

The following fall under the global kernel lock.  The module will not be
unloaded during the call, unless a call with a potential reschedule e.g.
kmalloc() is called.  No other synchronization assertion is made.
  dev->open()
  dev->do_ioctl()
  dev->get_stats()
Caution: The lock for dev->open() is commonly broken with request_irq() or
kmalloc().  It is best to avoid any lock-breaking call in do_ioctl() and
get_stats(), or additional module locking code must be implemented.

The following is self-serialized (no simultaneous entry)
  An handler registered with request_irq().

IV. Notes

IVb. References

http://www.scyld.com/expert/100mbps.html
http://scyld.com/expert/NWay.html
http://www.myson.com.hk/mtd/datasheet/mtd803.pdf
   Myson does not require a NDA to read the datasheet.

IVc. Errata

No undocumented errata.
*/



/* PCI probe routines. */

static void *myson_probe1(struct pci_dev *pdev, void *init_dev,
						   long ioaddr, int irq, int chip_idx, int find_cnt);
static int netdev_pwr_event(void *dev_instance, int event);

/* Chips prior to the 803 have an external MII transceiver. */
enum chip_capability_flags { HasMIIXcvr=1, HasChipXcvr=2 };

#ifdef USE_IO_OPS
#define PCI_IOTYPE (PCI_USES_MASTER | PCI_USES_IO  | PCI_ADDR0)
#define PCI_IOSIZE	256
#else
#define PCI_IOTYPE (PCI_USES_MASTER | PCI_USES_MEM | PCI_ADDR1)
#define PCI_IOSIZE	1024
#endif

static struct pci_id_info pci_id_tbl[] = {
	{"Myson mtd803 Fast Ethernet", {0x08031516, 0xffffffff, },
	 PCI_IOTYPE, PCI_IOSIZE, HasChipXcvr},
	{"Myson mtd891 Gigabit Ethernet", {0x08911516, 0xffffffff, },
	 PCI_IOTYPE, PCI_IOSIZE, HasChipXcvr},
	{0,},						/* 0 terminated list. */
};

struct drv_id_info myson803_drv_id = {
	"myson803", 0, PCI_CLASS_NETWORK_ETHERNET<<8, pci_id_tbl, myson_probe1,
	netdev_pwr_event };

/* This driver was written to use PCI memory space, however x86-oriented
   hardware sometimes works only with I/O space accesses. */
#ifdef USE_IO_OPS
#undef readb
#undef readw
#undef readl
#undef writeb
#undef writew
#undef writel
#define readb inb
#define readw inw
#define readl inl
#define writeb outb
#define writew outw
#define writel outl
#endif

/* Offsets to the various registers.
   Most accesses must be longword aligned. */
enum register_offsets {
	StationAddr=0x00, MulticastFilter0=0x08, MulticastFilter1=0x0C,
	FlowCtrlAddr=0x10, RxConfig=0x18, TxConfig=0x1a, PCIBusCfg=0x1c,
	TxStartDemand=0x20, RxStartDemand=0x24,
	RxCurrentPtr=0x28, TxRingPtr=0x2c, RxRingPtr=0x30,
	IntrStatus=0x34, IntrEnable=0x38,
	FlowCtrlThreshold=0x3c,
	MIICtrl=0x40, EECtrl=0x40, RxErrCnts=0x44, TxErrCnts=0x48,
	PHYMgmt=0x4c,
};

/* Bits in the interrupt status/mask registers. */
enum intr_status_bits {
	IntrRxErr=0x0002, IntrRxDone=0x0004, IntrTxDone=0x0008,
	IntrTxEmpty=0x0010, IntrRxEmpty=0x0020, StatsMax=0x0040, RxEarly=0x0080,
	TxEarly=0x0100, RxOverflow=0x0200, TxUnderrun=0x0400,
	IntrPCIErr=0x2000, NWayDone=0x4000, LinkChange=0x8000,
};

/* Bits in the RxMode (np->txrx_config) register. */
enum rx_mode_bits {
	RxEnable=0x01, RxFilter=0xfe,
	AcceptErr=0x02, AcceptRunt=0x08, AcceptBroadcast=0x40,
	AcceptMulticast=0x20, AcceptAllPhys=0x80, AcceptMyPhys=0x00,
	RxFlowCtrl=0x2000,
	TxEnable=0x40000, TxModeFDX=0x00100000, TxThreshold=0x00e00000,
};

/* Misc. bits. */
enum misc_bits {
	BCR_Reset=1,				/* PCIBusCfg */
	TxThresholdInc=0x200000,
};

/* The Rx and Tx buffer descriptors. */
/* Note that using only 32 bit fields simplifies conversion to big-endian
   architectures. */
struct netdev_desc {
	u32 status;
	u32 ctrl_length;
	u32 buf_addr;
	u32 next_desc;
};

/* Bits in network_desc.status */
enum desc_status_bits {
	DescOwn=0x80000000,
	RxDescStartPacket=0x0800, RxDescEndPacket=0x0400, RxDescWholePkt=0x0c00,
	RxDescErrSum=0x80, RxErrRunt=0x40, RxErrLong=0x20, RxErrFrame=0x10,
	RxErrCRC=0x08, RxErrCode=0x04,
	TxErrAbort=0x2000, TxErrCarrier=0x1000, TxErrLate=0x0800,
	TxErr16Colls=0x0400, TxErrDefer=0x0200, TxErrHeartbeat=0x0100,
	TxColls=0x00ff,
};
/* Bits in network_desc.ctrl_length */
enum ctrl_length_bits {
	TxIntrOnDone=0x80000000, TxIntrOnFIFO=0x40000000,
	TxDescEndPacket=0x20000000, TxDescStartPacket=0x10000000,
	TxAppendCRC=0x08000000, TxPadTo64=0x04000000, TxNormalPkt=0x3C000000,
};

#define PRIV_ALIGN	15 	/* Required alignment mask */
/* Use  __attribute__((aligned (L1_CACHE_BYTES)))  to maintain alignment
   within the structure. */
struct netdev_private {
	/* Descriptor rings first for alignment. */
	struct netdev_desc rx_ring[RX_RING_SIZE];
	struct netdev_desc tx_ring[TX_RING_SIZE];
	struct net_device *next_module;		/* Link for devices of this type. */
	void *priv_addr;					/* Unaligned address for kfree */
	/* The addresses of receive-in-place skbuffs. */
	struct sk_buff* rx_skbuff[RX_RING_SIZE];
	/* The saved address of a sent-in-place packet/buffer, for later free(). */
	struct sk_buff* tx_skbuff[TX_RING_SIZE];
	struct net_device_stats stats;
	struct timer_list timer;	/* Media monitoring timer. */
	/* Frequently used values: keep some adjacent for cache effect. */
	int msg_level;
	int max_interrupt_work;
	int intr_enable;
	int chip_id, drv_flags;
	struct pci_dev *pci_dev;

	struct netdev_desc *rx_head_desc;
	unsigned int cur_rx, dirty_rx;		/* Producer/consumer ring indices */
	unsigned int rx_buf_sz;				/* Based on MTU+slack. */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -