Linux Network card Driver Learning (i) (Analysis of a virtual hardware network-driven example)

Source: Internet
Author: User

On Linux, the network is divided into two tiers, each of which is the network stack protocol support layer, and the device driver layer that receives and sends the network protocol.

The network stack is a separate part of the hardware. Mainly used to support a variety of protocols such as TCP/IP, network device driver layer is connected to the network stack protocol layer and network hardware middle tier.

The main functions of the network device driver are:

(1) Initialization of module loading or kernel boot-related processing

(2) processing when the module is cleared

(3) Searching and probing of network equipment

(4) Initialization and registration of network equipment

(5) Turn network devices on or off

(6) Sending network data

(7) Receiving network data

(8) Interrupt processing (when the data is sent out.) The hardware generates an interrupt to the kernel. Tells the kernel that the data has been sent for completion. When the network device receives the data, an interrupt is also required to tell the kernel. Data has arrived, please timely processing)

(9) Timeout processing

(10) Multicast processing

(11) Control IOCTL of network equipment

The main function of Linux network device is the initialization of network equipment, the configuration of network equipment, and the sending and receiving of data packets.

The following code is a sample of network-driven virtual hardware

2. Code

#undef pdebug/* undef it, just in case */#ifdef snull_debug# ifdef __kernel__/* This one if debugging I s on, and kernel space */# define PDEBUG (FMT, args ...) printk (kern_debug "snull:" Fmt, # # args) # Else * * this on E for user space */# define PDEBUG (FMT, args ...) fprintf (stderr, FMT, # # args) # endif#else# define Pdebug (FMT, args. .) /* Not debugging:nothing */#endif #undef pdebugg#define Pdebugg (fmt, args ...)/* nothing:it ' s a placeholder *//* these AR E The flags in the Statusword * * #define SNULL_RX_INTR 0x0001#define snull_tx_intr 0x0002/* Default Timeout period */#defin E snull_timeout 6/* in Jiffies * * #include <linux/module.h> #include <linux/sched.h> #include <linux/kerne l.h>/* PRINTK () */#include <linux/slab.h>/* KMALLOC () */#include <linux/errno.h>/* ERROR codes */#inclu De <linux/types.h> * size_t */#include <linux/interrupt.h>/mark_bh */#include <linux/in.h># Include <linux/netdevice.h&Gt /* struct device, and other headers */#include <linux/etherdevice.h>/* Eth_type_trans */#include <linux/ip.h&gt          ; /* struct IPHDR */#include <linux/tcp.h>/* struct TCPHDR */#include <linux/skbuff.h> #include <linu x/if_ether.h> #include <linux/in6.h> #include <asm/uaccess.h> #include <asm/checksum.h>static int lockup = 0;static int timeout = snull_timeout;struct Net_device snull_devs[2];//Define two devices here, one is snull0, the other is snull1// Network device structure, as net_device->privstruct snull_priv {struct net_device_stats stats;//useful statistics int status;//Network device status information. is to send out the packet. or receive the packet length received by the network packet int rx_packetlen;//U8 *rx_packetdata;//received data int tx_packetlen;//packet length sent U8 *TX_PACKETDA ta;//sent data struct Sk_buff *skb;//socket buffer structure, the transmission of data between the network layer is through this structure to achieve spinlock_t lock;//spin lock};void Snull_tx_timeo    UT (struct net_device *dev);///network interface open function int snull_open (struct net_device *dev) {PRINTK ("call snull_open/n"); memcpy (dev->dev_addr, "/0snUL0 ", eth_alen);//Assign a hardware address, Eth_alen is the length of the hardware address of the network device netif_start_queue (dev),//Open the transmission queue so that the ability to transfer data return 0;}    int snull_release (struct net_device *dev) {PRINTK ("call snull_release/n"); Netif_stop_queue (Dev); When the network interface is closed, call the Stop method. This function indicates that the data can no longer be sent return 0;}    packet function void Snull_rx (struct net_device *dev, int len, unsigned char *buf) {struct Sk_buff *skb;     struct Snull_priv *priv = (struct Snull_priv *) dev->priv; /* * The packet have been retrieved from the transmission * medium. Build an SKB around it, so upper layers can handle it */SKB = DEV_ALLOC_SKB (len+2);//Assign a socket buffer and initialize SKB-&G        T;data,skb->tail and Skb->head if (!SKB) {PRINTK ("Snull rx:low on Mem-packet dropped/n");        priv->stats.rx_dropped++;    Return } skb_reserve (SKB, 2);  /* Align IP on 16B boundary */memcpy (Skb_put (SKB, Len), buf, Len),//skb_put is writing data to socket buffer/* Write metadata,  And then pass to the receive level */Skb->dev = dev;  Skb->protocol = Eth_type_trans (SKB, dev);//Returns the protocol number skb->ip_summed = Checksum_unnecessary; Here does not check the number of priv->stats.rx_packets++;//received packets +1 priv->stats.rx_bytes + = len;//received packet length NETIF_RX (SKB);//Notification kernel The package has been received.          and encapsulated into the socket buffer to the upper return;} /* * The typical interrupt entry point *///interrupt processing. There is no hardware in this program, so there is no real hardware interrupt, just a simulated interrupt after the network packet has been sent out. Interrupts are generated//used to notify the kernel that a packet has been sent, and interrupts occur when a new packet arrives at the network interface.    Notifies that a new packet has arrived void Snull_interrupt (int irq, void *dev_id, struct pt_regs *regs) {int statusword;//is used to identify whether to send complete or receive new packets    struct Snull_priv *priv;     /* As usual, check the "device" pointer for shared handlers.    * Then assign "struct device *dev" */struct Net_device *dev = (struct net_device *) dev_id;    /* ... and check with HW if it ' s really ours */if (!dev/*paranoid*/) return;    /* Lock the device */priv = (struct Snull_priv *) dev->priv;    Spin_lock (&priv->lock); /* Retrieve statusword:real netdevices use I/o instructions */Statusword= priv->status; if (Statusword & snull_rx_intr) {//assume is receive/* Send it to SNULL_RX for handling */Snull_rx (Dev, priv->r    X_packetlen, Priv->rx_packetdata); } if (Statusword & snull_tx_intr) {//assuming send complete/* A transmission is over:free the SKB */priv->stats        . tx_packets++;        Priv->stats.tx_bytes + = priv->tx_packetlen; DEV_KFREE_SKB (PRIV-&GT;SKB);//release SKB Socket buffer}/* Unlock the device and we are doing */Spin_unlock (&priv->lo    CK); return;} /* * Transmit a packet (Low level interface) *///true processing of sending packets//simulation from one network to another network sending packet void Snull_hw_tx (char *buf, int len, Stru CT net_device *dev) {/* * This function deals with HW details.     This interface loops * Back the packet to the other Snull interface (if any). * In other words, this function implements the Snull behaviour, * and all other procedures is rather device-indepen Dent */struct IPHDR *ih;//ip head struct net_device *dest;//target device structure. NEt_device stores important information of a network interface, which is the core of network driver Snull_priv *priv; U32 *saddr, *daddr;//source device address and target device address/* I am paranoid. Ain ' t I? */if (len < sizeof (struct ETHHDR) + sizeof (struct IPHDR)) {PRINTK ("snull:hmm ... packet Too short (%i octet        s)/n ", Len);    Return     }/* * Ethhdr is bytes, and the kernel arranges for IPHDR * to was aligned (i.e., ETHHDR is unaligned) */    IH = (struct IPHDR *) (buf+sizeof (struct ETHHDR));    SADDR = &ih->saddr;    DADDR = &ih->daddr; Simulate two networks on the same machine. Different network segment addresses, to send network packets with the Receiving network packet ((U8 *) saddr) [2] ^= 1;    /* Change the third octet (class C) ^ is a bitwise XOR operator that makes the third part of the network address XOR with 1, because data from the same network is not forwarded */(((U8 *) daddr) [2] ^= 1;         Ih->check = 0;    /* and rebuild the checksum (IP needs it) */Ih->check = Ip_fast_csum ((unsigned char *) IH,IH-&GT;IHL); if (dev = = Snull_devs) Pdebugg ("%08x:%05i-to-%08x:%05i/n", Ntohl (IH-&GT;SADDR), Ntohs ((struct TCP  HDR *) (ih+1))->source),             Ntohl (IH-&GT;DADDR), Ntohs ((struct TCPHDR *) (ih+1))); else Pdebugg ("%08x:%05i <--%08x:%05i/n", Ntohl (IH-&GT;DADDR), Ntohs (((struct TCPHDR *) (ih+1))    dest), Ntohl (IH-&GT;SADDR), Ntohs ((struct TCPHDR *) (ih+1)),->source);  /* Ok, now the packet are ready for Transmission:first simulate A * receive interrupt on the twin device and then A * Transmission-done on the transmitting device */dest = Snull_devs + (Dev==snull_devs? 1:0);//Assuming Dev is 0, then D EST is 1, assuming Dev is 1.    Then dest is 0 priv = (struct Snull_priv *) dest->priv;//dest priv in target priv->status = snull_rx_intr;    Priv->rx_packetlen = Len;    Priv->rx_packetdata = BUF;    Snull_interrupt (0, dest, NULL);    Priv = (struct Snull_priv *) dev->priv;    Priv->status = Snull_tx_intr;    Priv->tx_packetlen = Len;    Priv->tx_packetdata = BUF; if (Lockup && ((priv->stats.tx_packets + 1)% lockup) = = 0) {/* Simulate a Dropped transmit interrupt */netif_stop_queue (dev);    Pdebug ("Simulate lockup at%ld, Txp%ld/n", jiffies, (unsigned long) priv->stats.tx_packets); } else snull_interrupt (0, Dev, NULL);} /* * Transmit a packet (called by the kernel) *///packet function int snull_tx (struct sk_buff *skb, struct net_device *dev) {int    Len    Char *data;    struct Snull_priv *priv = (struct Snull_priv *) dev->priv;        if (SKB = = NULL) {pdebug ("tint for%p, SKB%p/n", Dev, SKB);        Snull_tx_timeout (Dev);    if (SKB = = NULL) return 0; } len = Skb->len < Eth_zlen? Eth_zlen:skb->len;//eth_zlen is the length of the smallest packet sent data = skb->data;//the part of the packet that will be sent Dev->trans_start = jiffies;    Save current Send time PRIV-&GT;SKB = SKB; SNULL_HW_TX (data, Len, dev);//True send function return 0; /* Our simple device can not fail */}/* * Deal with a transmit timeout. *///calls Snull_tx_timeoutvoid Snull_tx_timeout once the Watchdog_timeo is exceeded (struct NET_DEVIce *dev) {PRINTK ("call snull_tx_timeout/n");    struct Snull_priv *priv = (struct Snull_priv *) dev->priv;    Pdebug ("Transmit timeout at%ld, latency%ld/n", jiffies, Jiffies-dev->trans_start);    Priv->status = Snull_tx_intr; Snull_interrupt (0, Dev, NULL);//Interrupt after timeout priv->stats.tx_errors++;//the number of errors sent netif_wake_queue (dev); To send the data again, call this function again to start the Send queue return;}    /* * IOCTL commands */int snull_ioctl (struct net_device *dev, struct ifreq *rq, int cmd) {pdebug ("ioctl/n"); return 0;} /* * Return statistics to the caller */struct net_device_stats *snull_stats (struct net_device *dev) {struct SNULL_PRIV    *priv = (struct Snull_priv *) dev->priv;    Return &priv->stats;//Get statistical information}//Device initialization function int snull_init (struct net_device *dev) {PRINTK ("call snull_init/n"); /* Then, assign other fields in Dev, using Ether_setup () and some * hand assignments */ether_setup (dev); Populate some Ethernet devices in the structure of the item Dev->open = Snull_Open    Dev->stop = Snull_release;    Dev->set_config = Snull_config;    Dev->hard_start_xmit = Snull_tx;    Dev->do_ioctl = Snull_ioctl;    Dev->get_stats = Snull_stats;    DEV-&GT;CHANGE_MTU = SNULL_CHANGE_MTU;    Dev->rebuild_header = Snull_rebuild_header;    Dev->hard_header = Snull_header;    Dev->tx_timeout = snull_tx_timeout;//timeout processing Dev->watchdog_timeo = timeout;    /* Keep the default flags, just add Noarp */dev->flags |= iff_noarp;      Dev->hard_header_cache = NULL;    /* Disable Caching */Set_module_owner (dev); /* Then, allocate the Priv field.     This encloses the statistics * and a few private fields.  *///allocates memory for priv Dev->priv = kmalloc (sizeof (struct snull_priv), gfp_kernel);    if (Dev->priv = = NULL) Return-enomem;    memset (dev->priv, 0, sizeof (struct snull_priv));   Spin_lock_init (& (struct Snull_priv *) dev->priv)->lock); return 0;} struct Net_device snull_devs[2] = {{init:snull_init,},/* init, nothing more */{init:snull_init,}};int Snul   L_init_module (void) {int i,result=0; strcpy (Snull_devs[0].name, "snull0"); the name in the//net_device struct represents the device name strcpy (snull_devs[1].name, "snull1");//defines two devices,  Snull0 and Snull1 for (i=0; i<2; i++) if (result = Register_netdev (snull_devs+i))//Register device PRINTK ("Snull:error%i registering Device/"     %s/"/n", result, snull_devs[i].name); return 0;}     void Snull_cleanup (void) {int i;  for (i=0; i<2;        i++) {kfree (SNULL_DEVS[I].PRIV);    Unregister_netdev (Snull_devs+i); } return; Module_init (Snull_init_module); Module_exit (Snull_cleanup);



Linux Network card Driver Learning (i) (Analysis of a virtual hardware network-driven example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.