当前位置:网站首页>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 )》;
边栏推荐
- [test development] software testing - Basics
- Superscalar processor design yaoyongbin Chapter 7 register rename excerpt
- NFT liquidity market security issues occur frequently - Analysis of the black incident of NFT trading platform quixotic
- [template] [Luogu p4630] duathlon Triathlon (round square tree)
- 我写了一份初学者的学习实践教程!
- 新享科技发布小程序UniPro小优 满足客户移动办公场景
- Firewall basic transparent mode deployment and dual machine hot standby
- Win32 API 访问路由的加密网页
- Offline and open source version of notation -- comprehensive evaluation of note taking software anytype
- 网页游戏引擎
猜你喜欢
Zhijieyun - meta universe comprehensive solution service provider
[Huawei HCIA continuous update] SDN and FVC
Chow Tai Fook fulfills the "centenary commitment" and sincerely serves to promote green environmental protection
Vb无法访问数据库stocks
KS007基于JSP实现人个人博客系统
整理混乱的头文件,我用include what you use
我写了一份初学者的学习实践教程!
leetcode:421. The maximum XOR value of two numbers in the array
Superscalar processor design yaoyongbin Chapter 5 instruction set excerpt
Talk about seven ways to realize asynchronous programming
随机推荐
关于nacos启动时防火墙开启8848的坑
NFT liquidity market security issues occur frequently - Analysis of the black incident of NFT trading platform quixotic
码农版隐秘的角落:作为开发者最讨厌的5件
High school physics: force, object and balance
上网成瘾改变大脑结构:语言功能受影响,让人话都说不利索
detectron2安装方法
中断的顶半部和底半部介绍以及实现方式(tasklet 和 工作队列)
What is low code development?
Superscalar processor design yaoyongbin Chapter 5 instruction set excerpt
将Opencv绘制图片显示在MFC Picture Control控件上
就在今天丨汇丰4位专家齐聚,共讨银行核心系统改造、迁移、重构难题
Leetcode list summary
OPPO小布推出预训练大模型OBERT,晋升KgCLUE榜首
第十八届IET交直流輸電國際會議(ACDC2022)於線上成功舉辦
Zhijieyun - meta universe comprehensive solution service provider
Talk about seven ways to realize asynchronous programming
Developers, MySQL column finish, help you easily from installation to entry
kaili不能输入中文怎么办???
R语言plotly可视化:plotly可视化多分类变量小提琴图(multiple variable violin plot in R with plotly)
聊聊异步编程的 7 种实现方式