Skip to main content

strat9_kernel/s9vm/
svm_vmcb.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 VMCB layout, intercepts and `#VMEXIT` decoding.
24//!
25//! Counterpart of [`super::control`] (VMCS fields) and [`super::exit`] for
26//! AMD-V. Pure module: it manipulates a 4 KiB page of bytes through typed
27//! accessors, with no hardware access, so it is testable on the host.
28//!
29//! Offsets come from AMD64 APM vol. 2, appendix B ("Layout of VMCB"): the
30//! control area occupies bytes `0x000..0x400`, the state-save area starts at
31//! `0x400`. Every offset, intercept bit and exit code was cross-checked against
32//! the Linux `arch/x86/include/asm/svm.h` and `uapi/asm/svm.h` headers.
33
34use super::exit::ExitClass;
35
36/// Size of the VMCB (one page).
37pub const VMCB_SIZE: usize = 4096;
38
39/// Control-area offsets.
40pub mod ctl {
41    /// Intercept CR reads (u16) / writes (u16).
42    pub const INTERCEPT_CR: usize = 0x000;
43    /// Intercept DR reads (u16) / writes (u16).
44    pub const INTERCEPT_DR: usize = 0x004;
45    /// Exception intercept bitmap (u32, one bit per vector 0..31).
46    pub const INTERCEPT_EXCEPTIONS: usize = 0x008;
47    /// Intercept vector 3 (u32), see [`super::intercept3`].
48    pub const INTERCEPT3: usize = 0x00C;
49    /// Intercept vector 4 (u32), see [`super::intercept4`].
50    pub const INTERCEPT4: usize = 0x010;
51    /// Pause filter threshold (u16).
52    pub const PAUSE_FILTER_THRESHOLD: usize = 0x03C;
53    /// Pause filter count (u16).
54    pub const PAUSE_FILTER_COUNT: usize = 0x03E;
55    /// I/O permission map physical address (u64).
56    pub const IOPM_BASE_PA: usize = 0x040;
57    /// MSR permission map physical address (u64).
58    pub const MSRPM_BASE_PA: usize = 0x048;
59    /// TSC offset added to the guest's `rdtsc` (u64).
60    pub const TSC_OFFSET: usize = 0x050;
61    /// Guest ASID (u32).
62    pub const ASID: usize = 0x058;
63    /// TLB control (u8), see [`super::tlb`].
64    pub const TLB_CONTROL: usize = 0x05C;
65    /// Virtual interrupt control (u64).
66    pub const V_INTR: usize = 0x060;
67    /// Interrupt shadow (u64, bit 0).
68    pub const INTERRUPT_SHADOW: usize = 0x068;
69    /// Exit code (u64).
70    pub const EXIT_CODE: usize = 0x070;
71    /// Exit information 1 (u64).
72    pub const EXIT_INFO1: usize = 0x078;
73    /// Exit information 2 (u64).
74    pub const EXIT_INFO2: usize = 0x080;
75    /// Interrupted event information (u64).
76    pub const EXIT_INT_INFO: usize = 0x088;
77    /// Error code of the interrupted event (u32).
78    pub const EXIT_INT_INFO_ERR: usize = 0x08C;
79    /// Nested paging control (u64, bit 0 = enable).
80    pub const NESTED_CTL: usize = 0x090;
81    /// Event injection (u32).
82    pub const EVENT_INJ: usize = 0x0A8;
83    /// Event injection error code (u32).
84    pub const EVENT_INJ_ERR: usize = 0x0AC;
85    /// Nested page table root (`nCR3`, u64).
86    pub const NESTED_CR3: usize = 0x0B0;
87    /// LBR virtualization control (u64).
88    pub const LBR_CTL: usize = 0x0B8;
89    /// VMCB clean bits (u32).
90    pub const CLEAN: usize = 0x0C0;
91    /// Next sequential RIP, valid with `NRIP_SAVE` (u64).
92    pub const NEXT_RIP: usize = 0x0C8;
93    /// Number of valid instruction bytes (u8), decode assists.
94    pub const INSN_LEN: usize = 0x0D0;
95    /// Fetched instruction bytes (15 bytes), decode assists.
96    pub const INSN_BYTES: usize = 0x0D1;
97}
98
99/// State-save-area offsets (absolute within the VMCB).
100pub mod save {
101    /// Start of the state-save area.
102    pub const BASE: usize = 0x400;
103    /// Segment registers: 16 bytes each (selector u16, attrib u16, limit u32, base u64).
104    pub const ES: usize = BASE;
105    pub const CS: usize = BASE + 0x10;
106    pub const SS: usize = BASE + 0x20;
107    pub const DS: usize = BASE + 0x30;
108    pub const FS: usize = BASE + 0x40;
109    pub const GS: usize = BASE + 0x50;
110    pub const GDTR: usize = BASE + 0x60;
111    pub const LDTR: usize = BASE + 0x70;
112    pub const IDTR: usize = BASE + 0x80;
113    pub const TR: usize = BASE + 0x90;
114    /// Current privilege level (u8).
115    pub const CPL: usize = BASE + 0xCB;
116    pub const EFER: usize = BASE + 0xD0;
117    pub const CR4: usize = BASE + 0x148;
118    pub const CR3: usize = BASE + 0x150;
119    pub const CR0: usize = BASE + 0x158;
120    pub const DR7: usize = BASE + 0x160;
121    pub const DR6: usize = BASE + 0x168;
122    pub const RFLAGS: usize = BASE + 0x170;
123    pub const RIP: usize = BASE + 0x178;
124    pub const RSP: usize = BASE + 0x1D8;
125    pub const RAX: usize = BASE + 0x1F8;
126    pub const STAR: usize = BASE + 0x200;
127    pub const LSTAR: usize = BASE + 0x208;
128    pub const CSTAR: usize = BASE + 0x210;
129    pub const SFMASK: usize = BASE + 0x218;
130    pub const KERNEL_GS_BASE: usize = BASE + 0x220;
131    pub const SYSENTER_CS: usize = BASE + 0x228;
132    pub const SYSENTER_ESP: usize = BASE + 0x230;
133    pub const SYSENTER_EIP: usize = BASE + 0x238;
134    pub const CR2: usize = BASE + 0x240;
135    pub const G_PAT: usize = BASE + 0x268;
136}
137
138/// Intercept vector 3 bits (offset `0x00C`).
139pub mod intercept3 {
140    pub const INTR: u32 = 1 << 0;
141    pub const NMI: u32 = 1 << 1;
142    pub const SMI: u32 = 1 << 2;
143    pub const INIT: u32 = 1 << 3;
144    pub const VINTR: u32 = 1 << 4;
145    pub const RDTSC: u32 = 1 << 14;
146    pub const RDPMC: u32 = 1 << 15;
147    pub const CPUID: u32 = 1 << 18;
148    pub const INVD: u32 = 1 << 22;
149    pub const PAUSE: u32 = 1 << 23;
150    pub const HLT: u32 = 1 << 24;
151    pub const INVLPG: u32 = 1 << 25;
152    pub const INVLPGA: u32 = 1 << 26;
153    /// I/O instructions, filtered by the I/O permission map.
154    pub const IOIO_PROT: u32 = 1 << 27;
155    /// `rdmsr`/`wrmsr`, filtered by the MSR permission map.
156    pub const MSR_PROT: u32 = 1 << 28;
157    pub const TASK_SWITCH: u32 = 1 << 29;
158    pub const SHUTDOWN: u32 = 1 << 31;
159}
160
161/// Intercept vector 4 bits (offset `0x010`).
162pub mod intercept4 {
163    /// `vmrun` **must** be intercepted (hardware requirement).
164    pub const VMRUN: u32 = 1 << 0;
165    pub const VMMCALL: u32 = 1 << 1;
166    pub const VMLOAD: u32 = 1 << 2;
167    pub const VMSAVE: u32 = 1 << 3;
168    pub const STGI: u32 = 1 << 4;
169    pub const CLGI: u32 = 1 << 5;
170    pub const SKINIT: u32 = 1 << 6;
171    pub const RDTSCP: u32 = 1 << 7;
172    pub const WBINVD: u32 = 1 << 9;
173    pub const MONITOR: u32 = 1 << 10;
174    pub const MWAIT: u32 = 1 << 11;
175    pub const XSETBV: u32 = 1 << 13;
176}
177
178/// Intercepts that the base layer always installs: the hardware requires
179/// `vmrun`, and the guest must not be able to use the other SVM instructions.
180pub const MANDATORY_INTERCEPT4: u32 = intercept4::VMRUN
181    | intercept4::VMMCALL
182    | intercept4::VMLOAD
183    | intercept4::VMSAVE
184    | intercept4::STGI
185    | intercept4::CLGI
186    | intercept4::SKINIT;
187
188/// `TLB_CONTROL` values.
189pub mod tlb {
190    pub const DO_NOTHING: u8 = 0;
191    pub const FLUSH_ALL: u8 = 1;
192    pub const FLUSH_ASID: u8 = 3;
193    pub const FLUSH_ASID_LOCAL: u8 = 7;
194}
195
196/// `NESTED_CTL` bit 0: nested paging enable.
197pub const NESTED_CTL_NP_ENABLE: u64 = 1;
198
199/// `EVENT_INJ` encoding (APM vol. 2, 15.20).
200pub mod event_inj {
201    /// Valid bit.
202    pub const VALID: u32 = 1 << 31;
203    /// Error code valid bit.
204    pub const ERROR_CODE_VALID: u32 = 1 << 11;
205    /// Type: external interrupt.
206    pub const TYPE_INTR: u32 = 0 << 8;
207    /// Type: NMI.
208    pub const TYPE_NMI: u32 = 2 << 8;
209    /// Type: hardware exception.
210    pub const TYPE_EXCEPTION: u32 = 3 << 8;
211    /// Type: software interrupt.
212    pub const TYPE_SOFT: u32 = 4 << 8;
213
214    /// Encodes an event with no error code.
215    pub const fn encode(vector: u8, kind: u32) -> u32 {
216        VALID | kind | vector as u32
217    }
218
219    /// Encodes a hardware exception with an error code.
220    pub const fn encode_with_error(vector: u8) -> u32 {
221        VALID | ERROR_CODE_VALID | TYPE_EXCEPTION | vector as u32
222    }
223}
224
225/// `#VMEXIT` codes (APM vol. 2, appendix C).
226pub mod exit_code {
227    pub const CR_READ_BASE: u64 = 0x00;
228    pub const CR_WRITE_BASE: u64 = 0x10;
229    pub const DR_READ_BASE: u64 = 0x20;
230    pub const DR_WRITE_BASE: u64 = 0x30;
231    pub const EXCEPTION_BASE: u64 = 0x40;
232    pub const INTR: u64 = 0x60;
233    pub const NMI: u64 = 0x61;
234    pub const SMI: u64 = 0x62;
235    pub const INIT: u64 = 0x63;
236    pub const VINTR: u64 = 0x64;
237    pub const RDTSC: u64 = 0x6E;
238    pub const RDPMC: u64 = 0x6F;
239    pub const CPUID: u64 = 0x72;
240    pub const INVD: u64 = 0x76;
241    pub const PAUSE: u64 = 0x77;
242    pub const HLT: u64 = 0x78;
243    pub const INVLPG: u64 = 0x79;
244    pub const INVLPGA: u64 = 0x7A;
245    pub const IOIO: u64 = 0x7B;
246    pub const MSR: u64 = 0x7C;
247    pub const TASK_SWITCH: u64 = 0x7D;
248    pub const SHUTDOWN: u64 = 0x7F;
249    pub const VMRUN: u64 = 0x80;
250    pub const VMMCALL: u64 = 0x81;
251    pub const VMLOAD: u64 = 0x82;
252    pub const VMSAVE: u64 = 0x83;
253    pub const STGI: u64 = 0x84;
254    pub const CLGI: u64 = 0x85;
255    pub const SKINIT: u64 = 0x86;
256    pub const RDTSCP: u64 = 0x87;
257    pub const WBINVD: u64 = 0x89;
258    pub const MONITOR: u64 = 0x8A;
259    pub const MWAIT: u64 = 0x8B;
260    pub const MWAIT_COND: u64 = 0x8C;
261    pub const XSETBV: u64 = 0x8D;
262    pub const CR_WRITE_TRAP_BASE: u64 = 0x90;
263    /// Nested page fault (the EPT violation of AMD).
264    pub const NPF: u64 = 0x400;
265    /// Invalid guest state: `vmrun` failed its consistency checks.
266    pub const INVALID: u64 = u64::MAX;
267}
268
269/// Classifies an exit code into the shared [`ExitClass`], so that the
270/// dispatcher written for VT-x can be reused unchanged.
271pub const fn classify(code: u64) -> ExitClass {
272    use exit_code as c;
273    match code {
274        0x00..=0x1F | 0x90..=0x9F => ExitClass::ControlRegister,
275        0x20..=0x3F => ExitClass::DebugRegister,
276        0x40..=0x5F => ExitClass::ExceptionOrNmi,
277        c::INTR | c::SMI | c::INIT => ExitClass::ExternalInterrupt,
278        c::NMI => ExitClass::ExceptionOrNmi,
279        c::VINTR => ExitClass::InterruptWindow,
280        c::RDTSC | c::RDTSCP | c::RDPMC => ExitClass::Timestamp,
281        c::CPUID => ExitClass::Cpuid,
282        c::INVD | c::WBINVD => ExitClass::Cache,
283        c::PAUSE => ExitClass::Pause,
284        c::HLT => ExitClass::Halt,
285        c::INVLPG | c::INVLPGA => ExitClass::Tlb,
286        c::IOIO => ExitClass::IoPort,
287        c::MSR => ExitClass::Msr,
288        c::SHUTDOWN => ExitClass::TripleFault,
289        c::VMMCALL => ExitClass::Call,
290        c::MONITOR | c::MWAIT | c::MWAIT_COND => ExitClass::MonitorWait,
291        c::XSETBV => ExitClass::ExtendedState,
292        c::NPF => ExitClass::EptViolation,
293        c::INVALID => ExitClass::EntryFailure,
294        _ => ExitClass::Unknown,
295    }
296}
297
298/// Decoded nested page fault (`EXIT_INFO1` of an `NPF` exit).
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300pub struct NestedFault {
301    /// The translation was present (protection fault) rather than missing.
302    pub present: bool,
303    /// The access was a write.
304    pub write: bool,
305    /// The access was an instruction fetch.
306    pub fetch: bool,
307    /// The fault occurred while walking the guest page tables.
308    pub during_guest_walk: bool,
309    /// Faulting guest physical address (`EXIT_INFO2`).
310    pub gpa: u64,
311}
312
313impl NestedFault {
314    /// Decodes `EXIT_INFO1` / `EXIT_INFO2`.
315    pub const fn decode(info1: u64, info2: u64) -> Self {
316        Self {
317            present: info1 & 1 != 0,
318            write: info1 & (1 << 1) != 0,
319            fetch: info1 & (1 << 4) != 0,
320            // Bit 32: final guest physical address access; bit 33: guest page table access.
321            during_guest_walk: info1 & (1 << 33) != 0,
322            gpa: info2,
323        }
324    }
325}
326
327/// Decoded I/O intercept (`EXIT_INFO1` of an `IOIO` exit, APM vol. 2, 15.10.2).
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub struct IoExit {
330    /// Port number.
331    pub port: u16,
332    /// `in` (read from the port) rather than `out`.
333    pub is_in: bool,
334    /// String instruction (`ins`/`outs`).
335    pub string: bool,
336    /// `rep` prefix.
337    pub rep: bool,
338    /// Access size in bytes (1, 2 or 4).
339    pub size: u8,
340    /// RIP of the instruction that follows (`EXIT_INFO2`).
341    pub next_rip: u64,
342}
343
344impl IoExit {
345    /// Decodes `EXIT_INFO1` / `EXIT_INFO2`. Returns `None` if no size bit is
346    /// set (malformed information).
347    pub const fn decode(info1: u64, info2: u64) -> Option<Self> {
348        let size = if info1 & (1 << 4) != 0 {
349            1
350        } else if info1 & (1 << 5) != 0 {
351            2
352        } else if info1 & (1 << 6) != 0 {
353            4
354        } else {
355            return None;
356        };
357        Some(Self {
358            port: (info1 >> 16) as u16,
359            is_in: info1 & 1 != 0,
360            string: info1 & (1 << 2) != 0,
361            rep: info1 & (1 << 3) != 0,
362            size,
363            next_rip: info2,
364        })
365    }
366}
367
368/// True if an `MSR` exit is a `wrmsr` (`EXIT_INFO1` = 1) rather than `rdmsr`.
369/// The MSR index is in the guest `ecx`.
370pub const fn msr_exit_is_write(info1: u64) -> bool {
371    info1 & 1 != 0
372}
373
374/// One VMCB: 4 KiB, page-aligned, zero-initialized.
375#[repr(C, align(4096))]
376pub struct Vmcb {
377    bytes: [u8; VMCB_SIZE],
378}
379
380impl Vmcb {
381    /// A zeroed VMCB.
382    pub const fn new() -> Self {
383        Self {
384            bytes: [0; VMCB_SIZE],
385        }
386    }
387
388    /// Raw view, for hardware access.
389    pub fn as_bytes(&self) -> &[u8; VMCB_SIZE] {
390        &self.bytes
391    }
392
393    /// Reads a `u8` field.
394    pub fn read8(&self, offset: usize) -> u8 {
395        self.bytes[offset]
396    }
397
398    /// Reads a `u16` field.
399    pub fn read16(&self, offset: usize) -> u16 {
400        u16::from_le_bytes([self.bytes[offset], self.bytes[offset + 1]])
401    }
402
403    /// Reads a `u32` field.
404    pub fn read32(&self, offset: usize) -> u32 {
405        let mut raw = [0u8; 4];
406        raw.copy_from_slice(&self.bytes[offset..offset + 4]);
407        u32::from_le_bytes(raw)
408    }
409
410    /// Reads a `u64` field.
411    pub fn read64(&self, offset: usize) -> u64 {
412        let mut raw = [0u8; 8];
413        raw.copy_from_slice(&self.bytes[offset..offset + 8]);
414        u64::from_le_bytes(raw)
415    }
416
417    /// Writes a `u8` field.
418    pub fn write8(&mut self, offset: usize, value: u8) {
419        self.bytes[offset] = value;
420    }
421
422    /// Writes a `u16` field.
423    pub fn write16(&mut self, offset: usize, value: u16) {
424        self.bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
425    }
426
427    /// Writes a `u32` field.
428    pub fn write32(&mut self, offset: usize, value: u32) {
429        self.bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
430    }
431
432    /// Writes a `u64` field.
433    pub fn write64(&mut self, offset: usize, value: u64) {
434        self.bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
435    }
436
437    /// Writes a segment register (selector, attributes, limit, base).
438    ///
439    /// `attrib` uses the VMCB packed format: bits 0-7 = type/S/DPL/P,
440    /// bits 8-11 = AVL/L/D/B/G (the access-rights byte followed by the
441    /// flags nibble of a descriptor).
442    pub fn write_segment(&mut self, offset: usize, selector: u16, attrib: u16, limit: u32, base: u64) {
443        self.write16(offset, selector);
444        self.write16(offset + 2, attrib);
445        self.write32(offset + 4, limit);
446        self.write64(offset + 8, base);
447    }
448
449    /// Reads a segment register as `(selector, attrib, limit, base)`.
450    pub fn read_segment(&self, offset: usize) -> (u16, u16, u32, u64) {
451        (
452            self.read16(offset),
453            self.read16(offset + 2),
454            self.read32(offset + 4),
455            self.read64(offset + 8),
456        )
457    }
458
459    /// Installs the always-on intercepts (see [`MANDATORY_INTERCEPT4`]).
460    pub fn install_mandatory_intercepts(&mut self) {
461        let current = self.read32(ctl::INTERCEPT4);
462        self.write32(ctl::INTERCEPT4, current | MANDATORY_INTERCEPT4);
463    }
464
465    /// Enables nested paging with the given `nCR3` and guest ASID.
466    ///
467    /// ASID 0 is reserved for the host: the guest ASID must be non-zero.
468    pub fn enable_nested_paging(&mut self, ncr3: u64, asid: u32) {
469        debug_assert!(asid != 0);
470        self.write64(ctl::NESTED_CTL, NESTED_CTL_NP_ENABLE);
471        self.write64(ctl::NESTED_CR3, ncr3);
472        self.write32(ctl::ASID, asid);
473        // The cached state of the VMCB is stale: force a reload.
474        self.write32(ctl::CLEAN, 0);
475    }
476
477    /// Exit code of the last `#VMEXIT`.
478    pub fn exit_code(&self) -> u64 {
479        self.read64(ctl::EXIT_CODE)
480    }
481
482    /// Class of the last `#VMEXIT`.
483    pub fn exit_class(&self) -> ExitClass {
484        classify(self.exit_code())
485    }
486
487    /// Decoded nested page fault, if the last exit was one.
488    pub fn nested_fault(&self) -> Option<NestedFault> {
489        if self.exit_code() != exit_code::NPF {
490            return None;
491        }
492        Some(NestedFault::decode(
493            self.read64(ctl::EXIT_INFO1),
494            self.read64(ctl::EXIT_INFO2),
495        ))
496    }
497
498    /// Queues an event for injection at the next `vmrun`.
499    pub fn inject(&mut self, event: u32, error_code: u32) {
500        self.write32(ctl::EVENT_INJ, event);
501        self.write32(ctl::EVENT_INJ_ERR, error_code);
502    }
503
504    /// Advances the guest RIP past the intercepted instruction using the
505    /// hardware-provided `NEXT_RIP` (requires `NRIP_SAVE`). Returns `false`
506    /// if `NEXT_RIP` is zero (feature absent): the caller must decode.
507    pub fn advance_rip_from_next(&mut self) -> bool {
508        let next = self.read64(ctl::NEXT_RIP);
509        if next == 0 {
510            return false;
511        }
512        self.write64(save::RIP, next);
513        true
514    }
515}
516
517impl Default for Vmcb {
518    fn default() -> Self {
519        Self::new()
520    }
521}
522
523const _: () = assert!(core::mem::size_of::<Vmcb>() == VMCB_SIZE);
524const _: () = assert!(core::mem::align_of::<Vmcb>() == 4096);