21.7 Establishing the Kernel Timekeeping System
Within the Linux kernel, the Timekeeping System is a highly complex hierarchical architecture. It must not only process real-world questions like "what time is it now," but also handle precision scheduling concerns such as "how long has this thread executed" and "wake me up in exactly 1 microsecond."
We can deconstruct the kernel timekeeping system into three core sections: core components, time categories, and update mechanisms.
The system relies on the tight coordination of clock sources (Clocksource), clock event devices (Clock Event Device), and timekeeping logic. A clock source is typically a physical hardware counter (such as the CPU's internal TSC, a motherboard's HPET, or the ACPI Timer). Its sole responsibility is to continuously increment a numerical counter, allowing the kernel to extract fine-grained, nanosecond-level time deltas. A clock event device is a hardware component capable of asserting interrupts (such as the local APIC Timer), which the kernel programs to fire an exception at a precise future moment to drive scheduling and timers. The timekeeper is a global subsystem structure inside the kernel that maintains various independent timelines, tracking the delta values read from the clock source after converting them into standardized human-readable units.
The kernel does not maintain a single monolithic time base; instead, it manages multiple parallel timelines simultaneously, which primarily encompass:
-
Wall Time (CLOCK_REALTIME):
The real-world UTC clock time. This timeline is subject to sudden changes or steps (such as discontinuous adjustments triggered by NTP calibrations or manual administrator modifications). -
Monotonic Time (CLOCK_MONOTONIC):
A continuous time base initialized from 0 at system boot. It is guaranteed to never step backward and is immune to sudden NTP clock-stepping anomalies, making it the primary choice for calculating task execution duration. -
Raw Monotonic Time (CLOCK_MONOTONIC_RAW):
An even lower-level monotonic timeline that is completely insulated from frequency adjustments or fine-tuning updates performed by NTP. -
Boot Time (CLOCK_BOOTTIME):
A specialized monotonic timeline that concurrently tracks and includes the duration spent suspended in low-power system sleep states. -
Atomic Clock Time (CLOCK_TAI):
International Atomic Time, which integrates leap second offset adjustments relative to UTC.
The continuous execution of the timekeeping system relies on a cyclical feedback loop. Initially driven by hardware stimulation, a clock event device fires a periodic or targeted single-shot interrupt. The clock event flow handler tick_handle_periodic() dispatches the core routine tick_periodic(). Following this invocation, tick_periodic() executes do_timer() to update the global system jiffies counter and adjust the wall-clock baseline, triggers update_wall_time() to calibrate the core timekeeper subsystem data, and subsequently delegates process-specific local bookkeeping tasks via update_process_times().
The routine update_process_times() calls run_local_timers(), which internally dispatches hrtimer_run_queues() to evaluate high-resolution timer queues. Concurrently, if the loop uncovers that a traditional low-resolution task within the Timer Wheel has crossed its expiration boundary, run_local_timers() asserts a software interrupt via raise_softirq(TIMER_SOFTIRQ), signaling to the CPU core that an expired timing workload requires immediate attention.
The core timekeeping logic polls the active counter value from the clock source, uses predefined multiplication (Mult) and bit-shifting (Shift) mathematical constants to translate the raw ticks into nanoseconds, and aggregates the resulting delta onto the global timelines managed inside the main timekeeper administrative block (struct timekeeper). The timekeeper handles the registration, management, and distribution of system-wide time bases, serving as the definitive architectural bridge linking low-level physical hardware counters to high-level application time APIs. It operates as a globally unique structural singleton (typically maintained under the context of tk_core), archiving every time-related offset value and operational state flag inside the kernel. Whenever a user application triggers a gettimeofday() system call or an internal kernel module evaluates ktime_get(), the execution path reads directly from a synchronized data replica maintained by this master timekeeper instance.
In simpler terms, the clock source supplies the raw digital pulses, while the timekeeping subsystem translates these pulses into exact metrics inside the timekeeper data structures, guaranteeing that the entire kernel image and all active execution threads reference a synchronized, accurate set of clocks.
Within the kernel bootstrap sequence, the function timekeeping_init() executes immediately succeeding the conclusion of init_timers(), serving as the core framework-level initialization handler for the kernel's timekeeping subsystem. The function is defined within the source file git/kernel/time/timekeeping.c, and its definition is implemented as follows:
void __init timekeeping_init(void)
{
struct timespec64 wall_time, boot_offset, wall_to_mono;
struct timekeeper *tk = &tk_core.timekeeper;
struct clocksource *clock;
unsigned long flags;
read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
if (timespec64_valid_settod(&wall_time) && timespec64_to_ns(&wall_time) > 0) {
persistent_clock_exists = true;
} else if (timespec64_to_ns(&wall_time) != 0) {
pr_warn("Persistent clock returned invalid value");
wall_time = (struct timespec64){0};
}
if (timespec64_compare(&wall_time, &boot_offset) < 0)
boot_offset = (struct timespec64){0};
wall_to_mono = timespec64_sub(boot_offset, wall_time);
raw_spin_lock_irqsave(&timekeeper_lock, flags);
write_seqcount_begin(&tk_core.seq);
ntp_init();
clock = clocksource_default_clock();
if (clock->enable)
clock->enable(clock);
tk_setup_internals(tk, clock);
tk_set_xtime(tk, &wall_time);
tk->raw_sec = 0;
tk_set_wall_to_mono(tk, wall_to_mono);
timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
write_seqcount_end(&tk_core.seq);
raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
}
If init_timers() is conceptually structured to "establish the alarm clock management framework," then timekeeping_init() acts to "calibrate the master system clock."
While init_timers() operates entirely on relative time frames, timekeeping_init() orchestrates absolute time frames. It initializes the real-world time (wall time), boot time, monotonic time, and the underlying default clock source.
The core functionalities responsible for configuring the wall time and system uptime can be broadly partitioned into three primary architectural segments:
-
Polling the current calendar date and chronological time (year, month, day, hours, minutes, seconds) directly from the persistent Real-Time Clock (RTC) chip residing on the motherboard.
-
Bootstrapping the master timekeeper descriptor (struct timekeeper). This global structural singleton archives the kernel's active time axes (such as CLOCK_REALTIME, CLOCK_MONOTONIC, and associated offsets).
-
Binding the active clock source. This pass selects a high-precision hardware counting device (such as the processor's native TSC or an on-board HPET) to serve as the definitive mathematical reference for future time increments.
The routine leverages tk_core.timekeeper as the master timekeeper instance. It first dispatches read_persistent_wall_and_boot_offset() to extract the persistent wall time (routinely harvested from the RTC) alongside the boot offset metric, subsequently auditing whether the resolved timestamp satisfies validation constraints. If the extracted time evaluates as invalid, the routine issues a diagnostic warning and overrides the invalid field by resetting it to 0 (which conceptually tethers the wall time baseline to the Unix Epoch boundary of January 1, 1970). Following this check, it executes timespec64_compare() to evaluate the chronological magnitude of wall_time relative to boot_offset. If wall_time is less than boot_offset, the boot_offset variable is overridden and reset to 0.
Linux concurrently coordinates three critical timeframes: wall time (wall_time, scaling chronologically from the 1970 Epoch), monotonic time (scaling continuously from system boot, excluding durations spent suspended in sleep states), and boot time (scaling continuously from system boot, fully encapsulating sleep durations). Their architectural inter-relationship is mathematically governed by the following equation:
$$monotonic=wall_time + wall_to_mono$$
Where wall_to_mono tracks the explicit structural offset required to translate wall time down to the monotonic timeline.
The invocation of timespec64_sub(boot_offset, wall_time) computes this precise delta between the boot offset and wall time components, mathematically ensuring that the structural equilibrium of the equation is cleanly maintained.
To safeguard state consistency across multi-core, multi-threaded execution environments, Linux heavily relies on specialized locking disciplines to coordinate shared memory access. The subsequent execution block acquires the master timekeeper spinlock and proceeds to initialize the individual tracking fields of the core timekeeper structure. This sequence bootstraps the Network Time Protocol (NTP) state machine, calls tk_setup_internals() to bind the default system clock source onto the timekeeper context, establishes the initial wall-clock time via tk_set_xtime(), and triggers timekeeping_update() to synchronize the global time arrays while broadcasting an explicit architecture notification (TK_CLOCK_WAS_SET) stating that the system clock has been formally established. This initialization sequence is executed under the protection of a sequence lock (seqcount), ensuring that concurrent reading threads can continuously poll time telemetry payload replicas locklessly without stalling the update path.
Only after the conclusion of timekeeping_init() does the operating system gain access to highly precise, nanosecond-level timekeeping. Following this milestone, whenever a low-level hardware clock event device fires a scheduling tick interrupt, the exception handler updates process scheduling tracking parameters via update_process_times(), triggers the software interrupt vector TIMER_SOFTIRQ, and ultimately executes timekeeping_update() to advance the core timekeeper matrices, thereby ensuring that the system's "master clock" ticks forward continuously.