Skip to content
systemcoding.dev
Kernels

Program the PIT and APIC Timer for Timekeeping

Program the 8253 PIT for a periodic tick, then calibrate the local APIC timer against it and run a 1000 Hz tick, with a tick counter and a sleep function.

9 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and Intel logos.

A kernel without a clock cannot sleep, cannot time out, cannot share the CPU between tasks and cannot tell you how long anything took. Every one of those starts with the same device: a counter that interrupts the CPU at a known rate. A PC has several, and two of them are what a hobby kernel meets first. The Programmable Interval Timer, the PIT, is a 1980s chip with a fixed input clock that works everywhere, including every emulator. The local APIC timer is built into each CPU core, is much more flexible, and has a clock frequency that nobody tells you, so you measure it. This post programs both: the PIT in periodic mode for a first tick, then the APIC timer calibrated against the PIT and set to 1,000 interrupts a second. It ends with a tick counter, a millisecond sleep and what to watch for. The interrupt plumbing it uses is in the post on the 8259 PIC and the guide to interrupts, memory and paging.

The PIT

The PIT, the Intel 8253 or 8254, has three channels, each with a 16-bit down-counter fed by a clock of 1,193,182 Hz. That number, 14.31818 MHz divided by 12, is a leftover from the original IBM PC, and it has been kept so that old software works. The channels have fixed jobs: channel 0 is connected to IRQ 0 and is the system timer, channel 1 once refreshed memory, and channel 2 drives the PC speaker and can be read through a status bit.

The ports:

PortUse
0x40Channel 0 data
0x41Channel 1 data
0x42Channel 2 data
0x43Mode and command register, write only

A command byte written to 0x43 selects a channel, an access mode and an operating mode:

BitsFieldValues
7 to 6Channel0, 1, 2, or 3 for readback
5 to 4Access1 low byte, 2 high byte, 3 low then high, 0 latch count
3 to 1Operating mode0 interrupt on terminal count, 2 rate generator, 3 square wave
0BCD0 for binary

For a periodic timer interrupt, the usual choice is mode 3 or mode 2. Channel 0, access low and high byte, mode 3, binary, is the byte 00 11 011 0 = 0x36. After the command, write the 16-bit divisor, low byte first, to port 0x40. The interrupt rate is the input clock divided by the divisor.

timer.cc
#define PIT_CHANNEL0 0x40
#define PIT_COMMAND  0x43
#define PIT_HZ       1193182UL

void pit_init(uint32_t hz)
{
    uint32_t divisor = PIT_HZ / hz;
    if (divisor > 0xFFFF)
        divisor = 0xFFFF;               /* the slowest tick is about 18.2 Hz */

    outb(PIT_COMMAND, 0x36);
    outb(PIT_CHANNEL0, divisor & 0xFF);
    outb(PIT_CHANNEL0, (divisor >> 8) & 0xFF);
}

For pit_init(100) the divisor is 11,931, and the tick period is 11,931 divided by 1,193,182, which is 9.9998 milliseconds. A divisor of 0 means 65,536, so the longest period is about 54.9 ms. The rate you get is not exactly the rate you asked for, since the divisor is an integer: the error is under 0.01% at 100 Hz, and it accumulates in a kernel clock that counts ticks, which is one reason serious kernels calibrate against a second time source.

A tick counter and a sleep

The handler is short. It increments a counter and returns, with the interrupt controller acknowledged by the dispatcher:

timer.cc
static volatile uint64_t ticks;
static uint32_t tick_hz;

void timer_tick(void)
{
    ticks++;
}

void timer_start(uint32_t hz)
{
    tick_hz = hz;
    irq_register(0, timer_tick);
    pit_init(hz);
    irq_unmask(0);
}

uint64_t time_ms(void)
{
    return ticks * 1000 / tick_hz;
}

void sleep_ms(uint32_t ms)
{
    uint64_t end = time_ms() + ms;
    while (time_ms() < end)
        __asm__ volatile ("hlt");       /* wake on the next interrupt, check again */
}

The volatile on ticks is required, since the compiler must reload it each time around the loop. The sleep uses hlt so the CPU idles between interrupts instead of spinning, and it relies on interrupts being enabled. The granularity is one tick: at 100 Hz, sleep_ms(1) can return after anywhere from 0 to 10 ms. To print once a second you test ticks % 100 == 0 inside the handler's caller, and the output looks like:

Text
uptime: 1 s
uptime: 2 s
uptime: 3 s

The APIC timer

The local APIC contains its own timer, one per core, and the reasons to prefer it are practical. It exists on every CPU, so a multicore kernel can give each core its own tick. It is programmable down to a single bus clock. It does not need the I/O APIC or the PIC to route its interrupt, because it delivers a local vector directly. And the PIT, an ISA-era device, is gone from some modern chipsets or reached through slow legacy paths.

The problem is its clock. The APIC timer counts at a rate derived from the core crystal clock or the bus clock, divided by a configurable divider, and the architecture does not say what that frequency is. Modern Intel CPUs can report the crystal frequency through cpuid leaf 0x15, and in many cases it is left at zero, so the portable approach is to measure it against a clock you trust. The PIT is that clock.

The timer's registers are at offsets from the local APIC base, which you read from the IA32_APIC_BASE MSR, 0x1B, normally 0xFEE00000, mapped into the kernel's address space as uncached memory:

OffsetRegister
0xB0End of interrupt
0xF0Spurious interrupt vector, bit 8 enables the APIC
0x320LVT timer
0x380Initial count
0x390Current count
0x3E0Divide configuration

Access helpers read and write 32-bit values through a volatile pointer:

apic.cc
static volatile uint32_t *lapic;        /* virtual address of the local APIC page */

static inline uint32_t lapic_read(uint32_t reg)
{
    return lapic[reg / 4];
}

static inline void lapic_write(uint32_t reg, uint32_t value)
{
    lapic[reg / 4] = value;
}

#define LAPIC_EOI       0x0B0
#define LAPIC_SVR       0x0F0
#define LAPIC_LVT_TIMER 0x320
#define LAPIC_TIMER_INIT 0x380
#define LAPIC_TIMER_CUR  0x390
#define LAPIC_TIMER_DIV  0x3E0

The index is reg / 4 because the pointer is to 32-bit words and the registers are at byte offsets. The registers are 16 bytes apart in the architecture, but only the first dword of each is used.

Calibrating the APIC timer against the PIT

The calibration runs the APIC timer for a fixed, known interval measured by the PIT, and counts how far the APIC counter fell. The interval is measured with PIT channel 2, whose output can be read from a status bit with no interrupt involved. Port 0x61 controls channel 2's gate and speaker: bit 0 enables the gate, bit 1 enables the speaker, and bit 5 reads the channel's output. With the speaker off, channel 2 in mode 0, interrupt on terminal count, counts down from the programmed value and sets its output bit when it reaches zero. A divisor of 11,932 gives 10 milliseconds (11,932 / 1,193,182 = 0.0100 s).

apic.cc
static uint32_t apic_ticks_per_ms;

void apic_timer_calibrate(void)
{
    lapic_write(LAPIC_TIMER_DIV, 0x3);              /* divide by 16 */

    /* Channel 2: gate on, speaker off. */
    outb(0x61, (inb(0x61) & 0xFD) | 0x01);
    outb(0x43, 0xB0);                               /* channel 2, lo/hi, mode 0, binary */
    outb(0x42, 11932 & 0xFF);
    outb(0x42, 11932 >> 8);

    /* Restart the gate so counting starts from the programmed value. */
    uint8_t g = inb(0x61) & 0xFE;
    outb(0x61, g);
    outb(0x61, g | 0x01);

    lapic_write(LAPIC_TIMER_INIT, 0xFFFFFFFF);      /* start the APIC timer counting down */

    while (!(inb(0x61) & 0x20))                     /* wait for the PIT to reach zero */
        ;

    uint32_t elapsed = 0xFFFFFFFF - lapic_read(LAPIC_TIMER_CUR);
    lapic_write(LAPIC_TIMER_INIT, 0);               /* stop it */

    apic_ticks_per_ms = elapsed / 10;
}

The sequence has a reason for each step. The divide configuration value 0x3 selects divide by 16, which slows the counter so that a 32-bit count lasts a useful time. Setting the PIT gate low then high reloads channel 2 and begins counting at a known moment. The APIC timer is written with the largest count and counts down. The loop polls bit 5 of port 0x61, which goes high when the 10 ms interval ends. The number of APIC ticks elapsed in 10 ms, divided by 10, is the rate in ticks per millisecond. Run it once and keep the result, and with interrupts masked, since an interrupt during calibration lengthens the interval and makes the measured rate too low.

On QEMU, the result is a stable, round-looking number, since the emulated APIC timer runs from a fixed internal clock. A representative log line, for a divider of 16:

Text
apic timer: 62500 ticks/ms (divide 16)

That is the value for an emulated clock of 1 GHz and a divider of 16. On real hardware, the number will be different on every model and may vary a little from run to run, which is why it is measured and not assumed. The calibration is accurate to the PIT's resolution, about 0.01%, plus the polling latency of the loop, so repeating it a few times and averaging improves it.

Starting the periodic tick

With the rate known, configure the timer in periodic mode. The LVT timer register holds the interrupt vector in its low byte, a mode field in bits 17 and 18, where 01 means periodic, and a mask bit at bit 16:

apic.cc
#define LAPIC_TIMER_PERIODIC (1u << 17)
#define APIC_TIMER_VECTOR    0xEF

void apic_timer_start(uint32_t hz)
{
    lapic_write(LAPIC_TIMER_DIV, 0x3);
    lapic_write(LAPIC_LVT_TIMER, APIC_TIMER_VECTOR | LAPIC_TIMER_PERIODIC);
    lapic_write(LAPIC_TIMER_INIT, apic_ticks_per_ms * 1000 / hz);
}

For hz of 1,000 the initial count is exactly the ticks per millisecond, and the hardware reloads it each time it reaches zero and raises vector 0xEF. The handler for that vector increments the same tick counter, and acknowledges the interrupt to the local APIC, with a write of zero to the EOI register, since the 8259 is not involved:

apic.cc
void apic_timer_handler(void)
{
    ticks++;
    lapic_write(LAPIC_EOI, 0);
}

Before the timer can fire, the APIC must be software-enabled, by setting bit 8 in the spurious vector register with a valid spurious vector, for example lapic_write(LAPIC_SVR, 0x100 | 0xFF);, and the 8259 must be masked so the PIT's IRQ 0 does not also arrive. The setup of the APIC base and the I/O APIC is in the post on programming the local APIC and I/O APIC.

Which tick rate

The choice of frequency is a trade-off. A higher rate gives finer sleep resolution and more responsive scheduling, and costs more interrupts: at 1,000 Hz, each core spends its time in the handler a thousand times a second, and the cost of an interrupt, saving registers, running the handler, restoring them and the cache disturbance, is paid each time. Linux uses a configurable tick, typically 250 or 1,000 Hz, and many kernels now run tickless, programming the timer for the next event instead of a fixed period. A hobby kernel starts with 100 or 1,000 Hz because it is simple and works, and adds one-shot mode later: in one-shot mode, the APIC timer, with the LVT mode bits clear, fires once after the initial count, and the kernel arms it for the next deadline.

Other time sources

The timer interrupt gives you intervals, not wall-clock time. The real-time clock, the CMOS RTC, holds the date and time and is read through ports 0x70 and 0x71; it is slow and only has one-second granularity without its alarm interrupt. For high-resolution timestamps, the CPU's time stamp counter, read with rdtsc, increments at a rate that on modern CPUs is constant across power states, and a kernel typically calibrates it against the PIT or the APIC timer in the same way. The TSC-deadline mode of the APIC timer lets you program an absolute TSC value for the next interrupt, which suits a tickless design. The HPET and the ACPI power management timer are other memory-mapped or port-based timers described in ACPI tables.

Where this does not fit

This is a boot-time, single-core design. A multicore kernel calibrates once on the boot processor and programs each core's timer separately, or reads a frequency from cpuid. The PIT calibration assumes the PIT is accessible and accurate, which holds for emulators and PCs, and fails on platforms without it. A virtual machine may report a timer that stops or runs at an uncertain rate, so a kernel in a hypervisor often prefers paravirtual clocks. And the tick counter drifts: it counts interrupts, not elapsed time, and a long interrupt-disabled section loses ticks, so a kernel that needs accurate time anchors it to the TSC or the RTC.

Also inAssembly
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.