本文分析了Linux2.6.29中hrtimer的實現。
Linux2.6中實現了一種新的定時器hrtimer。與傳統定時器使用時間輪算法不同,hrtimer使用了紅黑樹算法。hrtimer本身可以配置成高精度和普通精度兩種,在單CPU系統和多CPU系統中的實現也有區別。這裡先分析最簡單的配置成普通精度、單CPU的情況。配置成高精度的情況見後續文章。
1. 時鐘源的定義
為了實現hrtimer,Linux為系統中每一個CPU定義了一個hrtimer_cpu_base,這個結構體的定義如下:
- struct hrtimer_cpu_base {
- raw_spinlock_t lock;
- struct hrtimer_clock_base clock_base[HRTIMER_MAX_CLOCK_BASES]; //時鐘源 #define HRTIMER_MAX_CLOCK_BASES 2
- #ifdef CONFIG_HIGH_RES_TIMERS
- ktime_t expires_next;
- int hres_active;
- int hang_detected;
- unsigned long nr_events;
- unsigned long nr_retries;
- unsigned long nr_hangs;
- ktime_t max_hang_time;
- #endif
- };
- <p> </p><pre class="cpp" name="code">struct hrtimer_clock_base {
- struct hrtimer_cpu_base *cpu_base;
- clockid_t index;
- struct rb_root active;
- struct rb_node *first;
- ktime_t resolution;
- ktime_t (*get_time)(void);
- ktime_t softirq_time;
- #ifdef CONFIG_HIGH_RES_TIMERS
- ktime_t offset;
- #endif
- };
在hrtimer.c中,有為每個CPU具體定義hrtimer_cpu_base的代碼:
- DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
- {
-
- .clock_base =
- {
- {
- .index = CLOCK_REALTIME,
- .get_time = &ktime_get_real,
- .resolution = KTIME_LOW_RES,
- },
- {
- .index = CLOCK_MONOTONIC,
- .get_time = &ktime_get,
- .resolution = KTIME_LOW_RES,
- },
- }
- };
1.1 時鐘源類型
可以看出,每個CPU都必須定義兩個時鐘源:REALTIME和MONOTONIC。REALTIME代表實時時鐘,MONOTONIC代表單調遞增時鐘。兩者的區別在於,當用戶更改系統時間時,REALTIME時鐘會收到影響,但MONOTONIC不受影響。這可以從它們兩個的get_time函數指針看出來,REALTIME時鐘指向的是ktime_get_real,MONOTONIC指向的是ktime_get。
時鐘源的結構體定義為struct hrtimer_clock_base,其中有兩個域struct rb_node *first和struct rb_root active,這兩個域維護了hrtimer的紅黑樹。也就是說,每一個hrtimer_clock_base都維護了自己的一個紅黑樹。
hrtimer在初始化時,都需要加入到某一個時鐘源的紅黑樹中,這個時鐘源要麼是REALTIME,要麼是MONOTONIC,這個關聯通過struct hrtimer的base域實現。
- struct hrtimer {
- struct rb_node node;
- ktime_t _expires;
- ktime_t _softexpires;
- enum hrtimer_restart (*function)(struct hrtimer *);
- struct hrtimer_clock_base *base;
- unsigned long state;
- #ifdef CONFIG_TIMER_STATS
- int start_pid;
- void *start_site;
- char start_comm[16];
- #endif
- };