Interaction between Linux User State and kernel state (1) -- Linux general technology-Linux programming and kernel information. The following is a detailed description. ReferencesImplementation and Analysis of communication between Linux kernel space and user space Chen Xin Yang? D
This is a learning note. It mainly analyzes the source code imp2 in Linux kernel space and user space communication implementation and analysis (this article has been reproduced on this site. The source code can be downloaded from the following URL:
Http://www-128.ibm.com/developerworks/cn/linux/l-netlink/imp2.tar.gz TheoryIn Linux Versions later than 2.4, almost all interrupt processes communicate with user-State processes using netlink sockets, such as iprote2 network management tools, netlink is used for interaction with the kernel. Netfilter, the famous kernel package filtering framework, is also changing to netlink in the latest version, it will be one of the main methods for communication between Linux User and kernel. Its communication is based on a process ID, which is generally the ID of the process. When one end of the communication is interrupted, this ID is 0. When netlink socket is used for communication, both parties of the communication are user-State processes, the method of use is similar to message queue. However, one end of the communication is the interruption process, but the Use method is different. The biggest feature of netlink socket is its support for the interrupt process. It no longer requires you to start a kernel program when receiving user space data in the kernel space, instead, it calls the receiving function specified in advance through another Soft Interrupt. Working Principle
(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/pub/attachment/2006/9/835279.gif'); "> here, Soft Interrupt is used instead of the kernel thread to receive data, which ensures real-time data reception. When netlink socket is used for communication between the kernel space and the user space, the method for creating a user space is similar to that for a general socket, but the method for creating a kernel space is different, is the process created when netlink socket implements such communication:
(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/pub/attachment/2006/9/835281.gif'); "> User spaceUser-mode applications use standard sockets to communicate with the kernel, standard socket API functions, socket (), bind (), sendmsg (), recvmsg () and close () it is easy to apply to netlink socket. To create a netlink socket, you need to use the following parameters to call socket (): [table = 400] [tr] [td] socket (AF_NETLINK, SOCK_RAW, netlink_type) [/td] [/tr] [/table] The protocol cluster corresponding to netlink is AF_NETLINK. The second parameter must be SOCK_RAW or SOCK_DGRAM. The third parameter specifies the netlink protocol type, it can be a custom type or a pre-defined type of the kernel: [table = 400] [tr] [td] # define NETLINK_ROUTE 0/* Routing/device hook */# define NETLINK_W1 1/* 1-wire subsystem */# define NETLINK_USERSOCK 2/ * Reserved for user mode socket protocols */# define NETLINK_FIREWALL 3/* Firewalling hook */# define sockets 4/* INET socket monitoring */# define NETLINK_NFLOG 5/* netfilter/iptables ULOG */# define NETLINK_XFRM 6/* ipsec */# define NETLINK_SELINUX 7/* SELinux event specifications */# define NETLINK_ISCSI 8/* Open-iSCSI */# define NETLINK_AUDIT 9/* auditing */# define versions 10 # define NETLINK_CONNECTOR 11 # define NETLINK_NETFILTER 12/* netfilter subsystem */# define versions 13 # define NETLINK_DNRTMSG 14/* DECnet routing messages */# define versions 15/ * Kernel messages to userspace */# define NETLINK_GENERIC 16
[/Td] [/tr]
[/Table] Similarly, the socket returned by the socket function can be called by the bind function: [table = 400] [tr] [td] static int skfd; skfd = socket (PF_NETLINK, SOCK_RAW, NL_IMP2); if (skfd <0) {printf ("can not create a netlink socket \ n"); exit (0 );}
[/Td] [/tr]
[/Table] The bind function needs to bind the Protocol address. The netlink socket address uses the struct sockaddr_nl Structure Description: [table = 400] [tr] [td] struct sockaddr_nl {sa_family_t nl_family; unsigned short nl_pad; _ u32 nl_pid; _ u32 nl_groups ;};
[/Td] [/tr]
[/Table]
The member nl_family is the protocol cluster AF_NETLINK, and the member nl_pad is not currently used. Therefore, always set it to 0, and the member nl_pid is the ID of the process that receives or sends messages, if you want the kernel to process messages or multicast messages, set this field to 0; otherwise, set it to the process ID for message processing. The member nl_groups is used to specify multicast groups. The bind function is used to add the calling process to the multicast group specified by this field. If it is set to 0, the caller is not added to any multicast group:
[Table = 400] [tr] [td] struct sockaddr_nl local; memset (& local, 0, sizeof (local); local. nl_family = AF_NETLINK; local. nl_pid = getpid ();/* Set pid to your own pid value */local. nl_groups = 0;/* bind socket */if (bind (skfd, (struct sockaddr *) & local, sizeof (local ))! = 0) {printf ("bind () error \ n"); return-1;} [/td] [/tr] [/table]
The user space can call the send function cluster to send messages to the kernel, such as sendto and sendmsg. Similarly, you can use struct sockaddr_nl to describe a peer address to be called by the send function, slightly different from the local address, because the peer is the kernel, The nl_pid member needs to be set to 0:
[Table = 400] [tr] [td] struct sockaddr_nl kpeer; memset (& kpeer, 0, sizeof (kpeer); kpeer. nl_family = AF_NETLINK; kpeer. nl_pid = 0; kpeer. nl_groups = 0; [/td] [/tr] [/table] Another problem is the composition of messages sent by the kernel. If we send an IP network packet, the packet structure is "IP packet header + IP data". Similarly, the message structure of netlink is "netlink message header + data ". The Netlink message header uses the struct nlmsghdr structure to describe: [table = 400] [tr] [td] struct nlmsghdr {_ u32 nlmsg_len; /* Length of message */_ b2nlmsg_type;/* Message type */_ b2nlmsg_flags;/* Additional flags */_ u32 nlmsg_seq; /* Sequence number */_ u32 nlmsg_pid;/* Sending process PID */};
[/Td]
[/Tr]
[/Table]
The nlmsg_len field specifies the total length of the message, including the length of the Data part that follows the structure and the size of the structure. Generally, we use the macro NLMSG_LENGTH provided by netlink to calculate the length, you only need to provide the length of the data to be sent to the NLMSG_LENGTH macro. It automatically calculates the total length after Alignment:
/* Calculate the length of the datagram containing the header */
# Define NLMSG_LENGTH (len) + NLMSG_ALIGN (sizeof (struct nlmsghdr )))
/* Byte alignment */
# Define NLMSG_ALIGN (len) + NLMSG_ALIGNTO-1 )&~ (NLMSG_ALIGNTO-1 ))
We can also see a lot of macros provided by netlink. These macros provide great convenience for us to compile netlink macros.
The nlmsg_type field is used to define the message type within the application. It is transparent to the netlink kernel. Therefore, in most cases, it is set to 0. The nlmsg_flags field is used to set the message flag, you can set it to 0, but only some advanced applications (such as netfilter and daemon require it to perform some complex operations). The fields nlmsg_seq and nlmsg_pid are used for application tracing, the former indicates the sequence number, and the latter indicates the ID of the message source process.
Struct msg_to_kernel
/* Custom message header, which only contains the netlink message header */
{
Struct nlmsghdr hdr;
};
Struct msg_to_kernel message;
Memset (& message, 0, sizeof (message ));
Message. hdr. nlmsg_len = NLMSG_LENGTH (0 );
/* Calculate the message. Because only one request message is sent, there is no extra data. Therefore, the data length is 0 */
Message. hdr. nlmsg_flags = 0;
Message. hdr. nlmsg_type = IMP2_U_PID;/* set the custom message type */
Message. hdr. nlmsg_pid = local. nl_pid;/* set the PID of the sender */
In this way, with the local address, peer address, and sent data, you can call the sending function to send messages to the kernel:
/* Send a request */
Sendto (skfd, & message, message. hdr. nlmsg_len, 0,
(Struct sockaddr *) & kpeer, sizeof (kpeer ));
After sending the request, you can call the recv function cluster to receive data from the kernel,
The received data includes the netlink message header and the data to be transmitted:
/* The received data includes the netlink message header and Custom Data Structure */
Struct u_packet_info
{
Struct nlmsghdr hdr;
Struct packet_info icmp_info;
};
Struct u_packet_info info;
While (1)
{
Kpeerlen = sizeof (struct sockaddr_nl );
/* Receive the data returned by the kernel space */
Rcvlen = recvfrom (skfd, & info, sizeof (struct u_packet_info ),
0, (struct sockaddr *) & kpeer, & kpeerlen );
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