2023.7.15 linux timer

发布时间 2023-07-15 23:46:08作者: 杨大茄子

Dynamic tick/tickless kernel

If, however, a CPU leaves the idle state upon an interrupt (the architecture code calls handle_IRQ(), which indirectly calls tick_irq_enter()), this CPU tick device is enabled (first in one-shot mode), and before it performs any task, the tick_nohz_irq_ enter() function is called to ensure that jiffies are up to date so that the interrupt handler does not have to deal with a stale jiffy value, and then it resumes the periodic tick, which is kept active until the next call to tick_nohz_idle_stop_tick() (which is essentially called from do_idle()).

Using standard kernel low-precision (low-res) timers    CONFIG_HZ

Jiffies and HZ    zcat /proc/config.gz |grep CONFIG_HZ  ;    #Jiffies每秒增加HZ次,一次tick 就是 1/HZ 秒

Kernel timer APIs

定时器:struct timer_list { struct hlist_node entry; unsigned long expires; void (*function)(struct timer_list *); u32 flags; );

void timer_setup( struct timer_list *timer,  void (*function)( struct timer_list *),  unsigned int flags);  #动态设置一个定时器

#define DEFINE_TIMER(_name, _function) [...]    #静态设置定时器的宏

int mod_timer(struct timer_list *timer, unsigned long expires);  #修改一个定时器,重设它的到期时间,return 0 如果timer先前是不活动的,timer pending 或在执行func则return 1;

void add_timer(struct timer_list *timer);    #启动定时器,需要先把定时器设置好;比如 my_timer.expires = jiffies + ((12 * HZ) / 10); /* 1.2s */ add_timer(&my_timer);

删除或取消定时器:

int del_timer(struct timer_list *timer);    #return 0 if timer is inactive,else 1

int del_timer_sync(struct timer_list *timer);    #会等待每个核心的定时器的func完成后才return,非原子操作专用

int timer_pending(const struct timer_list *timer); #检查timer 状态