我的目标是使用hrtimer
结构在linux内核中创建一个定期任务。我希望它每500毫秒重复一次。
但是,我对hrtimer
在Linux内核中的工作方式感到有些困惑(参见linux/hrtimer.h
)。我知道时间是指定的,回调应返回HRTIMER_RESTART
或HRTIMER_NORESTART
。我在网上找到了一些来源,说明需要使用hrtimer_forward
方法在回调中重置计时器。然而,我所看到的消息来源对于如何增加时间有点不清楚。这是我到目前为止的代码:
static struct hrtimer timer;
static enum hrtimer_restart timer_callback(struct hrtimer *timer)
{
printk(KERN_ERR "Callback\n");
//I know something needs to go here to reset the timer
return HRTIMER_RESTART;
}
static int init_timer(void)
{
ktime_t ktime;
unsigned long delay_in_ms = 500L;
printk(KERN_ERR "Timer being set up\n");
ktime = ktime_set(0,delay_in_ms*1E6L);
hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
timer.function = &timer_callback;
printk(KERN_ERR "Timer starting to fire\n");
printk(KERN_ERR "in %ldms %ld\n", delay_in_ms, jiffies);
hrtimer_start(&timer, ktime, HRTIMER_MODE_REL);
return 0;
}
static void clean_load_balancing_timer(void)
{
int cancelled = hrtimer_cancel(&timer);
if (cancelled)
printk(KERN_ERR "Timer still running\n");
else
printk(KERN_ERR "Timer cancelled\n");
}
有人可以准确解释重置计时器在回调函数中的工作原理吗?谢谢!
答案 0 :(得分:9)
如果查看函数sched_rt_period_timer中第170行的kernel / sched.c,您将看到一个示例用法。基本路线是
now = hrtimer_cb_get_time(timer);
overrun = hrtimer_forward(timer, now, rt_b->rt_period);
现在得到计时器的当前时间为ktime_t,rt_b-> rt_period是另一个ktime_t,指定推进计时器的时间段。 hrtimer的到期时间将连续增加一段时间,直到它大于当前时间。如果为了使到期时间大于当前时间而花费多于一个周期,则返回值将大于1(表示更多的溢出)。它可以为零,如果计时器到期根本没有进展。
参考:http://lwn.net/Articles/167897/
它使用的API来自内核的不同版本,因此一些参数已经改变。基本思路仍然相同。
答案 1 :(得分:1)
以下是简单的解决方案,
#include <linux/slab.h>
#include <linux/time.h>
#include <asm/string.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/ktime.h>
#define NSEC_PER_MSEC 1000000L
static struct hrtimer hr_timer;
enum hrtimer_restart enHRTimer=HRTIMER_NORESTART;
s64 i64TimeInNsec = 500 * NSEC_PER_MSEC;
enum hrtimer_restart my_hrtimer_callback( struct hrtimer *timer )
{
hrtimer_forward(timer,hrtimer_cb_get_time(timer),ktime_set(0,i64TimeInNsec));
return enHRTimer;
}
void hrtimer_event_init_module(void)
{
ktime_t kt;
enHRTimer = HRTIMER_RESTART;
//HRT init
kt = ktime_set(0, i64TimeInNsec);
hrtimer_init( &hr_timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
hrtimer_set_expires(&hr_timer, kt);
hr_timer.function = &my_hrtimer_callback;
hrtimer_start( &hr_timer, kt, HRTIMER_MODE_ABS);
}
void hrtimer_event_cleanup_module( void )
{
//Reset
hrtimer_cancel(&hr_timer);
enHRTimer = HRTIMER_NORESTART;
printk("HR-Timer module uninstalized\n");
}