1#![cfg(all(target_os = "linux", guest_is_native))]
7#![expect(missing_docs)]
8#![expect(unsafe_code)]
10#![expect(clippy::undocumented_unsafe_blocks)]
11
12mod arch;
13mod gsi;
14mod memory;
15
16cfg_select! {
17 guest_arch = "x86_64" => {
18 mod snp;
19 pub use snp::SnpError;
20 use snp::SnpLaunchState;
21 }
22 _ => {}
23}
24
25pub use arch::Kvm;
26pub use memory::MemoryError;
27
28#[cfg(guest_arch = "x86_64")]
29use anyhow::Context as _;
30use guestmem::GuestMemory;
31use inspect::Inspect;
32use memory::KvmMemoryBackingMode;
33use memory::KvmMemoryRangeState;
34use memory_range::MemoryRange;
35use parking_lot::Mutex;
36use std::sync::Arc;
37use thiserror::Error;
38use virt::state::StateError;
39
40pub fn is_available() -> Result<bool, KvmError> {
42 match std::fs::metadata("/dev/kvm") {
43 Ok(_) => Ok(true),
44 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
45 Err(err) => Err(KvmError::AvailableCheck(err)),
46 }
47}
48
49#[cfg(guest_arch = "x86_64")]
51pub fn is_nested_state_available() -> bool {
52 let probe = || -> anyhow::Result<bool> {
53 let kvm = kvm::Kvm::new().context("open KVM for nested-state probe")?;
54 Ok(kvm
55 .check_extension(kvm::KVM_CAP_NESTED_STATE)
56 .context("query KVM_CAP_NESTED_STATE")?
57 > 0)
58 };
59 match probe() {
60 Ok(supported) => supported,
61 Err(err) => {
62 tracing::warn!(error = &*err, "KVM nested-state probe failed");
63 false
64 }
65 }
66}
67
68use arch::KvmVpInner;
69use std::sync::atomic::Ordering;
70use virt::VpIndex;
71use vmcore::vmtime::VmTimeAccess;
72
73#[derive(Error, Debug)]
74pub enum KvmError {
75 #[error("operation not supported")]
76 NotSupported,
77 #[error("vtl2 is not supported on this hypervisor")]
78 Vtl2NotSupported,
79 #[error("isolation is not supported on this hypervisor")]
80 IsolationNotSupported,
81 #[error("kvm error")]
82 Kvm(#[from] kvm::Error),
83 #[error(transparent)]
84 Memory(#[from] MemoryError),
85 #[cfg(guest_arch = "x86_64")]
86 #[error(transparent)]
87 Snp(#[from] SnpError),
88 #[error("failed to stat /dev/kvm")]
89 AvailableCheck(#[source] std::io::Error),
90 #[error(transparent)]
91 State(#[from] Box<StateError<KvmError>>),
92 #[error("invalid state while restoring: {0}")]
93 InvalidState(&'static str),
94 #[error("unsupported isolation configuration: {0}")]
95 UnsupportedIsolationConfiguration(&'static str),
96 #[error("misaligned gic base address")]
97 Misaligned,
98 #[error("host does not support GICv2 or GICv3")]
99 NoGic,
100 #[error("host does not support required cpu capabilities")]
101 Capabilities(virt::PartitionCapabilitiesError),
102 #[cfg(guest_arch = "aarch64")]
103 #[error("failed to set MPIDR_EL1 for VP {vp_index}")]
104 SetMpidr {
105 vp_index: u32,
106 #[source]
107 err: kvm::Error,
108 },
109 #[cfg(guest_arch = "x86_64")]
110 #[error("nested virtualization was requested but the host does not support it")]
111 NestedVirtUnsupported,
112 #[cfg(guest_arch = "x86_64")]
113 #[error("restoring saved nested state is not supported; only reset is implemented")]
114 NestedStateRestoreUnsupported,
115 #[cfg(guest_arch = "x86_64")]
116 #[error("unsupported CPU vendor")]
117 UnsupportedCpuVendor,
118 #[cfg(guest_arch = "x86_64")]
119 #[error("failed to compute topology cpuid")]
120 TopologyCpuid(#[source] virt::x86::topology::UnknownVendor),
121}
122
123#[derive(Inspect)]
124pub struct KvmPartition {
125 #[inspect(flatten)]
126 inner: Arc<KvmPartitionInner>,
127 #[cfg(guest_arch = "x86_64")]
128 #[inspect(skip)]
129 synic_ports: Arc<virt::synic::SynicPorts<KvmPartitionInner>>,
130 #[inspect(skip)]
131 irqfd_state: Arc<gsi::KvmIrqFdState>,
132}
133
134#[derive(Inspect)]
135struct KvmPartitionInner {
136 #[inspect(skip)]
137 kvm: kvm::Partition,
138 #[cfg(guest_arch = "x86_64")]
139 #[inspect(skip)]
140 sev: Option<std::fs::File>,
141 #[cfg(guest_arch = "x86_64")]
142 #[inspect(skip)]
143 snp_config: Option<snp::KvmSnpConfig>,
144 #[cfg(guest_arch = "x86_64")]
145 #[inspect(skip)]
146 snp_launch_state: Mutex<SnpLaunchState>,
147 memory: Mutex<KvmMemoryRangeState>,
148 memory_backing_mode: KvmMemoryBackingMode,
149 #[inspect(iter_by_index)]
150 ram_ranges: Vec<MemoryRange>,
151 hv1_enabled: bool,
152 gm: GuestMemory,
153 #[cfg(guest_arch = "x86_64")]
154 #[inspect(skip)]
155 bsp_cpuid: Vec<kvm::kvm_cpuid_entry2>,
156 #[inspect(skip)]
157 vps: Vec<KvmVpInner>,
158 #[inspect(skip)]
159 gsi_routing: Mutex<gsi::GsiRouting>,
160 caps: virt::PartitionCapabilities,
161
162 #[cfg(guest_arch = "x86_64")]
164 cpuid: virt::CpuidLeafSet,
165
166 #[cfg(guest_arch = "x86_64")]
167 reserved_vps_per_socket: u32,
168
169 #[cfg(guest_arch = "x86_64")]
172 mce_cmci_supported: bool,
173
174 #[cfg(guest_arch = "aarch64")]
176 #[inspect(skip)]
177 _gic_device: kvm::Device,
178 #[cfg(guest_arch = "aarch64")]
180 #[inspect(skip)]
181 _its_device: Option<kvm::Device>,
182 #[cfg(guest_arch = "aarch64")]
184 #[inspect(skip)]
185 gic_msi: vm_topology::processor::aarch64::GicMsiController,
186 #[cfg(guest_arch = "aarch64")]
188 gic_nr_irqs: u32,
189 #[cfg(guest_arch = "x86_64")]
190 synic_ports: virt::synic::SynicPortMap,
191}
192
193#[derive(Debug, Error)]
195enum KvmRunVpError {
196 #[error("KVM internal error: {0:#x}")]
197 InternalError(u32),
198 #[error("invalid vp state")]
199 InvalidVpState,
200 #[error("failed to run VP")]
201 Run(#[source] kvm::Error),
202 #[error("unhandled system event type: {0:#x}")]
203 UnhandledSystemEvent(u32),
204 #[cfg(guest_arch = "x86_64")]
205 #[error("unhandled KVM hypercall: nr={nr:#x}, flags={flags:#x}")]
206 UnhandledHypercall { nr: u64, flags: u64 },
207 #[cfg(guest_arch = "x86_64")]
208 #[error(
209 "SEV guest requested termination: ghcb_msr={ghcb_msr:#x} reason_set={reason_set:#x} reason={reason:#x}"
210 )]
211 SevTermination {
212 ghcb_msr: u64,
213 reason_set: u64,
214 reason: u64,
215 },
216 #[cfg(guest_arch = "x86_64")]
217 #[error("failed to inject an extint interrupt")]
218 ExtintInterrupt(#[source] kvm::Error),
219 #[cfg(guest_arch = "x86_64")]
220 #[error("cannot inject an extint: the VP is not ready for interrupt injection")]
221 ExtintNotInjectable,
222}
223
224pub struct KvmProcessorBinder {
225 partition: Arc<KvmPartitionInner>,
226 vpindex: VpIndex,
227 vmtime: VmTimeAccess,
228}
229
230impl KvmPartitionInner {
231 #[cfg(guest_arch = "x86_64")]
232 fn bsp(&self) -> &KvmVpInner {
233 &self.vps[0]
234 }
235
236 fn vp(&self, vp_index: VpIndex) -> Option<&KvmVpInner> {
237 self.vps.get(vp_index.index() as usize)
238 }
239
240 fn evaluate_vp(&self, vp_index: VpIndex) {
241 let Some(vp) = self.vp(vp_index) else { return };
242 vp.set_eval(true, Ordering::Relaxed);
243
244 let vp_id = cfg_select! {
245 guest_arch = "x86_64" => vp.vp_info().apic_id,
246 guest_arch = "aarch64" => vp.vp_info().base.vp_index.index(),
247 };
248 self.kvm.vp(vp_id).force_exit();
249 }
250}