1 // Copyright © 2019 Intel Corporation 2 // 3 // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause 4 // 5 // Copyright © 2020, Microsoft Corporation 6 // 7 // Copyright 2018-2019 CrowdStrike, Inc. 8 // 9 // 10 11 #[cfg(target_arch = "aarch64")] 12 use crate::aarch64::VcpuInit; 13 #[cfg(target_arch = "aarch64")] 14 use crate::arch::aarch64::gic::Vgic; 15 #[cfg(feature = "tdx")] 16 use crate::arch::x86::CpuIdEntry; 17 use crate::cpu::Vcpu; 18 use crate::device::Device; 19 #[cfg(target_arch = "x86_64")] 20 use crate::ClockData; 21 use crate::CreateDevice; 22 use crate::UserMemoryRegion; 23 use crate::{IoEventAddress, IrqRoutingEntry}; 24 #[cfg(feature = "kvm")] 25 use kvm_ioctls::Cap; 26 #[cfg(target_arch = "x86_64")] 27 use std::fs::File; 28 use std::sync::Arc; 29 #[cfg(target_arch = "aarch64")] 30 use std::sync::Mutex; 31 use thiserror::Error; 32 use vmm_sys_util::eventfd::EventFd; 33 34 /// 35 /// I/O events data matches (32 or 64 bits). 36 /// 37 #[derive(Debug)] 38 pub enum DataMatch { 39 DataMatch32(u32), 40 DataMatch64(u64), 41 } 42 43 impl From<DataMatch> for u64 { 44 fn from(dm: DataMatch) -> u64 { 45 match dm { 46 DataMatch::DataMatch32(dm) => dm.into(), 47 DataMatch::DataMatch64(dm) => dm, 48 } 49 } 50 } 51 52 #[derive(Error, Debug)] 53 /// 54 /// Enum for VM error 55 pub enum HypervisorVmError { 56 /// 57 /// Create Vcpu error 58 /// 59 #[error("Failed to create Vcpu: {0}")] 60 CreateVcpu(#[source] anyhow::Error), 61 /// 62 /// Identity map address error 63 /// 64 #[error("Failed to set identity map address: {0}")] 65 SetIdentityMapAddress(#[source] anyhow::Error), 66 /// 67 /// TSS address error 68 /// 69 #[error("Failed to set TSS address: {0}")] 70 SetTssAddress(#[source] anyhow::Error), 71 /// 72 /// Create interrupt controller error 73 /// 74 #[error("Failed to create interrupt controller: {0}")] 75 CreateIrq(#[source] anyhow::Error), 76 /// 77 /// Register interrupt event error 78 /// 79 #[error("Failed to register interrupt event: {0}")] 80 RegisterIrqFd(#[source] anyhow::Error), 81 /// 82 /// Un register interrupt event error 83 /// 84 #[error("Failed to unregister interrupt event: {0}")] 85 UnregisterIrqFd(#[source] anyhow::Error), 86 /// 87 /// Register IO event error 88 /// 89 #[error("Failed to register IO event: {0}")] 90 RegisterIoEvent(#[source] anyhow::Error), 91 /// 92 /// Unregister IO event error 93 /// 94 #[error("Failed to unregister IO event: {0}")] 95 UnregisterIoEvent(#[source] anyhow::Error), 96 /// 97 /// Set GSI routing error 98 /// 99 #[error("Failed to set GSI routing: {0}")] 100 SetGsiRouting(#[source] anyhow::Error), 101 /// 102 /// Create user memory error 103 /// 104 #[error("Failed to create user memory: {0}")] 105 CreateUserMemory(#[source] anyhow::Error), 106 /// 107 /// Remove user memory region error 108 /// 109 #[error("Failed to remove user memory: {0}")] 110 RemoveUserMemory(#[source] anyhow::Error), 111 /// 112 /// Create device error 113 /// 114 #[error("Failed to set GSI routing: {0}")] 115 CreateDevice(#[source] anyhow::Error), 116 /// 117 /// Get preferred target error 118 /// 119 #[error("Failed to get preferred target: {0}")] 120 GetPreferredTarget(#[source] anyhow::Error), 121 /// 122 /// Enable split Irq error 123 /// 124 #[error("Failed to enable split Irq: {0}")] 125 EnableSplitIrq(#[source] anyhow::Error), 126 /// 127 /// Enable SGX attribute error 128 /// 129 #[error("Failed to enable SGX attribute: {0}")] 130 EnableSgxAttribute(#[source] anyhow::Error), 131 /// 132 /// Get clock error 133 /// 134 #[error("Failed to get clock: {0}")] 135 GetClock(#[source] anyhow::Error), 136 /// 137 /// Set clock error 138 /// 139 #[error("Failed to set clock: {0}")] 140 SetClock(#[source] anyhow::Error), 141 /// 142 /// Create passthrough device 143 /// 144 #[error("Failed to create passthrough device: {0}")] 145 CreatePassthroughDevice(#[source] anyhow::Error), 146 /// Write to Guest memory 147 /// 148 #[error("Failed to write to guest memory: {0}")] 149 GuestMemWrite(#[source] anyhow::Error), 150 /// 151 /// Read Guest memory 152 /// 153 #[error("Failed to read guest memory: {0}")] 154 GuestMemRead(#[source] anyhow::Error), 155 /// 156 /// Read from MMIO Bus 157 /// 158 #[error("Failed to read from MMIO Bus: {0}")] 159 MmioBusRead(#[source] anyhow::Error), 160 /// 161 /// Write to MMIO Bus 162 /// 163 #[error("Failed to write to MMIO Bus: {0}")] 164 MmioBusWrite(#[source] anyhow::Error), 165 /// 166 /// Read from IO Bus 167 /// 168 #[error("Failed to read from IO Bus: {0}")] 169 IoBusRead(#[source] anyhow::Error), 170 /// 171 /// Write to IO Bus 172 /// 173 #[error("Failed to write to IO Bus: {0}")] 174 IoBusWrite(#[source] anyhow::Error), 175 /// 176 /// Start dirty log error 177 /// 178 #[error("Failed to get dirty log: {0}")] 179 StartDirtyLog(#[source] anyhow::Error), 180 /// 181 /// Stop dirty log error 182 /// 183 #[error("Failed to get dirty log: {0}")] 184 StopDirtyLog(#[source] anyhow::Error), 185 /// 186 /// Get dirty log error 187 /// 188 #[error("Failed to get dirty log: {0}")] 189 GetDirtyLog(#[source] anyhow::Error), 190 /// 191 /// Assert virtual interrupt error 192 /// 193 #[error("Failed to assert virtual Interrupt: {0}")] 194 AsserttVirtualInterrupt(#[source] anyhow::Error), 195 196 #[cfg(feature = "tdx")] 197 /// 198 /// Error initializing TDX on the VM 199 /// 200 #[error("Failed to initialize TDX: {0}")] 201 InitializeTdx(#[source] std::io::Error), 202 #[cfg(feature = "tdx")] 203 /// 204 /// Error finalizing the TDX configuration on the VM 205 /// 206 #[error("Failed to finalize TDX: {0}")] 207 FinalizeTdx(#[source] std::io::Error), 208 #[cfg(feature = "tdx")] 209 /// 210 /// Error initializing the TDX memory region 211 /// 212 #[error("Failed to initialize memory region TDX: {0}")] 213 InitMemRegionTdx(#[source] std::io::Error), 214 /// 215 /// Create Vgic error 216 /// 217 #[error("Failed to create Vgic: {0}")] 218 CreateVgic(#[source] anyhow::Error), 219 } 220 /// 221 /// Result type for returning from a function 222 /// 223 pub type Result<T> = std::result::Result<T, HypervisorVmError>; 224 225 /// Configuration data for legacy interrupts. 226 /// 227 /// On x86 platforms, legacy interrupts means those interrupts routed through PICs or IOAPICs. 228 #[derive(Copy, Clone, Debug)] 229 pub struct LegacyIrqSourceConfig { 230 pub irqchip: u32, 231 pub pin: u32, 232 } 233 234 /// Configuration data for MSI/MSI-X interrupts. 235 /// 236 /// On x86 platforms, these interrupts are vectors delivered directly to the LAPIC. 237 #[derive(Copy, Clone, Debug, Default)] 238 pub struct MsiIrqSourceConfig { 239 /// High address to delivery message signaled interrupt. 240 pub high_addr: u32, 241 /// Low address to delivery message signaled interrupt. 242 pub low_addr: u32, 243 /// Data to write to delivery message signaled interrupt. 244 pub data: u32, 245 /// Unique ID of the device to delivery message signaled interrupt. 246 pub devid: u32, 247 } 248 249 /// Configuration data for an interrupt source. 250 #[derive(Copy, Clone, Debug)] 251 pub enum InterruptSourceConfig { 252 /// Configuration data for Legacy interrupts. 253 LegacyIrq(LegacyIrqSourceConfig), 254 /// Configuration data for PciMsi, PciMsix and generic MSI interrupts. 255 MsiIrq(MsiIrqSourceConfig), 256 } 257 258 /// 259 /// Trait to represent a Vm 260 /// 261 /// This crate provides a hypervisor-agnostic interfaces for Vm 262 /// 263 pub trait Vm: Send + Sync { 264 #[cfg(target_arch = "x86_64")] 265 /// Sets the address of the one-page region in the VM's address space. 266 fn set_identity_map_address(&self, address: u64) -> Result<()>; 267 #[cfg(target_arch = "x86_64")] 268 /// Sets the address of the three-page region in the VM's address space. 269 fn set_tss_address(&self, offset: usize) -> Result<()>; 270 /// Creates an in-kernel interrupt controller. 271 fn create_irq_chip(&self) -> Result<()>; 272 /// Registers an event that will, when signaled, trigger the `gsi` IRQ. 273 fn register_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()>; 274 /// Unregister an event that will, when signaled, trigger the `gsi` IRQ. 275 fn unregister_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()>; 276 /// Creates a new KVM vCPU file descriptor and maps the memory corresponding 277 fn create_vcpu(&self, id: u8, vm_ops: Option<Arc<dyn VmOps>>) -> Result<Arc<dyn Vcpu>>; 278 #[cfg(target_arch = "aarch64")] 279 fn create_vgic( 280 &self, 281 vcpu_count: u64, 282 dist_addr: u64, 283 dist_size: u64, 284 redist_size: u64, 285 msi_size: u64, 286 nr_irqs: u32, 287 ) -> Result<Arc<Mutex<dyn Vgic>>>; 288 289 /// Registers an event to be signaled whenever a certain address is written to. 290 fn register_ioevent( 291 &self, 292 fd: &EventFd, 293 addr: &IoEventAddress, 294 datamatch: Option<DataMatch>, 295 ) -> Result<()>; 296 /// Unregister an event from a certain address it has been previously registered to. 297 fn unregister_ioevent(&self, fd: &EventFd, addr: &IoEventAddress) -> Result<()>; 298 // Construct a routing entry 299 fn make_routing_entry(&self, gsi: u32, config: &InterruptSourceConfig) -> IrqRoutingEntry; 300 /// Sets the GSI routing table entries, overwriting any previously set 301 fn set_gsi_routing(&self, entries: &[IrqRoutingEntry]) -> Result<()>; 302 /// Creates a memory region structure that can be used with {create/remove}_user_memory_region 303 fn make_user_memory_region( 304 &self, 305 slot: u32, 306 guest_phys_addr: u64, 307 memory_size: u64, 308 userspace_addr: u64, 309 readonly: bool, 310 log_dirty_pages: bool, 311 ) -> UserMemoryRegion; 312 /// Creates a guest physical memory slot. 313 fn create_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> Result<()>; 314 /// Removes a guest physical memory slot. 315 fn remove_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> Result<()>; 316 /// Creates an emulated device in the kernel. 317 fn create_device(&self, device: &mut CreateDevice) -> Result<Arc<dyn Device>>; 318 /// Returns the preferred CPU target type which can be emulated by KVM on underlying host. 319 #[cfg(target_arch = "aarch64")] 320 fn get_preferred_target(&self, kvi: &mut VcpuInit) -> Result<()>; 321 /// Enable split Irq capability 322 #[cfg(target_arch = "x86_64")] 323 fn enable_split_irq(&self) -> Result<()>; 324 #[cfg(target_arch = "x86_64")] 325 fn enable_sgx_attribute(&self, file: File) -> Result<()>; 326 /// Retrieve guest clock. 327 #[cfg(target_arch = "x86_64")] 328 fn get_clock(&self) -> Result<ClockData>; 329 /// Set guest clock. 330 #[cfg(target_arch = "x86_64")] 331 fn set_clock(&self, data: &ClockData) -> Result<()>; 332 #[cfg(feature = "kvm")] 333 /// Checks if a particular `Cap` is available. 334 fn check_extension(&self, c: Cap) -> bool; 335 /// Create a device that is used for passthrough 336 fn create_passthrough_device(&self) -> Result<Arc<dyn Device>>; 337 /// Start logging dirty pages 338 fn start_dirty_log(&self) -> Result<()>; 339 /// Stop logging dirty pages 340 fn stop_dirty_log(&self) -> Result<()>; 341 /// Get dirty pages bitmap 342 fn get_dirty_log(&self, slot: u32, base_gpa: u64, memory_size: u64) -> Result<Vec<u64>>; 343 #[cfg(feature = "tdx")] 344 /// Initalize TDX on this VM 345 fn tdx_init(&self, cpuid: &[CpuIdEntry], max_vcpus: u32) -> Result<()>; 346 #[cfg(feature = "tdx")] 347 /// Finalize the configuration of TDX on this VM 348 fn tdx_finalize(&self) -> Result<()>; 349 #[cfg(feature = "tdx")] 350 /// Initalize a TDX memory region for this VM 351 fn tdx_init_memory_region( 352 &self, 353 host_address: u64, 354 guest_address: u64, 355 size: u64, 356 measure: bool, 357 ) -> Result<()>; 358 } 359 360 pub trait VmOps: Send + Sync { 361 fn guest_mem_write(&self, gpa: u64, buf: &[u8]) -> Result<usize>; 362 fn guest_mem_read(&self, gpa: u64, buf: &mut [u8]) -> Result<usize>; 363 fn mmio_read(&self, gpa: u64, data: &mut [u8]) -> Result<()>; 364 fn mmio_write(&self, gpa: u64, data: &[u8]) -> Result<()>; 365 #[cfg(target_arch = "x86_64")] 366 fn pio_read(&self, port: u64, data: &mut [u8]) -> Result<()>; 367 #[cfg(target_arch = "x86_64")] 368 fn pio_write(&self, port: u64, data: &[u8]) -> Result<()>; 369 } 370