Skip to main content

strat9_kernel/hardware/timer/
hpet.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23// HPET (High Precision Event Timer) Driver
24// Reference: HPET spec 1.0a
25//
26// Uses the kernel's ACPI subsystem (already initialized) to locate the HPET
27// table, then maps and configures the HPET MMIO registers.
28
29#![allow(dead_code)]
30
31use crate::memory::{self, phys_to_virt};
32use core::{
33    ptr,
34    sync::atomic::{AtomicBool, Ordering},
35};
36use spin::Mutex;
37
38const HPET_GENERAL_CAP_ID: usize = 0x000;
39const HPET_GENERAL_CONFIG: usize = 0x010;
40const HPET_MAIN_COUNTER: usize = 0x0F0;
41
42const HPET_CAP_NUM_TIMERS_MASK: u64 = 0x0000_0000_0000_1F00;
43const HPET_CAP_COUNTER_SIZE: u64 = 1 << 13;
44const HPET_CAP_COUNTER_CLK_PERIOD_SHIFT: u32 = 32;
45
46const HPET_CONFIG_ENABLE: u64 = 0x0000_0000_0000_0001;
47
48const GAS_ADDR_SPACE_MEMORY: u8 = 0;
49
50/// HPET MMIO register page size (minimum 1 KiB, map one full page).
51const HPET_MMIO_MAP_SIZE: u64 = 0x1000;
52
53pub struct HpetInfo {
54    base_addr: u64,
55    mmio_base: usize,
56    num_timers: u8,
57    tick_period_fs: u32,
58    tick_period_ns: u32,
59    is_64bit: bool,
60}
61
62unsafe impl Send for HpetInfo {}
63unsafe impl Sync for HpetInfo {}
64
65static HPET_INFO: Mutex<Option<HpetInfo>> = Mutex::new(None);
66static HPET_INITIALIZED: AtomicBool = AtomicBool::new(false);
67
68/// Performs the hpet read operation.
69unsafe fn hpet_read(mmio_base: usize, offset: usize) -> u64 {
70    core::ptr::read_volatile((mmio_base + offset) as *const u64)
71}
72
73/// Performs the hpet write operation.
74unsafe fn hpet_write(mmio_base: usize, offset: usize, value: u64) {
75    core::ptr::write_volatile((mmio_base + offset) as *mut u64, value);
76}
77
78/// Initialize HPET using the already-discovered ACPI table.
79pub fn init() -> Result<(), &'static str> {
80    log::info!("[HPET] Searching for HPET...");
81
82    let hpet_acpi = crate::acpi::hpet::HpetAcpiTable::get().ok_or("HPET ACPI table not found")?;
83
84    // Read packed fields safely using unaligned loads.
85    let gas = unsafe { ptr::read_unaligned(core::ptr::addr_of!(hpet_acpi.gen_addr_struct)) };
86    let base_addr = gas.phys_addr;
87    let address_space = gas.address_space;
88    let comparator_desc =
89        unsafe { ptr::read_unaligned(core::ptr::addr_of!(hpet_acpi.comparator_descriptor)) };
90    let min_tick =
91        unsafe { ptr::read_unaligned(core::ptr::addr_of!(hpet_acpi.min_periodic_clock_tick)) };
92
93    log::info!(
94        "[HPET] Found HPET: base=0x{:x}, comparators={}, min_tick={}",
95        base_addr,
96        (comparator_desc >> 3) & 0x1F,
97        min_tick,
98    );
99
100    if address_space != GAS_ADDR_SPACE_MEMORY {
101        return Err("HPET: address space is not memory-mapped");
102    }
103    if base_addr == 0 || (base_addr & 0x7) != 0 {
104        return Err("HPET: base address invalid or misaligned");
105    }
106
107    // Map the HPET MMIO page(s) into the HHDM before any register access.
108    memory::paging::ensure_identity_map_range(base_addr, HPET_MMIO_MAP_SIZE);
109
110    let mmio_base = phys_to_virt(base_addr) as usize;
111
112    unsafe {
113        let cap_id = hpet_read(mmio_base, HPET_GENERAL_CAP_ID);
114        let num_timers = ((cap_id & HPET_CAP_NUM_TIMERS_MASK) >> 8) as u8 + 1;
115        let is_64bit = (cap_id & HPET_CAP_COUNTER_SIZE) != 0;
116        let tick_period_fs = (cap_id >> HPET_CAP_COUNTER_CLK_PERIOD_SHIFT) as u32;
117        if tick_period_fs == 0 {
118            return Err("HPET counter period is zero");
119        }
120        if tick_period_fs > 1_000_000_000 {
121            return Err("HPET counter period out of range");
122        }
123        let tick_period_ns = core::cmp::max(1, tick_period_fs / 1_000_000);
124
125        let info = HpetInfo {
126            base_addr,
127            mmio_base,
128            num_timers,
129            tick_period_fs,
130            tick_period_ns,
131            is_64bit,
132        };
133
134        *HPET_INFO.lock() = Some(info);
135
136        let mut config = hpet_read(mmio_base, HPET_GENERAL_CONFIG);
137        config &= !0x02;
138        config |= HPET_CONFIG_ENABLE;
139        hpet_write(mmio_base, HPET_GENERAL_CONFIG, config);
140
141        HPET_INITIALIZED.store(true, Ordering::SeqCst);
142
143        log::info!(
144            "[HPET] Initialized: {} timers, {}-bit, {} ns/tick",
145            num_timers,
146            if is_64bit { 64 } else { 32 },
147            tick_period_ns,
148        );
149    }
150
151    Ok(())
152}
153
154/// Read main counter value
155pub fn read_counter() -> u64 {
156    let info = HPET_INFO.lock();
157    match *info {
158        Some(ref hpet) => unsafe { hpet_read(hpet.mmio_base, HPET_MAIN_COUNTER) },
159        None => 0,
160    }
161}
162
163/// Get tick period in nanoseconds
164pub fn tick_period_ns() -> u32 {
165    let info = HPET_INFO.lock();
166    match *info {
167        Some(ref hpet) => hpet.tick_period_ns,
168        None => 0,
169    }
170}
171
172/// Get HPET frequency in Hz
173pub fn frequency_hz() -> u64 {
174    let info = HPET_INFO.lock();
175    match *info {
176        Some(ref hpet) if hpet.tick_period_fs > 0 => {
177            1_000_000_000_000_000u64 / hpet.tick_period_fs as u64
178        }
179        _ => 0,
180    }
181}
182
183/// Check if HPET is initialized
184pub fn is_available() -> bool {
185    HPET_INITIALIZED.load(Ordering::Relaxed)
186}
187
188/// Get number of timers
189pub fn num_timers() -> u8 {
190    let info = HPET_INFO.lock();
191    match *info {
192        Some(ref hpet) => hpet.num_timers,
193        None => 0,
194    }
195}
196
197/// High-precision delay in microseconds.
198///
199/// Reads `mmio_base` and `period_ns` once (single lock acquisition), then
200/// spins on the HPET main counter with direct volatile reads : no further
201/// lock traffic in the hot loop.
202pub fn delay_us(us: u64) {
203    if !is_available() {
204        // Fallback: no HPET, spin roughly (no accurate base).
205        let iters = us.saturating_mul(100);
206        for _ in 0..iters {
207            core::hint::spin_loop();
208        }
209        return;
210    }
211
212    // Snapshot the values we need under a single lock acquisition.
213    let (mmio_base, period_ns) = {
214        let info = HPET_INFO.lock();
215        match *info {
216            Some(ref h) if h.tick_period_ns > 0 => (h.mmio_base, h.tick_period_ns as u64),
217            _ => return,
218        }
219    };
220
221    let ticks_needed = if us == 0 {
222        0
223    } else {
224        core::cmp::max(1, (us.saturating_mul(1000)) / period_ns)
225    };
226
227    // Direct volatile read : no Mutex involved.
228    let start = unsafe { hpet_read(mmio_base, HPET_MAIN_COUNTER) };
229    while unsafe { hpet_read(mmio_base, HPET_MAIN_COUNTER) }.wrapping_sub(start) < ticks_needed {
230        core::hint::spin_loop();
231    }
232}
233
234/// High-precision delay in milliseconds
235pub fn delay_ms(ms: u64) {
236    delay_us(ms.saturating_mul(1000));
237}
238
239/// Get elapsed time since boot in milliseconds
240pub fn uptime_ms() -> u64 {
241    if !is_available() {
242        return 0;
243    }
244
245    let counter = read_counter() as u128;
246    let period_ns = tick_period_ns() as u128;
247    ((counter.saturating_mul(period_ns)) / 1_000_000) as u64
248}
249
250/// Get elapsed time since boot in seconds
251pub fn uptime_secs() -> u64 {
252    uptime_ms() / 1000
253}