LKDS8.Linux内核的双向链表代码解析(8) 拼接链表、获取链表首/尾元素的宏、list_for_each系列的安全版本的宏

目录

1.拼接链表

list_splice()

__list_splice()

和栈的关系

list_splice_init()

list_splice_tail()

list_splice_tail_init()

2.获取链表中节点的宏

[获取首节点: list_first_entry_or_null](#获取首节点: list_first_entry_or_null)

[获取尾节点: list_last_entry_or_null](#获取尾节点: list_last_entry_or_null)

[获取下一个节点: list_next_entry_circular](#获取下一个节点: list_next_entry_circular)

[获取前一个节点: list_prev_entry_circular](#获取前一个节点: list_prev_entry_circular)

3.list_for_each系列的安全版本的宏

list_for_each_safe

[提问: safe在哪里?](#提问: safe在哪里?)

list_for_each_entry_safe_continue

list_prepare_entry

list_for_each_prev_safe

list_for_each_entry_safe

list_safe_reset_next

list_for_each_entry_safe_reverse

list_for_each_entry_safe_from


1.拼接链表

list_splice()

当list不为空的时候才能将list拼接到head上

cpp 复制代码
/**
 * list_splice - join two lists, this is designed for stacks
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 */
static inline void list_splice(const struct list_head *list,
				struct list_head *head)
{
	if (!list_empty(list))
		__list_splice(list, head, head->next);
}

__list_splice()

传了2个参数,是将list链表拼接到head链表,具体的拼接的实现要看__list_splice():

cpp 复制代码
static inline void __list_splice(const struct list_head *list,
				 struct list_head *prev,
				 struct list_head *next)
{
	struct list_head *first = list->next;
	struct list_head *last = list->prev;

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

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

画个图演示一下,假设head和list初始时分别是这样的:

标上传入__list_splice()的参数:

bash 复制代码
flowchart LR
    head["head<br/>list_head"]
    A["n1 的 list_head"]

    head -->|next| A
    A -->|next| head 

    A -.->|prev| head
    head -.->|prev| A
bash 复制代码
flowchart LR
    head["head<br/>list_head"]
    A["m1 的 list_head"]
    B["m2 的 list_head"]
    C["m3 的 list_head"]
 
    head -->|next| A
    A -->|next| B
    B -->|next| C
    C -->|next| head
 
    A -.->|prev| head
    B -.->|prev| A
    C -.->|prev| B
    head -.->|prev| C

执行__list_splice()后:

问题来了,现在有2个头节点,到底保留哪一个呢?

可以分别尝试遍历一下,假设从A这个头节点开始遍历:

发现链表成环了,从A节点开始遍历,但最终回不到A

假设从B这个头节点开始遍历,没问题,从B节点开始遍历,最终能回到B,所以保留的肯定是B

其实不用遍历也可以推出来,要理解list_splice()的语义"join two lists",将list加入head,那么最终保留的肯定是head,而不是list

注意,如果list链表是动态分配的话,list_splice()是没有释放A节点的空间的,需要开发者手动释放

和栈的关系

list_splice()的注释中"this is designed for stacks"提到了栈,这个和栈有什么关系?

读者可以看看《数据结构 (C语言版 第3版)》的第 3 章 栈和队列 → 3.3 栈的表示和实现→ 3.3.3 链栈的表示和实现

这里摘抄一些内容:

链栈是指采链式存储结构实现的栈。通常链栈用单链表来表

示,如图 3.4 所示。链栈的结点结构与单链表的结构相同,在此用

StackNode表示,定义如下 :

cpp 复制代码
//- - - - - 链栈的存储结构 - - - - -
typedef struct StackNode
{
    ElemType data;
    struct StackNode *next;
}StackNode,*LinkStack;

由于对栈的主要操作是在栈顶插入和删除元素,显然以链表的头

部作为栈顶是最方便的,而且没必要像单链表那样为了操作方便附加一个头结点。

list_splice_init()

cpp 复制代码
/**
 * 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, head->next);
		INIT_LIST_HEAD(list);
	}
}

内部实现和list_splice()相比,list_splice_init()只多了个INIT_LIST_HEAD(list),

结论: list_splice_init() == list_splice() +list表头初始化

list_splice_tail()

cpp 复制代码
/**
 * list_splice_tail - join two lists, each list being a queue
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 */
static inline void list_splice_tail(struct list_head *list,
				struct list_head *head)
{
	if (!list_empty(list))
        //list_splice()是__list_splice(list, head, head->next)
		__list_splice(list, head->prev, head);
}

从传的参数可以看到list_splice_tail()是将list插入到head的尾部,可以用来模拟队列,这里就不画图演示了

list_splice_tail_init()

list_splice_tail_init()在list_splice_tail()基础上加了init:

cpp 复制代码
/**
 * list_splice_tail_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.
 *
 * Each of the lists is a queue.
 * The list at @list is reinitialised
 */
static inline void list_splice_tail_init(struct list_head *list,
					 struct list_head *head)
{
	if (!list_empty(list)) {
		__list_splice(list, head->prev, head);
		INIT_LIST_HEAD(list);
	}
}

2.获取链表中节点的宏

获取首节点: list_first_entry_or_null

cpp 复制代码
/**
 * list_first_entry_or_null - get the first element from a list
 * @ptr:	the list head to take the element from.
 * @type:	the type of the struct this is embedded in.
 * @member:	the name of the list_head within the struct.
 *
 * Note that if the list is empty, it returns NULL.
 */
#define list_first_entry_or_null(ptr, type, member) ({ \
	struct list_head *head__ = (ptr); \
	struct list_head *pos__ = READ_ONCE(head__->next); \
	pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
})

ptr、type、member参数的含义类似container_of的参数的意思差不多,这里不再解释

取得的第一个元素有2种情况:

1.pos__ == head__,说明链表为空,只有哨兵头节点

2.pos__ != head__,说明链表至少有一个有效节点

所以宏在命名的时候就使用了first_entry ornull

注: list_first_entry_or_null_acquire涉及SMP,这里不讲

获取尾节点: list_last_entry_or_null

cpp 复制代码
/**
 * list_last_entry_or_null - get the last element from a list
 * @ptr:	the list head to take the element from.
 * @type:	the type of the struct this is embedded in.
 * @member:	the name of the list_head within the struct.
 *
 * Note that if the list is empty, it returns NULL.
 */
#define list_last_entry_or_null(ptr, type, member) ({ \
	struct list_head *head__ = (ptr); \
	struct list_head *pos__ = READ_ONCE(head__->prev); \
	pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
})

取得的最后一个元素有2种情况:

1.pos__ == head__,说明链表为空,只有哨兵头节点

2.pos__ != head__,说明链表至少有一个有效节点

获取下一个节点: list_next_entry_circular

cpp 复制代码
/**
 * list_next_entry_circular - get the next element in list
 * @pos:	the type * to cursor.
 * @head:	the list head to take the element from.
 * @member:	the name of the list_head within the struct.
 *
 * Wraparound if pos is the last element (return the first element).
 * Note, that list is expected to be not empty.
 */
#define list_next_entry_circular(pos, head, member) \
	(list_is_last(&(pos)->member, head) ? \
	list_first_entry(head, typeof(*(pos)), member) : list_next_entry(pos, member))

获取下一个节点有2种情况:

1.不回绕

正常使用list_next_entry获取

2.回绕到头节点

当满足list_is_last,pos指向尾节点,尾节点的下一个节点是头节点,但头节点不存储有效数据,那么要使用list_first_entry返回结果

获取前一个节点: list_prev_entry_circular

cpp 复制代码
/**
 * list_prev_entry_circular - get the prev element in list
 * @pos:	the type * to cursor.
 * @head:	the list head to take the element from.
 * @member:	the name of the list_head within the struct.
 *
 * Wraparound if pos is the first element (return the last element).
 * Note, that list is expected to be not empty.
 */
#define list_prev_entry_circular(pos, head, member) \
	(list_is_first(&(pos)->member, head) ? \
	list_last_entry(head, typeof(*(pos)), member) : list_prev_entry(pos, member))

获取前一个节点有2种情况:

1.是正常节点

正常使用list_prev_entry获取

2.是头节点

当满足list_is_first,pos指向第一个有效节点(head->next),前一个是头节点,但头节点不存储有效数据,由于是双向循环链表,那么要使用list_last_entry返回链表的最后一个节点

注: list_first_entry、list_next_entry、list_prev_entry、list_last_entry在Linux内核的双向链表代码解析(2) 遍历算法文章讲过了

3.list_for_each系列的安全版本的宏

之前在Linux内核的双向链表代码解析(2) 遍历算法文章讲过list_for_each系列的部分宏,这些宏没有带safe,本文下面讲带safe的

list_for_each_safe

cpp 复制代码
/**
 * 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; \
	     !list_is_head(pos, (head)); \
	     pos = n, n = pos->next)

这里再给list_for_each的定义:

cpp 复制代码
/**
 * list_for_each	-	iterate over a list
 * @pos:	the &struct list_head to use as a loop cursor.
 * @head:	the head for your list.
 */
#define list_for_each(pos, head) \
	for (pos = (head)->next; !list_is_head(pos, (head)); pos = pos->next)

对比发现,传入这2个宏的参数数量不同,list_for_each需要2个参数,但list_for_each_safe需要3个参数,多出来的这个参数是n,用于提前获得pos->next,n相当于缓存的作用,这样在一次循环结束后,pos就能取得n的值,n再取新的pos->next,但list_for_each没有n,pos只能在一次循环结束后现取pos->next

提问: safe在哪里?

有读者可能会说"用n不是多此一举吗? list_for_each本身就能达到遍历的效果,为什么还要list_for_each_safe?" safe在哪里呢?

看list_for_each_safe的注释"iterate over a list safe against removal of list entry ",removal of list entry已经暗示了从内存释放的角度取考虑

n用于暂存pos的下一个结点的地址,避免了因为pos节点被释放而造成的断链,这也就体现了该宏的安全机制

也就是说,可以遍历完当前结节点后就将其删除,同时接着访问下一个结点,遍历完毕
后,就只剩下一个哨兵头结点

这里看一个真实的例子,定义在/mm/swapfile.c中的drain_mmlist():

cpp 复制代码
/*
 * After a successful try_to_unuse, if no swap is now in use, we know
 * we can empty the mmlist.  swap_lock must be held on entry and exit.
 * Note that mmlist_lock nests inside swap_lock, and an mm must be
 * added to the mmlist just after page_duplicate - before would be racy.
 */
static void drain_mmlist(void)
{
	struct list_head *p, *next;
	unsigned int type;

	for (type = 0; type < nr_swapfiles; type++)
		if (swap_usage_in_pages(swap_info[type]))
			return;
	spin_lock(&mmlist_lock);
	list_for_each_safe(p, next, &init_mm.mmlist)
		list_del_init(p);
	spin_unlock(&mmlist_lock);
}

不需要理解这个函数具体是干什么的,这里只需要看和链表操作相关的部分

先加锁,之后遍历链表,后解锁,显然执行list_for_each_safe只有一个线程,不需要考虑并发问题

cpp 复制代码
list_for_each_safe(p, next, &init_mm.mmlist)
    list_del_init(p);

遍历的链表是&init_mm.mmlist,提供的临时指针是p, next,p用于指向的是当前节点,next用于提前缓存下一个节点的位置

循环体内将p指向的节点从链表摘下来,然后让每个节点前后指针都指向自己,如下图:

mermaid代码:

bash 复制代码
flowchart LR
    head["&init_mm.mmlist<br/>list_head"]
    A["m1 的 list_head"]
    B["m2 的 list_head"]
    C["m3 的 list_head"]
 
    head -->|next| A
    A -->|next| B
    B -->|next| C
    C -->|next| head
 
    A -.->|prev| head
    B -.->|prev| A
    C -.->|prev| B
    head -.->|prev| C
cpp 复制代码
flowchart LR
    head["&init_mm.mmlist<br/>list_head"]
    A["m1 的 list_head"]
    B["m2 的 list_head"]
    C["m3 的 list_head"]

    head_r[" "]
    A_r[" "]
    B_r[" "]
    C_r[" "]

    head_l[" "]
    A_l[" "]
    B_l[" "]
    C_l[" "]

    head -- next --> head_r --> head
    A -- next --> A_r --> A
    B -- next --> B_r --> B
    C -- next --> C_r --> C

    head -- prev --> head_l --> head
    A -- prev --> A_l --> A
    B -- prev --> B_l --> B
    C -- prev --> C_l --> C

    classDef invisible fill:none,stroke:none,color:transparent;
    class head_r,A_r,B_r,C_r,head_l,A_l,B_l,C_l invisible;

list_for_each_entry_safe_continue

cpp 复制代码
/**
 * list_for_each_entry_safe_continue - continue list iteration safe against removal
 * @pos:	the type * to use as a loop cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_head within the struct.
 *
 * Iterate over list of given type, continuing after current point,
 * safe against removal of list entry.
 */
#define list_for_each_entry_safe_continue(pos, n, head, member) 		\
	for (pos = list_next_entry(pos, member), 				\
		n = list_next_entry(pos, member);				\
	     !list_entry_is_head(pos, head, member);				\
	     pos = n, n = list_next_entry(n, member))

list_for_each_entry_safe_continue是在list_for_each_entry_safe基础上实现continue,即从pos指向的下一个节点开始遍历,一直到链表头结束

但在执行这个宏之前,需要先执行list_prepare_entry

list_prepare_entry

cpp 复制代码
/**
 * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
 * @pos:	the type * to use as a start point
 * @head:	the head of the list
 * @member:	the name of the list_head within the struct.
 *
 * Prepares a pos entry for use as a start point in list_for_each_entry_continue().
 */
#define list_prepare_entry(pos, head, member) \
	((pos) ? : list_entry(head, typeof(*pos), member))

((pos) ? : list_entry(head, typeof(*pos), member))属于gcc的扩展语法,根据Conditionals (Using the GNU Compiler Collection (GCC)),有:

cpp 复制代码
((pos) ? : list_entry(head, typeof(*pos), member))

等价为

((pos) ? (pos) : list_entry(head, typeof(*pos), member))

如果pos不为空,就取pos,否则取head所在的对象(指把head当作 typeof(*pos) 类型中member成员的地址,反推出包含这个成员的外层结构体对象的指针)

list_for_each_prev_safe

list_for_each_safe是安全地逐个遍历下一个节点pos->next,而list_for_each_prev_safe反过来,是安全地逐个遍历前一个节点pos->prev,这里不再赘述

cpp 复制代码
/**
 * list_for_each_prev_safe - iterate over a list backwards 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_prev_safe(pos, n, head) \
	for (pos = (head)->prev, n = pos->prev; \
	     !list_is_head(pos, (head)); \
	     pos = n, n = pos->prev)

list_for_each_entry_safe

cpp 复制代码
/**
 * 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 cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_head within the struct.
 */
#define list_for_each_entry_safe(pos, n, head, member)			\
	for (pos = list_first_entry(head, typeof(*pos), member),	\
		n = list_next_entry(pos, member);			\
	     !list_entry_is_head(pos, head, member); 			\
	     pos = n, n = list_next_entry(n, member))

list_for_each_entry_safe在list_for_each_safe基础上只多做一步: 在取得struct list_head对象地址的基础上,向上找它所在的对象的首地址

list_safe_reset_next

安全取得pos的下一个节点(安全的原理同list_for_each系列),这是为了重置已失效的 list_for_each_entry_safe循环

cpp 复制代码
/**
 * list_safe_reset_next - reset a stale list_for_each_entry_safe loop
 * @pos:	the loop cursor used in the list_for_each_entry_safe loop
 * @n:		temporary storage used in list_for_each_entry_safe
 * @member:	the name of the list_head within the struct.
 *
 * list_safe_reset_next is not safe to use in general if the list may be
 * modified concurrently (eg. the lock is dropped in the loop body). An
 * exception to this is if the cursor element (pos) is pinned in the list,
 * and list_safe_reset_next is called after re-taking the lock and before
 * completing the current iteration of the loop body.
 */
#define list_safe_reset_next(pos, n, member)				\
	n = list_next_entry(pos, member)

list_for_each_entry_safe_reverse

list_for_each_entry_safe_reverse是list_for_each_entry_safe的反向遍历版本,不解释

cpp 复制代码
/**
 * list_for_each_entry_safe_reverse - iterate backwards over list safe against removal
 * @pos:	the type * to use as a loop cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_head within the struct.
 *
 * Iterate backwards over list of given type, safe against removal
 * of list entry.
 */
#define list_for_each_entry_safe_reverse(pos, n, head, member)		\
	for (pos = list_last_entry(head, typeof(*pos), member),		\
		n = list_prev_entry(pos, member);			\
	     !list_entry_is_head(pos, head, member); 			\
	     pos = n, n = list_prev_entry(n, member))

list_for_each_entry_safe_from

cpp 复制代码
/**
 * list_for_each_entry_safe_from - iterate over list from current point safe against removal
 * @pos:	the type * to use as a loop cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_head within the struct.
 *
 * Iterate over list of given type from current point, safe against
 * removal of list entry.
 */
#define list_for_each_entry_safe_from(pos, n, head, member) 			\
	for (n = list_next_entry(pos, member);					\
	     !list_entry_is_head(pos, head, member);				\
	     pos = n, n = list_next_entry(n, member))

"n = list_next_entry(pos, member)"是提前取得pos的下一个节点,保证安全,该宏是从pos指向的节点开始遍历,"!list_entry_is_head(pos, head, member)"说明一直遍历到链表头为止

内核中的双向链表的分析到此为止

相关推荐
渴了喝洗衣液26 分钟前
第一阶段项目
linux·运维·服务器
俊俊几年的1 小时前
嵌入式 Linux 应用开发:CMake 详解与交叉编译实践
linux·c++·嵌入式·cmake·linux应用开发
蹊黎10 小时前
Linux 进程概念(四):命令行参数与环境变量
linux·运维·服务器
蜗牛一步步往上爬20 小时前
第十一章 构建基本脚本
linux
星恒随风20 小时前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
飞奔的瓜牛20 小时前
Linux 数据盘分区、格式化与自动挂载完整实践
linux·运维·服务器
Lucas. Wáng1 天前
Linux网络编程之网络套接字
linux·服务器·网络
进击的荆棘1 天前
Linux网络——Socket编程TCP
linux·运维·服务器·网络·tcp/ip
大今野1 天前
2026 专转本计算机|Linux CentOS7 软件包管理:yum 仓库配置与常用命令考点全解(附例题)
linux·运维·服务器·专转本