Linux内核高精度定时器hrtimer 使用实例
一、内核为高精度定时器重新设计了一套软件架构,它可以为我们提供纳秒级的定时精度,以满足对精确时间有迫切需求的应用程序或内核驱动,以下学习使用hrtimer(high resolution timer)高精度定时器。
二、hrtimer_init函数初始化定时器工作模式。which_clock可以是CLOCK_REALTIME、CLOCK_MONOTONIC、CLOCK_BOOTTIME中的一种,mode则可以是相对时间HRTIMER_MODE_REL,也可以是绝对时间HRTIMER_MODE_ABS。
void hrtimer_init(struct hrtimer *timer, clockid_t which_clock,enum hrtimer_mode mode);
三、设定超时回调函数。
timer.function = hr_callback;
四、使用hrtimer_start激活该定时器。根据time和mode参数的值计算hrtimer的超时时间,并设置到timer->expire域。 expire设置的是绝对时间,所以如果参数mode的值为HRTIMER_MODE_REL(即参数tim的值为相对时间),那么需要将tim的值修正为绝对时间:expire = tim + timer->base->get_time(),调用enqueue_hrtimer,将hrtimer加入到红黑树中。
int hrtimer_start(struct hrtimer *timer, ktime_t tim,const enum hrtimer_mode mode);
五、使用hrtimer_cancel取消一个hrtimer。
int hrtimer_cancel(struct hrtimer *timer);
六、定时器一旦到期,function字段指定的回调函数会被调用,该函数的返回值为一个枚举值,它决定了该hrtimer是否需要被重新激活。
enum hrtimer_restart {HRTIMER_NORESTART, /* Timer is not restarted */HRTIMER_RESTART, /* Timer must be restarted */
};
七、把hrtimer的到期时间推进一个tick周期,返回HRTIMER_RESTART表明该hrtimer需要再次启动,以便产生下一个tick事件。
hrtimer_forward(timer, now, tick_period);return HRTIMER_RESTART;
}
八、测试代码
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include unsigned int timer_count=0;
struct hrtimer hrtimer_test_timer;
ktime_t m_kt;
int value=2000;static enum hrtimer_restart hrtimer_test_timer_poll(struct hrtimer *timer)
{printk("================timer_count=%d ==============\n",timer_count++);hrtimer_forward(timer, timer->base->get_time(), m_kt);//hrtimer_forward(timer, now, tick_period);//return HRTIMER_NORESTART;return HRTIMER_RESTART;
}int hrtimer_test_ioctl(struct inode *n, struct file *f, unsigned int cmd, unsigned long value){}
ssize_t hrtimer_test_write(struct file *f, const char __user *buf, size_t t, loff_t *len){int i;int ret = -1;printk("hrtimer Debug buf:%x size:%d\n",*buf,t);if(*buf == '0'){printk("hrtimer_start\n");m_kt=ktime_set(value / 1000, (value % 1000) * 1000000);hrtimer_start(&hrtimer_test_timer,m_kt, HRTIMER_MODE_REL);}else if(*buf == '1'){printk("hrtimer_cancel\n");hrtimer_cancel(&hrtimer_test_timer);}return t;
}
static const struct file_operations hrtimer_test_fops =
{.owner = THIS_MODULE,.write = hrtimer_test_write,.unlocked_ioctl = hrtimer_test_ioctl,
};struct miscdevice hrtimer_test_dev = {.minor = MISC_DYNAMIC_MINOR,.name = "hrtimer_test",.fops = &hrtimer_test_fops,
};static int __init hrtimer_test_init(void)
{int ret;ret = misc_register(&hrtimer_test_dev);hrtimer_init(&hrtimer_test_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);hrtimer_test_timer.function = hrtimer_test_timer_poll;return 0;}static void __exit hrtimer_test_exit(void)
{misc_deregister(&hrtimer_test_dev);
}module_init(hrtimer_test_init);
module_exit(hrtimer_test_exit);
MODULE_AUTHOR("hrtimer");
MODULE_LICENSE("GPL");
九、运行结果