Linux Network Interface source code analysis

Source: Internet
Author: User

I. Preface
In the Linux source code, the implementation of network interfaces is worth reading. by reading the source code, we not only have a deeper understanding of network protocols, but also help in network programming, more accurate understanding and grasp of application functions.
This article focuses on the overall structure of the network interface program, hoping to serve as some guiding texts when reading the source code.
This article takes linux2.4.16 kernel as the object to explain, the kernel source code can be downloaded on the http://www.kernel.org. When I read the source code, refer to the example.

2. Structure of Network Interface Program
Linux network interfaces are divided into four parts: network device interface, network interface core, network protocol family, and network interface socket layer.
The network device interface is mainly responsible for receiving and sending data from physical media. The implemented file is under the linu/driver/NET directory.
The core part of the network interface is the key part of the entire network interface. It provides a unified sending interface for the network protocol and shields various physical media, at the same time, it is responsible for distributing packets from lower layers to appropriate protocols. It is the central part of the network interface. Its main implementation files are in the Linux/NET/Core directory, where Linux/NET/CORE/dev. c is the main file for management.
The network protocol family is part of the implementation of various specific protocols. Linux supports TCP/IP, IPX, X.25, appletalk, and other protocols. The source code of various protocols is named in the Linux/NET/directory. Here we mainly discuss the TCP/IP (IPv4) protocol. The source code is Linux/NET/IPv4, and Linux/NET/IPv4/af_inet.c is the main file management.
The network interface socket layer is the programming interface for network services provided by users. The main source code is in Linux/NET/socket. c

Iii. Network Device Interface
There are many different types of network interface devices on the physical layer. In the 28 lines of the File Include/Linux/if_arp.h, the identifier of the various physical devices that ARP can process is defined. Network Device interfaces are responsible for controlling the specific physical media, receiving and sending data from the physical media, and setting various physical media such as the maximum data packet. Here we take the simple 3com3c501 NIC driver as an example to explain how this layer works. The source code is in Linux/Drivers/NET/3c501. C.
We intuitively consider that the most important thing for a network card is to receive and send data. Here we will look at the process of receiving and sending data.
Sending is relatively simple, in Linux/Drivers/NET/3c501. the el_start_xmit () function starting with row 475 in C is the function that actually sends data to the 3com3c501 ethernet card. The specific sending work is nothing more than reading and writing some registers. The source code comment is clear, let's take a look.
Receiving is relatively complicated. Generally, when a new package arrives or a package is sent, an interruption occurs. Linux/Drivers/NET/3c501. in the el_interrupt () function starting from 572 in C, the first half processes the report after the packet is sent, and the second half processes a new package, that is, new data is received. The el_interrupt () function does not perform too much processing on the new package, so it is handed over to the receiving handler el_receive (). El_receive () first checks whether the received package is correct. If it is a "good" package, a buffer structure (dev_alloc_skb () will be allocated to the package ()), in this way, the driver receives the package and calls the netif_rx () (net/CORE/dev. c1214 rows), and send the package to the upper layer.
Now the driver has the ability to send and receive data. How can the driver establish a connection with the upper layer? That is to say, after receiving the package, how can we send it to the upper layer and how can the upper layer call the sending function of the driver?
The bottom-up relationship is the netif_rx () (net/CORE/dev. c 1214 rows) implemented by the function. The driver uses this function to send the received data to the upper layer. Note that all Nic drivers need to call this function, this is the bridge between the core layer of the network interface and the network interface device.
The relationship from top to bottom is complex. The core layer of the network interface needs to know how many network devices can be used, and the function entry address of each device must be known. The core layer of the network interface shouted, "Hey, how many devices can send packets for me? If you can send the message to me, please make a team !". This team started with dev_base. the pointer structnet_device * dev_base (Linux/include/Linux/netdevice. h row 436) is to save all the devices known to the core layer of the network interface. For the core layer of the network interface, all devices are in a net_device structure. h, line 233 is defined as an abstract device from the perspective of the core layer of the network interface. Let's take a look at the features of the network device from the perspective of the core layer of the network interface:

Struct net_device {
.........
Open ()
Stop ()
Hard_start_xmit ()
Hard_header ()
Rebuild_header ()
Set_mac_address ()
Do_ioctl ()
Set_config ()
Hard_header_cache ()
Header_cache_update ()
Change_mtu ()
Tx_timeout ()
Hard_header_parse ()
Neigh_setup ()
Accept_fastpath ()
.........
}

If the core layer of the network interface needs to send data from the lower layer, after dev_base finds the device, it directly calls the dev-> hard_start_xmit () function to send data packets to the lower layer.
The driver needs to let the core layer of the network interface know its own existence. Of course, it needs to add the pointer chain pointed to by dev_base, and then map its own functions and various parameters to the corresponding fields in net_device. The pointer chain to which dev_base points is established through the register_netdev (& dev_3c50) (Linux/Drivers/NET/net_init.c, line 532) function. The relationship between your function and the corresponding fields and various parameters in net_device is established in elasticsearch probe1 () (Linux/Drivers/NET/3c501. C:
Elasticsearch probe1 (){
.........
Dev-> open = & el_open;
Dev-> hard_start_xmit = & el_start_xmit;
Dev-> tx_timeout = & el_timeout;
Dev-> watchdog_timeo = Hz;
Dev-> stop = & elease close;
Dev-> get_stats = & elasticsearch get_stats;
Dev-> set_multicast_list = & set_multicast_list;
.........
Ether_setup (Dev );
.........
}

Further corresponding work is carried out in ether_setup (Dev) (Drivers/NET/net_init.c, line 405. We noticed Dev-> hard_start_xmit = & el_start_xmit. In this way, the relationship between the sending function is established. The upper layer only knows to call Dev-> hard_start_xmit to send data, the above statement tells the upper layer of the actual sending function of the driver.

Iv. core parts of Network Interfaces
I just talked about how the driver connects to the core layer of the network interface. The core layer of the network interface knows that the function entry of the driver and the driver is directed to the device chain through * dev_base, and the lower layer is called by the function netif_rx () of this layer () (net/CORE/dev. c 1214 rows) Pass the data to this layer.
The upper layer of the core layer of the network interface is the specific network protocol, and the lower layer is the driver. We have resolved the relationship between the lower layer and the upper layer, but the relationship has not been resolved. First, we will discuss the relationship between the core layer of the network interface and the network protocol family. This relationship is essentially the relationship between receiving and sending.
Network protocols, such as IP and ARP, transmit data packets to this layer when sending data packets. What functions does this transfer take place? The Network Interface core layer uses dev_queue_xmit () (net/CORE/dev. c, line975) This function provides a unified sending interface to the upper layer. That is to say, whether it is an IP address or an ARP protocol, this function transmits the data to this layer, you can call this function when you want to send data. Dev_queue_xmit () is executed in Dev-> hard_start_xmit (), while Dev-> hard_start_xmit () calls the actual driver to complete the task of sending. For example, in the above example, calling Dev-> hard_start_xmit () actually calls el_start_xmit ().
Now we will discuss the receipt situation. The core layer of the network interface receives data sent from the upper layer through the function netif_rx () (net/CORE/dev. c 1214). At this time, the data packets must be sent to the upper layer. All the lower-layer protocols of the protocol family need to receive data, TCP/IP IP protocol and ARP protocol, and SPX/IPX protocol, appletalk's DDP and AARP protocols both need to receive data directly from the network interface core layer. How does the network interface core layer send packets to these protocols? In this case, the relationship with the lower layer is very similar. There may be many Nic drivers under the core layer of the network interface. In order to know how to send data to these drivers, the previous and later sections are outdated, the link is resolved through the * dev_base pointer. The link to the upper layer is resolved through static struct packet_ptype_base [16] (net/CORE/dev. C line 164. This array contains the protocol for receiving data packets and the entry to their receiving functions.
From the above, we can see that the IP protocol receives data through the ip_rcv () function, while the ARP protocol uses arp_rcv, the core layer of the network interface only needs to pass the data through this array to the upper-layer function.
If you want to add yourself to this array through a protocol, you can use the dev_add_pack () (net/CORE/dev. C, line233) function to delete the array through the dev_remove_pack () function. The IP layer registration is performed in the initialization function void _ init ip_init (void) (net/IPv4/ip_output.c, line 1003)

{
.........
Dev_add_pack (& ip_packet_type );
.........
}

Go back to our discussion about receipt. The netif_rx () (net/CORE/dev. row C) receives the data sent from the upper layer to see what this function has done.
Because the service is still interrupted, nothing can be processed too much, and the rest is done through cpu_raise_softirq (this_cpu, net_rx_softirq)
It is handed over to Soft Interrupt Processing. From open_softirq (net_rx_softirq, net_rx_action, null), we can know that the net_rx_softirq Soft Interrupt Processing Function is net_rx_action () (net/CORE/dev. c, line 1419), net_rx_action () finds the corresponding protocol in the array ptype_base [16] based on the protocol type of the data packet, and knows the received processing function, then, the data packet is handed over to the processing function, which is handed over to the upper layer for processing. The actual calling of the processing function is done through the pt_prev-> func () Sentence in net_rx_action. For example, if the packet is IP, ptype_base [eth_p_ip]-> func () (ip_rcv (), then the packet is handed over to the IP protocol.

V. network protocols
The protocol layer is actually implemented at this layer. In Linux/include/Linux/socket. h. in Linux, BSD socket defines protocol families that are supported by up to 32. pf_inet is the most familiar TCP/IP protocol family (IPv4, there are no special declarations that refer to IPv4 below ). Take this protocol family as an example to see how this layer works. The main file that implements the TCP/IP protocol family is under the inux/NET/IPv4/directory, and Linux/NET/IPv4/af_inet.c is the main management file.
In linux2.4.16, the IGMP, TCP, UDP, ICMP, ARP, and IP in the TCP/IP protocol family are implemented. Let's first discuss the relationship between these protocols. IP and ARP protocols are protocols that need to directly deal with network device interfaces, that is, they need to receive and send data from the core module of the network. Other protocols, such as TCP, UDP, IGMP, and ICMP, need to directly use the IP protocol. They need to receive data from the IP protocol and send data using the IP protocol, at the same time, direct call interfaces must be provided to the socket layer at the upper layer. It can be seen that the IP layer is a core protocol, and it needs to deal with the lower layer and provide the transmission and receiving services to the upper layer.
Let's take a look at the IP protocol layer. If the network core module (CORE) receives data from the IP layer, ip_packet_type-> ip_rcv () the function transmits data packets to the IP layer, that is, the IP layer receives data through this function ip_rcv () (Linux/NET/IPv4/ip_input.c. Ip_rcv () This function only performs some checksum checks on IP data protection. If the package is correct, the package is handed over to the next processing function ip_rcv_finish () (Note that the call is implemented using the nf_hook macro ). Now, the ip_rcv_finish () function really needs to complete some work on the IP layer. The main task of the IP layer is to route the data packets. Routing is implemented through the ip_route_input () function (/Linux/NET/IPv4/route. C, line 1622. Possible routes for incoming packets include:

• Local data (that is, upper-layer protocols that need to be passed to TCP, UDP, and IGMP );
• Data packets to be forwarded (gateway or NAT server );
• Data packets that cannot be routed (incorrect address information );
We are now concerned about how to process local data. Ip_route_input () call ip_route_input_slow () (net/IPv4/route. c, line 1312), in ip_route_input_slow (), the first line of rth-> U. DST. input = ip_local_deliver, which determines that the IP packet is a local data packet and returns the address of the local data packet processing function. Now that the routing is complete, return to ip_rcv_finish (). Ip_rcv_finish () finally calls pull SKB-> DST-> input (SKB). From the above, we can see that this actually calls the ip_local_deliver () function, while ip_local_deliver (), then, ip_local_deliver_finish () is called (). Now it's time to transfer data packets to the upper layer.
The current situation is very similar to the situation in which packets are transmitted from the Core Module layer (CORE) to the top layer. How can we select a suitable protocol from multiple protocols and transmit data to this Protocol? The Core Module layer of the network uses an array ptype_base [16] To save all registered protocols that can receive data, the network protocol layer also defines such an array, struct net_protocol * inet_protos [max_inet_protos] (/Linux/NET/IPv4/protocol. C # l102), which stores the addresses of the receiving and processing functions of all the upper-layer protocols (IGMP, TCP, UDP, and ICMP) that need to receive data from the IP protocol layer. Let's take a look at the data structure of the TCP protocol:

Linux/NET/IPv4/protocol. c line67
Static struct inet_protocol tcp_protocol = {
Handler: tcp_v4_rcv, // function for receiving data
Err_handler: tcp_v4_err, // function for error handling
Next: ipproto_previous,
Protocol: ipproto_tcp,
Name: "TCP"
};

The first item is what we are most concerned about. The IP layer can use this function to transmit data packets to the TCP layer. In the upper part of Linux/NET/IPv4/protocol. C, we can see that the processing functions of other protocol layers are igmp_rcv (), udp_rcv (), icmp_rcv (). Similarly, in Linux/NET/IPv4/protocol. C, adding the protocol to the array inet_protos [max_inet_protos] is achieved through the inet_add_protocol () function, and the deletion protocol is implemented through inet_del_protocol. Inet_protos [max_inet_protos] the initialization process is in the Linux/NET/IPv4/af_inet.c inet_init () initialization function.

Inet_init (){
......
Printk (kern_info "IP protocols :");
For (P = inet_protocol_base; P! = NULL ;){
Struct inet_protocol * TMP = (struct inet_protocol *) P-> next;
Inet_add_protocol (p); // Add Protocol
Printk ("% S % s", p-> name, TMP? ",":"");
P = TMP;
.........
}

If you pay attention to the startup information during Linux Startup, or run the dmesg command in Linux, you can see the output information of this program:
IP protocols: ICMP, UDP, TCP, IGMP which means that the inet_protos [] array now has the inet_protocol data structure of ICMP, UDP, TCP, and IGMP protocols, the data structure contains the processing functions of the data they receive.
Linux 2.4.16 in Linux/include/Linux/socket. h defines 32 supported bsdsocket protocols, including TCP/IP, IPX/SPX, and X.25. Each Protocol also provides different services, for example, the TCP/IP protocol supports the Connection Service through the TCP protocol and the UDP protocol supports the non-Connection Service. It is necessary to provide unified interfaces to users with so many protocols, this consistency is implemented through socket.
In the BSD Socket network programming mode, a series of unified functions are used to use communication services. For example, a typical TCP communication program is as follows:

Sock_descri & #112; tor = socket (af_inet, sock_stream, 0 );
Connect (sock_descri & #112; Tor, address ,);
Send (sock_descri & #112; Tor, "Hello World ");
Recv (sock_descri & #112; Tor, buffer );

The first function specifies the Protocol Inet protocol, namely the TCP/IP protocol, and uses connection-oriented services to correspond to the TCP protocol, subsequent operations will be performed using standard functions of socket.
We can see two problems from the above. First, the socket layer needs to select a Protocol from the following 32 protocols based on the protocol family specified by the user (af_inet above) to fulfill the user's requirements, after the protocol family is determined, specific services must be mapped to specific protocols in the protocol family. For example, when a user specifies a connection-oriented service, the inet protocol family maps to the TCP protocol.
Selecting a user-specified protocol from multiple protocols and handing the specific exit to the selected protocol is essentially the same as connecting the network core layer up and down, so the solution is the same, also through arrays. In Linux/NET/socket. C, this array staticstruct net_proto_family * net_families [nproto] is defined. The element of the array has been determined. net_families [2] is the TCP/IP protocol, and net_families [3] is the X.25 protocol. The specific protocol is included in include/Linux/socket. H is defined. However, the ops of the data structure net_proto_family of each item is empty, that is, the address of the specific protocol processing function is unknown. The processing function of the Protocol establishes a connection with OPS through the sock_register () (Linux/NET/socket. c) function. For example, the TCP/IP protocol establishes a connection like this:

Int _ init inet_init (void) (net/IPv4/af_inet.c)
{
(Void) sock_register (& inet_family_ops );

}

As long as af_inet is given (defined as 2 in the macro), you can find the processing function in net_failies [2.
The Protocol ing is completed, and now the service ing is required. Of course, it is impossible for the upper layer to know what protocols in the lower layer can correspond to specific services. Therefore, such mappings are naturally completed by the protocol family. In the TCP/IP protocol family, this ing is performed through struct
List_head inetsw [sock_max] (net/IPv4/af_inet.c)

This array is mapped. before talking about this array, let's look at another array, inetsw_array [] (net/IPv4/af_inet.c)

Static struct inet_protosw inetsw_array [] =
{
{
Type: sock_stream,
Protocol: ipproto_tcp,
Prot: & tcp_prot,
Ops: & inet_stream_ops,
Capability:-1,
No_check: 0,
Flags: inet_protosw_permanent,
},

{
Type: sock_dgram,
Protocol: ipproto_udp,
Prot: & udp_prot,
Ops: & inet_dgram_ops,
Capability:-1,
No_check: udp_csum_default,
Flags: inet_protosw_permanent,
},

{
Type: sock_raw,
Protocol: ipproto_ip,/* wild card */
Prot: & raw_prot,
Ops: & inet_dgram_ops,
Capability: cap_net_raw,
No_check: udp_csum_default,
Flags: inet_protosw_reuse,
}
};

We can see that sock_stream maps to the TCP protocol, sock_dgram maps to the UDP protocol, and sock_raw maps to the IP protocol. Now you only need to add the three items in inetsw_array to the array inetsw [sock_max]. The addition is implemented through the inet_register_protosw () function. This is done in inet_init () (net/IPv4/af_inet.c.
Another thing that needs to be mapped is socket, such as accept, send (),
How are the operation functions such as connect (), release (), and bind () mapped? Let's take a look at the TCP entry of the preceding array.
{
Type: sock_stream,
Protocol: ipproto_tcp,
Prot: & tcp_prot,
Ops: & inet_stream_ops,
Capability:-1,
No_check: 0,
Flags: inet_protosw_permanent,
},
We can see that this ing is mapped through OPS and Prot. Let's take a look at tcp_prot:
Struct proto tcp_prot = {
Name: "TCP ",
Close: tcp_close,
Connect: tcp_v4_connect,
Disconnect: tcp_disconnect,
Accept: tcp_accept,
IOCTL: tcp_ioctl,
Init: tcp_v4_init_sock,
Destroy: tcp_v4_destroy_sock,
Shutdown: tcp_shutdown,
Setsockopt: tcp_setsockopt,
Getsockopt: tcp_getsockopt,
Sendmsg: tcp_sendmsg,
Recvmsg: tcp_recvmsg,
Backlog_rcv: tcp_v4_do_rcv,
Hash: tcp_v4_hash,
Unhash: tcp_unhash,
Get_port: tcp_v4_get_port,
};
Therefore, the ing has been completed. The user calls the connect () function and actually calls the tcp_v4_connect () function. According to this figure, it is much easier to read the source code.

Socket Layer
In the previous section, we talked about most of the things to be discussed at the socket layer. Now we only talk about the connection between the socket layer and the user.
The system calls socket (), BIND (), connect (), accept, send (), and release () in Linux/NET/socket. in C, the system calls the implemented function with the prefix of SYS _ added to the corresponding function name.
Now let's take a look at what happened below when the user calls the socket () function.
Socket (af_inet, sock_stream, 0) calls sys_socket (), sys_socket (), and then calls socket_creat (), socket_creat () find a suitable protocol family in net_families [] based on the protocol family parameter provided by the user. If the protocol family is not installed, request to install the module of the protocol family, then, call the processing handle of the CREATE () function of the protocol family. According to the af_inet parameter, inet_creat () is called. In inet_creat (), select the appropriate protocol in inetsw [sock_max] based on the service type, and assign the operation set of the protocol to the socket, according to sock_stream, TCP protocol is selected,
Inet_creat (){
Answer = inetsw [user requirements Service];
Sock-> Ops = answer-> OPS;
SK-> prot = answer-> prot
}
So far, it's time for everyone to read the source code.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/unbutun/archive/2009/11/12/4804008.aspx

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.