Bootstrap

Linux 内核中的 container_of 宏:以 ipoib_rx_poll_rss 函数为例

在 Linux 内核编程中,container_of 是一个非常实用的宏,主要用于通过结构体的成员指针来获取包含该成员的整个结构体的指针。rx_ring = container_of(napi, struct ipoib_recv_ring, napi); 在代码中就是利用了这个宏,下面我们详细分析它的作用和工作原理。

背景知识

在内核开发中,struct napi_struct 是用于 NAPI(New API)机制的数据结构。NAPI 是 Linux 网络子系统中处理网络数据包接收的一种高效机制,能够减少中断处理开销,提高 CPU 利用率。而 struct ipoib_recv_ring 是一个封装了 InfiniBand 接收队列(QP,Queue Pair)相关信息的结构体,其中包含了 struct napi_struct 类型的成员变量 napi

container_of 宏的定义

container_of 宏的定义通常如下(以简化版为例):

#define container_of(ptr, type, member) ({ \
    const typeof( ((type *)0)->member ) *__mptr &#