garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/x86_64/timer.rs

raw

//! Time on a PC: the time-stamp counter for the clock, its rate from CPUID
//! where the core says it, else measured against the PIT's 1.193182 MHz
//! once at boot ([`calibrate`]); each core's local APIC timer for its
//! interrupts. Tickless as on ARM: at each switch the scheduler sets the
//! core's timer to what is due next there ([`arm`]), or turns it off.

use core::sync::atomic::{AtomicU64, Ordering};

/// Time slices a second, while tasks share a core.
pub const HZ: u64 = 100;
/// A time slice, in ms.
pub const SLICE_MS: u64 = 1000 / HZ;

static TSC_HZ: AtomicU64 = AtomicU64::new(0);
static START: AtomicU64 = AtomicU64::new(0);

/// Timer interrupts taken, by core.
static FIRED: [AtomicU64; crate::smp::MAX_CORES] = [const { AtomicU64::new(0) }; crate::smp::MAX_CORES];

/// The counter's rate, in Hz.
pub fn frequency() -> u64 {
    TSC_HZ.load(Ordering::Relaxed)
}

/// Finds the counter's rate, on the boot core, before anything asks the
/// time.
pub fn calibrate() {
    let top = crate::arch::cpuid(0)[0];
    let leaf = crate::arch::cpuid(0x15);
    let hz = if top >= 0x15 && leaf[0] != 0 && leaf[1] != 0 && leaf[2] != 0 {
        u64::from(leaf[2]) * u64::from(leaf[1]) / u64::from(leaf[0])
    } else if let Some(hz) = measure() {
        hz
    } else if top >= 0x16 && crate::arch::cpuid(0x16)[0] != 0 {
        // Intel's 6th to 10th generation name the ratio but not the
        // crystal (ECX 0), and laptops of those years may have the PIT's
        // clock gated off: the core's base frequency is the counter's.
        u64::from(crate::arch::cpuid(0x16)[0]) * 1_000_000
    } else {
        // Nothing says: a guess the log shows, better than no clock.
        crate::println!("timer: the counter's rate not found, 2 GHz assumed");
        2_000_000_000
    };
    TSC_HZ.store(hz, Ordering::Relaxed);
    START.store(crate::arch::tsc(), Ordering::Relaxed);
}

/// The counter's rate against PIT channel 2, counting down 50 ms with its
/// gate opened and the speaker off. None when the PIT does not count: a
/// laptop's firmware may gate its clock off, and its output then never
/// rises.
fn measure() -> Option<u64> {
    use crate::arch::{in8, out8, tsc};
    const PIT_HZ: u64 = 1_193_182;
    const TICKS: u64 = PIT_HZ / 20;
    let gate = in8(0x61);
    out8(0x61, (gate & !0x02) | 0x01);
    out8(0x43, 0b1011_0000); // channel 2, both bytes, mode 0
    out8(0x42, TICKS as u8);
    out8(0x42, (TICKS >> 8) as u8);
    let start = tsc();
    // Bit 5 of port 0x61 is channel 2's output: high once it reaches 0.
    // No counter runs at 20 GHz: past 1e9 counts (≥ 0.1 s), the PIT is not
    // counting.
    while in8(0x61) & 0x20 == 0 {
        if tsc() - start > 1_000_000_000 {
            out8(0x61, gate);
            return None;
        }
    }
    let end = tsc();
    out8(0x61, gate);
    Some((end - start) * 20)
}

/// Starts this core's timer: a slice from now.
pub fn start() {
    arm(Some(now_ms() + SLICE_MS));
}

/// Sets this core's timer to fire at `deadline` (ms since boot; at once if
/// that has passed), or turns it off.
pub fn arm(deadline: Option<u64>) {
    crate::apic::one_shot(deadline.map(|ms| ms.saturating_sub(now_ms())));
}

/// The timer's interrupt: counted. The switch that follows sets the next.
pub fn tick() {
    FIRED[crate::arch::core_id()].fetch_add(1, Ordering::Relaxed);
}

/// Timer interrupts core `core` has taken.
pub fn fired(core: usize) -> u64 {
    FIRED[core].load(Ordering::Relaxed)
}

/// Core 0's timer interrupts.
pub fn ticks() -> u64 {
    fired(0)
}

/// Milliseconds since boot.
pub fn now_ms() -> u64 {
    let hz = frequency().max(1);
    (crate::arch::tsc() - START.load(Ordering::Relaxed)) * 1000 / hz
}