Having the discussion of tick rate in my previous post, it is therefore appropriate to introduce jiffies in linux kernel. Jiffies is a global variable declared in <linux/jiffies.h> as:

extern unsigned long volatile jiffies;

Its only usage is to store the number of ticks occurred since system start-up. On kernel boot-up, jiffies is initialized to a special initial value, and it is incremented by one for each timer interrupt. As discussed in the previous post, since there are HZ ticks occurred in one second, and thus there are HZ jiffies in a second.

Jiffies and HZ can be used for time conversion. From previous discussion, we know that HZ is defined as number of ticks in one second:

HZ = no. ticks/sec

and jiffies is number of ticks occurred:

jiffies = no. of ticks

Therefore, it is not surprise that the following expression can be used to convert from seconds to unit jiffies:

seconds * HZ

and to convert from jiffies to seconds:

jiffies / HZ

The conversion from jiffies to seconds is typically implemented in user program, where the absolute time is needed to provide a more meaningful unit to user. On the other hand, since kernel rarely cares about the absolute time, conversion from seconds to ticks is a commonly used in kernel. Considering the importance of this conversion in kernel, an example of setting a value for some time in the future is illustrated here:

unsigned long now_tick = jiffies ; // now
unsigned long next_tick = jiffies + 1 ; // one tick from now
unsigned long timer_later = jiffies + (10*HZ) ; // 10s from now
unsigned long time_fraction = jiffies + (HZ/10) ; // 0.1s from now

With the knowledge of HZ and jiffies, the code above is self-explanatory. All variables in the code are declared as unsigned long, which is the data type of jiffies. The first variable, now_tick is assigned with jiffies, which contains number of ticks occurred at the time of assignment. Likewise, the next tick event can be assigned by incrementing the current jiffies by one, as shown in second line of the code.

For time conversion, a time unit is first multiplied with HZ, and summed with jiffies. This is exampled in third line of the code, where jiffies is summed with product of 10 and HZ to result a delay of 10 seconds. In a similar approach, 1/10 is multiplied with HZ, and summed with jiffies to result a fraction of time, which is 0.1 second, as shown in last line of code.