1 链表

链表是 linux 内核中最简单,同时也是应用最广泛的数据结构。内核中定义的是双向链表。

1.1 头文件简介

内核中关于链表定义的代码位于: include/linux/list.h。list.h 文件中对每个函数都有注释,其实刚开始只要先了解一个常用的链表操作(追加,删除,遍历)的实现方法,其他方法基本都是基于这些常用操作的。

1.2 链表代码的注意点

在阅读 list.h 文件之前,有一点必须注意:linux 内核中的链表使用方法和一般数据结构中定义的链表是有所不同的
一般的双向链表一般是如下的结构,

  • 有个单独的头结点 (head)
  • 每个节点 (node) 除了包含必要的数据之外,还有 2 个指针(pre,next)
  • pre 指针指向前一个节点 (node),next 指针指向后一个节点 (node)
  • 头结点 (head) 的 pre 指针指向链表的最后一个节点
  • 最后一个节点的 next 指针指向头结点 (head)

imgclip.png

传统的链表有个最大的缺点就是不好共通化,因为每个 node 中的 data1,data2 等等都是不确定的 (无论是个数还是类型)。linux 中的链表巧妙的解决了这个问题,linux 的链表不是将用户数据保存在链表节点中,而是将链表节点保存在用户数据中。
linux 的链表节点只有 2 个指针 (pre 和 next),这样的话,链表的节点将独立于用户数据之外,便于实现链表的共同操作。
imgclip_1.png

和传统的链表不同,linux 的链表节点 (node) 中没有包含用户的用户 data1,data2 等。整个 list.h 文件中,最复杂的代码就是获取用户数据的宏定义

  1. //type是包含用户数据和链表节点的结构体, ptr 指向 type 中链表节点的指针,member是 type 中定义链表节点是用的名字
  2. /*struct student
  3. {
  4. int id;
  5. char* name;
  6. struct list_head list;
  7. };
  8. * type 是 struct student
  9. * ptr 是指向 stuct list 的指针,也就是指向 member 类型的指针
  10. * member 就是 list
  11. */
  12. #define list_entry(ptr, type, member) \
  13. container_of(ptr, type, member)
  14. #define container_of(ptr, type, member) ({ \
  15. const typeof(((type *)0)->member)*__mptr = (ptr); \
  16. (type *)((char *)__mptr - offsetof(type, member)); })

下面分析一下 container_of 宏:

  1. // 步骤1:将数字0强制转型为type*,然后取得其中的member元素
  2. ((type *)0)->member // 相当于((struct student *)0)->list
  3. // 步骤2:定义一个临时变量__mptr,并将其也指向ptr所指向的链表节点
  4. const typeof(((type *)0)->member)*__mptr = (ptr);
  5. // 步骤3:计算member字段距离type中第一个字段的距离,也就是type地址和member地址之间的差
  6. // offset(type, member)也是一个宏,定义如下:
  7. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  8. // 步骤4:将__mptr的地址 - type地址和member地址之间的差,其实也就是获取type的地址

步骤 1,2,4 比较容易理解,下面的图以 sturct student 为例进行说明步骤 3:

imgclip_2.png

1.3 使用示例

构造了一个内核模块来实际使用一下内核中的链表,代码在 Ubuntu18.04 上运行通过。

  1. #include <linux/init.h>
  2. #include <linux/slab.h>
  3. #include <linux/module.h>
  4. #include <linux/kernel.h>
  5. #include <linux/list.h>
  6. MODULE_LICENSE("Dual BSD/GPL");
  7. struct student
  8. {
  9. int id;
  10. char* name;
  11. struct list_head list;
  12. };
  13. void print_student(struct student*);
  14. static int testlist_init(void)
  15. {
  16. struct student *stu1, *stu2, *stu3, *stu4;
  17. struct student *stu;
  18. // init a list head
  19. LIST_HEAD(stu_head);
  20. // init four list nodes
  21. stu1 = kmalloc(sizeof(*stu1), GFP_KERNEL);
  22. stu1->id = 1;
  23. stu1->name = "wyb";
  24. INIT_LIST_HEAD(&stu1->list);
  25. stu2 = kmalloc(sizeof(*stu2), GFP_KERNEL);
  26. stu2->id = 2;
  27. stu2->name = "wyb2";
  28. INIT_LIST_HEAD(&stu2->list);
  29. stu3 = kmalloc(sizeof(*stu3), GFP_KERNEL);
  30. stu3->id = 3;
  31. stu3->name = "wyb3";
  32. INIT_LIST_HEAD(&stu3->list);
  33. stu4 = kmalloc(sizeof(*stu4), GFP_KERNEL);
  34. stu4->id = 4;
  35. stu4->name = "wyb4";
  36. INIT_LIST_HEAD(&stu4->list);
  37. // add the four nodes to head
  38. list_add (&stu1->list, &stu_head);
  39. list_add (&stu2->list, &stu_head);
  40. list_add (&stu3->list, &stu_head);
  41. list_add (&stu4->list, &stu_head);
  42. // print each student from 4 to 1
  43. list_for_each_entry(stu, &stu_head, list)
  44. {
  45. print_student(stu);
  46. }
  47. // print each student from 1 to 4
  48. list_for_each_entry_reverse(stu, &stu_head, list)
  49. {
  50. print_student(stu);
  51. }
  52. // delete a entry stu2
  53. list_del(&stu2->list);
  54. list_for_each_entry(stu, &stu_head, list)
  55. {
  56. print_student(stu);
  57. }
  58. // replace stu3 with stu2
  59. list_replace(&stu3->list, &stu2->list);
  60. list_for_each_entry(stu, &stu_head, list)
  61. {
  62. print_student(stu);
  63. }
  64. return 0;
  65. }
  66. static void testlist_exit(void)
  67. {
  68. printk(KERN_ALERT "*************************\n");
  69. printk(KERN_ALERT "testlist is exited!\n");
  70. printk(KERN_ALERT "*************************\n");
  71. }
  72. void print_student(struct student *stu)
  73. {
  74. printk (KERN_ALERT "======================\n");
  75. printk (KERN_ALERT "id =%d\n", stu->id);
  76. printk (KERN_ALERT "name=%s\n", stu->name);
  77. printk (KERN_ALERT "======================\n");
  78. }
  79. module_init(testlist_init);
  80. module_exit(testlist_exit);

Makefile:

  1. obj-m := testlist.o
  2. #generate the path
  3. CURRENT_PATH:=$(shell pwd)
  4. #the current kernel version number
  5. LINUX_KERNEL:=$(shell uname -r)
  6. #the absolute path
  7. LINUX_KERNEL_PATH:=/usr/src/linux-headers-$(LINUX_KERNEL) #直接用发行版中的linux源码,不用再下载linux内核源码。注意,每个linux发行版的目录不一定一样
  8. #complie object
  9. all:
  10. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  11. clean:
  12. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean

安装, 卸载内核模块以及查看内核模块的运行结果:

  1. insmod testlist.ko
  2. rmmod testlist
  3. dmesg | tail -100

2 队列

内核中的队列是以字节形式保存数据的,所以获取数据的时候,需要知道数据的大小。如果从队列中取得数据时指定的大小不对的话,取得数据会不完整或过大。

2.1 头文件简介

内核中关于队列定义的头文件位于:linux/kfifo.h。头文件中定义的函数的实现位于:kernel/kfifo.c

2.2 队列代码的注意点

内核队列编程需要注意的是:

  • 队列的 size 在初始化时,始终设定为 2 的 n 次方
  • 使用队列之前将队列结构体中的锁 (spinlock) 释放

2.3 使用示例

构造了一个内核模块来实际使用一下内核中的队列,代码在ubuntu18.04上编译不过,需要使用2.6的内核。

  1. #include "kn_common.h"
  2. MODULE_LICENSE("Dual BSD/GPL");
  3. struct student
  4. {
  5. int id;
  6. char* name;
  7. };
  8. static void print_student(struct student*);
  9. static int testkfifo_init(void)
  10. {
  11. struct kfifo *fifo;
  12. struct student *stu1, *stu2, *stu3, *stu4;
  13. struct student *stu_tmp;
  14. char* c_tmp;
  15. int i;
  16. // !!importent init a unlocked lock
  17. spinlock_t sl = SPIN_LOCK_UNLOCKED;
  18. // init kfifo
  19. fifo = kfifo_alloc(4*sizeof(struct student), GFP_KERNEL, &sl);
  20. stu1 = kmalloc(sizeof(struct student), GFP_KERNEL);
  21. stu1->id = 1;
  22. stu1->name = "wyb1";
  23. kfifo_put(fifo, (char *)stu1, sizeof(struct student));
  24. stu2 = kmalloc(sizeof(struct student), GFP_KERNEL);
  25. stu2->id = 1;
  26. stu2->name = "wyb2";
  27. kfifo_put(fifo, (char *)stu2, sizeof(struct student));
  28. stu3 = kmalloc(sizeof(struct student), GFP_KERNEL);
  29. stu3->id = 1;
  30. stu3->name = "wyb3";
  31. kfifo_put(fifo, (char *)stu3, sizeof(struct student));
  32. stu4 = kmalloc(sizeof(struct student), GFP_KERNEL);
  33. stu4->id = 1;
  34. stu4->name = "wyb4";
  35. kfifo_put(fifo, (char *)stu4, sizeof(struct student));
  36. c_tmp = kmalloc(sizeof(struct student), GFP_KERNEL);
  37. printk(KERN_ALERT "current fifo length is : %d\n", kfifo_len(fifo));
  38. for (i=0; i < 4; i++) {
  39. kfifo_get(fifo, c_tmp, sizeof(struct student));
  40. stu_tmp = (struct student *)c_tmp;
  41. print_student(stu_tmp);
  42. printk(KERN_ALERT "current fifo length is : %d\n", kfifo_len(fifo));
  43. }
  44. printk(KERN_ALERT "current fifo length is : %d\n", kfifo_len(fifo));
  45. kfifo_free(fifo);
  46. kfree(c_tmp);
  47. return 0;
  48. }
  49. static void print_student(struct student *stu)
  50. {
  51. printk(KERN_ALERT "=========================\n");
  52. print_current_time(1);
  53. printk(KERN_ALERT "id = %d\n", stu->id);
  54. printk(KERN_ALERT "name = %s\n", stu->name);
  55. printk(KERN_ALERT "=========================\n");
  56. }
  57. static void testkfifo_exit(void)
  58. {
  59. printk(KERN_ALERT "*************************\n");
  60. printk(KERN_ALERT "testkfifo is exited!\n");
  61. printk(KERN_ALERT "*************************\n");
  62. }
  63. module_init(testkfifo_init);
  64. module_exit(testkfifo_exit);

其中引用的 kn_common.h 文件:

  1. #include <linux/init.h>
  2. #include <linux/slab.h>
  3. #include <linux/module.h>
  4. #include <linux/kernel.h>
  5. #include <linux/kfifo.h>
  6. #include <linux/time.h>
  7. void print_current_time(int);

kn_common.h 对应的 kn_common.c:

  1. #include "kn_common.h"
  2. void print_current_time(int is_new_line)
  3. {
  4. struct timeval *tv;
  5. struct tm *t;
  6. tv = kmalloc(sizeof(struct timeval), GFP_KERNEL);
  7. t = kmalloc(sizeof(struct tm), GFP_KERNEL);
  8. do_gettimeofday(tv);
  9. time_to_tm(tv->tv_sec, 0, t);
  10. printk(KERN_ALERT "%ld-%d-%d %d:%d:%d",
  11. t->tm_year + 1900,
  12. t->tm_mon + 1,
  13. t->tm_mday,
  14. (t->tm_hour + 8) % 24,
  15. t->tm_min,
  16. t->tm_sec);
  17. if (is_new_line == 1)
  18. printk(KERN_ALERT "\n");
  19. kfree(tv);
  20. kfree(t);
  21. }

Makefile:

  1. obj-m += fifo.o
  2. fifo-objs := testkfifo.o kn_common.o
  3. #generate the path
  4. CURRENT_PATH:=$(shell pwd)
  5. #the current kernel version number
  6. LINUX_KERNEL:=$(shell uname -r)
  7. #the absolute path
  8. LINUX_KERNEL_PATH:=/usr/src/kernels/$(LINUX_KERNEL)
  9. #complie object
  10. all:
  11. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  12. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c .tmp_versions *.unsigned
  13. #clean
  14. clean:
  15. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c *.ko .tmp_versions *.unsigned

安装, 卸载内核模块以及查看内核模块的运行结果:

  1. <pre>insmod fifo.ko
  2. rmmod fifo
  3. dmesg | tail -40</pre>

3. 映射

映射的有点像其他语言 (C 或者 python) 中的字典类型,每个唯一的 id 对应一个自定义的数据结构。

3.1 头文件简介

内核中关于映射定义的头文件位于:linux/idr.h。头文件中定义的函数的实现位于:lib/idr.c

3.2 映射代码的注意点

映射的使用需要注意的是,给自定义的数据结构申请一个 id 的时候,不能直接申请 id,先要分配 id(函数 idr_pre_get),分配成功后,再获取一个 id(函数 idr_get_new)。
idr 的结构比较复杂,但是 csdn 上有篇介绍 linux idr 结构的博客写的挺好,图文并茂:http://blog.csdn.net/paomadi/article/details/8539794

3.3 使用示例

构造了一个内核模块来实际使用一下内核中的映射,代码在ubuntu18.04上编译不过,需要使用2.6的内核。

  1. #include<linux/idr.h>
  2. #include "kn_common.h"
  3. MODULE_LICENSE("Dual BSD/GPL");
  4. struct student
  5. {
  6. int id;
  7. char* name;
  8. };
  9. static int print_student(int, void*, void*);
  10. static int testidr_init(void)
  11. {
  12. DEFINE_IDR(idp);
  13. struct student *stu[4];
  14. // struct student *stu_tmp;
  15. int id, ret, i;
  16. // init 4 struct student
  17. for (i=0; i<4; i++) {
  18. stu[i] = kmalloc(sizeof(struct student), GFP_KERNEL);
  19. stu[i]->id = i;
  20. stu[i]->name = "wyb";
  21. }
  22. // add 4 student to idr
  23. print_current_time(0);
  24. for (i=0; i < 4; i++) {
  25. do {
  26. if (!idr_pre_get(&idp, GFP_KERNEL))
  27. return -ENOSPC;
  28. ret = idr_get_new(&idp, stu[i], &id);
  29. printk(KERN_ALERT "id=%d\n", id);
  30. } while(ret == -EAGAIN);
  31. }
  32. // display all student in idr
  33. idr_for_each(&idp, print_student, NULL);
  34. idr_destroy(&idp);
  35. kfree(stu[0]);
  36. kfree(stu[1]);
  37. kfree(stu[2]);
  38. kfree(stu[3]);
  39. return 0;
  40. }
  41. static int print_student(int id, void *p, void *data)
  42. {
  43. struct student* stu = p;
  44. printk(KERN_ALERT "=========================\n");
  45. print_current_time(0);
  46. printk(KERN_ALERT "id = %d\n", stu->id);
  47. printk(KERN_ALERT "name = %s\n", stu->name);
  48. printk(KERN_ALERT "=========================\n");
  49. return 0;
  50. }
  51. static void testidr_exit(void)
  52. {
  53. printk(KERN_ALERT "*************************\n");
  54. print_current_time(0);
  55. printk(KERN_ALERT "testidr is exited!\n");
  56. printk(KERN_ALERT "*************************\n");
  57. }
  58. module_init(testidr_init);
  59. module_exit(testidr_exit);

注:其中用到的 kn_common.h 和 kn_common.c 文件与队列的示例中一样。

Makefile:

  1. obj-m += idr.o
  2. idr-objs := testidr.o kn_common.o
  3. #generate the path
  4. CURRENT_PATH:=$(shell pwd)
  5. #the current kernel version number
  6. LINUX_KERNEL:=$(shell uname -r)
  7. #the absolute path
  8. LINUX_KERNEL_PATH:=/usr/src/kernels/$(LINUX_KERNEL)
  9. #complie object
  10. all:
  11. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  12. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c .tmp_versions *.unsigned
  13. #clean
  14. clean:
  15. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c *.ko .tmp_versions *.unsigned

安装, 卸载内核模块以及查看内核模块的运行结果:

  1. <pre>insmod idr.ko
  2. rmmod idr
  3. dmesg | tail -30</pre>

4 红黑树

红黑树由于节点颜色的特性,保证其是一种自平衡的二叉搜索树。红黑树的一系列规则虽然实现起来比较复杂,但是遵循起来却比较简单,而且红黑树的插入,删除性能也还不错。
红黑树必须满足的规则:

  • 所有节点都有颜色,要么红色,要么黑色
  • 根节点是黑色,所有叶子节点也是黑色
  • 叶子节点中不包含数据
  • 非叶子节点都有 2 个子节点
  • 如果一个节点是红色,那么它的父节点和子节点都是黑色的
  • 从任何一个节点开始,到其下叶子节点的路径中都包含相同数目的黑节点

红黑树中最长的路径就是红黑交替的路径,最短的路径是全黑节点的路径,再加上根节点和叶子节点都是黑色,从而可以保证红黑树中最长路径的长度不会超过最短路径的 2 倍。

4.1 头文件简介

内核中关于红黑树定义的头文件位于:linux/rbtree.h。头文件中定义的函数的实现位于:lib/rbtree.c

4.2 红黑树代码的注意点

内核中红黑树的使用和链表 (list) 有些类似,是将红黑树的节点放入自定义的数据结构中来使用的。
首先需要注意的一点是红黑树节点的定义:

  1. struct rb_node
  2. {
  3. unsigned long rb_parent_color;
  4. #define RB_RED 0
  5. #define RB_BLACK 1
  6. struct rb_node *rb_right;
  7. struct rb_node *rb_left;
  8. } __attribute__((aligned(sizeof(long))));

刚开始看到这个定义的时候,我觉得很奇怪,等到看懂了之后,才知道原来作者巧妙的利用内存对齐来将 2 个内容存入到一个字段中。

字段rb_parent_color 中保存了 2 个信息:

  1. 父节点的地址
  2. 本节点的颜色

这 2 个信息是如何存入一个字段的呢?主要在于__attribute__((aligned(sizeof(long))));,这行代码的意思就是 struct rbnode 在内存中的地址需要按照 4 bytes 或者 8 bytes 对齐(sizeof(long) 在 32bit 系统中是 4 bytes,在 64bit 系统中是 8 bytes)。
struct rb_node 的地址按 4 bytes 对齐,意味着分配的地址都是 4 的倍数。4 的二进制为 100 ,所以申请分配的 struct rb_node 的地址的最后 2 位始终是零,struct rb_node 的字段 rb_parent_color 就是利用最后一位来保存节点的颜色信息的。

明白了这点之后,rb_tree.h 中很多宏的定义也就很好懂了。

  1. /* rb_parent_color 保存了父节点的地址和本节点的颜色 */
  2. /* 将 rb_parent_color 的最后2位置成0,即将颜色信息去掉,剩下的就是parent节点的地址 */
  3. #define rb_parent(r) ((struct rb_node *)((r)->rb_parent_color & ~3))
  4. /* 取得 rb_parent_color 二进制表示的最后一位,即用于保存颜色信息的那一位 */
  5. #define rb_color(r) ((r)->rb_parent_color & 1)
  6. /* 将 rb_parent_color 二进制表示的最后一位置为0,即置为红色 */
  7. #define rb_set_red(r) do { (r)->rb_parent_color &= ~1; } while (0)
  8. /* 将 rb_parent_color 二进制表示的最后一位置为1,即置为黑色 */
  9. #define rb_set_black(r) do { (r)->rb_parent_color |= 1; } while (0)

还有需要重点看的就是 rb_tree.c 中的 5 个函数,下面对这 5 个函数进行一些注释:

  1. 函数 1:左旋操作,当右子树的长度过大导致树不平衡时,进行左旋操作
  1. /*
  2. * 左旋操作其实就3个动作:见图left
  3. * 1\. node的右子树关联到right的左子树
  4. * 2\. right的左子树关联到node
  5. * 3\. right取代node的位置
  6. * 其他带代码都是一些相应的parent指针的变化
  7. */
  8. static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)
  9. {
  10. /* 初始化相对于node节点的父节点(图中的P)和右节点(图中的R) */
  11. struct rb_node *right = node->rb_right;
  12. struct rb_node *parent = rb_parent(node);
  13. /* 步骤1 */
  14. if ((node->rb_right = right->rb_left))
  15. rb_set_parent(right->rb_left, node);
  16. /* 步骤2 */
  17. right->rb_left = node;
  18. rb_set_parent(right, parent);
  19. /* node的parent NOT NULL 时,right取代原先的node的位置 */
  20. if (parent)
  21. {
  22. if (node == parent->rb_left)
  23. parent->rb_left = right;
  24. else
  25. parent->rb_right = right;
  26. }
  27. /* node的parent NULL 时,说明node原先时root节点,将新的root指向root即可 */
  28. else
  29. root->rb_node = right;
  30. rb_set_parent(node, right);
  31. }

左旋操作图解:

imgclip_3.png

  1. 函数 2:右旋操作,和左旋操作类似。
  2. 函数 3:追加节点后,设置此节点的颜色。
  1. /*
  2. * 本函数没有插入节点的功能,只是在插入新节点后,设置新节点的颜色,从而保证红黑树的平衡性。
  3. * 新插入的节点默认都是红色的。
  4. *
  5. * 下面的代码看着复杂,其实只要时时记住红黑树的几个重要特性,就会发现下面的都是在尽量保持住红黑树的这些特性。
  6. * 1\. 无论从哪个节点开始,到其叶子节点的路径中包含的黑色节点个数时一样的
  7. * 2\. 不能有连续的2个红色节点,即父节点和子节点不能同时为红色
  8. * 所以最简单的情况就是:插入节点的父节点是黑色的。那么插入一个红节点后不会有任何影响。
  9. * 3\. 左旋操作有减少右子树高度的作用
  10. * 4\. 同理,右旋操作有减少左子树高度的作用
  11. */
  12. void rb_insert_color(struct rb_node *node, struct rb_root *root)
  13. {
  14. struct rb_node *parent, *gparent;
  15. while ((parent = rb_parent(node)) && rb_is_red(parent))
  16. {
  17. gparent = rb_parent(parent);
  18. /* parent 是 gparent的左子树时 */
  19. if (parent == gparent->rb_left)
  20. {
  21. {
  22. /* gparent的左右子树的黑色节点都增加一个,仍然平衡 */
  23. register struct rb_node *uncle = gparent->rb_right;
  24. if (uncle && rb_is_red(uncle))
  25. {
  26. rb_set_black(uncle);
  27. rb_set_black(parent);
  28. rb_set_red(gparent);
  29. node = gparent;
  30. continue;
  31. }
  32. }
  33. /* node为parent右子树时 */
  34. if (parent->rb_right == node)
  35. {
  36. register struct rb_node *tmp;
  37. /* 左旋后,parent的位置被node取代,然后再交换parent和node的位置,
  38. * 相当于node是parent的左子树
  39. * 由于node和parent都是红色(否则到不了这一步),parent左右子树的黑色节点数仍然是相等的
  40. */
  41. __rb_rotate_left(parent, root);
  42. tmp = parent;
  43. parent = node;
  44. node = tmp;
  45. }
  46. /* parent 红->黑,gparent左子树比右子树多一个黑色节点
  47. * 右旋后,gparent左子树高度减一,减少的节点即parent,减少了一个黑色节点,parent变为新的gparent。
  48. * 所以右旋后,新的gparent的左右子树的黑色节点数再次平衡了
  49. */
  50. rb_set_black(parent);
  51. rb_set_red(gparent);
  52. __rb_rotate_right(gparent, root);
  53. /* parent 是 gparent的右子树时,和上面的过程类似 */
  54. } else {
  55. {
  56. register struct rb_node *uncle = gparent->rb_left;
  57. if (uncle && rb_is_red(uncle))
  58. {
  59. rb_set_black(uncle);
  60. rb_set_black(parent);
  61. rb_set_red(gparent);
  62. node = gparent;
  63. continue;
  64. }
  65. }
  66. if (parent->rb_left == node)
  67. {
  68. register struct rb_node *tmp;
  69. __rb_rotate_right(parent, root);
  70. tmp = parent;
  71. parent = node;
  72. node = tmp;
  73. }
  74. rb_set_black(parent);
  75. rb_set_red(gparent);
  76. __rb_rotate_left(gparent, root);
  77. }
  78. }
  79. rb_set_black(root->rb_node);
  80. }
  1. 函数 4:删除一个节点,并且调整删除后各节点的颜色。其中调整节点颜色其实是另一个单独的函数。
  1. /* 删除节点时,如果被删除的节点左子树==NULL或右子树==NULL或左右子树都==NULL
  2. * 那么只要把被删除节点的左子树或右子树直接关联到被删节点的父节点上即可,剩下的就是调整各节点颜色。
  3. * 只有被删节点是黑色才需要调整颜色,因为删除红色节点不影响红黑树的特性。
  4. *
  5. * 被删节点左右子树都存在的情况下,其实就是用中序遍历中被删节点的下一个节点来替代被删节点。
  6. * 代码中的操作只是将各个指针指向新的位置而已。
  7. */
  8. void rb_erase(struct rb_node *node, struct rb_root *root)
  9. {
  10. struct rb_node *child, *parent;
  11. int color;
  12. if (!node->rb_left)
  13. child = node->rb_right;
  14. else if (!node->rb_right)
  15. child = node->rb_left;
  16. else
  17. {
  18. struct rb_node *old = node, *left;
  19. /* 寻找中序遍历中被删节点的下一个节点 */
  20. node = node->rb_right;
  21. while ((left = node->rb_left) != NULL)
  22. node = left;
  23. /* 替换要删除的节点old */
  24. if (rb_parent(old)) {
  25. if (rb_parent(old)->rb_left == old)
  26. rb_parent(old)->rb_left = node;
  27. else
  28. rb_parent(old)->rb_right = node;
  29. } else
  30. root->rb_node = node;
  31. child = node->rb_right;
  32. parent = rb_parent(node);
  33. color = rb_color(node);
  34. if (parent == old) {
  35. parent = node;
  36. } else {
  37. if (child)
  38. rb_set_parent(child, parent);
  39. parent->rb_left = child;
  40. node->rb_right = old->rb_right;
  41. rb_set_parent(old->rb_right, node);
  42. }
  43. node->rb_parent_color = old->rb_parent_color;
  44. node->rb_left = old->rb_left;
  45. rb_set_parent(old->rb_left, node);
  46. goto color;
  47. }
  48. parent = rb_parent(node);
  49. color = rb_color(node);
  50. if (child)
  51. rb_set_parent(child, parent);
  52. if (parent)
  53. {
  54. if (parent->rb_left == node)
  55. parent->rb_left = child;
  56. else
  57. parent->rb_right = child;
  58. }
  59. else
  60. root->rb_node = child;
  61. color:
  62. if (color == RB_BLACK)
  63. __rb_erase_color(child, parent, root);
  64. }
  1. 函数 5:删除一个黑色节点后,重新调整相关节点的颜色。
  1. /* 这里的node就是上面函数中的child,所有node节点的左右子树肯定都是NULL
  2. * 不满足红黑树规则的就是从parent节点开始的子树,只要给从parent开始的子树增加一个黑色节点就行
  3. * 如果从parent节点开始的节点全是黑色,node和parent都继续向上移动
  4. */
  5. static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
  6. struct rb_root *root)
  7. {
  8. struct rb_node *other;
  9. /* (node不为NULL 且 node是黑色的) 或者 node == NULL */
  10. while ((!node || rb_is_black(node)) && node != root->rb_node)
  11. {
  12. if (parent->rb_left == node)
  13. {
  14. other = parent->rb_right;
  15. if (rb_is_red(other))
  16. {
  17. rb_set_black(other);
  18. rb_set_red(parent);
  19. __rb_rotate_left(parent, root);
  20. other = parent->rb_right;
  21. }
  22. /* 如果从parent节点开始的节点全是黑色,node和parent都继续向上移动 */
  23. if ((!other->rb_left || rb_is_black(other->rb_left)) &&
  24. (!other->rb_right || rb_is_black(other->rb_right)))
  25. {
  26. rb_set_red(other);
  27. node = parent;
  28. parent = rb_parent(node);
  29. }
  30. else
  31. {
  32. if (!other->rb_right || rb_is_black(other->rb_right))
  33. {
  34. rb_set_black(other->rb_left);
  35. rb_set_red(other);
  36. __rb_rotate_right(other, root);
  37. other = parent->rb_right;
  38. }
  39. rb_set_color(other, rb_color(parent));
  40. rb_set_black(parent);
  41. rb_set_black(other->rb_right);
  42. __rb_rotate_left(parent, root);
  43. node = root->rb_node;
  44. break;
  45. }
  46. }
  47. else
  48. {
  49. other = parent->rb_left;
  50. if (rb_is_red(other))
  51. {
  52. rb_set_black(other);
  53. rb_set_red(parent);
  54. __rb_rotate_right(parent, root);
  55. other = parent->rb_left;
  56. }
  57. if ((!other->rb_left || rb_is_black(other->rb_left)) &&
  58. (!other->rb_right || rb_is_black(other->rb_right)))
  59. {
  60. rb_set_red(other);
  61. node = parent;
  62. parent = rb_parent(node);
  63. }
  64. else
  65. {
  66. if (!other->rb_left || rb_is_black(other->rb_left))
  67. {
  68. rb_set_black(other->rb_right);
  69. rb_set_red(other);
  70. __rb_rotate_left(other, root);
  71. other = parent->rb_left;
  72. }
  73. rb_set_color(other, rb_color(parent));
  74. rb_set_black(parent);
  75. rb_set_black(other->rb_left);
  76. __rb_rotate_right(parent, root);
  77. node = root->rb_node;
  78. break;
  79. }
  80. }
  81. }
  82. if (node)
  83. rb_set_black(node);
  84. }

4.3 使用示例

构造了一个内核模块来实际使用一下内核中的红黑树,代码在ubuntu18.04上编译不过,需要使用2.6的内核。

  1. #include <linux/rbtree.h>
  2. #include <linux/string.h>
  3. #include "kn_common.h"
  4. MODULE_LICENSE("Dual BSD/GPL");
  5. struct student
  6. {
  7. int id;
  8. char* name;
  9. struct rb_node node;
  10. };
  11. static int insert_student(struct student*, struct rb_root*);
  12. static int remove_student(struct student*, struct rb_root*);
  13. static int display_student(struct rb_root*, int);
  14. static void display_student_from_small(struct rb_node*);
  15. static void display_student_from_big(struct rb_node*);
  16. static void print_student(struct student*);
  17. static int testrbtree_init(void)
  18. {
  19. #define N 10
  20. struct rb_root root = RB_ROOT;
  21. struct student *stu[N];
  22. char tmp_name[5] = {'w', 'y', 'b', '0', '\0'};
  23. int i;
  24. // init N struct student
  25. for (i=0; i<N; i++)
  26. {
  27. stu[i] = kmalloc(sizeof(struct student), GFP_KERNEL);
  28. stu[i]->id = i;
  29. stu[i]->name = kmalloc(sizeof(char)*5, GFP_KERNEL);
  30. tmp_name[3] = (char)(i+48);
  31. strcpy(stu[i]->name, tmp_name);
  32. // stu_name[3] = (char)(i+48);
  33. stu[i]->node.rb_left = NULL;
  34. stu[i]->node.rb_right = NULL;
  35. }
  36. for (i=0; i < N; ++i)
  37. {
  38. printk(KERN_ALERT "id=%d name=%s\n", stu[i]->id, stu[i]->name);
  39. }
  40. // add N student to rbtree
  41. print_current_time(0);
  42. for (i=0; i < N; i++)
  43. insert_student(stu[i], &root);
  44. // display all students
  45. printk(KERN_ALERT "print from small to big!\n");
  46. display_student(&root, -1);
  47. printk(KERN_ALERT "print from big to small!\n");
  48. display_student(&root, 1);
  49. // delete student 8
  50. remove_student(stu[7], &root);
  51. display_student(&root, -1);
  52. // free all student
  53. for (i=0; i<N; ++i)
  54. {
  55. kfree(stu[i]->name);
  56. kfree(stu[i]);
  57. }
  58. return 0;
  59. }
  60. static int insert_student(struct student* stu, struct rb_root* root)
  61. {
  62. struct rb_node* parent;
  63. struct rb_node* tmp_rb;
  64. struct student* tmp_stu;
  65. /* first time to insert node */
  66. if (!root->rb_node)
  67. {
  68. root->rb_node = &(stu->node);
  69. rb_set_parent(&(stu->node), NULL);
  70. rb_set_black(&(stu->node));
  71. return 0;
  72. }
  73. /* find where to insert node */
  74. tmp_rb = root->rb_node;
  75. while(tmp_rb)
  76. {
  77. parent = tmp_rb;
  78. tmp_stu = rb_entry(tmp_rb, struct student, node);
  79. if (tmp_stu->id > stu->id)
  80. tmp_rb = parent->rb_left;
  81. else if (tmp_stu->id < stu->id)
  82. tmp_rb = parent->rb_right;
  83. else
  84. break;
  85. }
  86. /* the student's id is already in the rbtree */
  87. if (tmp_rb)
  88. {
  89. printk(KERN_ALERT "this student has been inserted!\n");
  90. return 1;
  91. }
  92. if (tmp_stu->id > stu->id)
  93. parent->rb_left = &(stu->node);
  94. else
  95. parent->rb_right = &(stu->node);
  96. rb_set_parent(&(stu->node), parent);
  97. rb_insert_color(&(stu->node), root);
  98. return 0;
  99. }
  100. static int remove_student(struct student* stu, struct rb_root* root)
  101. {
  102. rb_erase(&(stu->node), root);
  103. return 0;
  104. }
  105. static int display_student(struct rb_root *root, int order)
  106. {
  107. if (!root->rb_node)
  108. return 1;
  109. if (order < 0)
  110. display_student_from_small(root->rb_node);
  111. else
  112. display_student_from_big(root->rb_node);
  113. return 0;
  114. }
  115. static void display_student_from_small(struct rb_node* node)
  116. {
  117. struct student *tmp_stu;
  118. if (node)
  119. {
  120. display_student_from_small(node->rb_left);
  121. tmp_stu = rb_entry(node, struct student, node);
  122. print_student(tmp_stu);
  123. display_student_from_small(node->rb_right);
  124. }
  125. }
  126. static void display_student_from_big(struct rb_node* node)
  127. {
  128. struct student *tmp_stu;
  129. if (node)
  130. {
  131. display_student_from_big(node->rb_right);
  132. tmp_stu = rb_entry(node, struct student, node);
  133. print_student(tmp_stu);
  134. display_student_from_big(node->rb_left);
  135. }
  136. }
  137. static void print_student(struct student* stu)
  138. {
  139. printk(KERN_ALERT "=========================\n");
  140. print_current_time(0);
  141. printk(KERN_ALERT "id=%d\tname=%s\n", stu->id, stu->name);
  142. printk(KERN_ALERT "=========================\n");
  143. }
  144. static void testrbtree_exit(void)
  145. {
  146. printk(KERN_ALERT "*************************\n");
  147. print_current_time(0);
  148. printk(KERN_ALERT "testrbtree is exited!\n");
  149. printk(KERN_ALERT "*************************\n");
  150. }
  151. module_init(testrbtree_init);
  152. module_exit(testrbtree_exit);

注:其中用到的 kn_common.h 和 kn_common.c 文件与队列的示例中一样。

Makefile:

  1. obj-m += rbtree.o
  2. rbtree-objs := testrbtree.o kn_common.o
  3. #generate the path
  4. CURRENT_PATH:=$(shell pwd)
  5. #the current kernel version number
  6. LINUX_KERNEL:=$(shell uname -r)
  7. #the absolute path
  8. LINUX_KERNEL_PATH:=/usr/src/kernels/$(LINUX_KERNEL)
  9. #complie object
  10. all:
  11. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  12. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c .tmp_versions *.unsigned
  13. #clean
  14. clean:
  15. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c *.ko .tmp_versions *.unsigned

安装, 卸载内核模块以及查看内核模块的运行结果:

  1. <pre>insmod rbtree.ko
  2. rmmod rbtree
  3. dmesg | tail -135</pre>