当前位置:网站首页>Introduction of time related knowledge in kernel
Introduction of time related knowledge in kernel
2022-07-04 17:43:00 【Snail taking off】
1、 Time related problems to be solved by the kernel
(1) How to measure time difference , How to compare time ;
(2) How to get the current time ;
(3) How to delay the operation for a specified period of time ;
(4) How to schedule asynchronous functions to execute after a specified time ;
2、 Measure the time difference
2.1、 How the kernel measures time
(1)Soc There is time related hardware , Like timers 、RTC etc. , Among them are counters , Is to add one to the value of the counter every other period of time . The value of the counter is saved in
In the register , The kernel can know the value of the counter by reading the register ;
(2) The length of the period that the value of the counter increases can be calculated , It's related to the clock frequency . For example, the clock frequency is 1000hz, Then every 1ms Add one to the value of the counter .
(3) Know the value of the counter and the time interval when the counter value increases , You can calculate how long it took . For example, the value of the counter increases 1000, Then the elapsed time is 1000*1ms=1s;
(4)Soc The built-in clock module may not calculate accurately , Sometimes you need an external clock chip ;
Reference blog :《ARM Chip development (S5PV210 chip )—— Timer 、 watchdog 、RTC》;
2.2、 Macro definition of kernel :HZ
(1) The system clock interrupt is generated by the system timing hardware at periodic intervals , This interval in the kernel is based on HZ To specify ;
(2)HZ In the kernel is a macro definition , Indicates how many clock interrupts occur in the kernel per second ,HZ The value of depends on the platform ;
(3) hypothesis HZ The value of is 100, It means every 10ms The value of the kernel counter is increased by one ;
(4) Generally, it is not modified HZ value , We have chosen the right one in kernel development HZ value , We just need to use HZ value ; Theoretically HZ The greater the value of , The shorter the period the counter increases , We can get a more accurate time , But increasing the clock interrupt frequency will bring additional overhead , Need to strike a balance between the two .
2.3、jiffies Counter
(1) There are two counters in the kernel jiffies and jiffies_64.jiffies_64 yes 64 Bit ( Even in 32 Bit architecture is also 64 position ),jiffies yes unsigned long Type variable , stay 64 Bit architecture is 64 position , stay 32 Bit architecture is 32 position .64 Bit architecture ,jiffies and jiffies_64 identical , stay 32 Bit architecture ,jiffies yes jiffies_64 It's low 32 position ;
(2) Preferred... Usually jiffies, Because of jiffies Your visit is fast ;
(3)jiffies The value of is initialized to 0, Every time the clock interrupt occurs ,jiffies The value of the counter is increased by one . therefore jiffies The value of the counter indicates that since the system was started , How many clock interrupts have occurred .
2.4、HZ and jiffies Relationship between counters
(1)HZ Indicates how many clock interrupts occur per second ,jiffies Record the number of interruptions after the system is started ;
(2) The elapsed time of system startup =jiffies / HZ;
(3) Calculate the time difference =(jiffies1-jiffies2) / HZ;
2.5、 Compare the two jiffies The value of the function
int time_after(unsigned long jiffies1, unsigned long jiffies2); //jiffies1 Represents the time ratio jiffies2 be in the rear , Then return to true
int time_before(unsigned long jiffies1, unsigned long jiffies2); //jiffies1 Represents the time ratio jiffies2 Lean forward , Then return to true
int time_after_eq(unsigned long jiffies1, unsigned long jiffies2); //jiffies1 Represents the time ratio jiffies2 Back or equal , Then return to true
int time_before_eq(unsigned long jiffies1, unsigned long jiffies2); //jiffies1 Represents the time ratio jiffies2 Front or equal , Then return to true
2.6、 Processor specific registers
(1) Sometimes a particularly high time accuracy is required , Some processors have made targeted design in hardware , Provide special time counter register , This is associated with a specific processor , There is no generality ;
(2) such as : stay X86 There are processors in the architecture TSC(timestamp counter, Time stamp counter ) register , It's a 64 Bit register , Record CPU Number of clock cycles ;
2.7、jiffies and struct timespes、struct timeval Structure conversion function
unsigned long timeval_to_jiffies(const struct timeval *value);
void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value);
unsigned long timespec_to_jiffies(const struct timespec *value);
void jiffies_to_timespec(const unsigned long jiffies, struct timespec *value);
3、 Get the current time
// Get the current time of the system
do_gettimeofday(struct timeval * tv);
// Convert the wall clock time to jiffies
static inline unsigned long mktime(const unsigned int year,
const unsigned int mon, const unsigned int day,
const unsigned int hour, const unsigned int min,
const unsigned int sec);
(1) Wall clock time : It refers to the time used in daily life , Expressed in years, days, hours, minutes and seconds ;
(2) In the driver , Generally, it doesn't need wall clock time , Most of them are calculating the time difference , In the upper application, wall clock time is used more ;
(3) The kernel provides functions to obtain the current timestamp :do_gettimeofday() function , Usage and C Library gettimeofday It's the same ;
(4) The kernel also provides wall clock time conversion to jiffies Function of ;
4、 Delayed Operation
4.1、 Introduction to delayed operation ideas
(1) Device drivers often need to delay the execution of certain code for a period of time , Such as operation a Wait for the operation b Execution completed ;
(2) There are two ways to realize delay operation : Busy waiting and giving up the processor ;
(3) Busy waiting : It still occupies CPU, Until the delay time is met , This is suitable for short delay , Comparing switching processes is also costly ;
(4) Give up the processor : Give up the processor within the delay time , Wait for the delay time to be scheduled , Suitable for long delay ;
4.2、 Waiting in line
Reference blog :《 Process sleep and wake ( Waiting in line )》;
4.3、 Short delay —— Busy waiting
// The time delay function , The three delay functions are all busy wait functions , Therefore, other tasks cannot be run during the delay
void ndelay(unsigned long nsecs);
void udelay(unsigned long usecs);
void mdelay(unsigned long msecs);
4.4、 Short delay —— Give up the processor
// Time delay msecs millisecond
void msleep(unsigned int msecs);
unsigned long msleep_interruptible(unsigned int msecs)
// Time delay seconds second
void ssleep(unsigned int seconds)
5、 Kernel timer
5.1、 Timer Introduction
(1) We need to schedule and execute an action at a certain time , At the same time, the current process will not be blocked until the time point arrives , You can use the kernel timer ; The kernel timer is implemented using interrupts , An interrupt occurs after reaching the specified point in time , Execute the registered function ;
(2) Timer management must be as lightweight as possible ;
(3) Its design must have good scalability when the activity timer increases greatly ;
(4) Most timers expire in a few seconds or minutes at most , There are few timers with long delays ;
(5) The timer should be registered in the same CPU Up operation ;
5.2、struct timer_list Structure
struct timer_list {
struct hlist_node entry;
unsigned long expires; // Expected timer execution jiffies value
void (*function)(unsigned long); // Bound execution function
unsigned long data; // Parameters passed to the execution function
u32 flags;
};
struct timer_list Structure describes timer in kernel , On arrival expires designated jiffies When the value of , perform function function , And put data Pass it to as a parameter function function ;
5.3、 The logical flow of timer work
(1) Build timer : initialization struct timer_list Structure , Binding execution function 、 The ginseng , Set the timing , There is a special initialization function ;
(2) Register the built timer with the kernel ;
(3) The set timing time is reached , Call the registration function ;
(4) Register the timer with the kernel again in the registration function ;
(5) The timer starts counting again , It is equivalent to executing circularly from the second step ;
5.4、 Sample code
/* Implement every second to the kernel log Print a message in */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/timer.h>
static struct timer_list tm;
struct timeval oldtv;
void callback(unsigned long arg)
{
struct timeval tv;
char *strp = (char*)arg;
printk("%s: %lu, %s\n", __func__, jiffies, strp);
do_gettimeofday(&tv);
printk("%s: %ld, %ld\n", __func__,
tv.tv_sec - oldtv.tv_sec, // Interval from last interrupt s
tv.tv_usec- oldtv.tv_usec); // Interval from last interrupt ms
oldtv = tv;
tm.expires = jiffies+1*HZ;
add_timer(&tm); // Register the timer again , Restart the clock
}
static int __init demo_init(void)
{
printk(KERN_INFO "%s : %s : %d - ok.\n", __FILE__, __func__, __LINE__);
init_timer(&tm); // Initialize the kernel timer
do_gettimeofday(&oldtv); // Get the current time
tm.function= callback; // Specifies the callback function after the timing time
tm.data = (unsigned long)"hello world"; // The parameters of the callback function
tm.expires = jiffies+1*HZ; // The timing is 1s
add_timer(&tm); // Register timer
return 0;
}
static void __exit demo_exit(void)
{
printk(KERN_INFO "%s : %s : %d - ok.\n", __FILE__, __func__, __LINE__);
del_timer(&tm); // Log off timer
}
module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("yikoupeng");
MODULE_DESCRIPTION("timerlist");
The above code is extracted from 《 A bite of linux》;
tasklet Mechanisms and work queues
Reference blog :《 The top half and bottom half of the interrupt are introduced and the implementation method (tasklet and Work queue )》;
边栏推荐
- kaili不能输入中文怎么办???
- Great Wall Securities security does not open a securities account
- 简单易用的地图可视化
- Pytorch深度学习之环境搭建
- Which domestic cloud management platform manufacturer is good in 2022? Why?
- CocosCreator事件派发使用
- 整理混乱的头文件,我用include what you use
- 【Proteus仿真】基于VSM 串口printf调试输出示例
- 超标量处理器设计 姚永斌 第6章 指令解码 摘录
- Perfectly integrated into win11 style, Microsoft's new onedrive client is the first to see
猜你喜欢
Zebras are recognized as dogs, and the reason for AI's mistakes is found by Stanford
[HCIA continuous update] WLAN overview and basic concepts
7 RSA Cryptosystem
解读数据安全治理能力评估框架2.0,第四批DSG评估征集中
解决el-input输入框.number数字输入问题,去掉type=“number“后面箭头问题也可以用这种方法代替
VB cannot access database stocks
Electronic pet dog - what is the internal structure?
Kunming Third Ring Road Closure project will pass through these places. Is there one near your home?
上网成瘾改变大脑结构:语言功能受影响,让人话都说不利索
kaili不能输入中文怎么办???
随机推荐
Is it safe for CITIC Securities to open an account online? Is the account opening fee charged
regular expression
Using win10 scheduling task program to automatically run jar package at fixed time
解决el-input输入框.number数字输入问题,去掉type=“number“后面箭头问题也可以用这种方法代替
ARTS_20220628
Rainfall warning broadcast automatic data platform bwii broadcast warning monitor
长城证券开户安全吗 证券账户怎么开通
[HCIA continuous update] WLAN overview and basic concepts
Load test practice of pingcode performance test
【Hot100】31. 下一个排列
安信证券属于什么档次 开户安全吗
Go micro tutorial - Chapter 2 go micro V3 using gin and etcd
Pytorch深度学习之环境搭建
Win32 API 访问路由的加密网页
PingCode 性能测试之负载测试实践
超标量处理器设计 姚永斌 第7章 寄存器重命名 摘录
What is low code development?
Two methods of MD5 encryption
网页游戏引擎
NFT流动性市场安全问题频发—NFT交易平台Quixotic被黑事件分析