当前位置:网站首页>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 )》;
边栏推荐
- 设置窗体透明 隐藏任务栏 与全屏显示
- Vscode modification indentation failed, indent four spaces as soon as it is saved
- 离线、开源版的 Notion—— 笔记软件Anytype 综合评测
- R language plot visualization: plot visualizes overlapping histograms and uses geom at the top edge of the histogram_ The rug function adds marginal rug plots
- S5PV210芯片I2C适配器驱动分析(i2c-s3c2410.c)
- 长城证券安全不 证券开户
- gatling 之性能测试
- 【HCIA持续更新】WLAN概述与基本概念
- OPPO小布推出预训练大模型OBERT,晋升KgCLUE榜首
- Difference between redis' memory obsolescence strategy and expiration deletion strategy
猜你喜欢

The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!

The 18th IET AC / DC transmission International Conference (acdc2022) was successfully held online
![[HCIA continuous update] overview of WLAN workflow](/img/0a/b3986307589a9f7379fe1dd707b9f8.png)
[HCIA continuous update] overview of WLAN workflow

To sort out messy header files, I use include what you use

Chow Tai Fook fulfills the "centenary commitment" and sincerely serves to promote green environmental protection

DataKit——真正的统一可观测性 Agent

第十八届IET交直流輸電國際會議(ACDC2022)於線上成功舉辦
![[test development] software testing - Basics](/img/43/514016f270574fe711e0e15b581022.png)
[test development] software testing - Basics

Ble HCI flow control mechanism

detectron2安装方法
随机推荐
curl 命令妙用
【系统分析师之路】第七章 复盘系统设计(结构化开发方法)
完美融入 Win11 风格,微软全新 OneDrive 客户端抢先看
[template] [Luogu p4630] duathlon Triathlon (round square tree)
使用3DMAX制作一枚手雷
【HCIA持续更新】WLAN概述与基本概念
Offline and open source version of notation -- comprehensive evaluation of note taking software anytype
防火墙基础透明模式部署和双机热备
Ks007 realizes personal blog system based on JSP
How to choose one plus 10 pro and iPhone 13?
解决el-input输入框.number数字输入问题,去掉type=“number“后面箭头问题也可以用这种方法代替
第十八届IET交直流输电国际会议(ACDC2022)于线上成功举办
Difference between redis' memory obsolescence strategy and expiration deletion strategy
大规模服务异常日志检索
补能的争议路线:快充会走向大一统吗?
Great Wall Securities security does not open a securities account
【华为HCIA持续更新】SDN与FVC
CocosCreator事件派發使用
第十八届IET交直流輸電國際會議(ACDC2022)於線上成功舉辦
解读数据安全治理能力评估框架2.0,第四批DSG评估征集中