內核定時器

內核的軟中斷提供了定時器軟中斷的類型 TIMER_SOFTIRQ
所以我們可以使用這個軟中斷來實現定時運行我們的程序
內核提供的API和數據結構如下
struct timer_list {
/*
* All fields that change during normal runtime grouped to the
* same cacheline
*/
struct hlist_node entry; //鏈表
unsigned long expires;//定時時間
void (*function)(unsigned long);//執行函數 定時器到達時間後 執行這個函數
unsigned long data; //傳入參數
u32 flags;
int slack;

#ifdef CONFIG_TIMER_STATS
int start_pid;
void *start_site;
char start_comm[16];
#endif
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
};

1.定義
struct timer_list my_timer;

2.初始化定時器
init_timer(&my_timer);

或者使用DEFINE_TIMER宏來定義
#define DEFINE_TIMER(_name, _function, _expires, _data) \
struct timer_list _name = \
TIMER_INITIALIZER(_function, _expires, _data)

3.增加定時器 去執行
add_timer(&m y_timer);

4.刪除定時器
del_timer(&my_timer);

5.修改定時器的expire
mod_timer(&my_timer, unsigned long expires)

定時器的到期時間往往是在目前的jiffies的基礎上添加 一個時延通常 jiffies + Hz就是1s

同時要想精度高點的定時器的話就是hrtimer的支持 可以從支持到微秒級別
1.初始化hrtimer定時器
void hrtimer_init(struct hrtimer *timer, clockid_t which_clock,enum hrtimer_mode mode);

struct hrtimer mytimer;
hrtimer_init(&mytimer, CLOCK_MONOTONIC,HRTIMER_MODE_REL);
mytimer.function = hr_callback;
2.啓動hrtimer
int hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode);
3.推後定時器的到期時間
static inline u64 hrtimer_forward_now(struct hrtimer *timer, ktime_t interval)
4.要取消一個hrtimer,使用hrtimer_cancel
int hrtimer_cancel(struct hrtimer *timer);

還有一個就是利用工作隊列和定時器實現的delayed_work
struct delayed_work {
struct work_struct work;
struct timer_list timer;

/* target workqueue and CPU ->timer uses to queue ->work */
struct workqueue_struct *wq;
int cpu;

};
可以通過一個函數調用一個delay_work在指定的延時後執行
static inline bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
使用方法
schedue_delayed_work(&work,msecs_to_jiffies(poll_interval));
msecs_to_jiffies可以將毫秒轉化爲jiffies

如果要週期的執行任務 就在delay_work的工作函數中再次調用schedule_delayed_work() 周而復始
取消一個delay_work:
int cancel_delayed_work(struct delayed_work * dwork)

通常驅動中需要用的就是ndelay udelay mdelay 原理就是根據CPU頻率進行一定次數的循環

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章