Timer and Time management
The system timer is a programmable hardware chip. It can generate interrupts at a fixed frequency. This interrupt is called a timer interrupt. The corresponding interrupt handler is responsible for updating the system time and also for performing tasks that need to be performed 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 that is used to delay running a program.
Say. Assuming that the floppy drive motor is inactive for a certain amount of time, the floppy driver uses a dynamic timer to turn off the floppy drive motor.
The kernel is capable of dynamically creating or destroying 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. Generates a clock interrupt. Enters the kernel clock interrupt handler for processing. 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). It is equal to one second of the beat rate score.
Wall time and system execution 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 interrupts 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;
Relying on overhead system calls poll () and select () can be performed with higher precision;
The system time is measured more finely.
Improve the accuracy of process preemption;
Increase the side effects of the beat rate:
Interrupt frequency increase system burden added;
Interrupt handlers consume more processor time;
Frequent interrupt processor Fast cache;
Jiffies
Jiffies: A global variable used to record the total number of beats that have been generated since the system started.
At startup, the kernel initializes the variable to 0. Thereafter each time the clock interrupt handler adds the value of the variable. Number of interrupts per second hz,jiffies add Hz within one second. System Execution Time = jiffie/hz.
Jiffies use: Calculate elapsed time and time management.
Jiffies variables are always unsigned long integers (unsignedlong). Therefore, on a 32-bit architecture is 32 bits, the 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 of macros to help with 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 after the system shuts down, the mini-battery on the motherboard provides the timing of the power-holding system. 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. Register interrupt handler, periodically triggering interrupt. Response Interrupt Handler.
Clock interrupt handlers
The clock interrupt handler can be divided into two parts: architecture-related parts and architecture-independent parts. Architecture-related routines are registered in the kernel as interrupt handlers for system timers, so that they can be executed accordingly when a clock interrupt is generated.
Although the detailed work of a handler relies on a particular architecture, the vast majority of handlers perform, for example, the following work:
1 ) to obtain Xtime_lock lock. to protect access to jiffies_64 and Wall time xtime .
2 ) to answer or set the system clock again when required.
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 runs the following tasks primarily by invoking an architecture-independent routine Do_timer :
1 ) to jiffies_64 Variable Additions 1 (This operation is even in + The bit architecture is also secure, because the previous Xtime_lock lock).
2 ) to update the statistical value of resource consumption. For example, the system time and user time consumed by the current process.
3 ) to run a dynamic timer that has expired.
4 ) Run 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
The actual time is the time displayed on the clock in reality. In fact, the kernel does not often use this time, mainly user-space programs sometimes need to get the current time. So the kernel also manages this time. The actual time is acquired after the boot. Read from RTC when the kernel is initialized.
The kernel reads this time and puts it into the xtime variable in the kernel, and updates the value continuously in the execution of the system.
Timer
Timers: The basis for managing kernel time. Run some code at the push or run 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 handler */ struct tvec_t_base_s *base; /* Timer internal value. Users 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.
It is assumed that My_timer was not activated at the time of invocation. The function returns 0. Otherwise , 1is returned.
Suppose you need to stop the timer. Ability to use del_timer and del_timer_sync functions .
Deferred operation
In addition to using the timer or the lower half mechanism, kernel code requires other methods to postpone the task. This delay usually occurs when the hardware is waiting for some work to complete, and the wait time 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 enough to use.
unsigned long delay = jiffies + 5 * hz;while (Time_before (jiffies, delay)) cond_resched ();
The Cond_resched function dispatches a new program into execution, but it only has the ability to take effect after the need_resched flag is set. Other words. The effective condition of this method is that there are more important tasks in the system that need to be executed. Note that 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 method causes the task that needs to be deferred to sleep until the specified delay time is exhausted and then executed again. However, there is no guarantee that the sleep time is equal to the specified delay--just 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 puts it back in the execution queue again.
/* 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 one of task_interruptible or task_uninterruptible two states before calling the Schedule_timeout function. Otherwise the task does not sleep.
Because the Schedule_timeout () function needs to invoke the scheduler. So the code that calls it must be guaranteed 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, can put itself into the waiting queue. Then call the scheduler to run the new task.
Once the event has occurred. The kernel calls the wake_up function to wake up the task on the sleep queue and put it into execution again.
sometimes. Waiting for a task on the queue might be waiting for a specific event to arrive and waiting for a specific time to come--see who comes faster. Such a case. The code can simply replace the schedule () function with the Schedule_timeout () function. So. When you want the specified time to expire. Tasks will be awakened. Of course, the code needs to check the reason for being awakened--it could be awakened by an event. It is also possible that due to the delay time expires, it is possible to receive a signal--and then run the corresponding operation.
activated or inactive timers can be used. Assuming the timer has not yet been activated, the function returns 0, otherwise 1is returned. Attention. There is no need to call this function for timers that have timed out, as they are actively removed by themselves. The difference is that del_timer_sync waits for the timer handlers executing on other processors to exit before executing. Therefore , Del_timer_sync cannot be used in an interrupt context.
But in terms of security considerations. Prefer to use del_timer_sync.
References
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
Linux kernel-Timer and time management