1. struct hrtimer
/**
* struct hrtimer - the basic hrtimer structure
* @node: timerqueue node, which also manages node.expires,
* the absolute expiry time in the hrtimers internal
* representation. The time is related to the clock on
* which the timer is based. Is setup by adding
* slack to the _softexpires value. For non range timers
* identical to _softexpires.
* @_softexpires: the absolute earliest expiry time of the hrtimer.
* The time which was given as expiry time when the timer
* was armed.
* @function: timer expiry callback function
* @base: pointer to the timer base (per cpu and per clock)
* @state: state information (See bit values above)
* @is_rel: Set if the timer was armed relative
*
* The hrtimer structure must be initialized by hrtimer_init()
*/
struct hrtimer {
struct timerqueue_node node;
ktime_t _softexpires;
enum hrtimer_restart (*function)(struct hrtimer *);
struct hrtimer_clock_base *base;
u8 state;
u8 is_rel;
};
定时器的到期时间用ktime_t来表示,_softexpires字段记录了时间,定时器一旦到期,function字段指定的回调函数会被调用,该函数的返回值为一个枚举值,它决定了该hrtimer是否需要被重新激活:
/*
* Return values for the callback function
*/
enum hrtimer_restart {
HRTIMER_NORESTART, /* Timer is not restarted */
HRTIMER_RESTART, /* Timer must be restarted */
};
2. 如何使用
1)需要定义一个hrtimer结构的实例
2)用hrtimer_init函数对它进行初始化
/**
* hrtimer_init - initialize a timer to the given clock
* @timer: the timer to be initialized
* @clock_id: the clock to be used
* @mode: timer mode abs/rel
*/
void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
enum hrtimer_mode mode);
其中clock_id可以是CLOCK_REALTIME、CLOCK_MONOTONIC、CLOCK_BOOTTIME中的一种,mode则可以是相对时间HRTIMER_MODE_REL,也可以是绝对时间HRTIMER_MODE_ABS。
3)设定回调函数
timer.function = hr_callback;
4)如果定时器无需指定一个到期范围,可以在设定回调函数后直接使用hrtimer_start激活该定时器;如果需要指定到期范围,则可以使用hrtimer_start_range_ns激活定时器。函数原型:
int hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode);
hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, unsigned long range_ns, const enum hrtimer_mode mode);
5)要取消一个hrtimer,使用hrtimer_cancel
int hrtimer_cancel(struct hrtimer *timer);
3. 示例
static struct hrtimer battery_kthread_timer;
enum hrtimer_restart battery_kthread_hrtimer_func(struct hrtimer *timer)
{
//bat_thread_wakeup();
do something
return HRTIMER_NORESTART;
}
void battery_kthread_hrtimer_init(void)
{
ktime_t ktime;
ktime = ktime_set(1, 0); //set 1s 定时
hrtimer_init(&battery_kthread_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
battery_kthread_timer.function = battery_kthread_hrtimer_func;
hrtimer_start(&battery_kthread_timer, ktime, HRTIMER_MODE_REL);
}