我编写了一个启动 hrtimer 的 linux 模块,它的回调函数每 20us 调用一次。假设开始时间为0,那么回调函数的执行时间应该是20us、40us、60us,……,但是在我的程序中,结果是在某些情况下,回调函数的执行可能会延迟一个很久。我想知道为什么会这样。
我的模块在 x86_64 平台上运行,tsc 用于计算延迟。以下是我的代码:
static enum hrtimer_restart hwt_timer_fn(struct hrtimer *timer) {
unsigned long long tick_start;
rdtscll(tick_start);
tick_err = tick_start - cmp_cycle;
cmp_cycle += tick_cycle; //cmp_cycle means the next execute time of the callback function
hrtimer_add_expires(timer, expires);
count++;
if(tick_err > max_err)
max_err = tick_err;
if(tick_err < min_err)
min_err = tick_err;
return HRTIMER_RESTART;
}
static int kthread_hrtimer(void *arg) {
struct timespec val;
unsigned long long tick_start;
val.tv_sec = 0;
val.tv_nsec = 20*1000;
expires = timespec_to_ktime(val);
count = 0;
max_err = min_err = 0;
tick_cycle = cpu_khz/50; //the tsc cycle of 20us
printk("cpu_freq:%u,tick_cycle:%llu\n",cpu_khz,tick_cycle);
hrtimer_init(&timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
timer.function = hwt_timer_fn;
rdtscll(tick_start);
hrtimer_start(&timer,expires,HRTIMER_MODE_REL);
cmp_cycle = tick_start + tick_cycle;
return 0;
}
int hwt_timer_init(void) {
cpumask_t mask;
cpus_clear(mask);
cpu_set(0,mask);
thread = kthread_create(kthread_hrtimer,NULL,"kthread_hrtimer");
if(IS_ERR(thread))
{
printk("create failure\n");
return 1;
}
set_cpus_allowed_ptr(thread,&mask);
wake_up_process(thread);
return 0;
}
void hwt_timer_exit(void) {
while(hrtimer_try_to_cancel(&timer) < 0);
printk("max_err:%lld,min_err:%lld\n",max_err,min_err);
printk("count:%lld\n",count);
printk("\n\n");
}