search
HomeSystem TutorialLINUXDetailed explanation of Linux kernel timer and delay work driver development

Detailed explanation of Linux kernel timer and delay work driver development

Feb 13, 2024 am 11:57 AM
linuxlinux tutoriallinux systemlinux commandshell scripttypedefoverflowembeddedlinuxGetting started with linuxlinux learning

Linux kernel timers and delay work are two commonly used mechanisms to implement scheduled tasks and delayed execution tasks. They allow the driver to execute specific functions at the appropriate time point to adapt to the needs and characteristics of the hardware device. But how do you properly use Linux kernel timers to work with delays? This article will introduce the basic knowledge and skills of Linux kernel timer and delay work driver development from both theoretical and practical aspects, as well as some common problems and solutions.

Detailed explanation of Linux kernel timer and delay work driver development

Kernel timer

The timer on the software ultimately relies on the hardware clock. Simply put, the kernel will detect whether each timer registered to the kernel has expired after the clock interrupt occurs. If it expires, the corresponding registration function will be called back. Do this as an interrupt to the bottom half. In fact, the clock interrupt handler triggers the TIMER_SOFTIRQ soft interrupt and runs all timers that have expired on the current processor.
Device drivers that want to obtain time information and require timing services can use kernel timers.

jiffies

To talk about the kernel timer, we must first talk about an important concept of time in the kernel: jiffies variable, as the basis of the kernel clock, jiffies will increase by 1 every fixed time , called adding a beat. This fixed interval is implemented by timer interrupts. How many timer interrupts are generated per second is determined by the HZ macro defined in . In this way, it can be passed jiffies obtains a period of time, for example jiffies/HZ represents the number of seconds since system startup. The next two seconds are (jiffies/HZ 2). The kernel uses jiffies for timing. Seconds are converted into jiffies: seconds*HZ, so the unit is jiffy and the current time is used as the basis for timing 2 seconds: ( jiffies/HZ 2)*HZ=jiffies 2*HZIf you want to get the current time, you can use **do_gettimeofday()**. This function fills a struct timeval structure with a resolution close to subtle.

//kernel/time/timekeeping.c
 473 /**
 474  * do_gettimeofday - Returns the time of day in a timeval
 475  * @tv:         pointer to the timeval to be set
 476  *
 477  * NOTE: Users should be converted to using getnstimeofday()
 478  */
 479 void do_gettimeofday(struct timeval *tv)   

In order to allow the hardware enough time to complete some tasks, the driver often needs to delay the execution of specific code for a period of time. Depending on the length of the delay, long delay and # are used in kernel development. ##Short delay Two concepts. The definition of long delay is: delay time > multiple jiffies. To achieve long delay, you can use the method of querying jiffies:

time_before(jiffies, new_jiffies);
time_after(new_jiffiesmjiffies);

**The definition of short delay is: the delay event is close to or shorter than one jiffy. To achieve short delay, you can call

udelay();
mdelay();

These two functions are busy waiting functions, which consume a lot of CPU time. The former uses software loops to delay a specified number of microseconds, and the latter uses the nesting of the former to achieve millisecond-level delays.

Timer

The driver can register a kernel timer to specify a function to be executed at a certain time in the future. The timer starts counting when it is registered to the kernel, and the registered function will be executed after the specified time is reached. That is, the timeout value is a jiffies value. When the jiffies value is greater than timer->expires, timer->function will be executed. The API is as follows

//定一个定时器
struct timer_list my_timer;

//初始化定时器
void init_timer(struct timer_list *timer);
mytimer.function = my_function;
mytimer.expires = jiffies +HZ;

//增加定时器
void add_timer(struct timer_list *timer);

//删除定时器
int del_tiemr(struct timer_list *timer);

Example
static struct timer_list tm;
struct timeval oldtv;

void callback(unsigned long arg)
{
    struct timeval tv;
    char *strp = (char*)arg;
    do_gettimeofday(&tv);
    printk("%s: %ld, %ld\n", __func__,
        tv.tv_sec - oldtv.tv_sec,
        tv.tv_usec- oldtv.tv_usec);
    oldtv = tv;
    tm.expires = jiffies+1*HZ;
    add_timer(&tm);
}

static int __init demo_init(void)
{
    init_timer(&tm);
    do_gettimeofday(&oldtv);
    tm.function= callback;
    tm.data    = (unsigned long)"hello world";
    tm.expires = jiffies+1*HZ;
    add_timer(&tm);
    return 0;
}

Delayed work

In addition to using the kernel timer to complete scheduled delay work, the Linux kernel also provides a set of encapsulated "shortcuts" -

delayed_work, which is similar to the kernel timer and essentially uses work queues and timing. Device implementation,

//include/linux/workqueue.h
100 struct work_struct {           
101         atomic_long_t data;
102         struct list_head entry;
103         work_func_t func;
104 #ifdef CONFIG_LOCKDEP
105         struct lockdep_map lockdep_map;
106 #endif
107 };
113 struct delayed_work {              
114         struct work_struct work;
115         struct timer_list timer;
116 
117         /* target workqueue and CPU ->timer uses to queue ->work */
118         struct workqueue_struct *wq;
119         int cpu;
120 };

struct work_struct
–103–>需要延迟执行的函数, typedef void (work_func_t)(struct work_struct work);

至此,我们可以使用一个delayed_work对象以及相应的调度API实现对指定任务的延时执行

//注册一个延迟执行
591 static inline bool schedule_delayed_work(struct delayed_work *dwork,unsigned long delay)
//注销一个延迟执行
2975 bool cancel_delayed_work(struct delayed_work *dwork)    

和内核定时器一样,延迟执行只会在超时的时候执行一次,如果要实现循环延迟,只需要在注册的函数中再次注册一个延迟执行函数。

schedule_delayed_work(&work,msecs_to_jiffies(poll_interval));

本文从理论和实践两方面,详细介绍了Linux内核定时器与延迟工作驱动开发的基本知识和技巧。我们首先了解了Linux内核定时器与延迟工作的概念、原理、特点和API函数,然后学习了如何使用Linux内核定时器与延迟工作来实现按键事件的检测和处理。最后,我们介绍了一些在Linux内核定时器与延迟工作驱动开发过程中可能遇到的问题,以及相应的解决方法。

通过本文,我们希望能够帮助你掌握Linux内核定时器与延迟工作驱动开发的基本方法和技巧,为你在嵌入式Linux领域的进一步学习和工作打下坚实的基础。

The above is the detailed content of Detailed explanation of Linux kernel timer and delay work driver development. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:良许Linux教程网. If there is any infringement, please contact admin@php.cn delete
What are the main tasks of a Linux system administrator?What are the main tasks of a Linux system administrator?Apr 19, 2025 am 12:23 AM

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Is it hard to learn Linux?Is it hard to learn Linux?Apr 18, 2025 am 12:23 AM

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

What is the salary of Linux administrator?What is the salary of Linux administrator?Apr 17, 2025 am 12:24 AM

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

What is the main purpose of Linux?What is the main purpose of Linux?Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Does the internet run on Linux?Does the internet run on Linux?Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations?What are Linux operations?Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

Boost Productivity with Custom Command Shortcuts Using Linux AliasesBoost Productivity with Custom Command Shortcuts Using Linux AliasesApr 12, 2025 am 11:43 AM

Introduction Linux is a powerful operating system favored by developers, system administrators, and power users due to its flexibility and efficiency. However, frequently using long and complex commands can be tedious and er

What is Linux actually good for?What is Linux actually good for?Apr 12, 2025 am 12:20 AM

Linux is suitable for servers, development environments, and embedded systems. 1. As a server operating system, Linux is stable and efficient, and is often used to deploy high-concurrency applications. 2. As a development environment, Linux provides efficient command line tools and package management systems to improve development efficiency. 3. In embedded systems, Linux is lightweight and customizable, suitable for environments with limited resources.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),