Linux內核中的一些基本操作

本文檔的Copyleft歸yfydz所有,使用GPL發佈,可以自由拷貝,轉載,轉載時請保持文檔的完整性,嚴禁用於任何商業用途。
msn: [email protected]
來源:http://yfydz.cublog.cn

1. 前言
 
本文介紹linux內核中一些常用的數據結構和操作。
 
2. 雙向鏈表(list)
 
linux內核中的雙向鏈表通過結構 struct list_head來將各個節點連接起來,此結構會作爲鏈表元素結構中的一個參數:
struct list_head {
 struct list_head *next, *prev;
};
 
鏈表頭的初始化,注意,結構中的指針爲NULL並不是初始化,而是指向自身才是初始化,如果只是按普通情況下的置爲NULL,而不是指向自身,系統會崩潰,這是一個容易犯的錯誤:
 
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) /
 struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { /
 (ptr)->next = (ptr); (ptr)->prev = (ptr); /
} while (0)
 
最常用的鏈表操作:
插入到鏈表頭:
void list_add(struct list_head *new, struct list_head *head);
 
插入到鏈表尾:
void list_add_tail(struct list_head *new, struct list_head *head);
 
刪除鏈表節點:
void list_del(struct list_head *entry);
 
將節點移動到另一鏈表:
void list_move(struct list_head *list, struct list_head *head);
 
將節點移動到鏈表尾:
void list_move_tail(struct list_head *list,struct list_head *head);
 
判斷鏈表是否爲空,返回1爲空,0非空
int list_empty(struct list_head *head);
 
把兩個鏈表拼接起來:
void list_splice(struct list_head *list, struct list_head *head);
 
取得節點指針:
#define list_entry(ptr, type, member) /
 ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
 
遍歷鏈表中每個節點:
#define list_for_each(pos, head) /
 for (pos = (head)->next, prefetch(pos->next); pos != (head); /
         pos = pos->next, prefetch(pos->next))
 
逆向循環鏈表中每個節點:
#define list_for_each_prev(pos, head) /
 for (pos = (head)->prev, prefetch(pos->prev); pos != (head); /
         pos = pos->prev, prefetch(pos->prev))
 
舉例:
 
LISH_HEAD(mylist);
 
struct my_list{
 struct list_head list;
 int data;
};
 
static int ini_list(void)
{
 struct my_list *p;
 int i;
 for(i=0; i<100; i++){
  p=kmalloc(sizeof(struct my_list), GFP_KERNEL);
  list_add(&p->list, &mylist);
 }
}

在內存中形成如下結構的一個雙向鏈表:
 
  +---------------------------------------------------------------+
  |                                                               |
  |  mylist         99            98                     0        |
  |  +----+    +---------+    +---------+           +---------+   |
  +->|next|--->|list.next|--->|list.next|--->...--->|list.next|---+
     |----|    |---------|    |---------|           |---------|
  +--|prev|<---|list.prev|<---|list.prev|<---...<---|list.prev|<--+
  |  +----+    |---------|    |---------|           |---------|   |
  |            |  data   |    |  data   |           |  data   |   |
  |            +---------+    +---------+           +---------+   |
  |                                                               |
  +---------------------------------------------------------------+
 
知道了鏈表頭就能遍歷整個鏈表,如果是用list_add()插入新節點的話,從鏈表頭的next方向看是一個堆棧型。
 
從鏈表中刪除節點很容易:
static void del_item(struct my_list *p)
{
 list_del(&p->list, &mylist);
 kfree(p);
}
 
最重要的宏是list_entry,這個宏的思路是根據鏈表元素結構中鏈表頭結構list_head的地址推算出鏈表元素結構的實際地址:
 
#define list_entry(ptr, type, member) /
 ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
 
ptr是鏈表元素結構(如struct my_list)中鏈表頭結構list_head的地址
member是鏈表元素結構(如struct my_list)中鏈表頭結構list_head參數的名稱
type是鏈表元素結構類型(如struct my_list)
計算原理是根據鏈表頭結構list_head的地址減去其在鏈表元素結構中的偏移位置而得到鏈表元素結構的地址。
 
例如:
static void print_list(void)
{
 struct list_head *cur;
 struct my_list *p;
 list_for_each(cur, &mylist){
  p=list_entry(cur, struct my_list, list);
  printk("data=%d/n", p->data);
 }
}
 
優點:
這樣就可以用相同的數據處理方式來描述所有雙向鏈表,不用再單獨爲各個鏈表編寫各種編輯函數。
 
缺點:
1) 鏈表頭中元素置爲NULL不是初始化,與普通習慣不同;
2) 仍然需要單獨編寫各自的刪除整個鏈表的函數,不能統一處理,因爲不能保證所有鏈表元素結構中鏈表頭結構list_head的偏移地址都是相同的,當然如果把鏈表頭結構list_head都作爲鏈表元素結構的第一個參數,就可以用統一的刪除整個鏈表的函數。

3. HASH表
 
HASH表適用於不需要對整個空間元素進行排序,而是只需要能快速找到某個元素的場合,是一種以空間換時間的方法,本質也是線性表,但由一個大的線性表拆分爲了多個小線性表,由於只需要查找小表,因此搜索速度就會線性查整個大表提高很多,理想情況下,有多少個小線性表,搜索速度就提高了多少倍,通常把小線性表的表頭綜合爲一個數組,大小就是HASH表的數量。
 
HASH錶速度的關鍵是HASH函數的設計,HASH函數根據每個元素中固定的參數進行計算,算出一個不大於HASH表數量的索引值,表示該元素需要放在該索引號對應的那個表中,對於固定的參數,計算結果始終是固定的,但對於不同的參數值,希望計算出來的結果能儘可能地平均到每個索引值,HASH函數計算得越平均,表示每個小表中元素的數量都會差不多,這樣搜索性能將越好。HASH函數也要儘可能的簡單,以減少計算時間,常用的算法是將參數累加求模,在include/linux/jhash.h中已經定義了一些HASH計算函數,可直接使用。
 
HASH表在路由cache表,狀態連接表等處用得很多。
 
舉例,連接跟蹤中根據tuple值計算HASH:
// net/ipv4/netfilter/ip_conntrack_core.c
u_int32_t
hash_conntrack(const struct ip_conntrack_tuple *tuple)
{
#if 0
 dump_tuple(tuple);
#endif
 return (jhash_3words(tuple->src.ip,
                      (tuple->dst.ip ^ tuple->dst.protonum),
                      (tuple->src.u.all | (tuple->dst.u.all << 16)),
                      ip_conntrack_hash_rnd) % ip_conntrack_htable_size);
}
 
// include/linux/jhash.h
static inline u32 jhash_3words(u32 a, u32 b, u32 c, u32 initval)
{
 a += JHASH_GOLDEN_RATIO;
 b += JHASH_GOLDEN_RATIO;
 c += initval;
 __jhash_mix(a, b, c);
 return c;
}
 
4. 定時器(timer)
 
linux內核定時器由以下結構描述:
 
/* include/linux/timer.h */
struct timer_list {
 struct list_head list;
 unsigned long expires;
 unsigned long data;
 void (*function)(unsigned long);
};
list:timer鏈表
expires:到期時間
function:到期函數,時間到期時調用的函數
data:傳給到期函數的數據,實際應用中通常是一個指針轉化而來,該指針指向一個結構

timer的操作:
 
增加timer,將timer掛接到系統的timer鏈表:
extern void add_timer(struct timer_list * timer);
 
刪除timer,將timer從系統timer鏈表中拆除:
extern int del_timer(struct timer_list * timer);
(del_timer()函數可能會失敗,這是因爲該timer本來已經不在系統timer鏈表中了,也就是已經刪除過了)
 
對於SMP系統,刪除timer最好使用下面的函數來防止衝突:
extern int del_timer_sync(struct timer_list * timer);
 
修改timer,修改timer的到期時間:
int mod_timer(struct timer_list *timer, unsigned long expires);
 
通常用法:
struct timer_list通常作爲數據結構中的一個參數,在初始化結構的時候初始化timer,表示到期時要進行的操作,實現定時動作,通常更多的是作爲超時處理的,timer函數作爲超時時的資源釋放函數。注意:如果超時了運行超時函數,此時系統是處在時鐘中斷的bottom half裏的,不能進行很複雜的操作,如果要完成一些複雜操作,如到期後的數據發送,不能直接在到期函數中處理,而是應該在到期函數中發個信號給特定內核線程轉到top half進行處理。
 
爲判斷時間的先後,內核中定義了以下宏來判斷:
#define time_after(a,b)  ((long)(b) - (long)(a) < 0)
#define time_before(a,b) time_after(b,a)
#define time_after_eq(a,b) ((long)(a) - (long)(b) >= 0)
#define time_before_eq(a,b) time_after_eq(b,a)
這裏用到了一個技巧,由於linux中的時間是無符號數,這裏先將其轉換爲有符號數後再判斷,就能解決時間迴繞問題,當然只是一次迴繞,迴繞兩次當然是判斷不出來的,具體可自己實驗體會。
 
5. 內核線程(kernel_thread)
 
內核中新線程的建立可以用kernel_thread函數實現,該函數在kernel/fork.c中定義:
long kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
fn:內核線程主函數;
arg:線程主函數的參數;
flags:建立線程的標誌;
 
內核線程函數通常都調用daemonize()進行後臺化作爲一個獨立的線程運行,然後設置線程的一些參數,如名稱,信號處理等,這也不是必須的,然後就進入一個死循環,這是線程的主體部分,這個循環不能一直在運行,否則系統就死在這了,或者是某種事件驅動的,在事件到來前是睡眠的,事件到來後喚醒進行操作,操作完後繼續睡眠;或者是定時睡眠,醒後操作完再睡眠;或者加入等待隊列通過schedule()調度獲得執行時間。總之是不能一直佔着CPU。
 
以下是內核線程的一個實例,取自kernel/context.c:
 
int start_context_thread(void)
{
 static struct completion startup __initdata = COMPLETION_INITIALIZER(startup);
 kernel_thread(context_thread, &startup, CLONE_FS | CLONE_FILES);
 wait_for_completion(&startup);
 return 0;
}
static int context_thread(void *startup)
{
 struct task_struct *curtask = current;
 DECLARE_WAITQUEUE(wait, curtask);
 struct k_sigaction sa;
 daemonize();
 strcpy(curtask->comm, "keventd");
 keventd_running = 1;
 keventd_task = curtask;
 spin_lock_irq(&curtask->sigmask_lock);
 siginitsetinv(&curtask->blocked, sigmask(SIGCHLD));
 recalc_sigpending(curtask);
 spin_unlock_irq(&curtask->sigmask_lock);
 complete((struct completion *)startup);
 /* Install a handler so SIGCLD is delivered */
 sa.sa.sa_handler = SIG_IGN;
 sa.sa.sa_flags = 0;
 siginitset(&sa.sa.sa_mask, sigmask(SIGCHLD));
 do_sigaction(SIGCHLD, &sa, (struct k_sigaction *)0);
 /*
  * If one of the functions on a task queue re-adds itself
  * to the task queue we call schedule() in state TASK_RUNNING
  */
 for (;;) {
  set_task_state(curtask, TASK_INTERRUPTIBLE);
  add_wait_queue(&context_task_wq, &wait);
  if (TQ_ACTIVE(tq_context))
   set_task_state(curtask, TASK_RUNNING);
  schedule();
  remove_wait_queue(&context_task_wq, &wait);
  run_task_queue(&tq_context);
  wake_up(&context_task_done);
  if (signal_pending(curtask)) {
   while (waitpid(-1, (unsigned int *)0, __WALL|WNOHANG) > 0)
    ;
   spin_lock_irq(&curtask->sigmask_lock);
   flush_signals(curtask);
   recalc_sigpending(curtask);
   spin_unlock_irq(&curtask->sigmask_lock);
  }
 }
}
 
6. 結構地址
 
在C中,結構地址和結構中第一個元素的地址是相同的,因此在linux內核中經常出現使用結構第一個元素的地址來表示結構地址的情況,在讀代碼時要注意這一點,這和list_entry宏的意思一樣。
 
如:
struct my_struct{
 int a;
 int b;
}c;
if(&c == &c.a){  // always true
...
}
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章