Skip to main content

strat9_kernel/s9vm/
svm.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 : AMD-V (SVM) hardware layer.
24//!
25//! Counterpart of the VT-x activation in [`super`]. Provides, for AMD CPUs:
26//!
27//! * detection ([`detect`]) through CPUID and `VM_CR`;
28//! * per-CPU activation ([`activate_current_cpu`]): `EFER.SVME`, host
29//!   state-save area (`VM_HSAVE_PA`) and the host extra-state page used by
30//!   `vmsave`/`vmload`;
31//! * the world switch [`vmrun`], written in assembly because it must preserve
32//!   the host general registers, swap the guest ones and bracket the entry
33//!   with `clgi`/`stgi`.
34//!
35//! The pure parts live in [`super::svm_caps`] (capability decoding) and
36//! [`super::svm_vmcb`] (VMCB layout, exit decoding), both host-testable.
37//!
38//! # Status
39//!
40//! Hardware layer of the AMD backend. [`init_probe`] only detects and logs:
41//! activation is never done implicitly, because setting `EFER.SVME` changes CPU
42//! behavior and must be an explicit decision of the caller. The vCPU that
43//! drives [`vmrun`] (VMCB setup, FPU/XCR0 switching, injection) is
44//! [`super::svm_vcpu`], and the nested page tables are
45//! [`super::mmu::SecondLevel::new_npt`].
46//!
47//! Not yet done: wiring into the VM life cycle of [`super::vm`] (backend
48//! selection, device model, exit dispatch) and execution on real hardware.
49
50use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
51
52use super::caps::HwCaps;
53use super::svm_caps::{self, SvmCaps, SvmCapsError};
54use super::InitError;
55use crate::memory::frame::{FrameAllocOptions, FramePurpose, PhysFrame};
56
57/// Maximum number of tracked CPUs (aligned with `percpu::MAX_CPUS`).
58const MAX_CPUS: usize = crate::arch::x86_64::percpu::MAX_CPUS;
59
60/// Per-CPU host state-save area (`VM_HSAVE_PA`), physical address.
61static HSAVE: [AtomicU64; MAX_CPUS] = [const { AtomicU64::new(0) }; MAX_CPUS];
62/// Per-CPU host extra-state page (`vmsave`/`vmload` target), physical address.
63static HOST_VMCB: [AtomicU64; MAX_CPUS] = [const { AtomicU64::new(0) }; MAX_CPUS];
64/// Number of CPUs on which SVM is enabled.
65static ACTIVE_CPUS: AtomicU32 = AtomicU32::new(0);
66/// CPUs on which SVM is enabled.
67static ACTIVATED: [AtomicBool; MAX_CPUS] = [const { AtomicBool::new(false) }; MAX_CPUS];
68
69/// Reads the raw SVM registers and decodes them. No CPU state is modified.
70pub fn detect() -> SvmCaps {
71    // CPUID is always available in long mode.
72    let ext_max = core::arch::x86_64::__cpuid(0x8000_0000).eax;
73    if ext_max < 0x8000_0001 {
74        return SvmCaps::from_raw(0, [0; 4], 0);
75    }
76    let ext1 = core::arch::x86_64::__cpuid(0x8000_0001);
77    let leaf_a = if ext_max >= 0x8000_000A {
78        let r = core::arch::x86_64::__cpuid(0x8000_000A);
79        [r.eax, r.ebx, r.ecx, r.edx]
80    } else {
81        [0; 4]
82    };
83    let supported = ext1.ecx & svm_caps::CPUID_EXT1_ECX_SVM != 0;
84    // `VM_CR` only exists when SVM is advertised: reading it otherwise faults.
85    let vm_cr = if supported {
86        crate::arch::x86_64::rdmsr(svm_caps::MSR_VM_CR)
87    } else {
88        0
89    };
90    SvmCaps::from_raw(ext1.ecx, leaf_a, vm_cr)
91}
92
93/// Probes AMD-V and logs the result. Never modifies CPU state.
94///
95/// Called by [`super::init`] when VT-x is absent.
96pub fn init_probe() {
97    let caps = detect();
98    if !caps.supported {
99        log::info!("[s9vm] AMD-V absent");
100        return;
101    }
102    log::info!("[s9vm] capabilities: {}", caps.summary());
103    match caps.validate() {
104        Ok(()) => log::info!(
105            "[s9vm] AMD-V usable (not activated: call svm::activate_current_cpu() explicitly)"
106        ),
107        Err(SvmCapsError::DisabledByFirmware) => {
108            log::info!("[s9vm] AMD-V disabled by firmware (VM_CR.SVMDIS)")
109        }
110        Err(error) => log::warn!("[s9vm] AMD-V unusable ({:?})", error),
111    }
112}
113
114/// Allocates one zeroed 4 KiB frame.
115fn alloc_zeroed_frame() -> Result<PhysFrame, InitError> {
116    let frame = crate::sync::with_irqs_disabled(|token| {
117        FrameAllocOptions::new()
118            .purpose(FramePurpose::KernelData)
119            .allocate(token)
120    })
121    .map_err(|_| InitError::OutOfMemory)?;
122    let virt = crate::memory::phys_to_virt(frame.start_address.as_u64()) as *mut u8;
123    // SAFETY: the frame is exclusively reserved and covered by the HHDM.
124    unsafe { core::ptr::write_bytes(virt, 0, 4096) };
125    Ok(frame)
126}
127
128fn free_frame(frame: PhysFrame) {
129    crate::sync::with_irqs_disabled(|token| crate::memory::free_frame(token, frame));
130}
131
132/// Enables SVM on the current CPU.
133///
134/// Idempotent. Allocates two frames (host state-save area and host extra-state
135/// page) that stay reserved for the lifetime of the CPU; they are released
136/// again if the activation fails. The caller must keep local interrupts
137/// disabled so the CPU cannot change under it.
138pub fn activate_current_cpu() -> Result<(), InitError> {
139    let cpu = crate::arch::x86_64::percpu::current_cpu_index();
140    if cpu >= MAX_CPUS {
141        return Err(InitError::NotSupported);
142    }
143    if ACTIVATED[cpu].load(Ordering::Acquire) {
144        return Ok(());
145    }
146
147    let caps = detect();
148    caps.validate().map_err(|error| match error {
149        SvmCapsError::NotSupported => InitError::NotSupported,
150        SvmCapsError::DisabledByFirmware => InitError::LockedByFirmware,
151        SvmCapsError::NestedPagingUnavailable | SvmCapsError::NoGuestAsid => {
152            InitError::EptUnavailable
153        }
154    })?;
155
156    let hsave_frame = alloc_zeroed_frame()?;
157    let host_vmcb_frame = match alloc_zeroed_frame() {
158        Ok(frame) => frame,
159        Err(error) => {
160            free_frame(hsave_frame);
161            return Err(error);
162        }
163    };
164    let hsave = hsave_frame.start_address.as_u64();
165    let host_vmcb = host_vmcb_frame.start_address.as_u64();
166
167    let efer = crate::arch::x86_64::rdmsr(svm_caps::MSR_EFER);
168    crate::arch::x86_64::wrmsr(svm_caps::MSR_EFER, efer | svm_caps::EFER_SVME);
169    // Read back: the write is silently ignored when SVM is locked out.
170    if crate::arch::x86_64::rdmsr(svm_caps::MSR_EFER) & svm_caps::EFER_SVME == 0 {
171        free_frame(hsave_frame);
172        free_frame(host_vmcb_frame);
173        return Err(InitError::ActivationFailed);
174    }
175    crate::arch::x86_64::wrmsr(svm_caps::MSR_VM_HSAVE_PA, hsave);
176
177    HSAVE[cpu].store(hsave, Ordering::Release);
178    HOST_VMCB[cpu].store(host_vmcb, Ordering::Release);
179    ACTIVATED[cpu].store(true, Ordering::Release);
180    ACTIVE_CPUS.fetch_add(1, Ordering::AcqRel);
181    log::info!(
182        "[s9vm] AMD-V activated (cpu {}, hsave {:#x}, host vmcb {:#x})",
183        cpu,
184        hsave,
185        host_vmcb
186    );
187    Ok(())
188}
189
190/// Number of CPUs on which SVM is enabled.
191pub fn active_cpu_count() -> u32 {
192    ACTIVE_CPUS.load(Ordering::Acquire)
193}
194
195/// Synthetic [`HwCaps`] for an AMD CPU, or `None` when SVM is unusable.
196///
197/// The VT-x-shaped fields mean, for AMD-V: nested paging is the "EPT" (4
198/// levels, 2 MiB pages, write-back), `unrestricted_guest` is true (SVM runs
199/// real mode natively), there are no fixed CR0/CR4 bits and no `invept`
200/// (flushing is by ASID, handled in the vCPU).
201pub fn hw_caps() -> Option<HwCaps> {
202    let caps = detect();
203    caps.validate().ok()?;
204    Some(HwCaps {
205        allowed: true,
206        feature_control_locked: true,
207        ept: true,
208        ept_four_levels: true,
209        ept_2mb: true,
210        ept_wb: true,
211        unrestricted_guest: true,
212        cr0_fixed0: 0,
213        cr0_fixed1: u64::MAX,
214        cr4_fixed0: 0,
215        cr4_fixed1: u64::MAX,
216        ..HwCaps::default()
217    })
218}
219
220/// True if SVM is enabled on `cpu`.
221pub fn is_activated(cpu: usize) -> bool {
222    cpu < MAX_CPUS && ACTIVATED[cpu].load(Ordering::Acquire)
223}
224
225/// Physical address of `cpu`'s host state-save area (`VM_HSAVE_PA`), if SVM is
226/// activated there. The SVM counterpart of the VT-x activation region.
227pub fn hsave_phys(cpu: usize) -> Option<u64> {
228    if !is_activated(cpu) {
229        return None;
230    }
231    Some(HSAVE[cpu].load(Ordering::Acquire))
232}
233
234/// Physical address of `cpu`'s host extra-state page (`vmsave`/`vmload`), if
235/// SVM is activated there. Pass it as `host_vmcb_pa` to [`vmrun`].
236pub fn host_vmcb_phys(cpu: usize) -> Option<u64> {
237    if !is_activated(cpu) {
238        return None;
239    }
240    Some(HOST_VMCB[cpu].load(Ordering::Acquire))
241}
242
243/// Guest general-purpose registers that `vmrun` does not keep in the VMCB.
244///
245/// `rax` and `rsp` live in the VMCB state-save area. The layout is fixed:
246/// the assembly below indexes it by offset.
247#[repr(C)]
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
249pub struct GuestGprs {
250    pub rbx: u64,
251    pub rcx: u64,
252    pub rdx: u64,
253    pub rsi: u64,
254    pub rdi: u64,
255    pub rbp: u64,
256    pub r8: u64,
257    pub r9: u64,
258    pub r10: u64,
259    pub r11: u64,
260    pub r12: u64,
261    pub r13: u64,
262    pub r14: u64,
263    pub r15: u64,
264}
265
266const _: () = assert!(core::mem::size_of::<GuestGprs>() == 14 * 8);
267
268// World switch.
269//
270//   rdi = guest VMCB physical address
271//   rsi = host extra-state page physical address (vmsave/vmload target)
272//   rdx = *mut GuestGprs
273//
274// `vmrun` saves only part of the host state (RIP, RSP, CR0/3/4, EFER, RFLAGS,
275// ES/CS/SS/DS, GDTR/IDTR) in the HSAVE area. FS/GS bases, TR, LDTR,
276// KernelGSBase and the syscall/sysenter MSRs are NOT saved, hence the
277// `vmsave`/`vmload` pair on the host page around the entry. The guest copy of
278// the same state is switched with `vmload`/`vmsave` on its own VMCB.
279//
280// Stack frame after the three pushes: [rsp] = guest pa, [rsp+8] = host pa,
281// [rsp+16] = GuestGprs*. GIF stays clear from `clgi` until the host state is
282// fully restored, so no interrupt can run on half-switched state.
283core::arch::global_asm!(
284    ".pushsection .text.s9vm_svm_vmrun,\"ax\",@progbits",
285    ".global s9vm_svm_vmrun",
286    ".type s9vm_svm_vmrun,@function",
287    "s9vm_svm_vmrun:",
288    "    push rbp",
289    "    push rbx",
290    "    push r12",
291    "    push r13",
292    "    push r14",
293    "    push r15",
294    "    push rdx",
295    "    push rsi",
296    "    push rdi",
297    "    clgi",
298    "    mov rax, [rsp + 8]",
299    "    vmsave rax",
300    "    mov rax, [rsp]",
301    "    vmload rax",
302    "    mov rdx, [rsp + 16]",
303    "    mov rbx, [rdx + 0]",
304    "    mov rcx, [rdx + 8]",
305    "    mov rsi, [rdx + 24]",
306    "    mov rdi, [rdx + 32]",
307    "    mov rbp, [rdx + 40]",
308    "    mov r8,  [rdx + 48]",
309    "    mov r9,  [rdx + 56]",
310    "    mov r10, [rdx + 64]",
311    "    mov r11, [rdx + 72]",
312    "    mov r12, [rdx + 80]",
313    "    mov r13, [rdx + 88]",
314    "    mov r14, [rdx + 96]",
315    "    mov r15, [rdx + 104]",
316    "    mov rdx, [rdx + 16]",
317    "    mov rax, [rsp]",
318    "    vmrun rax",
319    // Guest registers are live again; rax is the VMCB pa after #VMEXIT, so
320    // free rdx through the stack to reach the GuestGprs pointer.
321    "    push rdx",
322    "    mov rdx, [rsp + 24]",
323    "    mov [rdx + 0],   rbx",
324    "    mov [rdx + 8],   rcx",
325    "    mov [rdx + 24],  rsi",
326    "    mov [rdx + 32],  rdi",
327    "    mov [rdx + 40],  rbp",
328    "    mov [rdx + 48],  r8",
329    "    mov [rdx + 56],  r9",
330    "    mov [rdx + 64],  r10",
331    "    mov [rdx + 72],  r11",
332    "    mov [rdx + 80],  r12",
333    "    mov [rdx + 88],  r13",
334    "    mov [rdx + 96],  r14",
335    "    mov [rdx + 104], r15",
336    "    pop rax",
337    "    mov [rdx + 16],  rax",
338    "    mov rax, [rsp]",
339    "    vmsave rax",
340    "    mov rax, [rsp + 8]",
341    "    vmload rax",
342    "    stgi",
343    "    add rsp, 24",
344    "    pop r15",
345    "    pop r14",
346    "    pop r13",
347    "    pop r12",
348    "    pop rbx",
349    "    pop rbp",
350    "    ret",
351    ".size s9vm_svm_vmrun, . - s9vm_svm_vmrun",
352    ".popsection",
353);
354
355extern "C" {
356    fn s9vm_svm_vmrun(guest_vmcb_pa: u64, host_vmcb_pa: u64, regs: *mut GuestGprs);
357}
358
359/// Enters the guest described by `guest_vmcb_pa` and returns on `#VMEXIT`.
360///
361/// On return the guest registers are stored in `regs`, and the exit reason is
362/// in the VMCB (`EXIT_CODE`, see [`super::svm_vmcb`]).
363///
364/// # Safety
365/// - SVM must be activated on the current CPU ([`activate_current_cpu`]);
366/// - `guest_vmcb_pa` must be the physical address of a valid, page-aligned VMCB
367///   that intercepts `vmrun` ([`super::svm_vmcb::Vmcb::install_mandatory_intercepts`]);
368/// - `host_vmcb_pa` must come from [`host_vmcb_phys`] for this same CPU;
369/// - the caller must not be preempted or migrated while this runs;
370/// - the host FPU/XMM and XCR0 state is not saved here: the guest may clobber
371///   it, so the caller is responsible for switching it.
372pub unsafe fn vmrun(guest_vmcb_pa: u64, host_vmcb_pa: u64, regs: &mut GuestGprs) {
373    // SAFETY: function contract.
374    unsafe { s9vm_svm_vmrun(guest_vmcb_pa, host_vmcb_pa, regs as *mut GuestGprs) };
375}