Skip to main content

strat9_kernel/s9vm/
backend.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 : hardware backend abstraction (Intel VT-x or AMD-V).
24//!
25//! The world registry, the run loop and the device model of s9vm drive a vCPU
26//! through the API of [`Vcpu`] (VT-x). [`HwVcpu`] wraps either that vCPU or an
27//! [`SvmVcpu`] behind the same method names, so the callers stay written once.
28//! The `Vmx` variant forwards every call unchanged: the Intel path behaves as
29//! if the wrapper were not there.
30//!
31//! For AMD, exits are converted to the VT-x shape ([`super::svm_exit`]) and the
32//! few VT-x-only concepts are emulated or made no-ops:
33//!
34//! | VT-x concept | AMD-V counterpart |
35//! |---|---|
36//! | `load`/`clear`/`configure_host` (VMCS currency) | no-op: a VMCB is plain memory |
37//! | external-interrupt exiting | always on (`INTR` intercept) |
38//! | preemption timer | emulated from the TSC on `INTR` exits ([`SLICE_DIVISOR`]) |
39//! | interrupt-window exiting | `VINTR` intercept + virtual interrupt |
40
41use alloc::string::String;
42use core::sync::atomic::{AtomicU32, Ordering};
43
44use crate::s9vm::{
45    caps::HwCaps,
46    exit::{self, ExitReason},
47    guest::GuestState,
48    msr::MsrModel,
49    svm,
50    svm_exit,
51    svm_vcpu::{SvmVcpu, SvmVcpuError},
52    svm_vmcb::exit_code,
53    vcpu::{ExitInfo, Vcpu, VcpuError},
54    Backend,
55};
56
57/// Fraction of a second of guest time between two emulated preemption-timer
58/// exits on AMD (`1 / SLICE_DIVISOR` s). VT-x's default slice is of the same
59/// order (roughly 0.1-0.5 s).
60pub const SLICE_DIVISOR: u64 = 10;
61
62/// TSC frequency assumed when none was published (2 GHz).
63const FALLBACK_TSC_HZ: u64 = 2_000_000_000;
64
65/// The operations the device model needs from a vCPU, whatever the backend.
66pub trait VcpuOps {
67    /// Second-level translation root given to this vCPU (`EPTP` or `nCR3`).
68    fn second_level_pointer(&self) -> u64;
69    /// Guest state as of the last exit.
70    fn guest(&self) -> &GuestState;
71    /// True if the guest runs with paging enabled.
72    fn paging_enabled(&self) -> bool;
73    /// Reads a general-purpose register (x86 encoding order).
74    fn guest_gpr(&self, register: u8) -> u64;
75    /// Writes a general-purpose register.
76    ///
77    /// # Safety
78    /// The guest must not be running (exit handler).
79    unsafe fn set_guest_gpr(&mut self, register: u8, value: u64);
80    /// Sets the guest instruction pointer.
81    ///
82    /// # Safety
83    /// The guest must not be running (exit handler).
84    unsafe fn set_guest_rip(&mut self, rip: u64);
85    /// Per-vCPU MSR shadow model.
86    fn msr_mut(&mut self) -> &mut MsrModel;
87}
88
89impl VcpuOps for Vcpu {
90    fn second_level_pointer(&self) -> u64 {
91        Vcpu::second_level_pointer(self)
92    }
93    fn guest(&self) -> &GuestState {
94        Vcpu::guest(self)
95    }
96    fn paging_enabled(&self) -> bool {
97        Vcpu::paging_enabled(self)
98    }
99    fn guest_gpr(&self, register: u8) -> u64 {
100        Vcpu::guest_gpr(self, register)
101    }
102    unsafe fn set_guest_gpr(&mut self, register: u8, value: u64) {
103        // SAFETY: caller contract.
104        unsafe { Vcpu::set_guest_gpr(self, register, value) }
105    }
106    unsafe fn set_guest_rip(&mut self, rip: u64) {
107        // SAFETY: caller contract.
108        unsafe { Vcpu::set_guest_rip(self, rip) }
109    }
110    fn msr_mut(&mut self) -> &mut MsrModel {
111        Vcpu::msr_mut(self)
112    }
113}
114
115/// An AMD vCPU plus the state of its emulated preemption timer.
116pub struct SvmBackendVcpu {
117    vcpu: SvmVcpu,
118    /// TSC at the start of the current time slice (`configure`).
119    slice_start: u64,
120}
121
122/// A virtual CPU of either backend.
123pub enum HwVcpu {
124    /// Intel VT-x.
125    Vmx(Vcpu),
126    /// AMD-V.
127    Svm(SvmBackendVcpu),
128}
129
130impl From<SvmVcpuError> for VcpuError {
131    fn from(value: SvmVcpuError) -> Self {
132        match value {
133            SvmVcpuError::OutOfMemory => VcpuError::OutOfMemory,
134            SvmVcpuError::InterruptNotDeliverable => VcpuError::InterruptNotDeliverable,
135            other => VcpuError::Svm(other),
136        }
137    }
138}
139
140/// Next ASID to hand out; wraps within the CPU's range.
141static NEXT_ASID: AtomicU32 = AtomicU32::new(0);
142
143/// Allocates a guest ASID in `1..=max_guest_asid`.
144///
145/// ASIDs are recycled when the range is exhausted: two live vCPUs may then
146/// share one, which the entry path tolerates by flushing whenever the VMCB that
147/// ran last on a CPU differs.
148fn allocate_asid() -> u32 {
149    let max = svm::detect().max_guest_asid().max(1);
150    1 + NEXT_ASID.fetch_add(1, Ordering::Relaxed) % max
151}
152
153impl HwVcpu {
154    /// Creates the hardware context of a vCPU for the active backend.
155    ///
156    /// `pointer` is the value given by `WorldMemory::second_level_pointer`:
157    /// an `EPTP` on Intel, the `nCR3` on AMD.
158    pub fn new(caps: &HwCaps, pointer: u64) -> Result<Self, VcpuError> {
159        match crate::s9vm::backend() {
160            Backend::Svm => {
161                let vcpu = SvmVcpu::new(pointer, allocate_asid())?;
162                Ok(Self::Svm(SvmBackendVcpu {
163                    vcpu,
164                    slice_start: 0,
165                }))
166            }
167            _ => Ok(Self::Vmx(Vcpu::new(caps, pointer)?)),
168        }
169    }
170
171    /// True once the guest has been entered at least once.
172    pub fn entered(&self) -> bool {
173        match self {
174            Self::Vmx(v) => v.entered(),
175            Self::Svm(s) => s.vcpu.entered(),
176        }
177    }
178
179    /// Makes the hardware context current on this CPU.
180    ///
181    /// # Safety
182    /// VT-x: active on this CPU, vCPU not running.
183    pub unsafe fn load(&mut self) -> Result<(), VcpuError> {
184        match self {
185            // SAFETY: caller contract.
186            Self::Vmx(v) => unsafe { v.load() },
187            // A VMCB is plain memory: there is nothing to make current.
188            Self::Svm(_) => Ok(()),
189        }
190    }
191
192    /// Releases the hardware context (VMCS `VMCLEAR`).
193    ///
194    /// # Safety
195    /// VT-x: active on this CPU, vCPU not running.
196    pub unsafe fn clear(&mut self) -> Result<(), VcpuError> {
197        match self {
198            // SAFETY: caller contract.
199            Self::Vmx(v) => unsafe { v.clear() },
200            Self::Svm(_) => Ok(()),
201        }
202    }
203
204    /// Writes the host-state fields.
205    ///
206    /// # Safety
207    /// VT-x: the control block must be loaded.
208    pub unsafe fn configure_host(&mut self) -> Result<(), VcpuError> {
209        match self {
210            // SAFETY: caller contract.
211            Self::Vmx(v) => unsafe { v.configure_host() },
212            // `vmrun`/`vmsave` handle the host state themselves.
213            Self::Svm(_) => Ok(()),
214        }
215    }
216
217    /// Imports the architectural state the guest produced since the last RUN.
218    ///
219    /// # Safety
220    /// VT-x: the control block must be loaded and the guest inactive.
221    pub unsafe fn refresh_system_state(&mut self) -> Result<(), VcpuError> {
222        match self {
223            // SAFETY: caller contract.
224            Self::Vmx(v) => unsafe { v.refresh_system_state() },
225            // The state is mirrored out of the VMCB at every exit already.
226            Self::Svm(_) => Ok(()),
227        }
228    }
229
230    /// Writes the guest state and the execution controls.
231    ///
232    /// # Safety
233    /// VT-x: the control block must be loaded.
234    pub unsafe fn configure(&mut self, caps: &HwCaps, guest: &GuestState) -> Result<(), VcpuError> {
235        match self {
236            // SAFETY: caller contract.
237            Self::Vmx(v) => unsafe { v.configure(caps, guest) },
238            Self::Svm(s) => {
239                s.vcpu.configure(guest);
240                s.slice_start = core::arch::x86_64::_rdtsc();
241                Ok(())
242            }
243        }
244    }
245
246    /// Queues an NMI for the next entry.
247    ///
248    /// # Safety
249    /// VT-x: the control block must be loaded and the guest inactive.
250    pub unsafe fn inject_nmi(&mut self) -> Result<(), VcpuError> {
251        match self {
252            // SAFETY: caller contract.
253            Self::Vmx(v) => unsafe { v.inject_nmi() },
254            Self::Svm(s) => s.vcpu.inject_nmi().map_err(VcpuError::from),
255        }
256    }
257
258    /// Queues an external interrupt for the next entry.
259    ///
260    /// # Safety
261    /// VT-x: the control block must be loaded and the guest inactive.
262    pub unsafe fn inject_interrupt(&mut self, vector: u8) -> Result<(), VcpuError> {
263        match self {
264            // SAFETY: caller contract.
265            Self::Vmx(v) => unsafe { v.inject_interrupt(vector) },
266            Self::Svm(s) => s.vcpu.inject_interrupt(vector).map_err(VcpuError::from),
267        }
268    }
269
270    /// Arms or disarms interrupt-window exiting. Returns whether the control
271    /// is armed as requested.
272    ///
273    /// # Safety
274    /// VT-x: the control block must be loaded and the guest inactive.
275    pub unsafe fn set_interrupt_window_exiting(
276        &mut self,
277        caps: &HwCaps,
278        enabled: bool,
279    ) -> Result<bool, VcpuError> {
280        match self {
281            // SAFETY: caller contract.
282            Self::Vmx(v) => unsafe { v.set_interrupt_window_exiting(caps, enabled) },
283            Self::Svm(s) => {
284                s.vcpu.set_interrupt_window_exiting(enabled);
285                Ok(enabled)
286            }
287        }
288    }
289
290    /// Re-arms external-interrupt exiting.
291    ///
292    /// # Safety
293    /// VT-x: the control block must be loaded and the guest inactive.
294    pub unsafe fn set_external_interrupt_exiting(
295        &mut self,
296        caps: &HwCaps,
297        enabled: bool,
298    ) -> Result<bool, VcpuError> {
299        match self {
300            // SAFETY: caller contract.
301            Self::Vmx(v) => unsafe { v.set_external_interrupt_exiting(caps, enabled) },
302            // The `INTR` intercept is part of the base controls and cannot be
303            // turned off: a host IRQ must never reach the guest IDT.
304            Self::Svm(_) => Ok(true),
305        }
306    }
307
308    /// Interruptibility state (bit 0: STI / MOV-SS blocking).
309    ///
310    /// # Safety
311    /// VT-x: the control block must be loaded.
312    pub unsafe fn interruptibility(&self) -> Result<u32, VcpuError> {
313        match self {
314            // SAFETY: caller contract.
315            Self::Vmx(v) => unsafe { v.interruptibility() },
316            Self::Svm(s) => Ok(s.vcpu.interruptibility()),
317        }
318    }
319
320    /// Enters the guest and returns on the next exit, in the VT-x shape.
321    ///
322    /// # Safety
323    /// VT-x: the control block must be loaded. AMD-V: nothing beyond the
324    /// activation, which is done on demand on the current CPU.
325    pub unsafe fn run(&mut self) -> Result<ExitInfo, VcpuError> {
326        match self {
327            // SAFETY: caller contract.
328            Self::Vmx(v) => unsafe { v.run() },
329            Self::Svm(s) => {
330                // SAFETY: the VMCB, NPT and permission maps belong to this vCPU.
331                let raw = unsafe { s.vcpu.run() }?;
332                let rip = s.vcpu.guest().rip;
333                let mut translated =
334                    svm_exit::translate(raw.code, raw.info1, raw.info2, rip, raw.next_rip);
335                // VT-x bounds a guest's slice with the preemption timer; AMD-V
336                // has none. A host interrupt exit is the only point where the
337                // kernel regains control from a guest that never exits by
338                // itself, so it doubles as the slice boundary.
339                if raw.code == exit_code::INTR && slice_expired(s.slice_start) {
340                    translated.reason = ExitReason {
341                        reason: exit::PREEMPTION_TIMER,
342                        entry_failed: false,
343                    };
344                    s.slice_start = core::arch::x86_64::_rdtsc();
345                }
346                let interrupt_info = if raw.code == exit_code::NMI {
347                    exit::nmi_info()
348                } else {
349                    0
350                };
351                Ok(ExitInfo {
352                    raw_reason: translated.reason.raw(),
353                    reason: translated.reason,
354                    qualification: translated.qualification,
355                    guest_physical_address: translated.guest_physical_address,
356                    interrupt_info,
357                    vectoring_info: 0,
358                    vectoring_error: 0,
359                    instruction_length: translated.instruction_length,
360                    instruction_info: 0,
361                    entry_failed: translated.reason.entry_failed,
362                })
363            }
364        }
365    }
366
367    /// Pushes the MSR shadows into the hardware state.
368    ///
369    /// # Safety
370    /// VT-x: the control block must be loaded and the guest inactive.
371    pub unsafe fn sync_msr_state(&mut self) -> Result<(), VcpuError> {
372        match self {
373            // SAFETY: caller contract.
374            Self::Vmx(v) => unsafe { v.sync_msr_state() },
375            Self::Svm(s) => {
376                s.vcpu.sync_msr_state();
377                Ok(())
378            }
379        }
380    }
381
382    /// Dump of the hardware state, for failure logs.
383    ///
384    /// # Safety
385    /// VT-x: the control block must be loaded.
386    pub unsafe fn guest_diagnostics(&self) -> String {
387        match self {
388            // SAFETY: caller contract.
389            Self::Vmx(v) => unsafe { v.guest_diagnostics() },
390            Self::Svm(s) => s.vcpu.diagnostics(),
391        }
392    }
393
394    /// The VT-x vCPU, if that is the active backend (DOS boot and the VT-x
395    /// self-tests need VT-x specifics).
396    pub fn as_vmx(&self) -> Option<&Vcpu> {
397        match self {
398            Self::Vmx(v) => Some(v),
399            Self::Svm(_) => None,
400        }
401    }
402
403    /// Invalidates the guest TLB after a second-level mapping change.
404    pub fn flush_second_level(&mut self) {
405        if let Self::Svm(s) = self {
406            s.vcpu.request_tlb_flush();
407        }
408    }
409}
410
411/// True when the emulated slice (`1 / SLICE_DIVISOR` s of TSC) has elapsed.
412fn slice_expired(start: u64) -> bool {
413    let hz = crate::s9vm::tsc::get()
414        .map(|frequency| frequency.hz())
415        .unwrap_or(FALLBACK_TSC_HZ);
416    crate::arch::x86_64::rdtsc().wrapping_sub(start) >= hz / SLICE_DIVISOR
417}
418
419impl VcpuOps for HwVcpu {
420    fn second_level_pointer(&self) -> u64 {
421        match self {
422            Self::Vmx(v) => v.second_level_pointer(),
423            Self::Svm(s) => s.vcpu.nested_cr3(),
424        }
425    }
426    fn guest(&self) -> &GuestState {
427        match self {
428            Self::Vmx(v) => v.guest(),
429            Self::Svm(s) => s.vcpu.guest(),
430        }
431    }
432    fn paging_enabled(&self) -> bool {
433        match self {
434            Self::Vmx(v) => v.paging_enabled(),
435            Self::Svm(s) => s.vcpu.paging_enabled(),
436        }
437    }
438    fn guest_gpr(&self, register: u8) -> u64 {
439        match self {
440            Self::Vmx(v) => v.guest_gpr(register),
441            Self::Svm(s) => s.vcpu.guest_gpr(register),
442        }
443    }
444    unsafe fn set_guest_gpr(&mut self, register: u8, value: u64) {
445        match self {
446            // SAFETY: caller contract.
447            Self::Vmx(v) => unsafe { v.set_guest_gpr(register, value) },
448            Self::Svm(s) => s.vcpu.set_guest_gpr(register, value),
449        }
450    }
451    unsafe fn set_guest_rip(&mut self, rip: u64) {
452        match self {
453            // SAFETY: caller contract.
454            Self::Vmx(v) => unsafe { v.set_guest_rip(rip) },
455            Self::Svm(s) => s.vcpu.set_guest_rip(rip),
456        }
457    }
458    fn msr_mut(&mut self) -> &mut MsrModel {
459        match self {
460            Self::Vmx(v) => v.msr_mut(),
461            Self::Svm(s) => s.vcpu.msr_mut(),
462        }
463    }
464}