Timer and time management

Source: Internet
Author: User
Tags event timer

Author: gaopenghigh (gaopenghigh@gmail.com), reprinted please indicate the source.

The kernel needs to do two things about time:

  • Save the current time and date.
  • Maintain the timer.
Real-time clock of hardware and circuit (RTC)

Real-Time Clock (RTC) is a device used to store system Time permanently. After the system is shut down, it can also maintain system timing by using the battery on the motherboard. RTC can initiate periodic interruptions on irq8. When the system starts, the kernel initializes the wall time by reading RTC and stores the modification time in the xtime variable.

Timestamp counter (TSC)

All 80x86 processors contain a CLK input lead, which accepts the clock signal of the external oscillator, and also contains a counter, which adds 1 when each clock signal arrives. this Counter is a 64-bit Time Stamp Counter (Time Stamp Counter TSC ).

System Timer

The implementation of timers in various architectures is different, but the fundamental idea is to provide a periodic interrupt mechanism. It can be easily understood as a programmable hardware device, which can send electrical signals at a variable frequency as the interrupt source of clock interruption.

Programmable interval timer (PIT)

The Programmable Interval Timer PIT specifies a fixed frequency within the core and issues a special interrupt, namely, the clock interrupt (timer interrupt ). When Linux is started, it will program the first PIT in the PC to interrupt the clock at a certain frequency. The interval between the two interrupts is called a tick ).

CPU local Timer

The local apic of the 80x86 processor also provides a timing measuring device: the CPU local timer. The difference with PIT is that the local APIC timer only sends the interrupt to its processor, while PIT generates a global disconnection, which can be processed by any CPU in the system.

High-Precision Event timer (HPET)

HPET (High Precision Event Timer), commonly known as High Precision Timer, can provide more accurate time measurement, can be replaced by the configuration of PIT.

ACPI Power Management Timer (ACPI Power Management Timer, acpi pmt)

Acpi pmt is also a timer, mainly used for CPU downgrading or downgrading to save power.

Data Structures and Principles for timing in the kernel

As mentioned above, the computer may have a variety of different timers. during system initialization, the kernel selects the appropriate timer as the interrupt source.

Concept of time-related tick rate in the kernel)

The system timer is triggered at a certain frequency (often called hitting or popping) to interrupt the clock. This frequency can be programmed and scheduled, called the beat rate. The beat rate is defined through static preprocessing, that is, the HZ value.<asm/param.h>This value is defined in.

The advantage of high HZ is that the timer is more accurate, the system call that relies on scheduled execution (such as poll and epoll) is more accurate, the measurement of resource consumption equivalent has more fine-grained Resolution, and the process preemption is more accurate. The disadvantage of high HZ is that high clock interruptions mean a heavy burden on the system.

Tick)

The interval between two consecutive clock interruptions.

Wall time)

Actual time. The wall time is stored in the variable xtime.<kernel/time/timekeeping.c>. The main interface for obtaining the wall time from the user space isgettimeofday()In the kernel, the corresponding system call issys_gettimeofday()In essence, it is to read the content of xtime. The xtime data structure contains the number of seconds since January 1, January 1, 1970 and the number of nanoseconds since the previous second.

Jiffies

Global VariablesjiffiesUsed to record the total number of beats produced since the system was started. In a 64-bit system, this variable is equivalentjiffies_64.

Dynamic Timer

A dynamic timer or kernel timer is a mechanism provided by the kernel, allowing some work to run after a specified time. The data structure of the timer isstruct timer_listThe code is here.

You can use a set of interfaces provided by the kernel to create, modify, and delete timers. A field in the data structure of each timer indicates the expiration time of the timer. All timers are stored together in the form of a linked list. In order for the kernel to find a timeout timer, the kernel divides the timer into five groups based on their timeout time.

The timer uses TIMER_SOFTIRQ to interrupt execution.

Clock interrupt handler

IRQ0 indicates system timer, IRQ8 indicates RTC timer, and IRQ239 indicates local APIC clock interruption.

Work with clock interruption Processing

Clock interrupt processing includes:

  • Updates the system running time and actual time.
  • In the smp system, the running queues on each processor in the balanced scheduler. If the running queues are not balanced, try to balance them.
  • Process scheduling.
  • A dynamic timer for running timeout.
  • Update the statistics of resource consumption and processor time.

In a multi-processor system, all common tasks (such as running time-out dynamic timers and system time updates) are triggered by global timers (PIT or HPET. The work related to each CPU (such as the time consumed by the statistical progress and resource statistics) is triggered by the local timer of each CPU.

Main execution process of the clock interrupt handler
  • Obtain the xtime_lock (protects jiffies_64 and xtime ).
  • It must be a response or a reset of the system clock.
  • Periodically update RTC using the wall time.
  • Call the system structure-independent routine tick_periodic ():
    • Add 1 to the required fies_64 variable.
    • Update the statistical value of resource consumption, such as the system time and user time consumed by the current process.
    • Execute a dynamic timer that has expired.
    • Updates the time slice value of the current process.
    • Update the wall time (the event is stored in the xtime variable ).
    • Calculate the average load value.
Interrupt handler implementation

tick_periodic()The code is here.

/* * Periodic tick */static void tick_periodic(int cpu){        if (tick_do_timer_cpu == cpu) {                write_seqlock(&jiffies_lock);                /* Keep track of the next tick event */                tick_next_period = ktime_add(tick_next_period, tick_period);                do_timer(1);                write_sequnlock(&jiffies_lock);        }        update_process_times(user_mode(get_irq_regs()));        profile_tick(CPU_PROFILING);}

Where:

1

Call update_wall_time () to update the wall time.

2

Call calc_global_load () to calculate the average load. Here is the code.

3

Call update_process_times () to update the various beats:

update_process_times(user_mode(get_irq_regs()));

Whileupdate_process_times()Definition here:

/* * Called from the timer interrupt handler to charge one tick to the current * process.  user_tick is 1 if the tick is user time, 0 for system. */void update_process_times(int user_tick){        struct task_struct *p = current;        int cpu = smp_processor_id();        /* Note: this timer irq context must be accounted for as well. */        account_process_tick(p, user_tick);        run_local_timers();        rcu_check_callbacks(cpu, user_tick);#ifdef CONFIG_IRQ_WORK        if (in_irq())                irq_work_run();#endif        scheduler_tick();        run_posix_cpu_timers(p);}

3.1

user_tickIs used to indicate whether the system time or user time is updated for the process.user_tickThe value is set by viewing the system register. That is to say, when the kernel counts the time of a process, it classifies statistics based on the mode in which the processor is located when the interrupt occurs. It calculates all the previous beats to the process. Although the process may have entered and exited the kernel mode multiple times in the previous cycle, the current process is not necessarily the only process running in the previous cycle.

3.2

run_local_timers()Indicates a Soft Interrupt:raise_softirq(TIMER_SOFTIRQ)To run all expired timers.

3.3

scheduler_tick()The function is responsible for reducing the time slice Count value of the currently running process and setting it as needed.need_reschedFlag. In SMP machines, this function is also responsible for balancing the running queues on each processor.

References:

  • Man pages
  • Advanced Programming in UNIX environment
  • Linux kernel design and implementation
  • Deep understanding of Linux kernel

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.