1. Basic concepts of jiffies
jiffies are global variables in the Linux kernel, recording the number of "clock ticking" times after the system is started.
Whenever the system clock interrupt occurs, the jiffies value is increased by 1.
It is the basic unit of kernel measurement time, similar to the "seconds" in our daily lives.
2. HZ: the heartbeat frequency of jiffies
If jiffies are compared to heartbeat counting, then HZ is the frequency of heartbeat. Specifically, HZ defines the number of "heartbeats" of the system clock per second, that is, the number of times jiffies increase per second.
For example: If HZ=100, it is like the heart beats 100 times per second, then each jiffie represents 1/100th of a second, that is, 10 milliseconds. If HZ=1000, just like the heart beats 1000 times per second, then each jiffie represents 1 millisecond.
3. Characteristics of Jiffies
- Variable type: declared as volatile, ensuring that the latest value is read every time
- Memory Alignment: Use cache line alignment to reduce cache conflicts in multiprocessor systems
- Initial value: not starting at 0, but starting at INITIAL_JIFFIES (usually 300 seconds tick count)
- Storage size: Unsigned 32-bit integer for 32-bit system, unsigned 64-bit integer for 64-bit system
4. Comparison of jiffies overflow and time
Jiffies will overflow periodically, making simple sizes more unreliable.
The kernel provides a special comparison function to handle overflow situations:
-
time_after(a,b)
: Check if a is after b -
time_before(a,b)
: Check if a is before b -
time_after_eq(a,b)
: Check whether a is after b or equal to b -
time_before_eq(a,b)
: Check whether a is before b or equal to b
These functions handle overflow problems by turning the unsigned difference into signed numbers.
5. Time unit conversion
The conversion relationship between jiffies and common time units:
- 1 second = HZ jiffies
- 1 millisecond ≈ HZ/1000 jiffies
The kernel provides a conversion function:
- msecs_to_jiffies(): milliseconds to jiffies
- jiffies_to_msecs(): jiffies rotate milliseconds
Since HZ may not be a multiple of 1000, there may be rounding errors in the conversion process.
Summarize
Jiffies are the basis of time management in Linux kernel. Despite its accuracy limitations, its simplicity and reliability make it the most commonly used time counting mechanism. Understanding how jiffies work and best practices is crucial for kernel and driver development.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.