strat9_kernel/s9vm/fpu.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 : host/guest FPU and SIMD state switching around a guest entry.
24//!
25//! Neither VT-x nor AMD-V switches x87/SSE/AVX state: after `vmrun`/`vmlaunch`
26//! the registers hold whatever the guest left. The kernel switches FPU state
27//! only at task context switches, so a guest entered from a syscall would
28//! destroy the calling task's live SIMD registers, and the host would destroy
29//! the guest's between two exits. [`FpuSwitch`] saves the host state, loads the
30//! guest's, and does the opposite on the way out.
31//!
32//! The XCR0 of the guest can differ from the host's (AMD-V runs the guest with
33//! the real XCR0). It is switched together with the state it describes.
34
35use alloc::vec::Vec;
36
37use super::svm_state::validate_xcr0;
38
39/// FPU switching errors.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum FpuError {
42 /// The save areas could not be allocated.
43 OutOfMemory,
44}
45
46/// `XCR0.SSE`.
47const XCR0_SSE: u64 = 1 << 1;
48
49/// One 64-byte unit, so a `Vec` of them is 64-byte aligned (XSAVE alignment).
50#[repr(C, align(64))]
51#[derive(Clone, Copy)]
52struct Chunk([u8; 64]);
53
54/// A zero-initialized, 64-byte aligned XSAVE/FXSAVE area.
55///
56/// Zero is a valid initial image: a null `XSTATE_BV` means "init state", and
57/// the XSAVE header must stay zero beyond the bytes `xsave` writes. `MXCSR` is
58/// pre-set to its reset value since a zero `MXCSR` unmasks every SIMD
59/// exception.
60struct FpuArea {
61 chunks: Vec<Chunk>,
62}
63
64impl FpuArea {
65 fn new(bytes: usize) -> Result<Self, FpuError> {
66 let count = bytes.div_ceil(64);
67 let mut chunks = Vec::new();
68 chunks
69 .try_reserve_exact(count)
70 .map_err(|_| FpuError::OutOfMemory)?;
71 chunks.resize(count, Chunk([0; 64]));
72 let mut area = Self { chunks };
73 // MXCSR lives at byte 24 of both the FXSAVE and XSAVE legacy areas.
74 area.chunks[0].0[24..28].copy_from_slice(&0x1F80u32.to_le_bytes());
75 Ok(area)
76 }
77
78 fn ptr(&mut self) -> *mut u8 {
79 self.chunks.as_mut_ptr().cast()
80 }
81
82 /// Clears the `XSTATE_BV` bits (XSAVE header, byte 512) that `allowed`
83 /// does not contain. `xrstor` raises `#GP` when `XSTATE_BV` names a
84 /// component that XCR0 disables, which happens if the guest narrows its
85 /// XCR0 after an image was saved under the wider one.
86 fn mask_xstate_bv(&mut self, allowed: u64) {
87 // Byte 512 is the first byte of chunk 8 (512 / 64).
88 if let Some(chunk) = self.chunks.get_mut(8) {
89 let mut raw = [0u8; 8];
90 raw.copy_from_slice(&chunk.0[0..8]);
91 let masked = u64::from_le_bytes(raw) & allowed;
92 chunk.0[0..8].copy_from_slice(&masked.to_le_bytes());
93 }
94 }
95}
96
97/// Saves the FPU/SIMD state of the current CPU into `area`.
98///
99/// # Safety
100/// `area` must be 64-byte aligned and large enough for the current XCR0.
101unsafe fn save(area: *mut u8, xsave: bool) {
102 // SAFETY: function contract; the requested-feature mask is ANDed with XCR0
103 // by the hardware.
104 unsafe {
105 if xsave {
106 core::arch::asm!(
107 "xsave64 [{area}]",
108 area = in(reg) area,
109 in("eax") u32::MAX,
110 in("edx") u32::MAX,
111 options(nostack),
112 );
113 } else {
114 core::arch::asm!("fxsave64 [{area}]", area = in(reg) area, options(nostack));
115 }
116 }
117}
118
119/// Restores the FPU/SIMD state of the current CPU from `area`.
120///
121/// # Safety
122/// `area` must hold an image produced by [`save`] (or the pristine zero image)
123/// under the same XCR0.
124unsafe fn restore(area: *mut u8, xsave: bool) {
125 // SAFETY: function contract.
126 unsafe {
127 if xsave {
128 core::arch::asm!(
129 "xrstor64 [{area}]",
130 area = in(reg) area,
131 in("eax") u32::MAX,
132 in("edx") u32::MAX,
133 options(nostack),
134 );
135 } else {
136 core::arch::asm!("fxrstor64 [{area}]", area = in(reg) area, options(nostack));
137 }
138 }
139}
140
141/// Proof that [`FpuSwitch::enter`] ran, carrying the host XCR0 to restore.
142#[must_use = "pass it to FpuSwitch::leave"]
143pub struct HostFpu {
144 host_xcr0: u64,
145 guest_xcr0: u64,
146}
147
148/// Host and guest FPU/SIMD state of one vCPU.
149pub struct FpuSwitch {
150 host: FpuArea,
151 guest: FpuArea,
152 uses_xsave: bool,
153 /// XCR0 bits the host supports (upper bound for the guest).
154 supported_xcr0: u64,
155 /// XCR0 the guest believes it has; `0` = follow the host's XCR0.
156 guest_xcr0: u64,
157}
158
159impl FpuSwitch {
160 /// Allocates the two save areas.
161 pub fn new() -> Result<Self, FpuError> {
162 let uses_xsave = crate::arch::x86_64::cpuid::host_uses_xsave();
163 let (bytes, supported_xcr0) = if uses_xsave {
164 let info = crate::arch::x86_64::cpuid::host();
165 (info.xsave_size_max.max(576), info.supported_xcr0)
166 } else {
167 (512, 1)
168 };
169 Ok(Self {
170 host: FpuArea::new(bytes)?,
171 guest: FpuArea::new(bytes)?,
172 uses_xsave,
173 supported_xcr0,
174 guest_xcr0: 0,
175 })
176 }
177
178 /// XCR0 as seen by the guest (`None` while it follows the host's).
179 pub fn guest_xcr0(&self) -> Option<u64> {
180 (self.guest_xcr0 != 0).then_some(self.guest_xcr0)
181 }
182
183 /// Sets the guest XCR0 after an `xsetbv`. Returns `false`, changing
184 /// nothing, when the value is architecturally invalid or unsupported.
185 pub fn set_guest_xcr0(&mut self, value: u64) -> bool {
186 if !validate_xcr0(value, self.supported_xcr0) {
187 return false;
188 }
189 self.guest_xcr0 = value;
190 true
191 }
192
193 /// XCR0 programmed while the guest runs.
194 ///
195 /// `SSE` is always included: the XMM registers must be switched even when
196 /// the guest never enabled them in XCR0, otherwise the host's XMM contents
197 /// would be visible to (and clobbered by) the guest.
198 fn hardware_guest_xcr0(&self, host_xcr0: u64) -> u64 {
199 if self.guest_xcr0 == 0 {
200 host_xcr0
201 } else {
202 self.guest_xcr0 | XCR0_SSE
203 }
204 }
205
206 /// Saves the host state, then loads the guest's (and its XCR0).
207 ///
208 /// # Safety
209 /// Local interrupts must be disabled from this call until the matching
210 /// [`Self::leave`]: a context switch in between would save the guest state
211 /// into the interrupted task's area.
212 pub unsafe fn enter(&mut self) -> HostFpu {
213 let host_xcr0 = if self.uses_xsave {
214 crate::arch::x86_64::xgetbv(0)
215 } else {
216 1
217 };
218 let guest_xcr0 = self.hardware_guest_xcr0(host_xcr0);
219 if self.uses_xsave {
220 // The guest image may have been saved under a wider XCR0 (the
221 // guest narrowed it, or the host XCR0 differs from the last
222 // entry's: the scheduler switches it per task).
223 self.guest.mask_xstate_bv(guest_xcr0);
224 }
225 // SAFETY: function contract; both areas are 64-byte aligned and sized
226 // for the largest XCR0, and each image is saved/restored under the
227 // XCR0 it was produced with.
228 unsafe {
229 save(self.host.ptr(), self.uses_xsave);
230 if self.uses_xsave && guest_xcr0 != host_xcr0 {
231 crate::arch::x86_64::xsetbv(0, guest_xcr0);
232 }
233 restore(self.guest.ptr(), self.uses_xsave);
234 }
235 HostFpu {
236 host_xcr0,
237 guest_xcr0,
238 }
239 }
240
241 /// Saves the guest state, then restores the host's (and its XCR0).
242 ///
243 /// # Safety
244 /// Same as [`Self::enter`]; `token` must come from the matching `enter`.
245 pub unsafe fn leave(&mut self, token: HostFpu) {
246 // SAFETY: function contract.
247 unsafe {
248 save(self.guest.ptr(), self.uses_xsave);
249 if self.uses_xsave && token.guest_xcr0 != token.host_xcr0 {
250 crate::arch::x86_64::xsetbv(0, token.host_xcr0);
251 }
252 restore(self.host.ptr(), self.uses_xsave);
253 }
254 }
255}