Home > Operation and Maintenance > Linux Operation and Maintenance > Basics of Linux kernel - container_of principle and practical application

Basics of Linux kernel - container_of principle and practical application

Release: 2023-07-31 15:46:13
forward
1134 people have browsed it

container_of is often seen in the Linux kernel, and it is also widely used in actual driver writing.

container_of principle

##Function: through a member of the structure The variable address finds the first address of the structure.

is defined as follows:

/**
 * 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) );})
Copy after login

  • ptr: pointer to the structure member variable
  • type: Structure type
  • member: Name of structure member variable
In other words , called:

The address ptr of the member member of the known structure type is known, and the starting address of the structure type is solved.

The calculation formula is: starting address of type = ptr -size (size is the size of member)

Use a picture to illustrate the relationship between ptr, type, and member:

Basics of Linux kernel - container_of principle and practical application
  • Brief description of the principle: The beauty of

container_of is that uses 0 as a member variable The base address of member is .

An intermediate variable __mptr is defined, "__" represents internal use, "m" represents middle .

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
Copy after login

typeof( ((type *)0)->member )是获取member的类型,__mptr = (ptr)判断ptrmember是否为同一类型,offsetof计算成员member的大小size

驱动中的实际例子

例如内核的pwm驱动,通过成员变量chip,找到结构体bcm2835_pwm

struct bcm2835_pwm {
 struct pwm_chip chip;
 struct device *dev;
 void __iomem *base;
 struct clk *clk;
};

static inline struct bcm2835_pwm *to_bcm2835_pwm(struct pwm_chip *chip_ptr)
{
 return container_of(chip_ptr, struct bcm2835_pwm, chip);
}
Copy after login

使用container_of通常都会定义一个函数,并且命名为to_xxx或者to_find_xxx,代表要找xxx这个结构体,传参则传入成员变量指针,另外函数也会声明为inline

The above is the detailed content of Basics of Linux kernel - container_of principle and practical application. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:嵌入式Linux充电站
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template