Skip to main content

strat9_kernel/s9vm/
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//! s9vm : guest CPU description (CPUID model).
24//!
25//! The guest never executes the host `CPUID` instruction: the exit is
26//! intercepted and replayed in the kernel from a [`CpuidPolicy`]. This module
27//! is the **pure** model behind that replay: it performs no hardware access,
28//! holds no global state and can therefore be compiled and exercised on the
29//! host.
30//!
31//! # Model
32//!
33//! A [`CpuidPolicy`] describes one guest-visible processor:
34//!
35//! | Leaf | Contents |
36//! |---|---|
37//! | `0x0000_0000` | max basic leaf, 12-byte vendor string |
38//! | `0x0000_0001` | family/model/stepping, topology count, feature masks |
39//! | `0x0000_0004` | deterministic cache: zero (no cache hierarchy modelled) |
40//! | `0x0000_0007` | structured extended features: zero |
41//! | `0x0000_000B` | topology enumeration (SMT + core levels) |
42//! | `0x0000_000D` | XSAVE state: zero (XSAVE is not advertised) |
43//! | `0x0000_0015` | TSC/core-crystal ratio and crystal frequency |
44//! | `0x0000_0016` | nominal base frequency, in MHz |
45//! | `0x0000_001F` | extended topology enumeration (same topology) |
46//! | `0x8000_0000` | max extended leaf |
47//! | `0x8000_0001` | extended features (NX, long mode, `SYSCALL`, `RDTSCP`) |
48//! | `0x8000_0002..=0x8000_0004` | 48-byte processor brand string |
49//! | `0x8000_0007` | invariant TSC bit (always set: the TSC is never offset) |
50//! | `0x8000_0008` | physical/virtual address sizes |
51//!
52//! Every other leaf : including the `0x4000_0000` hypervisor range : returns
53//! zeros. A guest probing an unimplemented feature therefore sees it as absent
54//! instead of reading stale or host-derived values.
55//!
56//! # Invariants
57//!
58//! - **No nested virtualization**: the VMX bit (`leaf 1`, `ECX[5]`) can never
59//!   be set, not even through [`CpuidPolicy::set_feature`], and the SVM bit
60//!   (`0x8000_0001`, `ECX[2]`) is never advertised. A guest must not believe
61//!   it can run its own hypervisor on this CPU.
62//! - **No hypervisor present bit**: `leaf 1`, `ECX[31]` stays clear; s9vm does
63//!   not provide a hypervisor CPUID interface, so the `0x4000_0000` range is
64//!   zeroed.
65//! - **Deterministic and total**: [`CpuidPolicy::leaf`] is a pure function of
66//!   its arguments and the policy. It never panics, never blocks and returns
67//!   the same four words for the same inputs. The single documented exception
68//!   is the host fallback of the TSC leaves (`0x15`, `0x16`): when the policy
69//!   fields are zero, the host frequency cache of [`crate::s9vm::tsc`] is read
70//!   (it is immutable after detection); once a caller publishes explicit
71//!   leaves the replay is again a pure function of the policy.
72//! - **Coherent feature set**: only bits that the implementation can actually
73//!   honour are set by default. XSAVE/OSXSAVE, AVX and the `leaf 0x0000_0007`
74//!   features are deliberately absent because their instructions and
75//!   `XGETBV` are not modelled.
76//!
77//! # Limits
78//!
79//! The model is **per world**, not per vCPU: topology leaves report package
80//! and APIC identifier 0. An SMP guest would need the APIC identifier of the
81//! executing vCPU, which the current `leaf(leaf, subleaf)` signature does not
82//! take; that is a future evolution of the ABI (per-vCPU policy or an explicit
83//! APIC id parameter). Until then [`CpuidPolicy::cores`] and
84//! [`CpuidPolicy::threads`] only shape the counts advertised by leaves
85//! `0x0000_000B`, `0x0000_001F` and `0x8000_0008`.
86//!
87//! The TSC leaves assume an **invariant host TSC**: s9vm never offsets or
88//! scales the time-stamp counter, so the guest TSC is the host TSC. On a host
89//! without an invariant TSC the guest clock would drift with the P-state; the
90//! invariant bit is nevertheless published because s9vm itself cannot violate
91//! that property any further (it adds no offset and no scaling).
92
93use super::tsc::TscFrequency;
94
95// --- Identity --------------------------------------------------------------
96
97/// Length in bytes of the CPUID vendor string (three 32-bit words).
98pub const VENDOR_LEN: usize = 12;
99
100/// Vendor string reported by `CPUID.0`. Exactly twelve bytes, never padded.
101///
102/// The value is a synthetic identifier: it does not name any real vendor, so
103/// guest software cannot apply a real vendor's quirks to s9vm.
104pub const VENDOR: [u8; VENDOR_LEN] = *b"S9VMSTRAT9OS";
105
106/// Length in bytes of the processor brand string.
107pub const BRAND_LEN: usize = 48;
108
109/// Processor brand string reported by leaves `0x8000_0002..=0x8000_0004`.
110///
111/// The string is stored zero-padded to [`BRAND_LEN`] bytes. It is deliberately
112/// simple: a guest that prints it sees an explicitly virtual processor instead
113/// of a host identifier.
114pub const BRAND: [u8; BRAND_LEN] = build_brand();
115
116/// Base family reported in `CPUID.1:EAX`.
117pub const BASE_FAMILY: u32 = 6;
118
119/// Base model reported in `CPUID.1:EAX` (recent but synthetic; no
120/// model-specific behaviour is implemented).
121pub const BASE_MODEL: u32 = 0x8C;
122
123/// Stepping reported in `CPUID.1:EAX`.
124pub const BASE_STEPPING: u32 = 0x01;
125
126/// Guest-physical address bits reported by `0x8000_0008:EAX[7:0]`.
127pub const PHYSICAL_ADDRESS_BITS: u32 = 36;
128
129/// Guest-virtual address bits reported by `0x8000_0008:EAX[15:8]`.
130pub const VIRTUAL_ADDRESS_BITS: u32 = 48;
131
132// --- Leaf numbers ----------------------------------------------------------
133
134/// `CPUID.0`: max basic leaf and vendor string.
135pub const LEAF_VENDOR: u32 = 0x0000_0000;
136/// `CPUID.1`: version information and feature bits.
137pub const LEAF_FEATURES: u32 = 0x0000_0001;
138/// `CPUID.4`: deterministic cache parameters.
139pub const LEAF_CACHE: u32 = 0x0000_0004;
140/// `CPUID.7`: structured extended feature flags.
141pub const LEAF_STRUCTURED_FEATURES: u32 = 0x0000_0007;
142/// `CPUID.0xB`: topology enumeration.
143pub const LEAF_TOPOLOGY: u32 = 0x0000_000B;
144/// `CPUID.0xD`: XSAVE state components.
145pub const LEAF_XSAVE: u32 = 0x0000_000D;
146/// `CPUID.0x15`: TSC/core-crystal ratio and core-crystal frequency.
147pub const LEAF_TSC_RATIO: u32 = 0x0000_0015;
148/// `CPUID.0x16`: nominal processor base frequency.
149pub const LEAF_BASE_FREQUENCY: u32 = 0x0000_0016;
150/// `CPUID.0x1F`: extended topology enumeration.
151pub const LEAF_TOPOLOGY_V2: u32 = 0x0000_001F;
152/// `CPUID.0x8000_0000`: max extended leaf.
153pub const LEAF_EXTENDED_MAX: u32 = 0x8000_0000;
154/// `CPUID.0x8000_0001`: extended feature bits.
155pub const LEAF_EXTENDED_FEATURES: u32 = 0x8000_0001;
156/// `CPUID.0x8000_0007`: invariant TSC and advanced power management.
157///
158/// Only the invariant-TSC bit is published: s9vm adds no TSC offset and no
159/// scaling, so the guest TSC is the host TSC.
160pub const LEAF_EXTENDED_FREQUENCY: u32 = 0x8000_0007;
161/// Bit 8 of `CPUID.0x8000_0007:EDX`: the TSC is invariant.
162///
163/// Kept in sync with [`crate::s9vm::tsc::INVARIANT_TSC_BIT`]; duplicated here
164/// so the CPUID model stays readable without a cross-module constant.
165pub const INVARIANT_TSC_BIT: u32 = 1 << 8;
166/// First brand string leaf (`0x8000_0002`); the brand spans three leaves.
167pub const LEAF_BRAND: u32 = 0x8000_0002;
168/// `CPUID.0x8000_0008`: address size information.
169pub const LEAF_EXTENDED_ADDRESS_SIZES: u32 = 0x8000_0008;
170
171/// Highest basic leaf advertised by the default policy.
172///
173/// Leaf `0x0000_001F` is the last one that carries information; leaves between
174/// the implementation-specific ranges simply return zeros.
175pub const MAX_BASIC_LEAF: u32 = LEAF_TOPOLOGY_V2;
176
177/// Highest extended leaf advertised by the default policy.
178pub const MAX_EXTENDED_LEAF: u32 = LEAF_EXTENDED_ADDRESS_SIZES;
179
180// --- Feature bits ----------------------------------------------------------
181
182/// Bits of `CPUID.1:ECX` defined by this model.
183pub mod leaf1_ecx {
184    /// Streaming SIMD extensions 3.
185    pub const SSE3: u32 = 1 << 0;
186    /// Carry-less multiplication (`PCLMULQDQ`).
187    pub const PCLMUL: u32 = 1 << 1;
188    /// Supplemental SSE3.
189    pub const SSSE3: u32 = 1 << 9;
190    /// SSE4.1.
191    pub const SSE4_1: u32 = 1 << 19;
192    /// SSE4.2.
193    pub const SSE4_2: u32 = 1 << 20;
194    /// x2APIC (MSR-based local APIC interface).
195    pub const X2APIC: u32 = 1 << 21;
196    /// Population count instruction.
197    pub const POPCNT: u32 = 1 << 23;
198    /// TSC deadline timer.
199    pub const TSC_DEADLINE: u32 = 1 << 24;
200    /// VMX (nested virtualization). **Never advertised**: s9vm does not
201    /// virtualize VMX itself.
202    pub const VMX: u32 = 1 << 5;
203}
204
205/// Bits of `CPUID.1:EDX` defined by this model.
206pub mod leaf1_edx {
207    /// x87 floating-point unit.
208    pub const FPU: u32 = 1 << 0;
209    /// Time-stamp counter.
210    pub const TSC: u32 = 1 << 4;
211    /// Model-specific registers (`RDMSR`/`WRMSR`).
212    pub const MSR: u32 = 1 << 5;
213    /// Physical address extension.
214    pub const PAE: u32 = 1 << 6;
215    /// `CMPXCHG8B`.
216    pub const CX8: u32 = 1 << 8;
217    /// On-chip local APIC.
218    pub const APIC: u32 = 1 << 9;
219    /// `SYSENTER`/`SYSEXIT`.
220    pub const SEP: u32 = 1 << 11;
221    /// Conditional move instructions.
222    pub const CMOV: u32 = 1 << 15;
223    /// Page attribute table.
224    pub const PAT: u32 = 1 << 16;
225    /// `CLFLUSH`.
226    pub const CLFSH: u32 = 1 << 19;
227    /// MMX.
228    pub const MMX: u32 = 1 << 23;
229    /// `FXSAVE`/`FXRSTOR`.
230    pub const FXSR: u32 = 1 << 24;
231    /// SSE.
232    pub const SSE: u32 = 1 << 25;
233    /// SSE2.
234    pub const SSE2: u32 = 1 << 26;
235}
236
237/// Bits of `CPUID.0x8000_0001:ECX` defined by this model.
238pub mod extended1_ecx {
239    /// `LAHF`/`SAHF` in 64-bit mode.
240    pub const LAHF_LM: u32 = 1 << 0;
241    /// Secure virtual machine (AMD). **Never advertised**: s9vm does not
242    /// virtualize SVM.
243    pub const SVM: u32 = 1 << 2;
244}
245
246/// Bits of `CPUID.0x8000_0001:EDX` defined by this model.
247pub mod extended1_edx {
248    /// `SYSCALL`/`SYSRET` in 64-bit mode.
249    pub const SYSCALL: u32 = 1 << 11;
250    /// No-execute page protection.
251    pub const NX: u32 = 1 << 20;
252    /// One-gigabyte pages (not modelled by the guest page tables).
253    pub const PAGE_1GB: u32 = 1 << 26;
254    /// `RDTSCP`.
255    pub const RDTSCP: u32 = 1 << 27;
256    /// Long mode (IA-32e).
257    pub const LONG_MODE: u32 = 1 << 29;
258}
259
260/// Bits that this model can never advertise in `CPUID.1:ECX`.
261pub const LEAF1_ECX_FORBIDDEN: u32 = leaf1_ecx::VMX;
262
263/// Bits that this model can never advertise in `CPUID.0x8000_0001:ECX`.
264pub const EXTENDED1_ECX_FORBIDDEN: u32 = extended1_ecx::SVM;
265
266/// Default `CPUID.1:ECX`: early-boot SIMD bits plus x2APIC and TSC-deadline.
267pub const DEFAULT_LEAF1_ECX: u32 = leaf1_ecx::SSE3
268    | leaf1_ecx::PCLMUL
269    | leaf1_ecx::SSSE3
270    | leaf1_ecx::SSE4_1
271    | leaf1_ecx::SSE4_2
272    | leaf1_ecx::X2APIC
273    | leaf1_ecx::POPCNT
274    | leaf1_ecx::TSC_DEADLINE;
275
276/// Default `CPUID.1:EDX`: the baseline a 64-bit guest needs to boot.
277pub const DEFAULT_LEAF1_EDX: u32 = leaf1_edx::FPU
278    | leaf1_edx::TSC
279    | leaf1_edx::MSR
280    | leaf1_edx::PAE
281    | leaf1_edx::CX8
282    | leaf1_edx::APIC
283    | leaf1_edx::SEP
284    | leaf1_edx::CMOV
285    | leaf1_edx::PAT
286    | leaf1_edx::CLFSH
287    | leaf1_edx::MMX
288    | leaf1_edx::FXSR
289    | leaf1_edx::SSE
290    | leaf1_edx::SSE2;
291
292/// Default `CPUID.0x8000_0001:ECX`.
293pub const DEFAULT_EXTENDED1_ECX: u32 = 0;
294
295/// Default `CPUID.0x8000_0001:EDX`: the 64-bit execution environment.
296pub const DEFAULT_EXTENDED1_EDX: u32 =
297    extended1_edx::SYSCALL | extended1_edx::NX | extended1_edx::RDTSCP | extended1_edx::LONG_MODE;
298
299/// Builds the zero-padded brand string.
300const fn build_brand() -> [u8; BRAND_LEN] {
301    let text = b"s9vm virtual CPU";
302    let mut out = [0u8; BRAND_LEN];
303    let mut index = 0;
304    while index < text.len() && index < BRAND_LEN {
305        out[index] = text[index];
306        index += 1;
307    }
308    out
309}
310
311// --- Feature selector ------------------------------------------------------
312
313/// One bit of a CPUID feature register, used by
314/// [`CpuidPolicy::set_feature`] and [`CpuidPolicy::clear_feature`].
315///
316/// The payload is the bit number; numbers above 31 wrap (`bit % 32`), which
317/// keeps the helpers total instead of panicking.
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub enum Feature {
320    /// Bit of `CPUID.1:ECX`.
321    Leaf1Ecx(u8),
322    /// Bit of `CPUID.1:EDX`.
323    Leaf1Edx(u8),
324    /// Bit of `CPUID.0x8000_0001:ECX`.
325    Extended1Ecx(u8),
326    /// Bit of `CPUID.0x8000_0001:EDX`.
327    Extended1Edx(u8),
328}
329
330/// Guest-visible CPU description.
331///
332/// The policy is a small `Copy` value: the exit loop keeps one per world in
333/// its [`crate::s9vm::machine::Machine`] and replays every `CPUID` exit against
334/// it. [`CpuidPolicy::default`] is a safe, boot-capable 64-bit profile:
335/// family 6, one core, one thread, no nested virtualization, no XSAVE.
336///
337/// The fields are public so the syscall layer can assemble a policy from the
338/// ABI structure; the accessors and feature helpers enforce the invariants
339/// documented at module level.
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341pub struct CpuidPolicy {
342    /// Highest basic leaf, reported by `CPUID.0:EAX`.
343    pub max_basic_leaf: u32,
344    /// Highest extended leaf, reported by `CPUID.0x8000_0000:EAX`.
345    pub max_extended_leaf: u32,
346    /// Guest-visible family (`CPUID.1:EAX[11:8]`).
347    pub family: u32,
348    /// Guest-visible model, extended-model bits included.
349    pub model: u32,
350    /// Guest-visible stepping.
351    pub stepping: u32,
352    /// Number of physical cores per package (at least one).
353    pub cores: u32,
354    /// Number of hardware threads per core (at least one).
355    pub threads: u32,
356    /// Raw `CPUID.1:ECX` mask; forbidden bits are filtered when read.
357    pub leaf1_ecx: u32,
358    /// Raw `CPUID.1:EDX` mask.
359    pub leaf1_edx: u32,
360    /// Raw `CPUID.0x8000_0001:ECX` mask; forbidden bits are filtered when
361    /// read.
362    pub extended1_ecx: u32,
363    /// Raw `CPUID.0x8000_0001:EDX` mask.
364    pub extended1_edx: u32,
365    /// `CPUID.0x15:EAX` : TSC/core-crystal ratio denominator.
366    ///
367    /// Zero publishes the host value from the [`crate::s9vm::tsc`] cache, or
368    /// nothing when the host frequency is unknown.
369    pub tsc_ratio_denominator: u32,
370    /// `CPUID.0x15:EBX` : TSC/core-crystal ratio numerator.
371    pub tsc_ratio_numerator: u32,
372    /// `CPUID.0x15:ECX` : core-crystal frequency, in hertz.
373    pub crystal_hz: u32,
374    /// `CPUID.0x16:EAX` : nominal base frequency, in megahertz.
375    pub base_mhz: u32,
376}
377
378impl CpuidPolicy {
379    /// Builds the safe default profile.
380    ///
381    /// This is a `const fn` so a policy can back a `static` without runtime
382    /// initialization.
383    pub const fn new() -> Self {
384        Self {
385            max_basic_leaf: MAX_BASIC_LEAF,
386            max_extended_leaf: MAX_EXTENDED_LEAF,
387            family: BASE_FAMILY,
388            model: BASE_MODEL,
389            stepping: BASE_STEPPING,
390            cores: 1,
391            threads: 1,
392            leaf1_ecx: DEFAULT_LEAF1_ECX,
393            leaf1_edx: DEFAULT_LEAF1_EDX,
394            extended1_ecx: DEFAULT_EXTENDED1_ECX,
395            extended1_edx: DEFAULT_EXTENDED1_EDX,
396            tsc_ratio_denominator: 0,
397            tsc_ratio_numerator: 0,
398            crystal_hz: 0,
399            base_mhz: 0,
400        }
401    }
402
403    /// Publishes `frequency` in CPUID leaves `0x15` and `0x16`.
404    ///
405    /// The four fields are filled from
406    /// [`TscFrequency::cpuid_leaves`](crate::s9vm::tsc::TscFrequency::cpuid_leaves).
407    /// A caller that leaves them at zero keeps the host-derived fallback, which
408    /// is the right default for a world that should see the real host TSC.
409    pub fn set_tsc_frequency(&mut self, frequency: TscFrequency) {
410        let leaves = frequency.cpuid_leaves();
411        self.tsc_ratio_denominator = leaves.ratio_denominator;
412        self.tsc_ratio_numerator = leaves.ratio_numerator;
413        self.crystal_hz = leaves.crystal_hz;
414        self.base_mhz = leaves.base_mhz;
415    }
416
417    /// Number of logical processors per package, clamped to the 8-bit
418    /// `CPUID.1:EBX[23:16]` field. Never zero: an empty policy still describes
419    /// one processor.
420    pub fn logical_processors(&self) -> u32 {
421        self.cores
422            .max(1)
423            .saturating_mul(self.threads.max(1))
424            .min(0xFF)
425    }
426
427    /// Effective `CPUID.1:ECX`, with the forbidden bits cleared.
428    pub fn effective_leaf1_ecx(&self) -> u32 {
429        self.leaf1_ecx & !LEAF1_ECX_FORBIDDEN
430    }
431
432    /// Effective `CPUID.0x8000_0001:ECX`, with the forbidden bits cleared.
433    pub fn effective_extended1_ecx(&self) -> u32 {
434        self.extended1_ecx & !EXTENDED1_ECX_FORBIDDEN
435    }
436
437    /// `CPUID.1:EAX`: stepping, model and family encoding.
438    ///
439    /// The extended model field is used when `model > 0x0F`; the extended
440    /// family field is only used for families at or above `0x0F`, which the
441    /// default never is. Bits outside the architectural fields are zero.
442    pub fn signature(&self) -> u32 {
443        // Families at or above 0x0F set the base field to 0x0F and carry the
444        // remainder in the extended family field.
445        let (base_family, extended_family) = if self.family >= 0x0F {
446            (0x0Fu32, (self.family - 0x0F) & 0xFF)
447        } else {
448            (self.family & 0x0F, 0)
449        };
450        let base_model = self.model & 0x0F;
451        let extended_model = (self.model >> 4) & 0x0F;
452        (self.stepping & 0x0F)
453            | (base_model << 4)
454            | (base_family << 8)
455            | (extended_model << 16)
456            | (extended_family << 20)
457    }
458
459    /// Sets one feature bit.
460    ///
461    /// Forbidden bits ([`LEAF1_ECX_FORBIDDEN`], [`EXTENDED1_ECX_FORBIDDEN`])
462    /// are silently ignored: a caller can never enable nested virtualization
463    /// through this helper.
464    pub fn set_feature(&mut self, feature: Feature) {
465        let mask = feature_mask(feature.bit());
466        match feature {
467            Feature::Leaf1Ecx(_) => self.leaf1_ecx |= mask & !LEAF1_ECX_FORBIDDEN,
468            Feature::Leaf1Edx(_) => self.leaf1_edx |= mask,
469            Feature::Extended1Ecx(_) => self.extended1_ecx |= mask & !EXTENDED1_ECX_FORBIDDEN,
470            Feature::Extended1Edx(_) => self.extended1_edx |= mask,
471        }
472    }
473
474    /// Clears one feature bit.
475    pub fn clear_feature(&mut self, feature: Feature) {
476        let mask = feature_mask(feature.bit());
477        match feature {
478            Feature::Leaf1Ecx(_) => self.leaf1_ecx &= !mask,
479            Feature::Leaf1Edx(_) => self.leaf1_edx &= !mask,
480            Feature::Extended1Ecx(_) => self.extended1_ecx &= !mask,
481            Feature::Extended1Edx(_) => self.extended1_edx &= !mask,
482        }
483    }
484
485    /// Reports whether one feature bit is in effect, forbidden bits included.
486    pub fn has_feature(&self, feature: Feature) -> bool {
487        let mask = feature_mask(feature.bit());
488        match feature {
489            Feature::Leaf1Ecx(_) => self.effective_leaf1_ecx() & mask != 0,
490            Feature::Leaf1Edx(_) => self.leaf1_edx & mask != 0,
491            Feature::Extended1Ecx(_) => self.effective_extended1_ecx() & mask != 0,
492            Feature::Extended1Edx(_) => self.extended1_edx & mask != 0,
493        }
494    }
495
496    /// Replays one `CPUID` instruction: returns `[EAX, EBX, ECX, EDX]`.
497    ///
498    /// The function is total and deterministic. `leaf == 0` always answers
499    /// with the advertised basic range; a basic leaf above
500    /// [`CpuidPolicy::max_basic_leaf`] and an extended leaf above
501    /// [`CpuidPolicy::max_extended_leaf`] return zeros, as does every leaf
502    /// this model does not implement (notably the `0x4000_0000` hypervisor
503    /// range, because the hypervisor-present bit is never set).
504    pub fn leaf(&self, leaf: u32, subleaf: u32) -> [u32; 4] {
505        // Leaf 0 is always available: it advertises the range itself.
506        if leaf == LEAF_VENDOR {
507            return self.vendor_leaf();
508        }
509
510        // Basic range. The split point is deliberately the architectural
511        // boundary between basic and extended leaves, not the advertised max:
512        // a leaf outside the advertised range must read as zero even if later
513        // policy code happens to implement it.
514        if leaf <= 0x0000_FFFF {
515            if leaf > self.max_basic_leaf {
516                return [0; 4];
517            }
518            return match leaf {
519                LEAF_FEATURES => self.feature_leaf(),
520                LEAF_CACHE => [0; 4],
521                LEAF_STRUCTURED_FEATURES => [0; 4],
522                LEAF_TOPOLOGY | LEAF_TOPOLOGY_V2 => self.topology_leaf(subleaf),
523                LEAF_XSAVE => [0; 4],
524                LEAF_TSC_RATIO => self.tsc_ratio_leaf(),
525                LEAF_BASE_FREQUENCY => self.base_frequency_leaf(),
526                _ => [0; 4],
527            };
528        }
529
530        // Extended range, plus the 0x4000_0000..0x7FFF_FFFF hypervisor range
531        // which is intentionally not implemented.
532        if leaf == LEAF_EXTENDED_MAX {
533            return [self.max_extended_leaf, 0, 0, 0];
534        }
535        if leaf < LEAF_EXTENDED_MAX || leaf > self.max_extended_leaf {
536            return [0; 4];
537        }
538        match leaf {
539            LEAF_EXTENDED_FEATURES => self.extended_features_leaf(),
540            LEAF_EXTENDED_FREQUENCY => self.extended_frequency_leaf(),
541            LEAF_BRAND..=0x8000_0004 => self.brand_leaf(leaf),
542            LEAF_EXTENDED_ADDRESS_SIZES => self.address_sizes_leaf(),
543            _ => [0; 4],
544        }
545    }
546
547    /// `CPUID.0`: max basic leaf and vendor string.
548    fn vendor_leaf(&self) -> [u32; 4] {
549        let mut words = [0u32; 3];
550        let mut index = 0;
551        while index < 3 {
552            let offset = index * 4;
553            words[index] = u32::from_le_bytes([
554                VENDOR[offset],
555                VENDOR[offset + 1],
556                VENDOR[offset + 2],
557                VENDOR[offset + 3],
558            ]);
559            index += 1;
560        }
561        // Architectural order: EBX, EDX, ECX.
562        [self.max_basic_leaf, words[0], words[2], words[1]]
563    }
564
565    /// `CPUID.1`: signature, topology count and feature masks.
566    fn feature_leaf(&self) -> [u32; 4] {
567        // Brand index 0, 64-byte cache line (8 dwords), logical processors per
568        // package, initial APIC id 0.
569        let ebx = (8 << 8) | ((self.logical_processors() & 0xFF) << 16);
570        [
571            self.signature(),
572            ebx,
573            self.effective_leaf1_ecx(),
574            self.leaf1_edx,
575        ]
576    }
577
578    /// `CPUID.0x8000_0001`: extended feature masks.
579    fn extended_features_leaf(&self) -> [u32; 4] {
580        // EAX and EBX are reserved in this leaf.
581        [0, 0, self.effective_extended1_ecx(), self.extended1_edx]
582    }
583
584    /// `CPUID.0x15`: TSC/core-crystal ratio and crystal frequency.
585    ///
586    /// The policy fields win when they form a usable ratio (non-zero
587    /// denominator, numerator and crystal). Otherwise the host frequency cache
588    /// is consulted, so a guest sees the real host TSC frequency even when the
589    /// policy was not explicitly tuned; when neither source is available the
590    /// leaf reads as zero and the guest falls back to leaf `0x16` or to
591    /// calibration.
592    fn tsc_ratio_leaf(&self) -> [u32; 4] {
593        if self.tsc_ratio_denominator != 0 && self.tsc_ratio_numerator != 0 && self.crystal_hz != 0
594        {
595            return [
596                self.tsc_ratio_denominator,
597                self.tsc_ratio_numerator,
598                self.crystal_hz,
599                0,
600            ];
601        }
602        match super::tsc::get() {
603            Some(frequency) => {
604                let leaves = frequency.cpuid_leaves();
605                [
606                    leaves.ratio_denominator,
607                    leaves.ratio_numerator,
608                    leaves.crystal_hz,
609                    0,
610                ]
611            }
612            None => [0; 4],
613        }
614    }
615
616    /// `CPUID.0x16`: nominal base frequency in `EAX` (megahertz).
617    ///
618    /// The policy field wins; otherwise the host frequency cache is truncated
619    /// to megahertz. Zero means "not published".
620    fn base_frequency_leaf(&self) -> [u32; 4] {
621        if self.base_mhz != 0 {
622            return [self.base_mhz, 0, 0, 0];
623        }
624        match super::tsc::get() {
625            Some(frequency) => [frequency.cpuid_leaves().base_mhz, 0, 0, 0],
626            None => [0; 4],
627        }
628    }
629
630    /// `CPUID.0x8000_0007`: invariant TSC bit in `EDX`.
631    ///
632    /// Only bit 8 is set: the guest TSC is the host TSC, s9vm never offsets or
633    /// scales it, so the invariant-TSC guarantee is published unconditionally.
634    /// Advanced power-management bits are not advertised.
635    fn extended_frequency_leaf(&self) -> [u32; 4] {
636        [0, 0, 0, INVARIANT_TSC_BIT]
637    }
638
639    /// `CPUID.0x8000_0002..=0x8000_0004`: one quarter of the brand string.
640    fn brand_leaf(&self, leaf: u32) -> [u32; 4] {
641        let mut result = [0u32; 4];
642        let base = (leaf - LEAF_BRAND) as usize * 16;
643        let mut index = 0;
644        while index < 4 {
645            let offset = base + index * 4;
646            result[index] = u32::from_le_bytes([
647                BRAND[offset],
648                BRAND[offset + 1],
649                BRAND[offset + 2],
650                BRAND[offset + 3],
651            ]);
652            index += 1;
653        }
654        result
655    }
656
657    /// `CPUID.0x8000_0008`: physical and virtual address sizes.
658    fn address_sizes_leaf(&self) -> [u32; 4] {
659        // EBX (number of cores - 1) is only defined by AMD; topology is
660        // advertised through leaves 0x0B/0x1F instead.
661        [PHYSICAL_ADDRESS_BITS | (VIRTUAL_ADDRESS_BITS << 8), 0, 0, 0]
662    }
663
664    /// Topology enumeration, shared by `CPUID.0x0B` and `CPUID.0x1F`.
665    ///
666    /// Both leaves use the same `ECX[15:8]` level-type encoding (1 = SMT,
667    /// 2 = core) and terminate with an invalid type. `0x1F` additionally
668    /// carries the x2APIC identifier in `EDX[31:16]`; with a single package
669    /// identifier 0 both variants return the same words.
670    fn topology_leaf(&self, subleaf: u32) -> [u32; 4] {
671        match subleaf {
672            // SMT level: `threads` logical processors sharing this core.
673            0 => [0, self.threads.max(1), 1 << 8, 0],
674            // Core level: `cores * threads` logical processors in the package.
675            1 => [1, self.logical_processors(), 2 << 8, 0],
676            // Invalid level type terminates the enumeration.
677            _ => [0; 4],
678        }
679    }
680}
681
682impl Default for CpuidPolicy {
683    fn default() -> Self {
684        Self::new()
685    }
686}
687
688impl Feature {
689    /// Bit number carried by the selector.
690    fn bit(self) -> u8 {
691        match self {
692            Feature::Leaf1Ecx(bit)
693            | Feature::Leaf1Edx(bit)
694            | Feature::Extended1Ecx(bit)
695            | Feature::Extended1Edx(bit) => bit,
696        }
697    }
698}
699
700/// Builds a one-bit mask, wrapping the bit number instead of panicking.
701fn feature_mask(bit: u8) -> u32 {
702    1u32 << (bit & 31)
703}