Skip to main content

strat9_kernel/s9vm/
caps.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 : decoding of hardware virtualization capabilities (Intel VT-x).
24//!
25//! This module is **pure**: it reads no MSR itself, it receives a
26//! snapshot (`MsrSnapshot`) read by the kernel layer (`s9vm::mod`). It is
27//! therefore compilable and testable on the host (L2 tests).
28//!
29//! The encoding constants come from the Intel documentation (SDM
30//! vol. 3C, "VMX" chapters): MSRs `0x480`–`0x492`, `IA32_FEATURE_CONTROL`
31//! (`0x3A`). No value specific to a particular hypervisor is used.
32
33/// MSR `IA32_FEATURE_CONTROL`: lock and authorization of enabling.
34pub const MSR_FEATURE_CONTROL: u32 = 0x3A;
35/// `IA32_FEATURE_CONTROL` bit 0: MSR locked by the firmware.
36pub const FEATURE_CONTROL_LOCKED: u64 = 1 << 0;
37/// `IA32_FEATURE_CONTROL` bit 2: enabling allowed outside SMX.
38pub const FEATURE_CONTROL_ENABLE_OUTSIDE_SMX: u64 = 1 << 2;
39
40/// VT-x capability MSRs (range `0x480`–`0x492`).
41pub const MSR_BASIC: u32 = 0x480;
42pub const MSR_PIN_BASED: u32 = 0x481;
43pub const MSR_PRIMARY_PROC_BASED: u32 = 0x482;
44pub const MSR_EXIT_CONTROLS: u32 = 0x483;
45pub const MSR_ENTRY_CONTROLS: u32 = 0x484;
46pub const MSR_MISC: u32 = 0x485;
47pub const MSR_CR0_FIXED0: u32 = 0x486;
48pub const MSR_CR0_FIXED1: u32 = 0x487;
49pub const MSR_CR4_FIXED0: u32 = 0x488;
50pub const MSR_CR4_FIXED1: u32 = 0x489;
51pub const MSR_VMCS_ENUM: u32 = 0x48A;
52pub const MSR_SECONDARY_PROC_BASED: u32 = 0x48B;
53pub const MSR_EPT_VPID_CAP: u32 = 0x48C;
54pub const MSR_TRUE_PIN_BASED: u32 = 0x48D;
55pub const MSR_TRUE_PRIMARY_PROC_BASED: u32 = 0x48E;
56pub const MSR_TRUE_EXIT_CONTROLS: u32 = 0x48F;
57pub const MSR_TRUE_ENTRY_CONTROLS: u32 = 0x490;
58
59/// Bits of the `MSR_EPT_VPID_CAP` MSR that are useful to s9vm.
60pub mod ept_vpid_cap {
61    /// `invept` instruction available.
62    pub const INVEPT: u64 = 1 << 0;
63    /// 4-level EPT page walk (`PM4L`).
64    pub const WALK_LENGTH_4: u64 = 1 << 6;
65    /// *Uncacheable* memory type supported for EPT tables.
66    pub const MEMTYPE_UC: u64 = 1 << 8;
67    /// *Write-back* memory type supported for EPT tables.
68    pub const MEMTYPE_WB: u64 = 1 << 14;
69    /// 2 MiB pages supported in the EPT.
70    pub const PAGE_2MB: u64 = 1 << 16;
71    /// 1 GiB pages supported in the EPT.
72    pub const PAGE_1GB: u64 = 1 << 17;
73    /// *Accessed/dirty* (A/D) bits supported in the EPT.
74    pub const ACCESSED_DIRTY: u64 = 1 << 21;
75    /// `invvpid` with a single context.
76    pub const INVVPID_SINGLE_CONTEXT: u64 = 1 << 32;
77    /// `invvpid` with all contexts.
78    pub const INVVPID_ALL_CONTEXT: u64 = 1 << 33;
79    /// `invvpid` with an individual address.
80    pub const INVVPID_INDIVIDUAL_ADDRESS: u64 = 1 << 34;
81    /// `invvpid` with a single context, retaining the global entries.
82    pub const INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS: u64 = 1 << 35;
83}
84
85/// Useful bits of the `MSR_PIN_BASED`, `MSR_PRIMARY_PROC_BASED`,
86/// `MSR_SECONDARY_PROC_BASED` and `MSR_MISC` MSRs.
87pub mod control_bits {
88    /// "Pin-based" controls: exit on external interrupt.
89    pub const PIN_EXTERNAL_INTERRUPT_EXITING: u32 = 1 << 0;
90    /// "Pin-based" controls: exit on NMI.
91    pub const PIN_NMI_EXITING: u32 = 1 << 3;
92    /// "Pin-based" controls: virtual NMIs.
93    pub const PIN_VIRTUAL_NMIS: u32 = 1 << 5;
94    /// "Pin-based" controls: preemption timer (guest time slice).
95    pub const PIN_PREEMPTION_TIMER: u32 = 1 << 6;
96    /// "Pin-based" controls: posted interrupts.
97    pub const PIN_POSTED_INTERRUPTS: u32 = 1 << 7;
98
99    /// Primary controls: activate the secondary controls.
100    pub const PROC_ACTIVATE_SECONDARY: u32 = 1 << 31;
101    /// Primary controls: I/O bitmap.
102    pub const PROC_USE_IO_BITMAPS: u32 = 1 << 25;
103    /// Primary controls: MSR bitmap.
104    pub const PROC_USE_MSR_BITMAPS: u32 = 1 << 28;
105    /// Primary controls: exit on `hlt`.
106    pub const PROC_HLT_EXITING: u32 = 1 << 7;
107    /// Primary controls: exit on `rdtsc`.
108    pub const PROC_RDTSC_EXITING: u32 = 1 << 12;
109    /// Primary controls: exit on `mov cr`.
110    pub const PROC_CR3_LOAD_EXITING: u32 = 1 << 15;
111
112    /// Secondary controls: activate the EPT.
113    pub const PROC2_ENABLE_EPT: u32 = 1 << 1;
114    /// Secondary controls: virtual x2APIC mode.
115    pub const PROC2_VIRTUALIZE_X2APIC: u32 = 1 << 4;
116    /// Secondary controls: activate VPID.
117    pub const PROC2_ENABLE_VPID: u32 = 1 << 5;
118    /// Secondary controls: unrestricted guest (real mode without VM86).
119    pub const PROC2_UNRESTRICTED_GUEST: u32 = 1 << 7;
120    /// Secondary controls: virtualization of the APIC register.
121    pub const PROC2_APIC_REGISTER_VIRT: u32 = 1 << 8;
122    /// Secondary controls: virtual delivery of interrupts.
123    pub const PROC2_VIRTUAL_INTERRUPT_DELIVERY: u32 = 1 << 9;
124    /// Secondary controls: exit on `pause` loop (PLE).
125    pub const PROC2_PAUSE_LOOP_EXITING: u32 = 1 << 10;
126    /// Secondary controls: control block shadowing (nested).
127    pub const PROC2_CONTROL_SHADOWING: u32 = 1 << 14;
128    /// Secondary controls: `rdseed`.
129    pub const PROC2_ENABLE_RDSEED: u32 = 1 << 16;
130    /// Secondary controls: *page modification logging*.
131    pub const PROC2_ENABLE_PML: u32 = 1 << 17;
132    /// Secondary controls: XSAVES/XRSTORS.
133    pub const PROC2_ENABLE_XSAVES: u32 = 1 << 20;
134    /// Secondary controls: `umwait`.
135    pub const PROC2_ENABLE_UMWAIT: u32 = 1 << 21;
136    /// Secondary controls: `tpause`.
137    pub const PROC2_ENABLE_TPAUSE: u32 = 1 << 22;
138}
139
140/// Snapshot of the MSRs needed for detection. All values are
141/// raw (as read), decoding is done by [`HwCaps::from_snapshot`].
142#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
143pub struct MsrSnapshot {
144    pub feature_control: u64,
145    pub basic: u64,
146    pub pin_based: u64,
147    pub primary_proc_based: u64,
148    pub exit_controls: u64,
149    pub entry_controls: u64,
150    pub misc: u64,
151    pub cr0_fixed0: u64,
152    pub cr0_fixed1: u64,
153    pub cr4_fixed0: u64,
154    pub cr4_fixed1: u64,
155    pub secondary_proc_based: u64,
156    pub ept_vpid_cap: u64,
157    pub true_pin_based: Option<u64>,
158    pub true_primary_proc_based: Option<u64>,
159    pub true_exit_controls: Option<u64>,
160    pub true_entry_controls: Option<u64>,
161}
162
163impl MsrSnapshot {
164    /// Builds a snapshot from an MSR reader (the kernel provides
165    /// an `rdmsr` reader, the tests a synthetic reader).
166    pub fn from_reader<R: Fn(u32) -> u64>(read: R) -> Self {
167        let mut snapshot = Self {
168            feature_control: read(MSR_FEATURE_CONTROL),
169            basic: read(MSR_BASIC),
170            pin_based: read(MSR_PIN_BASED),
171            primary_proc_based: read(MSR_PRIMARY_PROC_BASED),
172            exit_controls: read(MSR_EXIT_CONTROLS),
173            entry_controls: read(MSR_ENTRY_CONTROLS),
174            misc: read(MSR_MISC),
175            cr0_fixed0: read(MSR_CR0_FIXED0),
176            cr0_fixed1: read(MSR_CR0_FIXED1),
177            cr4_fixed0: read(MSR_CR4_FIXED0),
178            cr4_fixed1: read(MSR_CR4_FIXED1),
179            secondary_proc_based: read(MSR_SECONDARY_PROC_BASED),
180            ept_vpid_cap: read(MSR_EPT_VPID_CAP),
181            true_pin_based: None,
182            true_primary_proc_based: None,
183            true_exit_controls: None,
184            true_entry_controls: None,
185        };
186        // The "TRUE_*" MSRs only exist if bit 55 of `MSR_BASIC` is
187        // set (default controls, SDM). On older CPUs, the base
188        // MSRs are authoritative.
189        if snapshot.basic & (1 << 55) != 0 {
190            snapshot.true_pin_based = Some(read(MSR_TRUE_PIN_BASED));
191            snapshot.true_primary_proc_based = Some(read(MSR_TRUE_PRIMARY_PROC_BASED));
192            snapshot.true_exit_controls = Some(read(MSR_TRUE_EXIT_CONTROLS));
193            snapshot.true_entry_controls = Some(read(MSR_TRUE_ENTRY_CONTROLS));
194        }
195        snapshot
196    }
197}
198
199/// Set of decoded capabilities, used by the `s9vm` engine.
200#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
201pub struct HwCaps {
202    /// The firmware allows enabling (bit 2 of `IA32_FEATURE_CONTROL`).
203    pub allowed: bool,
204    /// MSR `IA32_FEATURE_CONTROL` locked (if it is not, it can be
205    /// written once to allow enabling).
206    pub feature_control_locked: bool,
207    /// Control block revision identifier (bits 30:0 of `MSR_BASIC`).
208    pub control_block_revision: u32,
209    /// Size of the control block region in bytes (bits 44:32).
210    pub control_block_size: u16,
211    /// Recommended memory type for the region (bits 53:50; 6 = WB).
212    pub control_block_memory_type: u8,
213    /// The "TRUE_*" bits are available.
214    pub has_true_controls: bool,
215    /// EPT available (allowed on the secondary controls side).
216    pub ept: bool,
217    /// EPT with 4 walk levels.
218    pub ept_four_levels: bool,
219    /// EPT 2 MiB.
220    pub ept_2mb: bool,
221    /// EPT 1 GiB.
222    pub ept_1gb: bool,
223    /// EPT in write-back.
224    pub ept_wb: bool,
225    /// EPT with A/D bits.
226    pub ept_ad: bool,
227    /// `invept` available.
228    pub invept: bool,
229    /// VPID available.
230    pub vpid: bool,
231    /// `invvpid` variants available.
232    pub invvpid_single_context: bool,
233    pub invvpid_all_context: bool,
234    pub invvpid_individual_address: bool,
235    /// Unrestricted guest (16 bits without VM86).
236    pub unrestricted_guest: bool,
237    /// Virtual APIC (register + delivery).
238    pub apic_register_virt: bool,
239    pub virtual_interrupt_delivery: bool,
240    /// Posted interrupts.
241    pub posted_interrupts: bool,
242    /// Exit on `pause` loop (PLE).
243    pub pause_loop_exiting: bool,
244    /// Virtualized x2APIC.
245    pub virtualize_x2apic: bool,
246    /// Preemption timer.
247    pub preemption_timer: bool,
248    /// Virtual NMIs.
249    pub virtual_nmis: bool,
250    /// `rdseed` allowed in the guest.
251    pub rdseed: bool,
252
253    /// "Allowed" values (low / high 32 bits) of the control MSRs, after
254    /// selecting the `TRUE_*` MSRs when they exist.
255    pub pin_allowed: AllowedControls,
256    pub primary_proc_allowed: AllowedControls,
257    pub secondary_proc_allowed: AllowedControls,
258    pub exit_allowed: AllowedControls,
259    pub entry_allowed: AllowedControls,
260
261    /// Fixed CR0/CR4 masks.
262    pub cr0_fixed0: u64,
263    pub cr0_fixed1: u64,
264    pub cr4_fixed0: u64,
265    pub cr4_fixed1: u64,
266}
267
268/// Value of a control MSR: bits that must be 1 (low) and bits that may
269/// be 1 (high). See SDM "VMX capability MSRs".
270#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
271pub struct AllowedControls {
272    /// Bits that must be 1 in the field.
273    pub must_be_one: u32,
274    /// Bits that may be 1 in the field.
275    pub may_be_one: u32,
276}
277
278impl AllowedControls {
279    /// Decodes a 64-bit control MSR value.
280    pub const fn from_msr(value: u64) -> Self {
281        Self {
282            must_be_one: value as u32,
283            may_be_one: (value >> 32) as u32,
284        }
285    }
286
287    /// Builds the value to write for a desired control: the mandatory
288    /// bits are forced, the forbidden bits are cleared.
289    ///
290    /// `value = (desired & may_be_one) | must_be_one`
291    ///
292    /// The relative order of `must_be_one` and `may_be_one` does not matter:
293    /// the architecture guarantees that every mandatory bit is also allowed.
294    pub const fn apply(self, desired: u32) -> u32 {
295        (desired & self.may_be_one) | self.must_be_one
296    }
297
298    /// True if all requested bits are allowed (useful to diagnose
299    /// an overly ambitious requested configuration).
300    pub const fn supports(self, desired: u32) -> bool {
301        (desired & !self.may_be_one) == 0
302    }
303}
304
305impl HwCaps {
306    /// Decodes an MSR snapshot. `cpuid_vmx` is the result of
307    /// `CPUID.1:ECX[5]`; it is passed separately to keep this module pure.
308    pub fn from_snapshot(snapshot: &MsrSnapshot, cpuid_vmx: bool) -> Self {
309        let pin = snapshot
310            .true_pin_based
311            .map(AllowedControls::from_msr)
312            .unwrap_or_else(|| AllowedControls::from_msr(snapshot.pin_based));
313        let primary = snapshot
314            .true_primary_proc_based
315            .map(AllowedControls::from_msr)
316            .unwrap_or_else(|| AllowedControls::from_msr(snapshot.primary_proc_based));
317        let exit = snapshot
318            .true_exit_controls
319            .map(AllowedControls::from_msr)
320            .unwrap_or_else(|| AllowedControls::from_msr(snapshot.exit_controls));
321        let entry = snapshot
322            .true_entry_controls
323            .map(AllowedControls::from_msr)
324            .unwrap_or_else(|| AllowedControls::from_msr(snapshot.entry_controls));
325        let secondary = AllowedControls::from_msr(snapshot.secondary_proc_based);
326        let ept_vpid = snapshot.ept_vpid_cap;
327
328        let _ = cpuid_vmx; // The CPUID presence is checked by the caller.
329
330        Self {
331            allowed: snapshot.feature_control & FEATURE_CONTROL_ENABLE_OUTSIDE_SMX != 0
332                && cpuid_vmx,
333            feature_control_locked: snapshot.feature_control & FEATURE_CONTROL_LOCKED != 0,
334            control_block_revision: (snapshot.basic & 0x7FFF_FFFF) as u32,
335            control_block_size: ((snapshot.basic >> 32) & 0x1FFF) as u16,
336            control_block_memory_type: ((snapshot.basic >> 50) & 0xF) as u8,
337            has_true_controls: snapshot.true_pin_based.is_some(),
338            ept: cpuid_vmx && secondary.supports(control_bits::PROC2_ENABLE_EPT),
339            ept_four_levels: secondary.supports(control_bits::PROC2_ENABLE_EPT)
340                && ept_vpid & ept_vpid_cap::WALK_LENGTH_4 != 0,
341            ept_2mb: ept_vpid & ept_vpid_cap::PAGE_2MB != 0,
342            ept_1gb: ept_vpid & ept_vpid_cap::PAGE_1GB != 0,
343            ept_wb: ept_vpid & ept_vpid_cap::MEMTYPE_WB != 0,
344            ept_ad: ept_vpid & ept_vpid_cap::ACCESSED_DIRTY != 0,
345            invept: ept_vpid & ept_vpid_cap::INVEPT != 0,
346            vpid: secondary.supports(control_bits::PROC2_ENABLE_VPID),
347            invvpid_single_context: ept_vpid & ept_vpid_cap::INVVPID_SINGLE_CONTEXT != 0,
348            invvpid_all_context: ept_vpid & ept_vpid_cap::INVVPID_ALL_CONTEXT != 0,
349            invvpid_individual_address: ept_vpid & ept_vpid_cap::INVVPID_INDIVIDUAL_ADDRESS != 0,
350            unrestricted_guest: secondary.supports(control_bits::PROC2_UNRESTRICTED_GUEST),
351            apic_register_virt: secondary.supports(control_bits::PROC2_APIC_REGISTER_VIRT),
352            virtual_interrupt_delivery: secondary
353                .supports(control_bits::PROC2_VIRTUAL_INTERRUPT_DELIVERY),
354            posted_interrupts: pin.supports(control_bits::PIN_POSTED_INTERRUPTS),
355            pause_loop_exiting: secondary.supports(control_bits::PROC2_PAUSE_LOOP_EXITING),
356            virtualize_x2apic: secondary.supports(control_bits::PROC2_VIRTUALIZE_X2APIC),
357            preemption_timer: pin.supports(control_bits::PIN_PREEMPTION_TIMER),
358            virtual_nmis: pin.supports(control_bits::PIN_VIRTUAL_NMIS),
359            rdseed: secondary.supports(control_bits::PROC2_ENABLE_RDSEED),
360            pin_allowed: pin,
361            primary_proc_allowed: primary,
362            secondary_proc_allowed: secondary,
363            exit_allowed: exit,
364            entry_allowed: entry,
365            cr0_fixed0: snapshot.cr0_fixed0,
366            cr0_fixed1: snapshot.cr0_fixed1,
367            cr4_fixed0: snapshot.cr4_fixed0,
368            cr4_fixed1: snapshot.cr4_fixed1,
369        }
370    }
371
372    /// True if the platform can host the s9vm engine with EPT and VPID.
373    pub const fn can_run(&self) -> bool {
374        self.allowed && self.ept && self.ept_four_levels
375    }
376
377    /// Readable summary (one line) for boot logs.
378    pub fn summary(&self) -> alloc::string::String {
379        use alloc::format;
380        format!(
381            "allowed={} rev={} cb={}B ept={} 2mb={} 1gb={} ad={} vpid={} ug={} apicv={} pi={} ple={} x2apic={} ptimer={} cr0fix={:#x}/{:#x} cr4fix={:#x}/{:#x}",
382            self.allowed,
383            self.control_block_revision,
384            self.control_block_size,
385            self.ept,
386            self.ept_2mb,
387            self.ept_1gb,
388            self.ept_ad,
389            self.vpid,
390            self.unrestricted_guest,
391            self.apic_register_virt && self.virtual_interrupt_delivery,
392            self.posted_interrupts,
393            self.pause_loop_exiting,
394            self.virtualize_x2apic,
395            self.preemption_timer,
396            self.cr0_fixed0,
397            self.cr0_fixed1,
398            self.cr4_fixed0,
399            self.cr4_fixed1
400        )
401    }
402}
403
404/// Detection errors.
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum CapsError {
407    /// The CPU does not expose VT-x (CPUID.1:ECX[5] = 0).
408    NotSupported,
409    /// The firmware forbids enabling and the MSR is locked.
410    LockedByFirmware,
411    /// EPT absent or not usable in 4 levels.
412    EptUnavailable,
413}
414
415impl HwCaps {
416    /// Checks the enabling conditions and returns an explicit error.
417    pub fn validate(&self) -> Result<(), CapsError> {
418        if !self.allowed {
419            return Err(if self.feature_control_locked {
420                CapsError::LockedByFirmware
421            } else {
422                CapsError::NotSupported
423            });
424        }
425        if !self.ept || !self.ept_four_levels {
426            return Err(CapsError::EptUnavailable);
427        }
428        Ok(())
429    }
430}