Skip to main content

strat9_kernel/s9vm/
mod.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 : bare-metal virtualization system of strat9-os.
24//!
25//! # Principle
26//!
27//! **Bedrock provides the mechanism** (per-CPU VT-x activation, hardware
28//! control block, second-level translation, exit reception, event
29//! injection), **the policy silo** (to come) will decide the life cycle
30//! of machines, device model, and interrupt routing.
31//!
32//! # Layout
33//!
34//! | Module | Content | Host-testable |
35//! |---|---|---|
36//! | [`caps`] | VT-x capability MSR decoding | yes |
37//! | [`control`] | field encoding, control block primitives | yes (compiles) |
38//! | [`mmu`] | second-level translation tables | yes |
39//! | [`exit`] | exit decoding and classification | yes |
40//! | [`svm_caps`] | AMD-V capability decoding | yes |
41//! | [`svm_vmcb`] | AMD VMCB layout, exit decoding | yes |
42//! | [`svm_state`] | `GuestState` <-> VMCB translation, permission maps | yes |
43//! | [`svm`] | AMD-V activation and `vmrun` world switch | no |
44//! | [`svm_vcpu`] | AMD-V vCPU (VMCB, FPU switch, injection) | no |
45//!
46//! # Initialization cycle
47//!
48//! 1. very early detection (CPUID + MSR), without side effects;
49//! 2. per-CPU activation when the frame allocator is ready (component
50//!    `bootstrap`): `CR4.VMXE`, 4 KiB activation region, activation;
51//! 3. vCPUs will be created later by the policy layer.
52//!
53//! The absence of VT-x is never fatal: the kernel boots normally and
54//! logs `virtualisation inactive`.
55
56pub mod acpi;
57pub mod apic;
58pub mod backend;
59pub mod bios;
60pub mod biosrom;
61pub mod bootinfo;
62pub mod bootparams;
63pub mod bzimage;
64pub mod caps;
65pub mod control;
66pub mod cpuid;
67pub mod decode;
68pub mod dma;
69pub mod dosboot;
70pub mod emulate;
71pub mod exit;
72pub mod exitqueue;
73pub mod fdc;
74pub mod fpu;
75pub mod firmware;
76pub mod fwcfg;
77pub mod guest;
78pub mod guestcode;
79pub mod guestprog;
80pub mod guestpt;
81pub mod hpet;
82pub mod image;
83pub mod ioapic;
84pub mod iommu;
85pub mod keyboard;
86pub mod keyfeed;
87pub mod launch;
88pub mod linuxboot;
89pub mod machine;
90pub mod memmap;
91pub mod mmu;
92pub mod msr;
93pub mod pci;
94pub mod pic;
95pub mod pit;
96pub mod rtc;
97pub mod selftest;
98pub mod smp;
99pub mod svm;
100pub mod svm_caps;
101pub mod svm_exit;
102pub mod svm_state;
103pub mod svm_vcpu;
104pub mod svm_vmcb;
105pub mod system;
106pub mod timing;
107pub mod tsc;
108pub mod uart;
109pub mod vcpu;
110pub mod vga;
111pub mod virtio;
112pub mod virtio_blk;
113pub mod virtio_console;
114pub mod virtio_net;
115pub mod vm;
116pub mod zeropage;
117
118use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering};
119
120use caps::{CapsError, HwCaps, MsrSnapshot};
121
122/// Global compile/behavior switch.
123///
124/// When `false`, `init()` only logs: useful for a diagnostic kernel or
125/// an exotic platform. The code remains compiled, which avoids two
126/// binary variants.
127pub const S9VM_ENABLED: bool = true;
128
129/// `CR4.VMXE` bit (hardware extension enable).
130const CR4_VMXE: u64 = 1 << 13;
131
132/// Hardware virtualization backend selected at boot.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Backend {
135    /// No usable hardware virtualization.
136    None,
137    /// Intel VT-x.
138    Vmx,
139    /// AMD-V.
140    Svm,
141}
142
143/// Selected backend (`Backend as u8`).
144static BACKEND: AtomicU8 = AtomicU8::new(Backend::None as u8);
145
146/// The hardware virtualization backend in use.
147///
148/// Fixed by [`init`]: VT-x when the CPU has it, otherwise AMD-V when usable.
149pub fn backend() -> Backend {
150    match BACKEND.load(Ordering::Acquire) {
151        x if x == Backend::Vmx as u8 => Backend::Vmx,
152        x if x == Backend::Svm as u8 => Backend::Svm,
153        _ => Backend::None,
154    }
155}
156
157/// Maximum number of tracked CPUs (aligned with `percpu::MAX_CPUS`).
158const MAX_CPUS: usize = crate::arch::x86_64::percpu::MAX_CPUS;
159
160/// Per-CPU activation regions (physical address, 0 = not activated).
161static REGIONS: [AtomicU64; MAX_CPUS] = [const { AtomicU64::new(0) }; MAX_CPUS];
162/// CPU whose activation succeeded.
163static ACTIVATED: [AtomicBool; MAX_CPUS] = [const { AtomicBool::new(false) }; MAX_CPUS];
164/// Number of activated CPUs.
165static ACTIVE_CPUS: AtomicU32 = AtomicU32::new(0);
166/// Capabilities detected once and for all (0 = not detected).
167static CAPS_VALID: AtomicBool = AtomicBool::new(false);
168
169/// Initialization errors.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum InitError {
172    /// No VT-x on this CPU.
173    NotSupported,
174    /// Firmware has locked the activation prohibition.
175    LockedByFirmware,
176    /// EPT absent or unusable.
177    EptUnavailable,
178    /// Cannot allocate the activation region.
179    OutOfMemory,
180    /// The activation instruction failed.
181    ActivationFailed,
182}
183
184impl From<CapsError> for InitError {
185    fn from(value: CapsError) -> Self {
186        match value {
187            CapsError::NotSupported => Self::NotSupported,
188            CapsError::LockedByFirmware => Self::LockedByFirmware,
189            CapsError::EptUnavailable => Self::EptUnavailable,
190        }
191    }
192}
193
194/// Reads an MSR through the architecture layer.
195#[inline]
196fn read_msr(msr: u32) -> u64 {
197    crate::arch::x86_64::rdmsr(msr)
198}
199
200/// Writes an MSR through the architecture layer.
201#[inline]
202fn write_msr(msr: u32, value: u64) {
203    crate::arch::x86_64::wrmsr(msr, value);
204}
205
206/// Reads `CR4`.
207#[inline]
208fn read_cr4() -> u64 {
209    let value: u64;
210    // SAFETY: read of a control register, no side effects.
211    unsafe {
212        core::arch::asm!("mov {}, cr4", out(reg) value, options(nomem, nostack, preserves_flags));
213    }
214    value
215}
216
217/// Writes `CR4`.
218#[inline]
219unsafe fn write_cr4(value: u64) {
220    // SAFETY: the caller guarantees the modified bits are valid.
221    unsafe {
222        core::arch::asm!("mov cr4, {}", in(reg) value, options(nomem, nostack));
223    }
224}
225
226/// Explains why VT-x is unavailable, for logs and diagnostics.
227///
228/// Performs the same read-only CPUID/MSR probes as [`detect`] and returns a
229/// short cause. Never modifies CPU state.
230pub fn unavailable_reason() -> &'static str {
231    let info = crate::arch::x86_64::cpuid::host();
232    let cpuid_vmx = info
233        .features
234        .contains(crate::arch::x86_64::cpuid::CpuFeatures::VMX);
235    if !cpuid_vmx {
236        return "CPUID.1:ECX.VMX=0 (hypervisor or firmware hides VT-x)";
237    }
238    let feature_control = read_msr(caps::MSR_FEATURE_CONTROL);
239    if feature_control & caps::FEATURE_CONTROL_ENABLE_OUTSIDE_SMX != 0 {
240        return "unknown (CPUID and IA32_FEATURE_CONTROL both allow VT-x)";
241    }
242    if feature_control & caps::FEATURE_CONTROL_LOCKED != 0 {
243        "IA32_FEATURE_CONTROL is locked and forbids VMXON"
244    } else {
245        "IA32_FEATURE_CONTROL does not enable VMXON"
246    }
247}
248
249/// Detects hardware capabilities of the active backend. Does not modify any
250/// CPU state.
251///
252/// On Intel this is the VT-x capability set. On AMD it is a synthetic set
253/// derived from the SVM capabilities, so callers (the world registry, the run
254/// loop, the shell) work unchanged: no fixed CR bits, unrestricted guest, no
255/// `invept`, no preemption timer.
256pub fn detect() -> Option<HwCaps> {
257    if let Some(caps) = detect_vmx() {
258        return Some(caps);
259    }
260    svm::hw_caps()
261}
262
263/// Detects Intel VT-x capabilities only. Does not modify any CPU state.
264///
265/// The VT-x-specific code (activation, the VT-x self-tests, the DOS boot
266/// runner) must use this one: on an AMD CPU it returns `None`.
267pub fn detect_vmx() -> Option<HwCaps> {
268    let info = crate::arch::x86_64::cpuid::host();
269    let cpuid_vmx = info
270        .features
271        .contains(crate::arch::x86_64::cpuid::CpuFeatures::VMX);
272    if !cpuid_vmx {
273        return None;
274    }
275    let snapshot = MsrSnapshot::from_reader(read_msr);
276    Some(HwCaps::from_snapshot(&snapshot, true))
277}
278
279/// Attempts to activate VT-x on the current CPU.
280///
281/// This function is idempotent: an already activated CPU returns `Ok(())`.
282/// It allocates an activation region (a 4 KiB frame) that remains reserved
283/// for the entire lifetime of the CPU.
284pub fn activate_current_cpu() -> Result<(), InitError> {
285    match backend() {
286        Backend::Svm => svm::activate_current_cpu(),
287        _ => activate_current_cpu_vmx(),
288    }
289}
290
291/// Intel VT-x activation of the current CPU (see [`activate_current_cpu`]).
292fn activate_current_cpu_vmx() -> Result<(), InitError> {
293    let cpu = crate::arch::x86_64::percpu::current_cpu_index();
294    if cpu >= MAX_CPUS {
295        return Err(InitError::NotSupported);
296    }
297    if ACTIVATED[cpu].load(Ordering::Acquire) {
298        return Ok(());
299    }
300
301    let Some(mut caps) = detect_vmx() else {
302        return Err(InitError::NotSupported);
303    };
304
305    // Enables activation if the firmware has not done so but has not
306    // locked the MSR. If the MSR is locked without authorization, there is
307    // nothing to do: it is a BIOS setting.
308    if !caps.allowed {
309        if caps.feature_control_locked {
310            return Err(InitError::LockedByFirmware);
311        }
312        let feature_control = read_msr(caps::MSR_FEATURE_CONTROL);
313        write_msr(
314            caps::MSR_FEATURE_CONTROL,
315            feature_control
316                | caps::FEATURE_CONTROL_ENABLE_OUTSIDE_SMX
317                | caps::FEATURE_CONTROL_LOCKED,
318        );
319        let Some(updated) = detect_vmx() else {
320            return Err(InitError::NotSupported);
321        };
322        caps = updated;
323        if !caps.allowed {
324            return Err(InitError::LockedByFirmware);
325        }
326    }
327
328    caps.validate()?;
329
330    // Activation region: a zeroed, 4 KiB-aligned frame.
331    let frame = crate::sync::with_irqs_disabled(|token| {
332        crate::memory::frame::FrameAllocOptions::new()
333            .purpose(crate::memory::frame::FramePurpose::PageTable)
334            .allocate(token)
335    })
336    .map_err(|_| InitError::OutOfMemory)?;
337    let phys = frame.start_address.as_u64();
338
339    // The revision identifier must be written into the first 4 bytes.
340    let virt = crate::memory::phys_to_virt(phys) as *mut u32;
341    // SAFETY: the frame is exclusively reserved, the HHDM covers it, and
342    // the write targets its first 4 bytes.
343    unsafe {
344        core::ptr::write_volatile(virt, caps.control_block_revision);
345    }
346
347    // Enables CR4.VMXE then executes the hardware activation.
348    let cr4 = read_cr4();
349    // SAFETY: bit 13 is legal as soon as CPUID advertises it.
350    unsafe {
351        write_cr4(cr4 | CR4_VMXE);
352    }
353    // SAFETY: region initialized, CPU advertised compatible, local
354    // interrupts disabled by the caller (boot component).
355    let failed = unsafe { enable_virtualization(phys) };
356    if failed {
357        // SAFETY: restoration of the previous state.
358        unsafe {
359            write_cr4(cr4);
360        }
361        return Err(InitError::ActivationFailed);
362    }
363
364    REGIONS[cpu].store(phys, Ordering::Release);
365    ACTIVATED[cpu].store(true, Ordering::Release);
366    ACTIVE_CPUS.fetch_add(1, Ordering::AcqRel);
367    log::info!(
368        "[s9vm] hardware activation OK (cpu {}, region {:#x})",
369        cpu,
370        phys
371    );
372    Ok(())
373}
374
375/// Executes the hardware activation (`vmxon`) on a pre-initialized region.
376///
377/// # Safety
378/// - the CPU must advertise VT-x and `CR4.VMXE` must be set;
379/// - `region_phys` must be a 4 KiB-aligned frame, initialized with
380///   the revision identifier, exclusively reserved;
381/// - local interrupts must be disabled.
382unsafe fn enable_virtualization(region_phys: u64) -> bool {
383    let fail: u8;
384    // SAFETY: function contract.
385    unsafe {
386        core::arch::asm!(
387            "vmxon qword ptr [{region}]",
388            "setc {fail}",
389            region = in(reg) &region_phys,
390            fail = out(reg_byte) fail,
391            options(nostack)
392        );
393    }
394    fail != 0
395}
396
397/// Initialization called by the boot component.
398///
399/// Never panics: any unavailability is logged and the kernel
400/// continues booting.
401pub fn init() {
402    if !S9VM_ENABLED {
403        log::info!("[s9vm] disabled by configuration");
404        return;
405    }
406    // VT-x-free diagnostic: the loader dry run only needs world memory and the
407    // kernel ELF loader, so it runs on any host (the full loader phase needs
408    // VT-x for the guest entry).
409    selftest::maybe_run_loader_dry_from_boot_env();
410    let Some(caps) = detect_vmx() else {
411        log::info!(
412            "[s9vm] VT-x absent ({}), looking for AMD-V",
413            unavailable_reason()
414        );
415        init_svm();
416        return;
417    };
418    BACKEND.store(Backend::Vmx as u8, Ordering::Release);
419    CAPS_VALID.store(true, Ordering::Release);
420    log::info!("[s9vm] capabilities: {}", caps.summary());
421    match caps.validate() {
422        Ok(()) => {}
423        Err(error) => {
424            log::warn!(
425                "[s9vm] platform unusable ({:?}) : virtualization inactive",
426                error
427            );
428            return;
429        }
430    }
431    // Activation consumes a frame: it is only attempted at the
432    // `bootstrap` stage, after the frame allocator.
433    match activate_current_cpu() {
434        Ok(()) => {
435            log::info!(
436                "[s9vm] ready ({} CPU activated)",
437                ACTIVE_CPUS.load(Ordering::Acquire)
438            );
439            // Publish the host TSC frequency early so guest CPUID leaves
440            // 0x15/0x16 are meaningful from the first guest, and so the APIC
441            // timer conversion has a scale factor. The boot calibration is a
442            // nominal value (CPUID 0x15/0x16 or the PIT); a later lazy CPUID
443            // detection in `/dev/vmm` can only improve it (write-once cache).
444            publish_tsc_frequency();
445            selftest::maybe_run_from_boot_env(&caps);
446        }
447        Err(error) => log::warn!("[s9vm] activation failed ({:?})", error),
448    }
449}
450
451/// AMD-V initialization: detect, activate the boot CPU, select the backend.
452///
453/// Other CPUs are activated on demand, the first time a vCPU runs on them.
454/// Never panics: any unavailability is logged and the kernel keeps booting.
455fn init_svm() {
456    svm::init_probe();
457    let caps = svm::detect();
458    if caps.validate().is_err() {
459        return;
460    }
461    match svm::activate_current_cpu() {
462        Ok(()) => {
463            BACKEND.store(Backend::Svm as u8, Ordering::Release);
464            CAPS_VALID.store(true, Ordering::Release);
465            log::info!(
466                "[s9vm] ready on AMD-V ({} CPU activated)",
467                svm::active_cpu_count()
468            );
469            publish_tsc_frequency();
470        }
471        Err(error) => log::warn!("[s9vm] AMD-V activation failed ({:?})", error),
472    }
473}
474
475/// Publishes the host TSC frequency in the `tsc` cache, once.
476fn publish_tsc_frequency() {
477    use crate::s9vm::tsc::TscFrequency;
478    if crate::s9vm::tsc::get().is_some() {
479        return;
480    }
481    let khz = crate::arch::x86_64::boot_timestamp::tsc_khz();
482    if khz == 0 {
483        return;
484    }
485    if let Some(frequency) = TscFrequency::from_hz(khz.saturating_mul(1_000)) {
486        crate::s9vm::tsc::set(frequency);
487        log::info!(
488            "[s9vm] TSC frequency: {} MHz (published to guest CPUID)",
489            frequency.hz() / 1_000_000
490        );
491    }
492}
493
494/// Number of CPUs on which VT-x is active.
495pub fn active_cpu_count() -> u32 {
496    ACTIVE_CPUS.load(Ordering::Acquire) + svm::active_cpu_count()
497}
498
499/// True if the capabilities were detected at boot.
500pub fn detected() -> bool {
501    CAPS_VALID.load(Ordering::Acquire)
502}
503
504/// Physical address of a CPU's activation region, if activated.
505pub fn activation_region(cpu: usize) -> Option<u64> {
506    if backend() == Backend::Svm {
507        return svm::hsave_phys(cpu);
508    }
509    if cpu >= MAX_CPUS || !ACTIVATED[cpu].load(Ordering::Acquire) {
510        return None;
511    }
512    Some(REGIONS[cpu].load(Ordering::Acquire))
513}
514
515/// The memmap paging constants must remain aligned with those
516/// of the translation module.
517const _: () = assert!(crate::s9vm::memmap::PAGE_SIZE == crate::s9vm::mmu::PAGE_SIZE);
518const _: () = assert!(crate::s9vm::memmap::MAX_GPA == crate::s9vm::mmu::MAX_GPA);