Skip to main content

strat9_kernel/arch/x86_64/
cpuid.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//! CPU feature detection via CPUID instruction.
24//!
25//! Provides a `CpuInfo` struct populated at boot time with vendor, model,
26//! feature flags, and XSAVE geometry. All subsequent queries go through
27//! `host()` which returns the cached result.
28
29use crate::sync::SpinLock;
30use alloc::string::String;
31use bitflags::bitflags;
32use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33
34bitflags! {
35    /// Logical internal bitmap.
36    ///
37    /// Bit positions do NOT match raw CPUID register positions: flags coming
38    /// from different leaves/sub-registers are reallocated into one `u64`
39    /// space (SMEP/SMAP are deliberately relocated high to avoid collisions).
40    /// Only compare through the named constants : never raw bit positions.
41    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
42    pub struct CpuFeatures: u64 {
43        //  Leaf 0x01 ECX
44        const SSE3      = 1 << 0;
45        const SSSE3     = 1 << 1;
46        const FMA       = 1 << 2;
47        const SSE4_1    = 1 << 3;
48        const SSE4_2    = 1 << 4;
49        const POPCNT    = 1 << 5;
50        const AES_NI    = 1 << 6;
51        const XSAVE     = 1 << 7;
52        const OSXSAVE   = 1 << 8;
53        const AVX       = 1 << 12;
54        const F16C      = 1 << 9;
55        const VMX       = 1 << 10;
56        const X2APIC    = 1 << 11;
57        //  Leaf 0x01 EDX
58        const FPU       = 1 << 16;
59        const TSC       = 1 << 17;
60        const APIC      = 1 << 18;
61        const SSE       = 1 << 19;
62        const SSE2      = 1 << 20;
63        const FXSR      = 1 << 21;
64        //  Leaf 0x07 ECX
65        const SMEP      = 1 << 57; // CPUID(7).EBX bit 7 (relocated to avoid collision)
66        const SMAP      = 1 << 58; // CPUID(7).EBX bit 20 (relocated to avoid collision)
67        //  Leaf 0x07 EBX
68        const AVX2      = 1 << 32;
69        const AVX512F   = 1 << 33;
70        const AVX512BW  = 1 << 34;
71        const AVX512VL  = 1 << 35;
72        const SHA       = 1 << 36;
73        //  Leaf 0x80000001 EDX
74        const NX        = 1 << 48;
75        const PAGES_1G  = 1 << 49;
76        const RDTSCP    = 1 << 50;
77        const LONG_MODE = 1 << 51;
78        //  Leaf 0x80000001 ECX
79        const SVM       = 1 << 56;
80    }
81}
82
83/// XCR0 component bits.
84pub const XCR0_X87: u64 = 1 << 0;
85pub const XCR0_SSE: u64 = 1 << 1;
86pub const XCR0_AVX: u64 = 1 << 2;
87pub const XCR0_OPMASK: u64 = 1 << 5;
88pub const XCR0_ZMM_HI256: u64 = 1 << 6;
89pub const XCR0_HI16_ZMM: u64 = 1 << 7;
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CpuVendor {
93    Intel,
94    Amd,
95    Unknown,
96}
97
98/// Cached CPU identification and feature information.
99#[derive(Debug, Clone)]
100pub struct CpuInfo {
101    pub vendor: CpuVendor,
102    /// Raw CPUID(0) vendor string (EBX:EDX:ECX, 12 bytes, not NUL-terminated).
103    /// Preserves vendors classified as [`CpuVendor::Unknown`] by
104    /// [`Self::vendor_string`].
105    pub vendor_id: [u8; 12],
106    pub features: CpuFeatures,
107    /// Bitmap of extended state components the CPU supports
108    /// (CPUID.(0D,0):EDX:EAX). Capability bitmap, not a maximum value.
109    pub supported_xcr0: u64,
110    /// XSAVE area size (bytes) for the components enabled in XCR0 at
111    /// detect() time (CPUID.(0D,0):EBX). Depends on the OS-enabled state :
112    /// use [`xsave_size_for_xcr0`] for arbitrary masks.
113    pub xsave_size_current: usize,
114    /// XSAVE area size (bytes) required if every supported component were
115    /// enabled (CPUID.(0D,0):ECX). Upper bound for synthetic XCR0 masks.
116    pub xsave_size_max: usize,
117    pub family: u16,
118    pub model: u8,
119    pub stepping: u8,
120    pub model_name: [u8; 48],
121    model_name_len: usize,
122}
123
124impl CpuInfo {
125    /// Return the model name as a `&str`.
126    pub fn model_name_str(&self) -> &str {
127        let bytes = &self.model_name[..self.model_name_len];
128        core::str::from_utf8(bytes).unwrap_or("Unknown")
129    }
130
131    /// Return a vendor id string (e.g. "GenuineIntel").
132    pub fn vendor_string(&self) -> &'static str {
133        match self.vendor {
134            CpuVendor::Intel => "GenuineIntel",
135            CpuVendor::Amd => "AuthenticAMD",
136            CpuVendor::Unknown => "Unknown",
137        }
138    }
139}
140
141static HOST_CPU: SpinLock<Option<CpuInfo>> = SpinLock::new(None);
142static INITIALIZED: AtomicBool = AtomicBool::new(false);
143
144/// Lock-free copy of `CpuInfo::features.contains(XSAVE)`, published by
145/// `init()` before `INITIALIZED` becomes true and never cleared.
146///
147/// The context-switch path (`do_switch_context`, `do_restore_first_task`,
148/// `normalized_xcr0`) must not acquire `HOST_CPU` with interrupts disabled, so
149/// it reads this flag instead. Invariant: `INITIALIZED == true` implies this
150/// flag already holds the frozen boot CPU's XSAVE capability.
151static USES_XSAVE: AtomicBool = AtomicBool::new(false);
152
153/// Lock-free cache of the host's default XCR0 mask, written once during
154/// `init()`.  Used by `normalized_xcr0()` in the context-switch hot path
155/// to avoid acquiring the `HOST_CPU` spinlock with interrupts disabled.
156pub(crate) static HOST_DEFAULT_XCR0_CACHE: AtomicU64 = AtomicU64::new(0);
157
158/// Cached extended-state save profile, frozen once at `init()`.
159///
160/// Precomputed so context-switch / task-creation code never walks CPUID
161/// leaf 0x0D sub-leaves at runtime (see `xsave_size_for_xcr0`, which is
162/// correct but too slow for hot paths).
163#[derive(Debug, Clone, Copy)]
164pub struct XsaveProfile {
165    /// XCR0 mask the kernel programs (x87|SSE|AVX|AVX-512 as available).
166    pub xcr0_mask: u64,
167    /// Save-area size in bytes for that mask, rounded UP to a 64-byte
168    /// multiple so allocators can over-allocate safely.
169    pub area_size: usize,
170    /// Alignment required by the save instruction: XSAVE/XRSTOR fault (#GP)
171    /// on non-64-byte operands; FXSAVE/FXRSTOR only require 16 bytes, but we
172    /// standardize on 64 everywhere (over-alignment is harmless).
173    pub align: usize,
174}
175
176static PROFILE_XCR0: AtomicU64 = AtomicU64::new(0);
177static PROFILE_AREA_SIZE: core::sync::atomic::AtomicUsize =
178    core::sync::atomic::AtomicUsize::new(512);
179
180/// Return the frozen XSAVE profile. Before `init()` (or without XSAVE),
181/// returns the conservative FXSAVE baseline (mask=x87|SSE, 512 bytes).
182pub fn boot_xsave_profile() -> XsaveProfile {
183    let mask = PROFILE_XCR0.load(Ordering::Acquire);
184    let size = PROFILE_AREA_SIZE.load(Ordering::Acquire);
185    XsaveProfile {
186        xcr0_mask: mask,
187        area_size: size,
188        align: 64,
189    }
190}
191
192/// Detect and cache CPU information. Must be called once at BSP boot.
193pub fn init() {
194    crate::e9_mark!(b'X');
195    let info = detect();
196    crate::e9_mark!(b'Y');
197    crate::serial_println!(
198        "[CPUID] {} {} (family={} model={} stepping={})",
199        info.vendor_string(),
200        info.model_name_str(),
201        info.family,
202        info.model,
203        info.stepping,
204    );
205    crate::serial_println!(
206        "[CPUID] features={:?}, supported_xcr0={:#x}, xsave_cur={} xsave_max={}",
207        info.features,
208        info.supported_xcr0,
209        info.xsave_size_current,
210        info.xsave_size_max,
211    );
212    // Compute the default XCR0 *before* publishing `info`, so no reader can
213    // observe INITIALIZED=true with a stale/zero XCR0 cache (the previous
214    // order relied on the locked fallback to paper over the window).
215    let default_xcr0 = default_xcr0_for(&info);
216    // Freeze the boot-time save profile: area size for the kernel's chosen
217    // mask, rounded up to the 64-byte instruction-alignment granularity.
218    //
219    // NOTE: compute the size from the *local* `info`, not via the global
220    // cache (`xsave_size_for_xcr0`/`host_uses_xsave`). Those consult
221    // `INITIALIZED`, which is only published below : so during `init()` they
222    // always fall back to 512 bytes even when AVX/AVX-512 is present, leaving
223    // the XSAVE area too small and corrupting state on the first AVX context
224    // switch.
225    let profile_size = xsave_size_for_info(&info, default_xcr0).div_ceil(64) * 64;
226    PROFILE_XCR0.store(default_xcr0, Ordering::Release);
227    PROFILE_AREA_SIZE.store(profile_size, Ordering::Release);
228
229    crate::e9_mark!(b'J');
230    // Publish the lock-free XSAVE flag before INITIALIZED so a reader that
231    // observes INITIALIZED == true also observes the correct capability.
232    USES_XSAVE.store(
233        info.features.contains(CpuFeatures::XSAVE),
234        Ordering::Release,
235    );
236    *HOST_CPU.lock() = Some(info);
237    crate::e9_mark!(b'K');
238    HOST_DEFAULT_XCR0_CACHE.store(default_xcr0, Ordering::Release);
239    INITIALIZED.store(true, Ordering::Release);
240    crate::e9_mark!(b'i');
241}
242
243/// Return a clone of the cached host CPU info. Panics if `init()` not called.
244pub fn host() -> CpuInfo {
245    HOST_CPU
246        .lock()
247        .clone()
248        .expect("cpuid::init() not called yet")
249}
250
251/// Whether the boot CPU supports XSAVE.
252///
253/// Lock-free: reads the flag published by `init()`. Safe to call from the
254/// context-switch path, which runs with interrupts disabled and must not
255/// acquire `HOST_CPU`.
256pub fn host_uses_xsave() -> bool {
257    INITIALIZED.load(Ordering::Acquire) && USES_XSAVE.load(Ordering::Acquire)
258}
259
260/// Detect CPU features by interrogating CPUID leaves.
261fn detect() -> CpuInfo {
262    let cpuid = super::cpuid;
263    let cpu = raw_cpuid::CpuId::new();
264
265    crate::e9_mark!(b'D');
266    //  Vendor (leaf 0): keep the raw 12-byte id, then classify.
267    //
268    //  `raw_cpuid` only exposes the vendor as a UTF-8 `&str`, which cannot
269    //  preserve arbitrary bytes for vendors it cannot name, so leaf 0 is read
270    //  directly here. Everything below decodes bits via `raw_cpuid` getters.
271    let (max_leaf, ebx0, ecx0, edx0) = cpuid(0, 0);
272    crate::e9_mark!(b'E');
273    crate::e9_mark!(b'a');
274    let mut vendor_id = [0u8; 12];
275    crate::e9_mark!(b'b');
276    let b = ebx0.to_le_bytes();
277    vendor_id[0] = b[0];
278    vendor_id[1] = b[1];
279    vendor_id[2] = b[2];
280    vendor_id[3] = b[3];
281    crate::e9_mark!(b'c');
282    let d = edx0.to_le_bytes();
283    vendor_id[4] = d[0];
284    vendor_id[5] = d[1];
285    vendor_id[6] = d[2];
286    vendor_id[7] = d[3];
287    crate::e9_mark!(b'd');
288    let c = ecx0.to_le_bytes();
289    vendor_id[8] = c[0];
290    vendor_id[9] = c[1];
291    vendor_id[10] = c[2];
292    vendor_id[11] = c[3];
293    crate::e9_mark!(b'e');
294    let vendor = match (ebx0, edx0, ecx0) {
295        (0x756E_6547, 0x4965_6E69, 0x6C65_746E) => CpuVendor::Intel,
296        (0x6874_7541, 0x6974_6E65, 0x444D_4163) => CpuVendor::Amd,
297        _ => CpuVendor::Unknown,
298    };
299    crate::e9_mark!(b'f');
300
301    let mut features = CpuFeatures::empty();
302    let mut stepping = 0u8;
303    let mut family_full = 0u16;
304    let mut model = 0u8;
305
306    //  Leaf 0x01: main feature bits
307    crate::e9_mark!(b'1');
308    let feature_info = cpu.get_feature_info();
309    crate::e9_mark!(b'2');
310    crate::e9_mark!(b'd');
311    crate::e9_mark!(b'f');
312    crate::e9_mark!(b'e');
313    if let Some(fi) = feature_info {
314        stepping = fi.stepping_id();
315        let base_family = fi.base_family_id();
316        family_full = base_family as u16;
317        model = fi.base_model_id();
318        if base_family == 6 || base_family == 15 {
319            model |= fi.extended_model_id() << 4;
320        }
321        if base_family == 15 {
322            family_full += fi.extended_family_id() as u16;
323        }
324
325        if fi.has_sse3() {
326            features |= CpuFeatures::SSE3;
327        }
328        if fi.has_ssse3() {
329            features |= CpuFeatures::SSSE3;
330        }
331        if fi.has_fma() {
332            features |= CpuFeatures::FMA;
333        }
334        if fi.has_sse41() {
335            features |= CpuFeatures::SSE4_1;
336        }
337        if fi.has_sse42() {
338            features |= CpuFeatures::SSE4_2;
339        }
340        if fi.has_popcnt() {
341            features |= CpuFeatures::POPCNT;
342        }
343        if fi.has_aesni() {
344            features |= CpuFeatures::AES_NI;
345        }
346        if fi.has_xsave() {
347            features |= CpuFeatures::XSAVE;
348        }
349        if fi.has_oxsave() {
350            features |= CpuFeatures::OSXSAVE;
351        }
352        if fi.has_avx() {
353            features |= CpuFeatures::AVX;
354        }
355        if fi.has_x2apic() {
356            features |= CpuFeatures::X2APIC;
357        }
358        if fi.has_f16c() {
359            features |= CpuFeatures::F16C;
360        }
361        if fi.has_vmx() {
362            features |= CpuFeatures::VMX;
363        }
364
365        if fi.has_fpu() {
366            features |= CpuFeatures::FPU;
367        }
368        if fi.has_tsc() {
369            features |= CpuFeatures::TSC;
370        }
371        if fi.has_apic() {
372            features |= CpuFeatures::APIC;
373        }
374        if fi.has_fxsave_fxstor() {
375            features |= CpuFeatures::FXSR;
376        }
377        if fi.has_sse() {
378            features |= CpuFeatures::SSE;
379        }
380        if fi.has_sse2() {
381            features |= CpuFeatures::SSE2;
382        }
383    }
384
385    //  Leaf 0x07: extended features
386    crate::e9_mark!(b'3');
387    if let Some(ef) = cpu.get_extended_feature_info() {
388        crate::e9_mark!(b'5');
389        if ef.has_avx2() {
390            features |= CpuFeatures::AVX2;
391        }
392        if ef.has_avx512f() {
393            features |= CpuFeatures::AVX512F;
394        }
395        if ef.has_sha() {
396            features |= CpuFeatures::SHA;
397        }
398        if ef.has_avx512bw() {
399            features |= CpuFeatures::AVX512BW;
400        }
401        if ef.has_avx512vl() {
402            features |= CpuFeatures::AVX512VL;
403        }
404        // SMEP (EBX bit 7): Supervisor Mode Execution Prevention
405        if ef.has_smep() {
406            features |= CpuFeatures::SMEP;
407        }
408        // SMAP (EBX bit 20): Supervisor Mode Access Prevention
409        if ef.has_smap() {
410            features |= CpuFeatures::SMAP;
411        }
412    }
413
414    //  Leaf 0x0D: XSAVE geometry
415    //
416    // CPUID.(0D,0):EDX:EAX = bitmap of components supported by the CPU
417    // (XCR0 candidates). EBX = size of the save area for the components
418    // currently enabled in XCR0 (OS-chosen, not a constant). ECX = size if
419    // every supported component were enabled : the correct upper bound for
420    // synthetic masks. Supervisor states (managed via IA32_XSS, not XCR0)
421    // are filtered out so `supported_xcr0` stays a true XCR0 bitmap.
422    crate::e9_mark!(b'F');
423    let mut supported_xcr0 = XCR0_X87 | XCR0_SSE;
424    let mut xsave_size_current = 512usize;
425    let mut xsave_size_max = 512usize;
426    crate::e9_mark!(b'G');
427    let xsave_check = features.contains(CpuFeatures::XSAVE);
428    crate::e9_mark!(b'g');
429    let leaf0d_check = max_leaf >= 0x0D;
430    crate::e9_mark!(b'h');
431    if xsave_check && leaf0d_check {
432        crate::e9_mark!(b'H');
433        // `raw_cpuid` exposes only the EAX half of the XCR0 bitmap, so the
434        // 64-bit EDX:EAX value is read raw to keep `supported_xcr0` intact.
435        // The area sizes come from the getter.
436        let (eax_d, _ebx_d, _ecx_d, edx_d) = cpuid(0x0D, 0);
437        crate::e9_mark!(b'I');
438        supported_xcr0 = ((edx_d as u64) << 32) | eax_d as u64;
439        if let Some(es) = cpu.get_extended_state_info() {
440            xsave_size_current = es.xsave_area_size_enabled_features() as usize;
441            xsave_size_max = es.xsave_area_size_supported_features() as usize;
442        }
443    } else {
444        crate::e9_mark!(b'H');
445    }
446
447    //  Leaf 0x80000001: extended features (AMD-V, NX, 1G pages)
448    crate::e9_mark!(b'J');
449    let (max_ext, _, _, _) = cpuid(0x8000_0000, 0);
450    crate::e9_mark!(b'K');
451    if let Some(ext) = cpu.get_extended_processor_and_feature_identifiers() {
452        if ext.has_execute_disable() {
453            features |= CpuFeatures::NX;
454        }
455        if ext.has_1gib_pages() {
456            features |= CpuFeatures::PAGES_1G;
457        }
458        if ext.has_rdtscp() {
459            features |= CpuFeatures::RDTSCP;
460        }
461        if ext.has_64bit_mode() {
462            features |= CpuFeatures::LONG_MODE;
463        }
464        if ext.has_svm() {
465            features |= CpuFeatures::SVM;
466        }
467    }
468    crate::e9_mark!(b'L');
469
470    //  Leaves 0x80000002-0x80000004: brand string
471    let mut model_name = [0u8; 48];
472    let mut model_name_len = 0usize;
473    if max_ext >= 0x8000_0004 {
474        for (i, leaf) in (0x8000_0002u32..=0x8000_0004).enumerate() {
475            let (a, b, c, d) = cpuid(leaf, 0);
476            let offset = i * 16;
477            let ab = a.to_le_bytes();
478            model_name[offset] = ab[0];
479            model_name[offset + 1] = ab[1];
480            model_name[offset + 2] = ab[2];
481            model_name[offset + 3] = ab[3];
482            let bb = b.to_le_bytes();
483            model_name[offset + 4] = bb[0];
484            model_name[offset + 5] = bb[1];
485            model_name[offset + 6] = bb[2];
486            model_name[offset + 7] = bb[3];
487            let cb = c.to_le_bytes();
488            model_name[offset + 8] = cb[0];
489            model_name[offset + 9] = cb[1];
490            model_name[offset + 10] = cb[2];
491            model_name[offset + 11] = cb[3];
492            let db = d.to_le_bytes();
493            model_name[offset + 12] = db[0];
494            model_name[offset + 13] = db[1];
495            model_name[offset + 14] = db[2];
496            model_name[offset + 15] = db[3];
497        }
498        model_name_len = model_name
499            .iter()
500            .rposition(|&b| b != 0 && b != b' ')
501            .map_or(0, |p| p + 1);
502    }
503
504    CpuInfo {
505        vendor,
506        vendor_id,
507        features,
508        supported_xcr0,
509        xsave_size_current,
510        xsave_size_max,
511        family: family_full,
512        model,
513        stepping,
514        model_name,
515        model_name_len,
516    }
517}
518
519/// Pure helper: the XCR0 mask this kernel would enable for `info`
520/// (x87 + SSE always, plus AVX / AVX-512 states when the CPU announces
521/// them AND the hardware supports the required XCR0 bits).
522/// Shared by `init()` (pre-lock computation) and `host()`.
523fn default_xcr0_for(info: &CpuInfo) -> u64 {
524    const SSE_BASE: u64 = XCR0_X87 | XCR0_SSE;
525    const AVX_STATE: u64 = SSE_BASE | XCR0_AVX;
526    const AVX512_STATE: u64 = AVX_STATE | XCR0_OPMASK | XCR0_ZMM_HI256 | XCR0_HI16_ZMM;
527
528    if !info.features.contains(CpuFeatures::XSAVE) {
529        return SSE_BASE;
530    }
531
532    let available = info.supported_xcr0;
533    let mut wanted = SSE_BASE;
534
535    if info.features.contains(CpuFeatures::AVX) && (available & AVX_STATE) == AVX_STATE {
536        wanted = AVX_STATE;
537    }
538
539    if info.features.contains(CpuFeatures::AVX512F) && (available & AVX512_STATE) == AVX512_STATE {
540        wanted = AVX512_STATE;
541    }
542
543    wanted
544}
545
546impl CpuInfo {
547    /// Whether AVX may actually be executed: the hardware announces it AND
548    /// the kernel enabled the required states (CR4.OSXSAVE via XSAVE +
549    /// XCR0 bits 0|1|2). Never gate code paths on `features.contains(AVX)`
550    /// alone : that only reflects CPUID, not what the OS programmed.
551    pub fn avx_usable(&self) -> bool {
552        const REQUIRED: u64 = XCR0_X87 | XCR0_SSE | XCR0_AVX;
553        self.features
554            .contains(CpuFeatures::AVX | CpuFeatures::XSAVE | CpuFeatures::OSXSAVE)
555            && (self.supported_xcr0 & REQUIRED) == REQUIRED
556            && crate::arch::x86_64::cpuid_osxsave_enabled()
557            && host_default_xcr0() & XCR0_AVX != 0
558    }
559
560    /// Whether AVX-512 may actually be executed: hardware support plus all
561    /// required XCR0 states enabled (opmask, ZMM_Hi256, HI16_ZMM on top of
562    /// x87/SSE/AVX). See `avx_usable`.
563    pub fn avx512_usable(&self) -> bool {
564        const REQUIRED: u64 =
565            XCR0_X87 | XCR0_SSE | XCR0_AVX | XCR0_OPMASK | XCR0_ZMM_HI256 | XCR0_HI16_ZMM;
566        self.features.contains(
567            CpuFeatures::AVX512F | CpuFeatures::AVX | CpuFeatures::XSAVE | CpuFeatures::OSXSAVE,
568        ) && (self.supported_xcr0 & REQUIRED) == REQUIRED
569            && crate::arch::x86_64::cpuid_osxsave_enabled()
570            && host_default_xcr0() & REQUIRED == REQUIRED
571    }
572}
573
574/// Compute the XCR0 mask for a given set of allowed features,
575/// clamped to what the host actually supports.
576///
577/// NOTE: currently the host default mask is returned regardless of
578/// `features` (the kernel enables x87+SSE+AVX(+512) as one global profile).
579/// Kept as an API seam for per-feature XCR0 profiles.
580pub fn xcr0_for_features(_features: CpuFeatures) -> u64 {
581    let h = host();
582    default_xcr0_for(&h)
583}
584
585/// Compute the XSAVE area size needed for a given XCR0 mask directly from a
586/// `CpuInfo`, without consulting the global cache (`host_uses_xsave`/`host`).
587/// This is what `init()` must use, because the cache is not yet published when
588/// `init()` runs : otherwise AVX/AVX-512 would be given a 512-byte area.
589fn xsave_size_for_info(info: &CpuInfo, xcr0: u64) -> usize {
590    if !info.features.contains(CpuFeatures::XSAVE) {
591        return 512;
592    }
593    // Clamp to what the CPU actually supports; ignore unknown bits.
594    let xcr0 = xcr0 & info.supported_xcr0;
595    if xcr0 == info.supported_xcr0 {
596        // Fast path: requesting all components : use the ECX upper-bound.
597        return info.xsave_size_max.max(576);
598    }
599    xsave_area_size(xcr0, info.xsave_size_max)
600}
601
602/// Walk CPUID leaf 0x0D for the components in `xcr0` (skipping supervisor
603/// states managed via IA32_XSS) and return the save-area size, clamped to
604/// `max_bytes` and floored at 576 (legacy area + XSAVE header).
605fn xsave_area_size(xcr0: u64, max_bytes: usize) -> usize {
606    let mut size = 576usize;
607    if let Some(es) = raw_cpuid::CpuId::new().get_extended_state_info() {
608        for st in es.iter() {
609            if xcr0 & (1u64 << st.subleaf) == 0 || !st.is_in_xcr0() {
610                continue;
611            }
612            let comp_size = st.size() as usize;
613            if comp_size != 0 {
614                size = size.max((st.offset() as usize).saturating_add(comp_size));
615            }
616        }
617    }
618    size.min(max_bytes).max(576)
619}
620
621/// Compute the XSAVE area size needed for a given XCR0 mask.
622/// Falls back to 512 (FXSAVE) if XSAVE is not supported.
623pub fn xsave_size_for_xcr0(xcr0: u64) -> usize {
624    if !host_uses_xsave() {
625        return 512;
626    }
627    let h = host();
628    if xcr0 == h.supported_xcr0 {
629        return h.xsave_size_max;
630    }
631
632    // Enumerate each enabled XCR0 component via CPUID leaf 0xD sub-leaves.
633    // The total save area is max(offset + size) across all enabled components.
634    // NOTE: this walks CPUID per component : do not call from context-switch
635    // or task-creation hot paths; precompute profiles instead.
636    // The ceiling is xsave_size_max (CPUID.0D.0:ECX), valid for any mask;
637    // EBX would only be valid for the XCR0 currently programmed.
638    xsave_area_size(xcr0, h.xsave_size_max)
639}
640
641/// Return the host's default XCR0 mask from the lock-free cache, falling back
642/// to the locked query before `init()` is complete.
643#[inline]
644pub fn host_default_xcr0_fast() -> u64 {
645    let cached = HOST_DEFAULT_XCR0_CACHE.load(Ordering::Acquire);
646    if cached != 0 {
647        return cached;
648    }
649    host_default_xcr0()
650}
651
652/// Read the TSC frequency from CPUID leaf 0x15 (Time Stamp Counter and Core
653/// Crystal Clock Information). Returns kHz, or `None` if the leaf is absent or
654/// the core-crystal ratio is not enumerated.
655///
656/// This is the preferred method on Intel/AMD CPUs that support invariant TSC.
657/// Linux uses this as its primary TSC calibration source.
658pub fn tsc_frequency_khz() -> Option<u64> {
659    // `tsc_frequency()` is in Hz; the public API reports kHz.
660    raw_cpuid::CpuId::new()
661        .get_tsc_info()?
662        .tsc_frequency()?
663        .checked_div(1_000)
664}
665
666/// Return the host's default XCR0 mask (all supported features).
667/// Safe to call before `init()` : returns `XCR0_X87 | XCR0_SSE` if not yet initialized.
668pub fn host_default_xcr0() -> u64 {
669    if INITIALIZED.load(Ordering::Acquire) {
670        HOST_CPU
671            .lock()
672            .as_ref()
673            .map_or(XCR0_X87 | XCR0_SSE, default_xcr0_for)
674    } else {
675        XCR0_X87 | XCR0_SSE
676    }
677}
678
679/// Build a Linux-style `flags` string from CPU features.
680pub fn features_to_flags_string(f: CpuFeatures) -> String {
681    let mut flags = String::new();
682    let table: &[(CpuFeatures, &str)] = &[
683        (CpuFeatures::FPU, "fpu"),
684        (CpuFeatures::TSC, "tsc"),
685        (CpuFeatures::APIC, "apic"),
686        (CpuFeatures::FXSR, "fxsr"),
687        (CpuFeatures::SSE, "sse"),
688        (CpuFeatures::SSE2, "sse2"),
689        (CpuFeatures::SSE3, "sse3"),
690        (CpuFeatures::SSSE3, "ssse3"),
691        (CpuFeatures::SSE4_1, "sse4_1"),
692        (CpuFeatures::SSE4_2, "sse4_2"),
693        (CpuFeatures::POPCNT, "popcnt"),
694        (CpuFeatures::AES_NI, "aes"),
695        (CpuFeatures::XSAVE, "xsave"),
696        (CpuFeatures::OSXSAVE, "osxsave"),
697        (CpuFeatures::AVX, "avx"),
698        (CpuFeatures::F16C, "f16c"),
699        (CpuFeatures::FMA, "fma"),
700        (CpuFeatures::AVX2, "avx2"),
701        (CpuFeatures::AVX512F, "avx512f"),
702        (CpuFeatures::AVX512BW, "avx512bw"),
703        (CpuFeatures::AVX512VL, "avx512vl"),
704        (CpuFeatures::SHA, "sha_ni"),
705        (CpuFeatures::X2APIC, "x2apic"),
706        (CpuFeatures::NX, "nx"),
707        (CpuFeatures::PAGES_1G, "pdpe1gb"),
708        (CpuFeatures::RDTSCP, "rdtscp"),
709        (CpuFeatures::LONG_MODE, "lm"),
710        (CpuFeatures::VMX, "vmx"),
711        (CpuFeatures::SVM, "svm"),
712        (CpuFeatures::SMEP, "smep"),
713        (CpuFeatures::SMAP, "smap"),
714    ];
715    for &(feat, name) in table {
716        if f.contains(feat) {
717            if !flags.is_empty() {
718                flags.push(' ');
719            }
720            flags.push_str(name);
721        }
722    }
723    flags
724}