内核数据结构之双向循环链表

出于对内核工作效率的好奇,最近在研究内核数据结构。
在此整理一份双向循环链表的文档,并附上相关测试代码。
(后续继续补充其它数据结构及算法)
1.代码最关键部分是my_list.h头文件,里面涉及绝大大部分对链表的处理,如添加、查找、删除、拼接,遍历等。代码整理如下:

/**********************************************************
链表跟数组的不同:
1.链表元素可实现动态创建插入,编译时不用跟数组一样确定具体需要创建多少个元素
2.链表中每个元素创建的时间各不相同,在内存中无需占用连续内存区

根据以上特性:
各元素需要通过某种方式连接到一起,于是每个元素都包含下一个元素的指针,
当有元素加入或者从链表中删除时,调整指向下一个节点的指针就可以。

链表分类:
单向链表 环形单向链表
双向链表 环形双向链表
linux内核采用环形双向链表

使用链表存放数据的理想情况:
需要遍历所有数据或需要动态加入删除数据

Author:gang.li<xfxylg@163.com>
***************************************************************/

#ifndef _LINUX_MYLIST_H
#define _LINUX_MYLIST_H

struct list_head {
     struct list_head *next, *prev;
};

//-------------------------------------------------------------------
#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

#if 1   
    #define INIT_LIST_HEAD(ptr) do { \
        (ptr)->next = (ptr); (ptr)->prev = (ptr); \
    } while (0)
#else   
    static inline void INIT_LIST_HEAD(struct list_head *list)
    {
        list->next = list;
        list->prev = list;
    }
#endif
//------------------------------------------------------------------
static inline void __list_add(struct list_head *new,
                   struct list_head *prev,
                    struct list_head *next)
{
      next->prev = new;
      new->next = next;
      new->prev = prev;
      prev->next = new;
}

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

/**
 * list_add_tail - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
 static inline void list_add_tail(struct list_head *new, struct list_head *head)
 {
      __list_add(new, head->prev, head);
 } 

//-------------------------------------------------------------------

#define prefetch(x) __builtin_prefetch(x)

/**
  * list_for_each    -   iterate over a list
  * @pos:    the &struct list_head to use as a loop cursor.
  * @head:   the head for your list.
  * 遍历链表,pos用来指向当前项,head是提供需要遍历链表的头
  */
#define list_for_each(pos, head) \
     for (pos = (head)->next; prefetch(pos->next), pos != (head); \
             pos = pos->next)
/**
 * list_for_each_prev   -   iterate over a list backwards
 * @pos:    the &struct list_head to use as a loop counter.
 * @head:   the head for your list.
 */
#define list_for_each_prev(pos, head) \
    for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \
            pos = pos->prev)

/**
  * list_entry - get the struct for this entry
  * @ptr:    the &struct list_head pointer.
  * @member: the name of the list_struct within the struct.
  * 获取链表条目结构指针
  */
#define list_entry(ptr, type, member) \
       container_of(ptr, type, member)

#ifndef container_of
/**
 * container_of - cast a member of a structure out to the containing structure
 *     
 * @ptr:        the pointer to the member.
 * @type:       the type of the container struct this is embedded in.
 * @member:     the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({                      \
         const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
          (type *)( (char *)__mptr - offsetof(type,member) );})
#endif

#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

//-----------------------------------------------------------------------

/**
 * list_for_each_safe - iterate over a list safe against removal of list entry
 * @pos:    the &struct list_head to use as a loop cursor.
 * @n:      another &struct list_head to use as temporary storage
 * @head:   the head for your list.
 * 遍历链表,安全删除链表条目
 */
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

/**
 * list_for_each_entry  -   iterate over list of given type
 * @pos:    the type * to use as a loop counter.
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 * pos:包含list_head节点的对象指针(list_entry宏返回指针值)
 * head:需要遍历的链表
 * member:pos指针所指对象,成员(struct list_head)的变量名
 */
#define list_for_each_entry(pos, head, member)              \
    for (pos = list_entry((head)->next, typeof(*pos), member);  \
         prefetch(pos->member.next), &pos->member != (head);    \
         pos = list_entry(pos->member.next, typeof(*pos), member))

/**
 * list_for_each_entry_reverse - iterate backwards over list of given type.
 * @pos:    the type * to use as a loop counter.
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 * 与list_for_each_entry对应,为反向遍历
 */
#define list_for_each_entry_reverse(pos, head, member)          \
    for (pos = list_entry((head)->prev, typeof(*pos), member);  \
         prefetch(pos->member.prev), &pos->member != (head);    \
         pos = list_entry(pos->member.prev, typeof(*pos), member))

/**
 * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
 * @pos:    the type * to use as a loop counter.
 * @n:      another type * to use as temporary storage
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 */
#define list_for_each_entry_safe(pos, n, head, member)          \
    for (pos = list_entry((head)->next, typeof(*pos), member),  \
        n = list_entry(pos->member.next, typeof(*pos), member); \
         &pos->member != (head);                    \
         pos = n, n = list_entry(n->member.next, typeof(*n), member))


#define list_for_each_entry_safe_reverse(pos, n, head, member)          \
    for (pos = list_entry((head)->prev, typeof(*pos), member),  \
        n = list_entry(pos->member.prev, typeof(*pos), member); \
         &pos->member != (head);                    \
         pos = n, n = list_entry(n->member.prev, typeof(*n), member))       
 /*
  * Architectures might want to move the poison pointer offset
  * into some well-recognized area such as 0xdead000000000000,
  * that is also not mappable by user-space exploits:
  */
 #ifdef CONFIG_ILLEGAL_POINTER_VALUE
 # define POISON_POINTER_DELTA _AC(CONFIG_ILLEGAL_POINTER_VALUE, UL)
 #else
 # define POISON_POINTER_DELTA 0
 #endif

 /*
  * These are non-NULL pointers that will result in page faults
  * under normal circumstances, used to verify that nobody uses
  * non-initialized list entries.
  */ 
 #define LIST_POISON1  ((void *) 0x00100100 + POISON_POINTER_DELTA)
 #define LIST_POISON2  ((void *) 0x00200200 + POISON_POINTER_DELTA)

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
     next->prev = prev;
     prev->next = next;
}

/**
 * list_del - deletes entry from list.
 * @entry: the element to delete from the list.
 * Note: list_empty on entry does not return true after this, the entry is
 * in an undefined state.
 * 删除链表特定元素
 */
static inline void list_del(struct list_head *entry)
{
     __list_del(entry->prev, entry->next);
     entry->next = LIST_POISON1;
     entry->prev = LIST_POISON2;
}

/**
 * list_move - delete from one list and add as another's head
 * @list: the entry to move
 * @head: the head that will precede our entry
 * 从一个链表中移除节点list项,然后将其加入到另一链表的head节点后
 */
static inline void list_move(struct list_head *list, struct list_head *head)
{
        __list_del(list->prev, list->next);
        list_add(list, head);
}

/**
 * list_move_tail - delete from one list and add as another's tail
 * @list: the entry to move
 * @head: the head that will follow our entry
 * 从一个链表中移除节点list项,然后将其加入到另一链表的末尾
 */
static inline void list_move_tail(struct list_head *list,
                  struct list_head *head)
{
        __list_del(list->prev, list->next);
        list_add_tail(list, head);
}

//-------------------------------------------------------------------------

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static inline int list_empty(const struct list_head *head)
{
    return head->next == head;
}


static inline void __list_splice(struct list_head *list,
                 struct list_head *head)
{
    struct list_head *first = list->next;
    struct list_head *last = list->prev;
    struct list_head *at = head->next;

    first->prev = head;
    head->next = first;

    last->next = at;
    at->prev = last;
}

/**
 * list_splice - join two lists
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 * 合并两个链表,将list指向的链表插入到指定链表的head元素后面
 */
static inline void list_splice(struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
        __list_splice(list, head);
}

/**
 * list_splice_init - join two lists and reinitialise the emptied list.
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 *
 * The list at @list is reinitialised
 */
static inline void list_splice_init(struct list_head *list,
                    struct list_head *head)
{
    if (!list_empty(list)) {
        __list_splice(list, head);
        INIT_LIST_HEAD(list);
    }
}

#endif

2.编写的相关测试代码在main.c里面,如下:

#include <stdio.h>
#include <stdlib.h>
#include "./my_list.h"

typedef struct _data_node{
    int data;
    struct list_head list;
}data_node,*pnode;


pnode create_list()
{

    /*create double dir list,init head ptr,waring:actually data section no use*/    
    pnode head= (pnode)malloc(sizeof(data_node));   
    if (head == NULL) {
        printf("file,%s line,%d:malloc error!\n",__FILE__,__LINE__);
        exit(1);    
    }   
    INIT_LIST_HEAD(&head->list);

    return head;
}

pnode create_node(int data)
{
    /*create double dir list,init head ptr,waring:actually data section no use*/    
   pnode node = (pnode)malloc(sizeof(data_node));   
    if (node == NULL) {
        printf("file,%s line,%d:malloc error!\n",__FILE__,__LINE__);
        exit(1);    
    }   
    memset(node,0,sizeof(data_node));
    node->data = data;

    return node;
}

int main(int argc , int **argv)
{
    if(argc  !=  2){
        printf("%s parm input fail!!\n",argv[0]);
    }

    int num = atoi(argv[1]);
    srand(time(NULL));

    printf("once create list :");
    pnode head=create_list();
    int i=0;
    for(i=0; i<num; i++){
        pnode new_node= create_node(rand()%500);
        printf("%d ",new_node->data);
        list_add(&new_node->list,&head->list);
        //list_add_tail(&new_node->list, &list_2->list);
    }
    printf("\n\npositive traverse:");

    pnode entry;
    list_for_each_entry(entry,&head->list,list){
        printf("%d ",entry->data);  
    }
    printf("\nreverse traverse :");
    list_for_each_entry_reverse(entry,&head->list,list){
        printf("%d ",entry->data);  
    }
    printf("\n");



#if 1
    int del;
    printf("delete appoint node :");
    scanf("%d",&del);

    /*delete list appoint node*/
    struct list_head  *pos=NULL,*n=NULL;
    list_for_each_safe(pos,n,&head->list) {     
        entry = list_entry(pos, struct _data_node ,list);
        if(entry->data == del){
            //printf("num %d has removed from the list!\n",entry->data);        
            list_del(pos);  
            /*warning:每次安全删除链表条目后,必须free条目指针*/      
            free(entry);entry=NULL; 
        }else{
            //printf("\nappoint node: %d not exist\n ",del);    
            printf("%d ",entry->data);  
        }

    }   
    printf("\n\n");
#endif
#if 0   
    /*delete list all node*/
    pnode entry_tmp, pnext;
    list_for_each_entry_safe(entry_tmp,pnext,&head->list,list){
        printf("safe iterate over del   num %d has removed from the list!\n",entry_tmp->data);  
        free(entry_tmp);entry_tmp=NULL;
    }
#endif

#if 1
    printf("\ntwice create list:");
    pnode head_new=create_list();
    for(i=0; i<num; i++){
        pnode node_new= create_node(rand()%500);
        printf("%d ",node_new->data);
        list_add(&node_new->list,&head_new->list);
        //list_add_tail(&new_node->list, &list_2->list);
    }

    printf("\n\npositive traverse:");
    pnode entry_new;
    list_for_each_entry(entry_new,&head_new->list,list){
        printf("%d ",entry_new->data);  
    }
    printf("\n");

    /*two list splice*/
    list_splice(&head_new->list, &head->list);
    printf("two list splice back input :");
    list_for_each_entry(entry_new,&head->list,list){
        printf("%d ",entry_new->data);  
    }
    printf("\n"); 
#endif
}

3.Makefile文件

CC = gcc
RM = rm

CFLAGS = 

TARGETS := list_test
#OBJS = stu.o
OBJS = main.o

all:clean $(OBJS)
    $(CC) $(CFLAGS) -o $(TARGETS) $(OBJS)

%.o:%.c
    $(CC) -c -o $@ $(CFLAGS) $<
    @echo "gcc" $<

clean:
    -$(RM) -f *.o
    -$(RM) -f $(TARGETS)

在同一级目录下,添加以上三个文件,可直接编译运行,可根据个人需要添加相关测试代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值