3. 高精确度计时器(hrtimer)
高精确度计时器(简称 hrtimers)提供一个高精确度的计时器管理框架,这个框架独立于此前讨论过的标准计时器框架,原因是合并这两个框架太复杂。尽管计时器在 jiffies 粒度上运行,hrtimers 在纳秒粒度上运行。
hrtimer 框架的实现方式与标准计时器 API 不同。hrtimer 不使用 buckets 和串联操作,而是维护一个按时间排序的计时器数据结构(按时间顺序插入计时器,以最小化激活时的处理)。这个数据结构是一个 “红-黑” 树,对于注重性能的应用程序很理想(且恰好作为内核中的一个库普遍可用)。
hrtimer 框架作为内核中的一个 API 可用,用户空间应用程序也可以通过 nanosleep、itimers 和 Portable Operating System Interface (POSIX)-timers interface 使用它。hrtimer 框架被主线化(mainlined)到 2.6.21 内核中。
3.1 高精确度计时器 API
hrtimer API 与传统 API 有些相似,但它们之间的一些根本差别是它能够进行额外的时间控制。应该注意的第一点是:时间不是用 jiffies 表示的,而是以一种名为 ktime 的特殊数据类型表示。这种表示方法隐藏了在这个粒度上有效管理时间的一些细节。hrtimer API 正式确认(formalize)了绝对时间和相对时间之间的区别,要求调用者指定类型。
- union ktime {
- s64 tv64;
- #if BITS_PER_LONG != 64 && !defined(CONFIG_KTIME_SCALAR)
- struct {
- # ifdef __BIG_ENDIAN
- s32 sec, nsec;
- # else
- s32 nsec, sec;
- # endif
- } tv;
- #endif
- };
与传统的计时器 API 类似,高精确度计时器通过一个结构表示 — 这里是 hrtimer。这个结构从用户角度定义定时器(回调函数、过期时间等)并包含了管理信息(其中计时器存在于 “红-黑” 树、可选统计数据等中)。
定义过程首先通过 hrtimer_init 初始化一个计时器。这个调用包含计时器、时钟定义和计时器模式(绝对或相对)。使用的时钟在 ./include/linux/time.h 中定义,表示系统支持的各种时钟(比如实时时钟或者单一时钟,后者只表示从一个起点[比如系统启动]开始的时间)。计时器被初始化之后,就可以通过 hrtimer_start 启动。这个调用包含过期时间(在 ktime_t 中)和时间值的模式(绝对或相对值)。
- struct hrtimer {
- struct rb_node node;
- ktime_t _expires;
- ktime_t _softexpires;
- enum hrtimer_restart (*function)(struct hrtimer *);
- struct hrtimer_clock_base *base;
- unsigned long state;
- #ifdef CONFIG_TIMER_STATS
- int start_pid;
- void *start_site;
- char start_comm[16];
- #endif
- };
- void hrtimer_init( struct hrtimer *time, clockid_t which_clock,
- enum hrtimer_mode mode );
- int hrtimer_start(struct hrtimer *timer, ktime_t time, const
- enum hrtimer_mode mode);
hrtimer 启动后,可以通过调用 hrtimer_cancel 或 hrtimer_try_to_cancel 来取消。每个函数都包含将被停止的计时器的 hrtimer 引用。这两个函数的区别在于:hrtimer_cancel 函数试图取消计时器,但如果计时器已经发出,那么它将等待回调函数结束;hrtimer_try_to_cancel 函数也试图取消计时器,但如果计时器已经发出,它将返回失败。
- int hrtimer_cancel(struct hrtimer *timer);
- int hrtimer_try_to_cancel(struct hrtimer *timer);
