Overview
Thetime module provides system timing functionality using the Intel 8253/8254 Programmable Interval Timer (PIT). The timer is configured to generate interrupts at 100 Hz (every 10 milliseconds) via IRQ0.
Location: kernel/src/time/pit.rs
Configuration
Timer Frequency
Hardware Ports
Initialization
init()
Initializes the PIT to generate periodic interrupts at 100 Hz.
Location: kernel/src/time/pit.rs:45
0x36):
- Bits 7-6:
00= Channel 0 - Bits 5-4:
11= Access mode (low byte, then high byte) - Bits 3-1:
011= Mode 3 (square wave generator) - Bit 0:
0= Binary counter (not BCD)
Tick Counter
TICKS
Global tick counter incremented on each IRQ0 interrupt.
Location: kernel/src/time/pit.rs:17
ticks() function for safe access.
pit_tick()
Interrupt handler called by IRQ0 stub (defined in isr.asm).
Location: kernel/src/time/pit.rs:21
extern "C" calling convention and #[no_mangle] attribute.
Reading Time
ticks()
Atomically reads the current tick count.
Location: kernel/src/time/pit.rs:30
uptime_secs()
Returns system uptime in full seconds.
Location: kernel/src/time/pit.rs:36
uptime_hms()
Decomposes uptime into hours, minutes, and seconds.
Location: kernel/src/time/pit.rs:39
(hours, minutes, seconds).
Implementation:
Usage Examples
Basic Timing
Measuring Execution Time
Periodic Task Scheduling
Uptime Display
IRQ0 Integration
The PIT is wired to IRQ0 (interrupt vector 0x20) in the IDT: Location:kernel/src/arch/idt.rs:149
irq0_handler assembly stub (in isr.asm) calls pit_tick() and sends EOI to the PIC:
Technical Details
Timer Resolution
- Frequency: 100 Hz
- Period: 10 ms per tick
- Resolution: Minimum measurable interval is 10 ms
- Maximum uptime: 2^64 ticks ≈ 5.8 billion years at 100 Hz
PIT Mode 3 (Square Wave)
Mode 3 generates a square wave output:- Output starts HIGH
- Goes LOW when count reaches N/2
- Returns HIGH when count reaches N
- Automatically reloads and repeats
Atomic Access
All tick counter access uses volatile operations to ensure:- Compiler doesn’t optimize away reads in loops
- No torn reads (partial updates) on 64-bit counter
- Proper memory ordering between IRQ handler and kernel code
Wrapping Behavior
The tick counter uses wrapping arithmetic:Limitations
- Resolution: 10 ms minimum - cannot measure sub-millisecond intervals
- Busy-waiting: No sleep/yield mechanism - delays consume CPU
- Drift: Minor drift possible due to integer divisor rounding (1,193,182 / 11,931 ≈ 100.008 Hz)
- Single Timer: Only channel 0 is used; channels 1-2 unused
Future Enhancements
Possible improvements:- APIC timer support for better resolution and per-core timers
- High Precision Event Timer (HPET) support
- Sleep queue for non-busy waiting
- Monotonic clock abstraction
- Real-time clock (RTC) integration for wall-clock time