[linux内核][LINUX内核编程]学习笔记(一)

linux内核使用bitmap相关
 1,声明一个bitmap数组,可以表示100个bit,数组名字是bitmap

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. DECLARE_BITMAP(bitmap,100)  

 相关宏定义如下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #define DECLARE_BITMAP(name,bits) unsigned long name[BITS_TO_LONGS(bits)]  
  2. #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr,BITS_PER_BYTE*sizeof(long))  
  3. #define DIV_ROUND_UP(n,d) (((n)+(d)-1)/(d))  
  4. #define BITS_PER_BYTE 8  


 2,使用以上定义的bitmap数组
 检测bitmap某一位是否为1,用test_bit()函数,如检测第一个bit,则调用test_bit(0,bitmap)

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. static int test_bit(unsigned int nr,const unsigned long *addr)  
  2. {  
  3.  return ((1UL<<(nr%BITS_PER_LONG))&(((unsigned*)addr)[nr/BITS_PER_LONG])) !=0)  
  4. }  
  5. #define BITS_PER_LONG 32  

 使用实例:bootmem分配器~~

内核使用双向链表相关

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. struct list_head{  
  2.  struct list_head *next;  
  3.  struct list_head *priv;  
  4. };  


 list_entry()函数可以返回包含双向链表的结构, 指针ptr指向结构体type中的member成员,通过ptr返回结构体type的起始地址

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #define list_entry(ptr,type,member) container_of(ptr,type,member)   
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. list_add(struct list_head *new ,struct list_head *head)  

 该函数向指定链表的head节点后插入new节点,

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. list_for_each_entry(pos,head,member)  

 pos是一个指向包含list_head节点对象的指针,可以看成是list_entry()返回的值,head是遍历开始的位置,

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #define container_of(ptr, type, member) ({                         
  2. const typeof( ((type *)0)->member ) *__mptr = (ptr);       
  3. (type *)( (char *)__mptr - offsetof(type,member) );})  
  4. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)  

第一步,首先定义一个临时的数据类型(通过typeof( ((type *)0)->member )获得)与ptr相同的指针变量__mptr,然后用它来保存ptr的值。第二步,用(char *)__mptr减去member在结构体中的偏移量,得到的值就是整个结构体变量的首地址(整个宏的返回值就是这个首地址)。

typeof的解释如下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. const typeof( ((type *)0)->member ) *__mptr = (ptr);  

是定义一个叫做__mptr的指针。这个指针指向的内容是不可变的,指向的类型是一个type类型结构体中member的类型。

 

两个取反 !!的作用,

答:确保所得的结果为0或者1

原文地址:https://www.cnblogs.com/zhiliao112/p/4232149.html