This article analyzes in detail the implementation of the chain table structure in the 2.6.x kernel, and explains each chain table operation interface in detail through an instance.
I. Data Structure of linked lists
A linked list is a commonly used data structure for organizing ordered data. It connects a series of data nodes into a data link through a pointer. It is an important implementation method for linear tables. Compared with arrays, the linked list is more dynamic. When creating a linked list, you do not need to know the total amount of data in advance. You can randomly allocate space and efficiently insert or delete data anywhere in the linked list. The overhead of the linked list is mainly the access sequence and the Space Loss of the organizational chain.
Generally, the Linked List data structure should contain at least two domains: data domains and pointer domains. data domains are used to store data and pointer domains are used to establish connections with the next node. According to the organization of the pointer field and the connection form between nodes, the linked list can be divided into single-chain tables, double-chain tables, circular linked lists, and Other types. The following lists the common linked list types:
1. Single-chain table
Figure 1 single-chain table
A single-chain table is the simplest type of linked list. It has only one pointer field pointing to the next node. Therefore, the traversal of a single-chain table can only start from the beginning to the end (usually a null NULL pointer).
2. double-stranded table
Figure 2 double-stranded table
By designing two pointer fields, the dual-chain table can be traversed in two directions, which is different from the single-chain table. If the dependency between the predecessor and the successor is disrupted, a "binary tree" can be formed "; if the frontend of the first node points to the End Node of the linked list and the successor of the End Node points to the first node (the dotted line in 2), a circular linked list is formed. If more pointer fields are designed, to form a variety of complex tree data structures.
3. Circular linked list
The cyclic linked list feature that the tail node points to the first node. The double-loop linked list has been given in the previous section. It is characterized by any node and any data in the two directions can be found in the linked list. If the precursor pointer is removed, it is a single-loop linked list.
A large amount of linked list structures are used in the Linux kernel to organize data, including the device list and Data Organization in various functional modules. Most of these linked lists are implemented in [INCLUDE/Linux/list. H. The subsequent sections of this article will detail the organization and use of this data structure through examples.
II. Implementation of the data structure of Linux 2.6 kernel linked list
Although the 2.6 kernel is used as the basis for the explanation, the linked list structure in the 2.4 kernel is actually no different from that in the 2.6 kernel. The difference is that 2.6 expands the data structure of two linked lists: the read copy Update (RCU) and the hash linked list (hlist ). These two extensions are based on the most basic list structure. Therefore, this article mainly introduces the basic linked list structure, and then briefly introduces RCU and hlist.
The definition of the linked list data structure is very simple (Excerpted from [INCLUDE/Linux/list. H]. All the following code, unless described, is taken from this file ):
struct list_head { struct list_head *next, *prev; }; |
List_headThe structure contains twoList_headStructure pointer Prev and next, it can be seen that the chain table of the kernel has the double-chain table function, in fact, it is usually organized into a double-cycle linked list.
Unlike the double-chain table structure model introduced in Section 1List_headNo data domain. In the Linux kernel linked list, instead of containing data in the linked list structure, it contains linked list nodes in the data structure.
In data structure textbooks, the classic definition of linked lists is usually as follows (using a single-chain table as an example ):
struct list_node { struct list_node *next; ElemTypedata; }; |
Because of elemtype, each data item type needs to define its own linked list structure. Experienced C ++ programmers should know that the <list> in the standard template library uses the C ++ template to abstract the linked list operation interface unrelated to the data item type using the template.
In the Linux kernel linked list, the data that needs to be organized by the linked list usually containsStruct List_headFor example, in [INCLUDE/Linux/netfilter. H], an nf_sockopt_ops structure is defined to describe the getsockopt/setsockopt interface prepared by Netfilter for a protocol family (Struct List_headList) members. The nf_sockopt_ops structure of each protocol family is organized in a linked list through this list member. The header is nf_sockopts (Struct List_head). We can see that this generic linked list structure avoids the trouble of defining your own linked list for each data item type. Linux is simple and practical, and does not seek perfection or standard style, which is fully embodied here.
Figure 3 nf_sockopts linked list
Iii. Linked List Operation Interface
1. Declaration and initialization
In fact, Linux only defines linked list nodes and does not specifically define the linked list header. How can a linked list structure be created? Let's take a lookList_head() This macro:
#define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) |
When we useList_head(Nf_sockopts) When declaring a chain table header named nf_sockopts, its next and Prev pointers are initialized to point to itself, so that we have an empty chain table, in Linux, the next of the header pointer is used to determine whether the linked list is empty:
static inline int list_empty(const struct list_head *head) { return head->next == head; } |
BesidesList_head() In addition to initializing a linked list during macro declaration, Linux also provides an init _List_headMacro is used to initialize the linked list during runtime:
#define INIT_LIST_HEAD(ptr) do { / (ptr)->next = (ptr); (ptr)->prev = (ptr); / } while (0) |
We use init _List_head(& Nf_sockopts) to use it.
2. Insert/delete/merge
A) insert
Two insert operations are available for the linked list: Insert at the header and insert at the end of the table. Linux provides two interfaces for this purpose:
static inline void list_add(struct list_head *new, struct list_head *head); static inline void list_add_tail(struct list_head *new, struct list_head *head); |
Because the Linux linked list is a cyclic table, and the next and Prev of the header point to the first and last nodes in the linked list respectively, The list_add and list_add_tail are not very different. In fact, Linux uses
__list_add(new, head, head->next); |
And
__list_add(new, head->prev, head); |
To implement two interfaces. It can be seen that after the header is inserted after the head, and after the end of the table is inserted after the head-> Prev.
Suppose there is a new nf_sockopt_ops Structure Variable new_sockopt which needs to be added to the nf_sockopts linked list header. We should do this:
list_add(&new_sockopt.list, &nf_sockopts); |
From this we can see that the nf_sockopts linked list records not the address of new_sockopt, but the address of the list element. How can I access new_sockopt through a linked list? The following is a detailed introduction.
B) Delete
static inline void list_del(struct list_head *entry); |
To delete the new_sockopt entry added to the nf_sockopts linked list, perform the following operations:
list_del(&new_sockopt.list); |
The excluded new_sockopt.list, Prev, And next pointers are set to two special values: list_position2 and list_position1, respectively, this setting ensures that node items not in the linked list are inaccessible-Access to list_position1 and list_position2 will cause page faults. Correspondingly, after the list_del_init () function resolves the node from the linked list, it calls list_init_head () to set the node to the empty chain state.
C) Migration
Linux allows you to move a node that originally belongs to a linked list to another linked list. There are two types of nodes inserted into the new linked list:
static inline void list_move(struct list_head *list, struct list_head *head); static inline void list_move_tail(struct list_head *list, struct list_head *head); |
For example, list_move (& new_sockopt.list, & nf_sockopts) will delete new_sockopt from its linked list and link it to the header of nf_sockopts.
D) Merge
In addition to the insert and delete operations on nodes, the Linux linked list also provides the insert function for the entire linked list:
static inline void list_splice(struct list_head *list, struct list_head *head); |
Assume that there are two linked lists with the headers list1 and list2 (bothStruct List_headVariable). When list_splice (& list1, & list2) is called, as long as list1 is not empty, the contents of the list1 linked list will be mounted to the list2 linked list, it is located between list2 and list2.next (the first node of the original list2 table. The new list2 linked list takes the first node of the original list1 table as the first node, while the last node remains unchanged. (The virtual arrow is the next pointer ):
Figure 4 list_splice (& list1, & list2)
After list1 is mounted to list2, the next and Prev of list1 as the original header pointer still point to the original node. To avoid confusion, Linux provides a list_splice_init () function:
static inline void list_splice_init(struct list_head *list, struct list_head *head); |
This function calls init _List_head(List) set list to empty chain.
3. Traverse
Traversal is one of the most common operations of a linked list. To facilitate the core application of a traversal table, the Linux linked list abstracts the traversal operation into several macros. Before introducing rmacro, let's take a look at how to access the data items we actually need from the linked list.
A) from linked list nodes to data item Variables
We know that Linux linked lists only store the data item StructureList_headHow can we use thisList_headWhat if a member accesses node data as its owner? For this reason, Linux provides a list_entry (PTR, type, member) Macro, in which PTR points to the dataList_headThe member pointer, that is, the address value stored in the linked list. type is the data item type, while member is the data item type definition.List_headThe variable name of the member. For example, to access the first nf_sockopt_ops variable in the nf_sockopts linked list, call:
list_entry(nf_sockopts->next, struct nf_sockopt_ops, list); |
Here, "list" is the name of the node member variable defined in the nf_sockopt_ops structure for linked list operations.
The use of list_entry is quite simple. In contrast, its implementation is somewhat difficult:
# Define list_entry (PTR, type, member) container_of (PTR, type, member) container_of macro defined in [INCLUDE/Linux/kernel. h]: # define container_of (PTR, type, member) ({/const typeof (type *) 0)-> member) * _ mptr = (PTR ); /(type *) (char *) _ mptr-offsetof (type, member);}) offsetof macro is defined in [INCLUDE/Linux/stddef. h]: # define offsetof (type, member) (size_t) & (type *) 0)-> Member) |
Size_t is finally defined as unsigned int (i386 ).
Here we use a small technique that uses compiler technology, that is, first obtain the offset of the structure member in the structure, and then obtain the address of the Main Structure Variable Based on the address of the member variable.
Container_of () and offsetof () are not only used for linked list operations. The most interesting thing here is (type *) 0)-> member, it forces the 0 address to "convert" to the type structure pointer, and then accesses the Member member in the type structure. In the container_of macro, it is used to provide the typeof () parameter (typeof () is an extension of GCC, similar to sizeof (), to obtain the data type of member members; in offsetof () the address of this Member member is actually the offset of the Member member from the structure variable in the type data structure.
If this is not easy to understand, take a look at the figure below:
Figure 5 Principle of offsetof () Macro
Given a structure, offsetof (type, member) is a constant. list_entry () uses this constant offset to obtain the variable address of the linked list data item.
B) Bai Lihong
The nf_register_sockopt () function of [net/CORE/netfilter. C] contains the following:
…… struct list_head *i; …… list_for_each(i, &nf_sockopts) { struct nf_sockopt_ops *ops = (struct nf_sockopt_ops *)i; …… } …… |
The function first defines (Struct List_head*) Pointer variable I, and then call list_for_each (I, & nf_sockopts) to traverse. In [INCLUDE/Linux/list. H], the list_for_each () macro is defined as follows: |