Skip to main content

ostd/arch/x86/kernel/
tsc.rs

1// SPDX-License-Identifier: MPL-2.0
2#![expect(unused_variables)]
3
4use vstd::{arithmetic::div_mod::lemma_remainder_lower, prelude::*};
5
6use crate::specs::context::{CpuFeatureModel, cpu_feature_model};
7
8/*
9use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10
11use log::info;*/
12use x86::cpuid::cpuid;
13
14/*
15use crate::{
16    arch::{
17        timer::{
18            TIMER_FREQ,
19            pit::{self, OperatingMode},
20        },
21        trap::TrapFrame,
22    },
23    trap::irq::IrqLine,
24};
25*/
26
27/*
28/// The frequency of TSC(Hz)
29pub(in crate::arch) static TSC_FREQ: AtomicU64 = AtomicU64::new(0);
30
31pub fn init_tsc_freq() {
32    let tsc_freq =
33        determine_tsc_freq_via_cpuid().map_or_else(determine_tsc_freq_via_pit, |freq| freq);
34    TSC_FREQ.store(tsc_freq, Ordering::Relaxed);
35    info!("TSC frequency:{:?} Hz", tsc_freq);
36}
37*/
38
39verus! {
40
41impl CpuFeatureModel {
42    /// TSC frequency returned by OSTD in Hz, preserving its leaf gate and kHz truncation.
43    /// `base_eax` records the raw CPUID.16H:EAX value when the fallback reads it.
44    pub open spec fn tsc_frequency_hz(self, base_eax: Option<u32>) -> Option<u64> {
45        if self.max_basic_leaf <= 0x15 || self.tsc_denominator == 0 || self.tsc_numerator == 0 {
46            None
47        } else {
48            let crystal_khz = if self.crystal_hz / 1000 != 0 {
49                self.crystal_hz as int / 1000
50            } else {
51                base_eax.unwrap_or(0) as int * 1000 * self.tsc_denominator
52                    / self.tsc_numerator as int
53            };
54            if crystal_khz == 0 {
55                None
56            } else {
57                Some((crystal_khz * 1000 * self.tsc_numerator / self.tsc_denominator as int) as u64)
58            }
59        }
60    }
61}
62
63} // verus!
64/// Determines TSC frequency via CPUID. If the CPU does not support calculating TSC frequency by
65/// CPUID, the function will return None. The unit of the return value is KHz.
66///
67/// Ref: function `native_calibrate_tsc` in linux `arch/x86/kernel/tsc.c`
68///
69/// ## Safety
70/// - Arithmetic is proved panic-free assuming the CPUID base-frequency products
71///   fit in u32; native CPUID reads are trusted.
72///
73/// ## Functional Correctness
74/// - The result matches the sampled-register calculation, including kHz truncation.
75///   Physical clock accuracy is outside the proof.
76///
77#[verus_spec(
78    with Tracked(base_eax): Tracked<&mut Ghost<Option<u32>>>
79    ensures
80        ({
81            let model = cpu_feature_model();
82            final(base_eax)@.is_some() == (
83                model.max_basic_leaf >= 0x16 && model.tsc_denominator != 0
84                    && model.tsc_numerator != 0 && model.crystal_hz / 1000 == 0
85            )
86        }),
87    returns cpu_feature_model().tsc_frequency_hz(final(base_eax)@)
88)]
89pub fn determine_tsc_freq_via_cpuid() -> Option<u64> {
90    proof! {
91        *base_eax = Ghost(None);
92    }
93    // Check the max cpuid supported
94    let cpuid = cpuid!(0);
95    let max_cpuid = cpuid.eax;
96    if max_cpuid <= 0x15 {
97        return None;
98    }
99
100    // TSC frequecny = ecx * ebx / eax
101    // CPUID 0x15: Time Stamp Counter and Nominal Core Crystal Clock Information Leaf
102    let mut cpuid = cpuid!(0x15);
103    if cpuid.eax == 0 || cpuid.ebx == 0 {
104        return None;
105    }
106    let eax_denominator = cpuid.eax;
107    let ebx_numerator = cpuid.ebx;
108    let mut crystal_khz = cpuid.ecx / 1000;
109
110    // Some Intel SoCs like Skylake and Kabylake don't report the crystal
111    // clock, but we can easily calculate it to a high degree of accuracy
112    // by considering the crystal ratio and the CPU speed.
113    if crystal_khz == 0 && max_cpuid >= 0x16 {
114        cpuid = cpuid!(0x16);
115        let base_mhz = cpuid.eax;
116        proof! {
117            *base_eax = Ghost(Some(base_mhz));
118            // Assume the hardware-reported base frequency and crystal ratio keep
119            // both intermediate products within u32, as on practical CPUs.
120            assume(base_mhz * 1000 <= u32::MAX);
121            assume(base_mhz * 1000 * eax_denominator <= u32::MAX);
122        }
123        crystal_khz = base_mhz * 1000 * eax_denominator / ebx_numerator;
124        proof! {
125            lemma_remainder_lower(base_mhz * 1000 * eax_denominator, ebx_numerator as int);
126        }
127    }
128
129    if crystal_khz == 0 {
130        None
131    } else {
132        let crystal_hz = crystal_khz as u64 * 1000;
133        proof! {
134            assert(crystal_hz * ebx_numerator <= u64::MAX) by (nonlinear_arith)
135                requires
136                    0 <= crystal_khz * 1000 <= u32::MAX
137                        || 0 <= crystal_khz * ebx_numerator <= u32::MAX,
138                    crystal_hz == crystal_khz * 1000,
139                    0 < ebx_numerator <= u32::MAX,
140            {}
141        }
142        Some(crystal_hz * ebx_numerator as u64 / eax_denominator as u64)
143    }
144}
145
146/*
147/// When kernel cannot get the TSC frequency from CPUID, it can leverage
148/// the PIT to calculate this frequency.
149pub fn determine_tsc_freq_via_pit() -> u64 {
150    // Allocate IRQ
151    let mut irq = IrqLine::alloc().unwrap();
152    irq.on_active(pit_callback);
153
154    // Enable PIT
155    pit::init(OperatingMode::RateGenerator);
156    let irq = pit::enable_interrupt(irq);
157
158    static IS_FINISH: AtomicBool = AtomicBool::new(false);
159    static FREQUENCY: AtomicU64 = AtomicU64::new(0);
160
161    // Wait until `FREQUENCY` is ready
162    loop {
163        crate::arch::irq::enable_local_and_halt();
164
165        // Disable local IRQs so they won't come after checking `IS_FINISH`
166        // but before halting the CPU.
167        crate::arch::irq::disable_local();
168
169        if IS_FINISH.load(Ordering::Acquire) {
170            break;
171        }
172    }
173
174    // Disable PIT
175    drop(irq);
176
177    return FREQUENCY.load(Ordering::Acquire);
178
179    fn pit_callback(trap_frame: &TrapFrame) {
180        static IN_TIME: AtomicU64 = AtomicU64::new(0);
181        static TSC_FIRST_COUNT: AtomicU64 = AtomicU64::new(0);
182        // Set a certain times of callbacks to calculate the frequency
183        const CALLBACK_TIMES: u64 = TIMER_FREQ / 10;
184
185        let tsc_current_count = crate::arch::read_tsc();
186
187        if IN_TIME.load(Ordering::Relaxed) < CALLBACK_TIMES || IS_FINISH.load(Ordering::Acquire) {
188            if IN_TIME.load(Ordering::Relaxed) == 0 {
189                TSC_FIRST_COUNT.store(tsc_current_count, Ordering::Relaxed);
190            }
191            IN_TIME.fetch_add(1, Ordering::Relaxed);
192            return;
193        }
194
195        let tsc_first_count = TSC_FIRST_COUNT.load(Ordering::Relaxed);
196        let freq = (tsc_current_count - tsc_first_count) * (TIMER_FREQ / CALLBACK_TIMES);
197        FREQUENCY.store(freq, Ordering::Release);
198        IS_FINISH.store(true, Ordering::Release);
199    }
200}
201*/