当前位置:网站首页>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 )》;
边栏推荐
猜你喜欢
Detectron2 installation method
Implementation of super large-scale warehouse clusters in large commercial banks
我写了一份初学者的学习实践教程!
码农版隐秘的角落:作为开发者最讨厌的5件
聊聊异步编程的 7 种实现方式
Superscalar processor design yaoyongbin Chapter 6 instruction decoding excerpt
防火墙基础透明模式部署和双机热备
Ks007 realizes personal blog system based on JSP
Talk about seven ways to realize asynchronous programming
Offline and open source version of notation -- comprehensive evaluation of note taking software anytype
随机推荐
S5PV210芯片I2C适配器驱动分析(i2c-s3c2410.c)
金额计算用 BigDecimal 就万无一失了?看看这五个坑吧~~
完美融入 Win11 风格,微软全新 OneDrive 客户端抢先看
Solution of dealer collaboration system in building materials industry: empowering enterprises to build core competitiveness
【测试开发】软件测试——基础篇
ARTS_20220628
Implementation of super large-scale warehouse clusters in large commercial banks
一加10 Pro和iPhone 13怎么选?
R language plot visualization: plot visualization of multiple variable violin plot in R with plot
数学分析_笔记_第7章:多元函数的微分学
Superscalar processor design yaoyongbin Chapter 6 instruction decoding excerpt
Chow Tai Fook fulfills the "centenary commitment" and sincerely serves to promote green environmental protection
Detectron2 installation method
Two methods of MD5 encryption
I2C子系统之适配器的设备接口分析(i2c-dev.c文件分析)
超标量处理器设计 姚永斌 第7章 寄存器重命名 摘录
Ks007 realizes personal blog system based on JSP
【HCIA持续更新】WLAN工作流程概述
【华为HCIA持续更新】SDN与FVC
MVC mode and three-tier architecture