Linux全局变量jiffies的用法
相关话题
jiffies是Linux系统中的全局变量,与时间有关,那么jiffies变量具体有哪些作用呢?下面小编就给大家介绍下Linux全局变量jiffies的用法,感兴趣的朋友不妨来了解下吧。
系统运行时间以秒为单位,等于jiffies/Hz。
注意,jiffies类型为无符号长整型(unsigned long),其他任何类型存放它都不正确。
将以秒为单位的时间转化为jiffies:
seconds * Hz
将jiffies转化为以秒为单位的时间:
jiffies / Hz
相比之下,内核中将秒转换为jiffies用的多些。
jiffies的内部表示
jiffies定义于文件中:
/*
* The 64-bit value is not atomic - you MUST NOT read it
* without sampling the sequence number in xtime_lock.
* get_jiffies_64() will do this for you as appropriate.
*/
extern u64 __jiffy_data jiffies_64;
extern unsigned long volatile __jiffy_data jiffies;
ld(1)脚本用于连接主内核映像(在x86上位于arch/i386/kernel/vmlinux.lds.S中),然后用jiffies_64变量的初值覆盖jiffies变量。因此jiffies取整个jiffies_64变量的低32位。
访问jiffies的代码只会读取jiffies_64的低32位,通过get_jiffies_64()函数就可以读取整个64位的值。在64位体系结构上,jiffies_64和jiffies指的是同一个变量。
#if (BITS_PER_LONG 《 64)
u64 get_jiffies_64(void);
#else
static inline u64 get_jiffies_64(void)
{
return (u64)jiffies;
}
#endif
在中
#if (BITS_PER_LONG 《 64)
u64 get_jiffies_64(void)
{
unsigned long seq;
u64 ret;
do {
seq = read_seqbegin(&xtime_lock);
ret = jiffies_64;
} while (read_seqretry(&xtime_lock, seq));
return ret;
}
jiffies的回绕wrap around
当jiffies的值超过它的最大存放范围后就会发生溢出。对于32位无符号长整型,最大取值为(2^32)-1,即429496795。如果节拍计数达到了最大值后还要继续增加,它的值就会回绕到0。
内核提供了四个宏来帮助比较节拍计数,它们能正确的处理节拍计数回绕的问题:
/*
* These inlines deal with timer wrapping correctly. You are
* strongly encouraged to use them
* 1. Because people otherwise forget
* 2. Because if the timer wrap changes in future you won‘t have to
* alter your driver code.
*
* time_after(a,b) returns true if the time a is after time b.
*
* Do this with “《0” and “》=0” to only test the sign of the result. A
* good compiler would generate better code (and a really good compiler
* wouldn’t care)。 Gcc is currently neither.
*/
#define time_after(a,b) /
(typecheck(unsigned long, a) && /
typecheck(unsigned long, b) && /
((long)(b) - (long)(a) 《 0))
#define time_before(a,b) time_after(b,a)
#define time_after_eq(a,b) /
(typecheck(unsigned long, a) && /
typecheck(unsigned long, b) && /
((long)(a) - (long)(b) 》= 0))
#define time_before_eq(a,b) time_after_eq(b,a)
/* Same as above, but does so with platform independent 64bit types.
* These must be used when utilizing jiffies_64 (i.e. return value of
* get_jiffies_64() */
#define time_after64(a,b) /
(typecheck(__u64, a) && /
typecheck(__u64, b) && /
((__s64)(b) - (__s64)(a) 《 0))
#define time_before64(a,b) time_after64(b,a)
#define time_after_eq64(a,b) /
(typecheck(__u64, a) && /
typecheck(__u64, b) && /
((__s64)(a) - (__s64)(b) 》= 0))
#define time_before_eq64(a,b) time_after_eq64(b,a)
用户空间和HZ