Linux kernel-Timer and time management

Source: Internet
Author: User

Timer and Time management

The system timer is a programmable hardware chip that generates interrupts at a fixed frequency. This interrupt is called a timer interrupt, and its corresponding interrupt handler is responsible for updating the system time and performing tasks that need to be run periodically. The system timer and clock interrupt handlers are the backbone of the Linux system kernel management mechanism.

Another focus is on dynamic timers-a tool for delaying the execution of a program. For example, if the floppy drive motor is not active for a certain amount of time, the floppy driver uses a dynamic timer to turn off the floppy drive motor. The kernel can dynamically create or destroy dynamic timers.

The concept of time in the kernel

The kernel calculates and manages time with the help of the hardware. The hardware provides a system timer for the kernel to calculate elapsed time. The system timer triggers itself at some frequency, resulting in clock interruptions and processing in the kernel clock interrupt handler. This frequency can be programmed to be scheduled, called the beat rate (tick rates). The interval between two consecutive clock interrupts is called a beat (tick), which equals the beat rate of one second.

Wall time and system run time are calculated based on the clock interval.

Cycle rate Hz

The beat rate (HZ) is the frequency of the clock interruption, which represents the number of clock interrupts within one second. For example, hz=100 indicates that 100 clock interrupt programs are triggered within one second.

Increase the benefits of more frequent beat rate interrupts:

Improve the resolution of time-driven events;

Improve the accuracy of time-driven events;

Kernel timers with higher frequency and accuracy;

System calls poll () and select () rely on overhead to perform higher precision;

More granular system time measurement;

Improve the accuracy of process preemption;

Increase the side effects of the beat rate:

Interrupt frequency increases the burden of the system;

Interrupt handlers consume more processor time;

Frequent interrupt processor cache;

Jiffies

Jiffies: A global variable used to record the total number of beats that have been generated since the system started. The kernel initializes the variable to 0 at startup, and then each time the clock interrupt handler increments the value of the variable. Number of interrupts per second hz,jiffies Hz in one second. System Run time = jiffie/hz.

Jiffies use: Calculate elapsed time and time management.

The jiffies variable is always an unsigned long integer (unsignedlong), so on a 32-bit architecture is 32 bits, 64-bit architecture is 64-bit, and when the value of jiffies exceeds its maximum storage range, an overflow occurs, and its value wraps back to 0. The kernel provides four macros to help compare the beat count, which correctly handles the beat count wrapping situation.

Hard Clocks and timers

Real-time Clock (RTC): A device used to persist system time, even when the system is turned off, to provide power-holding system timing by a miniature battery on the motherboard. The system boot kernel initializes the wall time by reading the RTC, and the time is stored in the Xtime variable.

System timer: Kernel timing mechanism, registering interrupt handlers, periodically triggering interrupts, responding to interrupt handlers.

Clock interrupt handlers

The clock interrupt handler can be divided into two parts: architecture-related parts and architecture-independent parts. An architecture-related routine is registered with the kernel as an interrupt handler for the system timer, so that it can operate accordingly when a clock interrupt is generated. While the specific work of a handler depends on a particular architecture, the vast majority of handlers perform the following tasks at a minimum:

1 ) to obtain Xtime_lock lock so that access to the jiffies_64 and the time on the wall Xtime for protection.

2 answer or reset the system clock when needed.

3 The real time clock is updated periodically using the wall time.

4 ) Call the architecture-independent clock routines: Do_timer () .

The Interrupt service program performs the following tasks primarily by invoking an architecture-independent routine Do_timer :

1 ) to jiffies_64 variable Increment 1 (This operation is even in + The bit architecture is also secure, because the previous Xtime_lock lock).

2 updates the statistics for resource consumption, such as the system time and user time consumed by the current process.

3 ) to perform a dynamic timer that has expired.

4 ) Execution Scheduler_tick function.

5 ) to update the time on the wall, which is stored in Xtime variable.

6 ) calculates the average load value.

Actual time

Actual time is the reality of the clock display time, in fact, the kernel is not commonly used this time, mainly user space program sometimes need to get the current time, so the kernel also manages this time. The actual time obtained is read from the RTC when the kernel is initialized after booting. The kernel reads this time and then puts it into the xtime variable in the kernel, and updates the value continuously while the system is running.

Timer

Timers: The basis for managing kernel time, delaying or executing some code execution time. the timer by the structure time_list represents :

struct Timer_list {    struct list_head entry;                    /* Entry for Timer list */       unsigned long expires;                   /* Time value in jiffies units */    spinlock_t lock;                               /* Lock/    void (*function) for protection timer (unsigned long);    /* Timer handler function */    unsigned long data;                       /* Long shaping parameters passed to the processing function */    struct tvec_t_base_s *base;          /* Timer internal value, user do not use */};


Using timers:

struct timer_list my_timer;init_timer (&my_timer);                     /* Initialize Timer */my_timer.expires = jiffies + delay;     /* Number of Beats at timer timeout */my_timer.data = 0;                            /* Pass in 0 value to timer handler */my_timer.function = my_function;      /* Function */add_timer (&my_timer) called by timer timeout;                    /* Activate timer  */


If you need to change the time-out, you can call the mod_timer function:mod_timer function regardless of My_timer is activated and once returned from mod_timer ,themy_timer is activated and a new timing value is set. If my_timer is not activated when called, the function returns 0, otherwise 1is returned.

If you need to stop the timer, you can use the del_timer and del_timer_sync functions .

Deferred execution

In addition to using the timer or the lower half mechanism, kernel code requires other methods to postpone the execution of the task. This delay usually occurs when the hardware is waiting for some work to be done, and the time to wait is often very short.

Busy Waiting:

Busy waiting for an integer multiple of the beat when you want to delay the time, or when the exact requirement is not high to use.

unsigned long delay = jiffies + 5 * hz;while (Time_before (jiffies, delay))  cond_resched ();


The Cond_resched function dispatches a new program to run, but it only takes effect when the need_resched flag is set. In other words, the effective condition of this method is that there are more important tasks in the system that need to be run. Note Because the method calls the scheduler, it can only be used in the context of the process.

Short delay
void Udelay (unsigned long usecs); void Mdelay (unsigned long msecs);

The previous function uses a busy loop to defer a task to a specified number of microseconds, which delays the specified number of milliseconds.

Schedule_timeout

This approach causes tasks that require deferred execution to sleep until the specified delay time runs out and then rerun, but does not guarantee that the sleep time is equal to the specified delay time-only to try to keep the sleep time close to the specified delay time. When the specified time expires, the kernel wakes up the deferred task and re-puts it back into the run queue.

/* Set the task to interruptible Sleep state */set_current_state (task_interruptible);/* Take a nap and wake */schedule_timeout (S * HZ) after "s" seconds;

The only parameter is the relative time of the delay, in jiffies, and note that you must first set the task to task_interruptible or task_uninterruptible one of two states before calling the Schedule_timeout function. Otherwise the task does not sleep.

Because the Schedule_timeout () function needs to invoke the scheduler, the code that calls it must be able to sleep. In short, the calling code must be in the context of the process and cannot hold a lock.

Set the time-out to sleep on the waiting queue

code in the context of a process in order to wait for a specific leave to occur, you can put yourself in the waiting queue and then call the scheduler to perform the new task. Once the event occurs, the kernel calls the wake_up function to wake up the task on the sleep queue and put it back into operation.

Sometimes, waiting for a task on the queue might wait for a specific event to arrive and wait for a specific time to come--and see who comes faster. In this case, the code can simply use the schedule_timeout () function instead of the schedule () function, so that when you want the specified time to expire, the task will be awakened. Of course, the code needs to check the reason for being awakened--it could be waking up to an event, or it might be due to a delay, and possibly because a signal was received--and then the action was taken.


The activated or inactive timer can be used, and if the timer has not been activated, the function returns 0 , or return 1 . Note that this function does not need to be called for timers that have timed out, because they are automatically deleted. The difference is that Del_timer_sync waits for the timer handlers running on the other processors to exit before executing. Therefore , Del_timer_sync cannot be used in an interrupt context. But in terms of security, priority is given to using del_timer_sync.


Reference

Http://www.cnblogs.com/bastard/archive/2012/09/21/2696393.html

Http://www.cnblogs.com/pennant/archive/2012/12/31/2839545.html

Http://www.cnblogs.com/wang_yb/archive/2013/05/10/3070373.html

Linux kernel design and implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.