High resolution timers
Nearly all systems has some kind of Programmable Interrupt Timer (PIT) or High Precision Event Timer (HPET) that is programmed to periodically interrupt the operating system (if not configured with CONFIG_NO_HZ).
The kernel performs several tasks in these ticks such as timekeeping, calculate statistics for the currently running process, schedule a new process and so on. The interrupt occurs at regular intervals - exactly HZ times per second.
HZ is architecture specific and defined in asm-arch/param.h.
Jiffies is a central concept when talking about time management in the Linux kernel. A jiffy is simply the time between ticks. More exactly 1/HZ seconds. HZ has a typical value of 250 on IA-32/AMD64 architectures, and 100 on smaller systems such as ARM.
Most of the time management in the Linux-kernel is based on jiffies, even the timer_list (also known as low-resolution-timers).
High resolution timers (hrtimers) in the Linux kernel is timers that do not use a time specification based on jiffies, but employ nanosecond time stamps. In fact, the low resolution timers are implemented on top of the high-resolution mechanism, but that is another story.
Components of the hrtimer framework that are not universally applicable (not used by the low-resolution timers) is selected by CONFIG_HIGH_RES_TIMERS in the kernel configuration.
Setup a timer
The usage of the hrtimers quite straight forward.
Initialize a struct hrtimer:
1 hrtimer_init(struct hrtimer *timer, clockid_t which_clock, enum hrtimer_mode mode);
timer is a pointer to the instance of the struct hrtimer.
clock is the clock to bind the timer to, often CLOCK_MONOTONIC or CLOCK_REALTIME.
mode specifies if the timer is working with absolute or relative time values. Two constants are available: HRTIMER_MODE_ABS and HRTIMER_MODE_REL.
Set a callback function:
1 mytimer.function = my_callback;
Where my_callback is declared as:
1 enum hrtimer_restart my_callback(struct hrtimer *timer)
Start the timer with hrtimer_start:
1 struct ktime_t delay = ktime_set(5,0);
2 hrtimer_start(&mytimer, delay, CLOCK_MONOTONIC);
ktime_set initialize delay with 5 seconds and 0 nanoseconds.
Wait. The callback function will be called after 5s!
A full example
1 struct hrtimer mytimer;
2 ktime_t delay = ktime_set(5, 0);
3
4 enum hrtimer_restart my_callback(struct hrtimer *timer)
5 {
6 printk("Hello from timer!\n");
7 return HRTIMER_NORESTART;
8 }
9
10 void ....()
11 {
12 hrtimer_init(&mytimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
13 mytimer.function = my_callback;
14
15 hrtimer_start(&mytimer, delay, CLOCK_MONOTONIC);
16 }
Further reading
There is more functions related to the hrtimers. See incude/linux/hrtimer.h for a full list. Other useful functions are:
1 int hrtimer_cancel(struct hrtimer *timer)
2 int hrtimer_try_to_cancel(struct hrtimer *timer)
3 int hrtimer_restart(struct hrtimer *timer)