Linux核心中的一些基本編程操作

來源:互聯網
上載者:User
本文檔的Copyleft歸yfydz所有,使用GPL發布,可以自由拷貝,轉載,轉載時請保持文檔的完整性,嚴禁用於任何商業用途。
msn: yfydz_no1@hotmail.com

來源:http://yfydz.cublog.cn1. 前言 本文介紹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表數量的索引值,表示該元
素需要放在該索引號對應的那個表中,對於固定的參數,計算結果始終是固定的,但對於不同的參數值,希望計算出來的結果能儘可能地平均到每個索引
值,HASHFunction Compute得越平均,表示每個小表中元素的數量都會差不多,這樣搜尋效能將越好。HASH函數也要儘可能的簡單,以減少計算時間,常用的演算法是
將參數累加求模,在include/linux/jhash.h中已經定義了一些HASH計算函數,可直接使用。 HASH表在路由cache表,狀態串連表等處用得很多。 舉例,串連跟蹤中根據tuple值計算HASH:// net/ipv4/netfilter/ip_conntrack_core.cu_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
...
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.