


Detailed explanation of Linux kernel timer and delay work driver development
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.
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
//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);
udelay(); mdelay();
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;
}
Copy after login
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

Using Docker on Linux can improve development and deployment efficiency. 1. Install Docker: Use scripts to install Docker on Ubuntu. 2. Verify the installation: Run sudodockerrunhello-world. 3. Basic usage: Create an Nginx container dockerrun-namemy-nginx-p8080:80-dnginx. 4. Advanced usage: Create a custom image, build and run using Dockerfile. 5. Optimization and Best Practices: Follow best practices for writing Dockerfiles using multi-stage builds and DockerCompose.

The steps to start Apache are as follows: Install Apache (command: sudo apt-get install apache2 or download it from the official website) Start Apache (Linux: sudo systemctl start apache2; Windows: Right-click the "Apache2.4" service and select "Start") Check whether it has been started (Linux: sudo systemctl status apache2; Windows: Check the status of the "Apache2.4" service in the service manager) Enable boot automatically (optional, Linux: sudo systemctl

When the Apache 80 port is occupied, the solution is as follows: find out the process that occupies the port and close it. Check the firewall settings to make sure Apache is not blocked. If the above method does not work, please reconfigure Apache to use a different port. Restart the Apache service.

The steps to start an Oracle listener are as follows: Check the listener status (using the lsnrctl status command) For Windows, start the "TNS Listener" service in Oracle Services Manager For Linux and Unix, use the lsnrctl start command to start the listener run the lsnrctl status command to verify that the listener is started

This article describes how to effectively monitor the SSL performance of Nginx servers on Debian systems. We will use NginxExporter to export Nginx status data to Prometheus and then visually display it through Grafana. Step 1: Configuring Nginx First, we need to enable the stub_status module in the Nginx configuration file to obtain the status information of Nginx. Add the following snippet in your Nginx configuration file (usually located in /etc/nginx/nginx.conf or its include file): location/nginx_status{stub_status

This article introduces two methods of configuring a recycling bin in a Debian system: a graphical interface and a command line. Method 1: Use the Nautilus graphical interface to open the file manager: Find and start the Nautilus file manager (usually called "File") in the desktop or application menu. Find the Recycle Bin: Look for the Recycle Bin folder in the left navigation bar. If it is not found, try clicking "Other Location" or "Computer" to search. Configure Recycle Bin properties: Right-click "Recycle Bin" and select "Properties". In the Properties window, you can adjust the following settings: Maximum Size: Limit the disk space available in the Recycle Bin. Retention time: Set the preservation before the file is automatically deleted in the recycling bin

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information
