1 // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause 2 // 3 // Copyright © 2020, Microsoft Corporation 4 // 5 6 use std::any::Any; 7 use std::collections::HashMap; 8 #[cfg(feature = "sev_snp")] 9 use std::num::NonZeroUsize; 10 use std::sync::{Arc, RwLock}; 11 12 #[cfg(feature = "sev_snp")] 13 use arc_swap::ArcSwap; 14 use mshv_bindings::*; 15 #[cfg(target_arch = "x86_64")] 16 use mshv_ioctls::{set_registers_64, InterruptRequest}; 17 use mshv_ioctls::{Mshv, NoDatamatch, VcpuFd, VmFd, VmType}; 18 use vfio_ioctls::VfioDeviceFd; 19 use vm::DataMatch; 20 #[cfg(feature = "sev_snp")] 21 use vm_memory::bitmap::AtomicBitmap; 22 23 #[cfg(target_arch = "x86_64")] 24 use crate::arch::emulator::PlatformEmulator; 25 #[cfg(target_arch = "x86_64")] 26 use crate::arch::x86::emulator::Emulator; 27 #[cfg(target_arch = "x86_64")] 28 use crate::mshv::emulator::MshvEmulatorContext; 29 use crate::vm::{self, InterruptSourceConfig, VmOps}; 30 use crate::{cpu, hypervisor, vec_with_array_field, HypervisorType}; 31 #[cfg(feature = "sev_snp")] 32 mod snp_constants; 33 // x86_64 dependencies 34 #[cfg(target_arch = "x86_64")] 35 pub mod x86_64; 36 // aarch64 dependencies 37 #[cfg(target_arch = "aarch64")] 38 pub mod aarch64; 39 #[cfg(target_arch = "x86_64")] 40 use std::fs::File; 41 use std::os::unix::io::AsRawFd; 42 #[cfg(target_arch = "aarch64")] 43 use std::sync::Mutex; 44 45 #[cfg(target_arch = "aarch64")] 46 pub use aarch64::VcpuMshvState; 47 #[cfg(feature = "sev_snp")] 48 use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; 49 #[cfg(feature = "sev_snp")] 50 use snp_constants::*; 51 use vmm_sys_util::eventfd::EventFd; 52 #[cfg(target_arch = "x86_64")] 53 pub use x86_64::*; 54 #[cfg(target_arch = "x86_64")] 55 pub use x86_64::{emulator, VcpuMshvState}; 56 /// 57 /// Export generically-named wrappers of mshv-bindings for Unix-based platforms 58 /// 59 pub use { 60 mshv_bindings::mshv_create_device as CreateDevice, 61 mshv_bindings::mshv_device_attr as DeviceAttr, mshv_ioctls, mshv_ioctls::DeviceFd, 62 }; 63 64 #[cfg(target_arch = "aarch64")] 65 use crate::arch::aarch64::gic::{Vgic, VgicConfig}; 66 #[cfg(target_arch = "x86_64")] 67 use crate::arch::x86::{CpuIdEntry, FpuState, MsrEntry}; 68 #[cfg(target_arch = "x86_64")] 69 use crate::ClockData; 70 use crate::{ 71 CpuState, IoEventAddress, IrqRoutingEntry, MpState, UserMemoryRegion, 72 USER_MEMORY_REGION_ADJUSTABLE, USER_MEMORY_REGION_EXECUTE, USER_MEMORY_REGION_READ, 73 USER_MEMORY_REGION_WRITE, 74 }; 75 76 pub const PAGE_SHIFT: usize = 12; 77 78 impl From<mshv_user_mem_region> for UserMemoryRegion { 79 fn from(region: mshv_user_mem_region) -> Self { 80 let mut flags: u32 = USER_MEMORY_REGION_READ | USER_MEMORY_REGION_ADJUSTABLE; 81 if region.flags & (1 << MSHV_SET_MEM_BIT_WRITABLE) != 0 { 82 flags |= USER_MEMORY_REGION_WRITE; 83 } 84 if region.flags & (1 << MSHV_SET_MEM_BIT_EXECUTABLE) != 0 { 85 flags |= USER_MEMORY_REGION_EXECUTE; 86 } 87 88 UserMemoryRegion { 89 guest_phys_addr: (region.guest_pfn << PAGE_SHIFT as u64) 90 + (region.userspace_addr & ((1 << PAGE_SHIFT) - 1)), 91 memory_size: region.size, 92 userspace_addr: region.userspace_addr, 93 flags, 94 ..Default::default() 95 } 96 } 97 } 98 99 #[cfg(target_arch = "x86_64")] 100 impl From<MshvClockData> for ClockData { 101 fn from(d: MshvClockData) -> Self { 102 ClockData::Mshv(d) 103 } 104 } 105 106 #[cfg(target_arch = "x86_64")] 107 impl From<ClockData> for MshvClockData { 108 fn from(ms: ClockData) -> Self { 109 match ms { 110 ClockData::Mshv(s) => s, 111 /* Needed in case other hypervisors are enabled */ 112 #[allow(unreachable_patterns)] 113 _ => unreachable!("MSHV clock data is not valid"), 114 } 115 } 116 } 117 118 impl From<UserMemoryRegion> for mshv_user_mem_region { 119 fn from(region: UserMemoryRegion) -> Self { 120 let mut flags: u8 = 0; 121 if region.flags & USER_MEMORY_REGION_WRITE != 0 { 122 flags |= 1 << MSHV_SET_MEM_BIT_WRITABLE; 123 } 124 if region.flags & USER_MEMORY_REGION_EXECUTE != 0 { 125 flags |= 1 << MSHV_SET_MEM_BIT_EXECUTABLE; 126 } 127 128 mshv_user_mem_region { 129 guest_pfn: region.guest_phys_addr >> PAGE_SHIFT, 130 size: region.memory_size, 131 userspace_addr: region.userspace_addr, 132 flags, 133 ..Default::default() 134 } 135 } 136 } 137 138 impl From<mshv_ioctls::IoEventAddress> for IoEventAddress { 139 fn from(a: mshv_ioctls::IoEventAddress) -> Self { 140 match a { 141 mshv_ioctls::IoEventAddress::Pio(x) => Self::Pio(x), 142 mshv_ioctls::IoEventAddress::Mmio(x) => Self::Mmio(x), 143 } 144 } 145 } 146 147 impl From<IoEventAddress> for mshv_ioctls::IoEventAddress { 148 fn from(a: IoEventAddress) -> Self { 149 match a { 150 IoEventAddress::Pio(x) => Self::Pio(x), 151 IoEventAddress::Mmio(x) => Self::Mmio(x), 152 } 153 } 154 } 155 156 impl From<VcpuMshvState> for CpuState { 157 fn from(s: VcpuMshvState) -> Self { 158 CpuState::Mshv(s) 159 } 160 } 161 162 impl From<CpuState> for VcpuMshvState { 163 fn from(s: CpuState) -> Self { 164 match s { 165 CpuState::Mshv(s) => s, 166 /* Needed in case other hypervisors are enabled */ 167 #[allow(unreachable_patterns)] 168 _ => panic!("CpuState is not valid"), 169 } 170 } 171 } 172 173 impl From<mshv_bindings::StandardRegisters> for crate::StandardRegisters { 174 fn from(s: mshv_bindings::StandardRegisters) -> Self { 175 crate::StandardRegisters::Mshv(s) 176 } 177 } 178 179 impl From<crate::StandardRegisters> for mshv_bindings::StandardRegisters { 180 fn from(e: crate::StandardRegisters) -> Self { 181 match e { 182 crate::StandardRegisters::Mshv(e) => e, 183 /* Needed in case other hypervisors are enabled */ 184 #[allow(unreachable_patterns)] 185 _ => panic!("StandardRegisters are not valid"), 186 } 187 } 188 } 189 190 impl From<mshv_user_irq_entry> for IrqRoutingEntry { 191 fn from(s: mshv_user_irq_entry) -> Self { 192 IrqRoutingEntry::Mshv(s) 193 } 194 } 195 196 impl From<IrqRoutingEntry> for mshv_user_irq_entry { 197 fn from(e: IrqRoutingEntry) -> Self { 198 match e { 199 IrqRoutingEntry::Mshv(e) => e, 200 /* Needed in case other hypervisors are enabled */ 201 #[allow(unreachable_patterns)] 202 _ => panic!("IrqRoutingEntry is not valid"), 203 } 204 } 205 } 206 207 #[cfg(target_arch = "aarch64")] 208 impl From<mshv_bindings::MshvRegList> for crate::RegList { 209 fn from(s: mshv_bindings::MshvRegList) -> Self { 210 crate::RegList::Mshv(s) 211 } 212 } 213 214 #[cfg(target_arch = "aarch64")] 215 impl From<crate::RegList> for mshv_bindings::MshvRegList { 216 fn from(e: crate::RegList) -> Self { 217 match e { 218 crate::RegList::Mshv(e) => e, 219 /* Needed in case other hypervisors are enabled */ 220 #[allow(unreachable_patterns)] 221 _ => panic!("RegList is not valid"), 222 } 223 } 224 } 225 226 #[cfg(target_arch = "aarch64")] 227 impl From<mshv_bindings::MshvVcpuInit> for crate::VcpuInit { 228 fn from(s: mshv_bindings::MshvVcpuInit) -> Self { 229 crate::VcpuInit::Mshv(s) 230 } 231 } 232 233 #[cfg(target_arch = "aarch64")] 234 impl From<crate::VcpuInit> for mshv_bindings::MshvVcpuInit { 235 fn from(e: crate::VcpuInit) -> Self { 236 match e { 237 crate::VcpuInit::Mshv(e) => e, 238 /* Needed in case other hypervisors are enabled */ 239 #[allow(unreachable_patterns)] 240 _ => panic!("VcpuInit is not valid"), 241 } 242 } 243 } 244 245 struct MshvDirtyLogSlot { 246 guest_pfn: u64, 247 memory_size: u64, 248 } 249 250 /// Wrapper over mshv system ioctls. 251 pub struct MshvHypervisor { 252 mshv: Mshv, 253 } 254 255 impl MshvHypervisor { 256 #[cfg(target_arch = "x86_64")] 257 /// 258 /// Retrieve the list of MSRs supported by MSHV. 259 /// 260 fn get_msr_list(&self) -> hypervisor::Result<MsrList> { 261 self.mshv 262 .get_msr_index_list() 263 .map_err(|e| hypervisor::HypervisorError::GetMsrList(e.into())) 264 } 265 266 fn create_vm_with_type_and_memory_int( 267 &self, 268 vm_type: u64, 269 #[cfg(feature = "sev_snp")] _mem_size: Option<u64>, 270 ) -> hypervisor::Result<Arc<dyn crate::Vm>> { 271 let mshv_vm_type: VmType = match VmType::try_from(vm_type) { 272 Ok(vm_type) => vm_type, 273 Err(_) => return Err(hypervisor::HypervisorError::UnsupportedVmType()), 274 }; 275 let fd: VmFd; 276 loop { 277 match self.mshv.create_vm_with_type(mshv_vm_type) { 278 Ok(res) => fd = res, 279 Err(e) => { 280 if e.errno() == libc::EINTR { 281 // If the error returned is EINTR, which means the 282 // ioctl has been interrupted, we have to retry as 283 // this can't be considered as a regular error. 284 continue; 285 } else { 286 return Err(hypervisor::HypervisorError::VmCreate(e.into())); 287 } 288 } 289 } 290 break; 291 } 292 293 // Set additional partition property for SEV-SNP partition. 294 #[cfg(target_arch = "x86_64")] 295 if mshv_vm_type == VmType::Snp { 296 let snp_policy = snp::get_default_snp_guest_policy(); 297 let vmgexit_offloads = snp::get_default_vmgexit_offload_features(); 298 // SAFETY: access union fields 299 unsafe { 300 debug!( 301 "Setting the partition isolation policy as: 0x{:x}", 302 snp_policy.as_uint64 303 ); 304 fd.set_partition_property( 305 hv_partition_property_code_HV_PARTITION_PROPERTY_ISOLATION_POLICY, 306 snp_policy.as_uint64, 307 ) 308 .map_err(|e| hypervisor::HypervisorError::SetPartitionProperty(e.into()))?; 309 debug!( 310 "Setting the partition property to enable VMGEXIT offloads as : 0x{:x}", 311 vmgexit_offloads.as_uint64 312 ); 313 fd.set_partition_property( 314 hv_partition_property_code_HV_PARTITION_PROPERTY_SEV_VMGEXIT_OFFLOADS, 315 vmgexit_offloads.as_uint64, 316 ) 317 .map_err(|e| hypervisor::HypervisorError::SetPartitionProperty(e.into()))?; 318 } 319 } 320 321 // Default Microsoft Hypervisor behavior for unimplemented MSR is to 322 // send a fault to the guest if it tries to access it. It is possible 323 // to override this behavior with a more suitable option i.e., ignore 324 // writes from the guest and return zero in attempt to read unimplemented 325 // MSR. 326 #[cfg(target_arch = "x86_64")] 327 fd.set_partition_property( 328 hv_partition_property_code_HV_PARTITION_PROPERTY_UNIMPLEMENTED_MSR_ACTION, 329 hv_unimplemented_msr_action_HV_UNIMPLEMENTED_MSR_ACTION_IGNORE_WRITE_READ_ZERO as u64, 330 ) 331 .map_err(|e| hypervisor::HypervisorError::SetPartitionProperty(e.into()))?; 332 333 // Always create a frozen partition 334 fd.set_partition_property( 335 hv_partition_property_code_HV_PARTITION_PROPERTY_TIME_FREEZE, 336 1u64, 337 ) 338 .map_err(|e| hypervisor::HypervisorError::SetPartitionProperty(e.into()))?; 339 340 let vm_fd = Arc::new(fd); 341 342 #[cfg(target_arch = "x86_64")] 343 { 344 let msr_list = self.get_msr_list()?; 345 let num_msrs = msr_list.as_fam_struct_ref().nmsrs as usize; 346 let mut msrs: Vec<MsrEntry> = vec![ 347 MsrEntry { 348 ..Default::default() 349 }; 350 num_msrs 351 ]; 352 let indices = msr_list.as_slice(); 353 for (pos, index) in indices.iter().enumerate() { 354 msrs[pos].index = *index; 355 } 356 357 Ok(Arc::new(MshvVm { 358 fd: vm_fd, 359 msrs, 360 dirty_log_slots: Arc::new(RwLock::new(HashMap::new())), 361 #[cfg(feature = "sev_snp")] 362 sev_snp_enabled: mshv_vm_type == VmType::Snp, 363 #[cfg(feature = "sev_snp")] 364 host_access_pages: ArcSwap::new( 365 AtomicBitmap::new( 366 _mem_size.unwrap_or_default() as usize, 367 NonZeroUsize::new(HV_PAGE_SIZE).unwrap(), 368 ) 369 .into(), 370 ), 371 })) 372 } 373 374 #[cfg(target_arch = "aarch64")] 375 { 376 Ok(Arc::new(MshvVm { 377 fd: vm_fd, 378 dirty_log_slots: Arc::new(RwLock::new(HashMap::new())), 379 })) 380 } 381 } 382 } 383 384 impl MshvHypervisor { 385 /// Create a hypervisor based on Mshv 386 #[allow(clippy::new_ret_no_self)] 387 pub fn new() -> hypervisor::Result<Arc<dyn hypervisor::Hypervisor>> { 388 let mshv_obj = 389 Mshv::new().map_err(|e| hypervisor::HypervisorError::HypervisorCreate(e.into()))?; 390 Ok(Arc::new(MshvHypervisor { mshv: mshv_obj })) 391 } 392 /// Check if the hypervisor is available 393 pub fn is_available() -> hypervisor::Result<bool> { 394 match std::fs::metadata("/dev/mshv") { 395 Ok(_) => Ok(true), 396 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), 397 Err(err) => Err(hypervisor::HypervisorError::HypervisorAvailableCheck( 398 err.into(), 399 )), 400 } 401 } 402 } 403 404 /// Implementation of Hypervisor trait for Mshv 405 /// 406 /// # Examples 407 /// 408 /// ``` 409 /// use hypervisor::mshv::MshvHypervisor; 410 /// use std::sync::Arc; 411 /// let mshv = MshvHypervisor::new().unwrap(); 412 /// let hypervisor = Arc::new(mshv); 413 /// let vm = hypervisor.create_vm().expect("new VM fd creation failed"); 414 /// ``` 415 impl hypervisor::Hypervisor for MshvHypervisor { 416 /// 417 /// Returns the type of the hypervisor 418 /// 419 fn hypervisor_type(&self) -> HypervisorType { 420 HypervisorType::Mshv 421 } 422 423 /// 424 /// Create a Vm of a specific type using the underlying hypervisor, passing memory size 425 /// Return a hypervisor-agnostic Vm trait object 426 /// 427 /// # Examples 428 /// 429 /// ``` 430 /// use hypervisor::kvm::KvmHypervisor; 431 /// use hypervisor::kvm::KvmVm; 432 /// let hypervisor = KvmHypervisor::new().unwrap(); 433 /// let vm = hypervisor.create_vm_with_type(0, 512*1024*1024).unwrap(); 434 /// ``` 435 fn create_vm_with_type_and_memory( 436 &self, 437 vm_type: u64, 438 #[cfg(feature = "sev_snp")] _mem_size: u64, 439 ) -> hypervisor::Result<Arc<dyn vm::Vm>> { 440 self.create_vm_with_type_and_memory_int( 441 vm_type, 442 #[cfg(feature = "sev_snp")] 443 Some(_mem_size), 444 ) 445 } 446 447 fn create_vm_with_type(&self, vm_type: u64) -> hypervisor::Result<Arc<dyn crate::Vm>> { 448 self.create_vm_with_type_and_memory_int( 449 vm_type, 450 #[cfg(feature = "sev_snp")] 451 None, 452 ) 453 } 454 455 /// Create a mshv vm object and return the object as Vm trait object 456 /// 457 /// # Examples 458 /// 459 /// ``` 460 /// # extern crate hypervisor; 461 /// use hypervisor::mshv::MshvHypervisor; 462 /// use hypervisor::mshv::MshvVm; 463 /// let hypervisor = MshvHypervisor::new().unwrap(); 464 /// let vm = hypervisor.create_vm().unwrap(); 465 /// ``` 466 fn create_vm(&self) -> hypervisor::Result<Arc<dyn vm::Vm>> { 467 let vm_type = 0; 468 self.create_vm_with_type(vm_type) 469 } 470 #[cfg(target_arch = "x86_64")] 471 /// 472 /// Get the supported CpuID 473 /// 474 fn get_supported_cpuid(&self) -> hypervisor::Result<Vec<CpuIdEntry>> { 475 let mut cpuid = Vec::new(); 476 let functions: [u32; 2] = [0x1, 0xb]; 477 478 for function in functions { 479 cpuid.push(CpuIdEntry { 480 function, 481 ..Default::default() 482 }); 483 } 484 Ok(cpuid) 485 } 486 487 /// Get maximum number of vCPUs 488 fn get_max_vcpus(&self) -> u32 { 489 // TODO: Using HV_MAXIMUM_PROCESSORS would be better 490 // but the ioctl API is limited to u8 491 256 492 } 493 494 fn get_guest_debug_hw_bps(&self) -> usize { 495 0 496 } 497 498 #[cfg(target_arch = "aarch64")] 499 /// 500 /// Retrieve AArch64 host maximum IPA size supported by MSHV. 501 /// 502 fn get_host_ipa_limit(&self) -> i32 { 503 let host_ipa = self.mshv.get_host_partition_property( 504 hv_partition_property_code_HV_PARTITION_PROPERTY_PHYSICAL_ADDRESS_WIDTH as u64, 505 ); 506 507 match host_ipa { 508 Ok(ipa) => ipa, 509 Err(e) => { 510 panic!("Failed to get host IPA limit: {:?}", e); 511 } 512 } 513 } 514 } 515 516 #[cfg(feature = "sev_snp")] 517 struct Ghcb(*mut svm_ghcb_base); 518 519 #[cfg(feature = "sev_snp")] 520 // SAFETY: struct is based on GHCB page in the hypervisor, 521 // safe to Send across threads 522 unsafe impl Send for Ghcb {} 523 524 #[cfg(feature = "sev_snp")] 525 // SAFETY: struct is based on GHCB page in the hypervisor, 526 // safe to Sync across threads as this is only required for Vcpu trait 527 // functionally not used anyway 528 unsafe impl Sync for Ghcb {} 529 530 /// Vcpu struct for Microsoft Hypervisor 531 pub struct MshvVcpu { 532 fd: VcpuFd, 533 vp_index: u8, 534 #[cfg(target_arch = "x86_64")] 535 cpuid: Vec<CpuIdEntry>, 536 #[cfg(target_arch = "x86_64")] 537 msrs: Vec<MsrEntry>, 538 vm_ops: Option<Arc<dyn vm::VmOps>>, 539 vm_fd: Arc<VmFd>, 540 #[cfg(feature = "sev_snp")] 541 ghcb: Option<Ghcb>, 542 #[cfg(feature = "sev_snp")] 543 host_access_pages: ArcSwap<AtomicBitmap>, 544 } 545 546 /// Implementation of Vcpu trait for Microsoft Hypervisor 547 /// 548 /// # Examples 549 /// 550 /// ``` 551 /// use hypervisor::mshv::MshvHypervisor; 552 /// use std::sync::Arc; 553 /// let mshv = MshvHypervisor::new().unwrap(); 554 /// let hypervisor = Arc::new(mshv); 555 /// let vm = hypervisor.create_vm().expect("new VM fd creation failed"); 556 /// let vcpu = vm.create_vcpu(0, None).unwrap(); 557 /// ``` 558 impl cpu::Vcpu for MshvVcpu { 559 /// 560 /// Returns StandardRegisters with default value set 561 /// 562 fn create_standard_regs(&self) -> crate::StandardRegisters { 563 mshv_bindings::StandardRegisters::default().into() 564 } 565 /// 566 /// Returns the vCPU general purpose registers. 567 /// 568 fn get_regs(&self) -> cpu::Result<crate::StandardRegisters> { 569 Ok(self 570 .fd 571 .get_regs() 572 .map_err(|e| cpu::HypervisorCpuError::GetStandardRegs(e.into()))? 573 .into()) 574 } 575 576 /// 577 /// Sets the vCPU general purpose registers. 578 /// 579 fn set_regs(&self, regs: &crate::StandardRegisters) -> cpu::Result<()> { 580 let regs = (*regs).into(); 581 self.fd 582 .set_regs(®s) 583 .map_err(|e| cpu::HypervisorCpuError::SetStandardRegs(e.into())) 584 } 585 586 #[cfg(target_arch = "x86_64")] 587 /// 588 /// Returns the vCPU special registers. 589 /// 590 fn get_sregs(&self) -> cpu::Result<crate::arch::x86::SpecialRegisters> { 591 Ok(self 592 .fd 593 .get_sregs() 594 .map_err(|e| cpu::HypervisorCpuError::GetSpecialRegs(e.into()))? 595 .into()) 596 } 597 598 #[cfg(target_arch = "x86_64")] 599 /// 600 /// Sets the vCPU special registers. 601 /// 602 fn set_sregs(&self, sregs: &crate::arch::x86::SpecialRegisters) -> cpu::Result<()> { 603 let sregs = (*sregs).into(); 604 self.fd 605 .set_sregs(&sregs) 606 .map_err(|e| cpu::HypervisorCpuError::SetSpecialRegs(e.into())) 607 } 608 609 #[cfg(target_arch = "x86_64")] 610 /// 611 /// Returns the floating point state (FPU) from the vCPU. 612 /// 613 fn get_fpu(&self) -> cpu::Result<FpuState> { 614 Ok(self 615 .fd 616 .get_fpu() 617 .map_err(|e| cpu::HypervisorCpuError::GetFloatingPointRegs(e.into()))? 618 .into()) 619 } 620 621 #[cfg(target_arch = "x86_64")] 622 /// 623 /// Set the floating point state (FPU) of a vCPU. 624 /// 625 fn set_fpu(&self, fpu: &FpuState) -> cpu::Result<()> { 626 let fpu: mshv_bindings::FloatingPointUnit = (*fpu).clone().into(); 627 self.fd 628 .set_fpu(&fpu) 629 .map_err(|e| cpu::HypervisorCpuError::SetFloatingPointRegs(e.into())) 630 } 631 632 #[cfg(target_arch = "x86_64")] 633 /// 634 /// Returns the model-specific registers (MSR) for this vCPU. 635 /// 636 fn get_msrs(&self, msrs: &mut Vec<MsrEntry>) -> cpu::Result<usize> { 637 let mshv_msrs: Vec<msr_entry> = msrs.iter().map(|e| (*e).into()).collect(); 638 let mut mshv_msrs = MsrEntries::from_entries(&mshv_msrs).unwrap(); 639 let succ = self 640 .fd 641 .get_msrs(&mut mshv_msrs) 642 .map_err(|e| cpu::HypervisorCpuError::GetMsrEntries(e.into()))?; 643 644 msrs[..succ].copy_from_slice( 645 &mshv_msrs.as_slice()[..succ] 646 .iter() 647 .map(|e| (*e).into()) 648 .collect::<Vec<MsrEntry>>(), 649 ); 650 651 Ok(succ) 652 } 653 654 #[cfg(target_arch = "x86_64")] 655 /// 656 /// Setup the model-specific registers (MSR) for this vCPU. 657 /// Returns the number of MSR entries actually written. 658 /// 659 fn set_msrs(&self, msrs: &[MsrEntry]) -> cpu::Result<usize> { 660 let mshv_msrs: Vec<msr_entry> = msrs.iter().map(|e| (*e).into()).collect(); 661 let mshv_msrs = MsrEntries::from_entries(&mshv_msrs).unwrap(); 662 self.fd 663 .set_msrs(&mshv_msrs) 664 .map_err(|e| cpu::HypervisorCpuError::SetMsrEntries(e.into())) 665 } 666 667 #[cfg(target_arch = "x86_64")] 668 /// 669 /// X86 specific call to enable HyperV SynIC 670 /// 671 fn enable_hyperv_synic(&self) -> cpu::Result<()> { 672 /* We always have SynIC enabled on MSHV */ 673 Ok(()) 674 } 675 676 #[allow(non_upper_case_globals)] 677 fn run(&self) -> std::result::Result<cpu::VmExit, cpu::HypervisorCpuError> { 678 match self.fd.run() { 679 Ok(x) => match x.header.message_type { 680 hv_message_type_HVMSG_X64_HALT => { 681 debug!("HALT"); 682 Ok(cpu::VmExit::Reset) 683 } 684 hv_message_type_HVMSG_UNRECOVERABLE_EXCEPTION => { 685 warn!("TRIPLE FAULT"); 686 Ok(cpu::VmExit::Shutdown) 687 } 688 #[cfg(target_arch = "x86_64")] 689 hv_message_type_HVMSG_X64_IO_PORT_INTERCEPT => { 690 let info = x.to_ioport_info().unwrap(); 691 let access_info = info.access_info; 692 // SAFETY: access_info is valid, otherwise we won't be here 693 let len = unsafe { access_info.__bindgen_anon_1.access_size() } as usize; 694 let is_write = info.header.intercept_access_type == 1; 695 let port = info.port_number; 696 let mut data: [u8; 4] = [0; 4]; 697 let mut ret_rax = info.rax; 698 699 /* 700 * XXX: Ignore QEMU fw_cfg (0x5xx) and debug console (0x402) ports. 701 * 702 * Cloud Hypervisor doesn't support fw_cfg at the moment. It does support 0x402 703 * under the "fwdebug" feature flag. But that feature is not enabled by default 704 * and is considered legacy. 705 * 706 * OVMF unconditionally pokes these IO ports with string IO. 707 * 708 * Instead of trying to implement string IO support now which does not do much 709 * now, skip those ports explicitly to avoid panicking. 710 * 711 * Proper string IO support can be added once we gain the ability to translate 712 * guest virtual addresses to guest physical addresses on MSHV. 713 */ 714 match port { 715 0x402 | 0x510 | 0x511 | 0x514 => { 716 let insn_len = info.header.instruction_length() as u64; 717 718 /* Advance RIP and update RAX */ 719 let arr_reg_name_value = [ 720 ( 721 hv_register_name_HV_X64_REGISTER_RIP, 722 info.header.rip + insn_len, 723 ), 724 (hv_register_name_HV_X64_REGISTER_RAX, ret_rax), 725 ]; 726 set_registers_64!(self.fd, arr_reg_name_value) 727 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 728 return Ok(cpu::VmExit::Ignore); 729 } 730 _ => {} 731 } 732 733 assert!( 734 // SAFETY: access_info is valid, otherwise we won't be here 735 (unsafe { access_info.__bindgen_anon_1.string_op() } != 1), 736 "String IN/OUT not supported" 737 ); 738 assert!( 739 // SAFETY: access_info is valid, otherwise we won't be here 740 (unsafe { access_info.__bindgen_anon_1.rep_prefix() } != 1), 741 "Rep IN/OUT not supported" 742 ); 743 744 if is_write { 745 let data = (info.rax as u32).to_le_bytes(); 746 if let Some(vm_ops) = &self.vm_ops { 747 vm_ops 748 .pio_write(port.into(), &data[0..len]) 749 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 750 } 751 } else { 752 if let Some(vm_ops) = &self.vm_ops { 753 vm_ops 754 .pio_read(port.into(), &mut data[0..len]) 755 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 756 } 757 758 let v = u32::from_le_bytes(data); 759 /* Preserve high bits in EAX but clear out high bits in RAX */ 760 let mask = 0xffffffff >> (32 - len * 8); 761 let eax = (info.rax as u32 & !mask) | (v & mask); 762 ret_rax = eax as u64; 763 } 764 765 let insn_len = info.header.instruction_length() as u64; 766 767 /* Advance RIP and update RAX */ 768 let arr_reg_name_value = [ 769 ( 770 hv_register_name_HV_X64_REGISTER_RIP, 771 info.header.rip + insn_len, 772 ), 773 (hv_register_name_HV_X64_REGISTER_RAX, ret_rax), 774 ]; 775 set_registers_64!(self.fd, arr_reg_name_value) 776 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 777 Ok(cpu::VmExit::Ignore) 778 } 779 #[cfg(target_arch = "x86_64")] 780 msg_type @ (hv_message_type_HVMSG_UNMAPPED_GPA 781 | hv_message_type_HVMSG_GPA_INTERCEPT) => { 782 let info = x.to_memory_info().unwrap(); 783 let insn_len = info.instruction_byte_count as usize; 784 let gva = info.guest_virtual_address; 785 let gpa = info.guest_physical_address; 786 787 debug!("Exit ({:?}) GVA {:x} GPA {:x}", msg_type, gva, gpa); 788 789 let mut context = MshvEmulatorContext { 790 vcpu: self, 791 map: (gva, gpa), 792 }; 793 794 // Create a new emulator. 795 let mut emul = Emulator::new(&mut context); 796 797 // Emulate the trapped instruction, and only the first one. 798 let new_state = emul 799 .emulate_first_insn( 800 self.vp_index as usize, 801 &info.instruction_bytes[..insn_len], 802 ) 803 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 804 805 // Set CPU state back. 806 context 807 .set_cpu_state(self.vp_index as usize, new_state) 808 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 809 810 Ok(cpu::VmExit::Ignore) 811 } 812 #[cfg(feature = "sev_snp")] 813 hv_message_type_HVMSG_GPA_ATTRIBUTE_INTERCEPT => { 814 let info = x.to_gpa_attribute_info().unwrap(); 815 let host_vis = info.__bindgen_anon_1.host_visibility(); 816 if host_vis >= HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE { 817 warn!("Ignored attribute intercept with full host visibility"); 818 return Ok(cpu::VmExit::Ignore); 819 } 820 821 let num_ranges = info.__bindgen_anon_1.range_count(); 822 assert!(num_ranges >= 1); 823 if num_ranges > 1 { 824 return Err(cpu::HypervisorCpuError::RunVcpu(anyhow!( 825 "Unhandled VCPU exit(GPA_ATTRIBUTE_INTERCEPT): Expected num_ranges to be 1 but found num_ranges {:?}", 826 num_ranges 827 ))); 828 } 829 830 // TODO: we could also deny the request with HvCallCompleteIntercept 831 let mut gpas = Vec::new(); 832 let ranges = info.ranges; 833 let (gfn_start, gfn_count) = snp::parse_gpa_range(ranges[0]).unwrap(); 834 debug!( 835 "Releasing pages: gfn_start: {:x?}, gfn_count: {:?}", 836 gfn_start, gfn_count 837 ); 838 let gpa_start = gfn_start * HV_PAGE_SIZE as u64; 839 for i in 0..gfn_count { 840 gpas.push(gpa_start + i * HV_PAGE_SIZE as u64); 841 } 842 843 let mut gpa_list = 844 vec_with_array_field::<mshv_modify_gpa_host_access, u64>(gpas.len()); 845 gpa_list[0].page_count = gpas.len() as u64; 846 gpa_list[0].flags = 0; 847 if host_vis & HV_MAP_GPA_READABLE != 0 { 848 gpa_list[0].flags |= 1 << MSHV_GPA_HOST_ACCESS_BIT_READABLE; 849 } 850 if host_vis & HV_MAP_GPA_WRITABLE != 0 { 851 gpa_list[0].flags |= 1 << MSHV_GPA_HOST_ACCESS_BIT_WRITABLE; 852 } 853 854 // SAFETY: gpa_list initialized with gpas.len() and now it is being turned into 855 // gpas_slice with gpas.len() again. It is guaranteed to be large enough to hold 856 // everything from gpas. 857 unsafe { 858 let gpas_slice: &mut [u64] = 859 gpa_list[0].guest_pfns.as_mut_slice(gpas.len()); 860 gpas_slice.copy_from_slice(gpas.as_slice()); 861 } 862 863 self.vm_fd 864 .modify_gpa_host_access(&gpa_list[0]) 865 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(anyhow!( 866 "Unhandled VCPU exit: attribute intercept - couldn't modify host access {}", e 867 )))?; 868 // Guest is revoking the shared access, so we need to update the bitmap 869 self.host_access_pages.rcu(|_bitmap| { 870 let bm = self.host_access_pages.load().as_ref().clone(); 871 bm.reset_addr_range(gpa_start as usize, gfn_count as usize); 872 bm 873 }); 874 Ok(cpu::VmExit::Ignore) 875 } 876 #[cfg(target_arch = "x86_64")] 877 hv_message_type_HVMSG_UNACCEPTED_GPA => { 878 let info = x.to_memory_info().unwrap(); 879 let gva = info.guest_virtual_address; 880 let gpa = info.guest_physical_address; 881 882 Err(cpu::HypervisorCpuError::RunVcpu(anyhow!( 883 "Unhandled VCPU exit: Unaccepted GPA({:x}) found at GVA({:x})", 884 gpa, 885 gva, 886 ))) 887 } 888 #[cfg(target_arch = "x86_64")] 889 hv_message_type_HVMSG_X64_CPUID_INTERCEPT => { 890 let info = x.to_cpuid_info().unwrap(); 891 debug!("cpuid eax: {:x}", { info.rax }); 892 Ok(cpu::VmExit::Ignore) 893 } 894 #[cfg(target_arch = "x86_64")] 895 hv_message_type_HVMSG_X64_MSR_INTERCEPT => { 896 let info = x.to_msr_info().unwrap(); 897 if info.header.intercept_access_type == 0 { 898 debug!("msr read: {:x}", { info.msr_number }); 899 } else { 900 debug!("msr write: {:x}", { info.msr_number }); 901 } 902 Ok(cpu::VmExit::Ignore) 903 } 904 #[cfg(target_arch = "x86_64")] 905 hv_message_type_HVMSG_X64_EXCEPTION_INTERCEPT => { 906 //TODO: Handler for VMCALL here. 907 let info = x.to_exception_info().unwrap(); 908 debug!("Exception Info {:?}", { info.exception_vector }); 909 Ok(cpu::VmExit::Ignore) 910 } 911 #[cfg(target_arch = "x86_64")] 912 hv_message_type_HVMSG_X64_APIC_EOI => { 913 let info = x.to_apic_eoi_info().unwrap(); 914 // The kernel should dispatch the EOI to the correct thread. 915 // Check the VP index is the same as the one we have. 916 assert!(info.vp_index == self.vp_index as u32); 917 // The interrupt vector in info is u32, but x86 only supports 256 vectors. 918 // There is no good way to recover from this if the hypervisor messes around. 919 // Just unwrap. 920 Ok(cpu::VmExit::IoapicEoi( 921 info.interrupt_vector.try_into().unwrap(), 922 )) 923 } 924 #[cfg(feature = "sev_snp")] 925 hv_message_type_HVMSG_X64_SEV_VMGEXIT_INTERCEPT => { 926 let info = x.to_vmg_intercept_info().unwrap(); 927 let ghcb_data = info.ghcb_msr >> GHCB_INFO_BIT_WIDTH; 928 let ghcb_msr = svm_ghcb_msr { 929 as_uint64: info.ghcb_msr, 930 }; 931 // Safe to use unwrap, for sev_snp guest we already have the 932 // GHCB pointer wrapped in the option, otherwise this place is not reached. 933 let ghcb = self.ghcb.as_ref().unwrap().0; 934 935 // SAFETY: Accessing a union element from bindgen generated bindings. 936 let ghcb_op = unsafe { ghcb_msr.__bindgen_anon_2.ghcb_info() as u32 }; 937 // Sanity check on the header fields before handling other operations. 938 assert!(info.header.intercept_access_type == HV_INTERCEPT_ACCESS_EXECUTE as u8); 939 940 match ghcb_op { 941 GHCB_INFO_HYP_FEATURE_REQUEST => { 942 // Pre-condition: GHCB data must be zero 943 assert!(ghcb_data == 0); 944 let mut ghcb_response = GHCB_INFO_HYP_FEATURE_RESPONSE as u64; 945 // Indicate support for basic SEV-SNP features 946 ghcb_response |= 947 (GHCB_HYP_FEATURE_SEV_SNP << GHCB_INFO_BIT_WIDTH) as u64; 948 // Indicate support for SEV-SNP AP creation 949 ghcb_response |= (GHCB_HYP_FEATURE_SEV_SNP_AP_CREATION 950 << GHCB_INFO_BIT_WIDTH) 951 as u64; 952 debug!( 953 "GHCB_INFO_HYP_FEATURE_REQUEST: Supported features: {:0x}", 954 ghcb_response 955 ); 956 let arr_reg_name_value = 957 [(hv_register_name_HV_X64_REGISTER_GHCB, ghcb_response)]; 958 set_registers_64!(self.fd, arr_reg_name_value) 959 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 960 } 961 GHCB_INFO_REGISTER_REQUEST => { 962 let mut ghcb_gpa = hv_x64_register_sev_ghcb::default(); 963 964 // Disable the previously used GHCB page. 965 self.disable_prev_ghcb_page()?; 966 967 // SAFETY: Accessing a union element from bindgen generated bindings. 968 unsafe { 969 ghcb_gpa.__bindgen_anon_1.set_enabled(1); 970 ghcb_gpa 971 .__bindgen_anon_1 972 .set_page_number(ghcb_msr.__bindgen_anon_2.gpa_page_number()); 973 } 974 // SAFETY: Accessing a union element from bindgen generated bindings. 975 let reg_name_value = unsafe { 976 [( 977 hv_register_name_HV_X64_REGISTER_SEV_GHCB_GPA, 978 ghcb_gpa.as_uint64, 979 )] 980 }; 981 982 set_registers_64!(self.fd, reg_name_value) 983 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 984 985 let mut resp_ghcb_msr = svm_ghcb_msr::default(); 986 // SAFETY: Accessing a union element from bindgen generated bindings. 987 unsafe { 988 resp_ghcb_msr 989 .__bindgen_anon_2 990 .set_ghcb_info(GHCB_INFO_REGISTER_RESPONSE as u64); 991 resp_ghcb_msr.__bindgen_anon_2.set_gpa_page_number( 992 ghcb_msr.__bindgen_anon_2.gpa_page_number(), 993 ); 994 debug!("GHCB GPA is {:x}", ghcb_gpa.as_uint64); 995 } 996 // SAFETY: Accessing a union element from bindgen generated bindings. 997 let reg_name_value = unsafe { 998 [( 999 hv_register_name_HV_X64_REGISTER_GHCB, 1000 resp_ghcb_msr.as_uint64, 1001 )] 1002 }; 1003 1004 set_registers_64!(self.fd, reg_name_value) 1005 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 1006 } 1007 GHCB_INFO_SEV_INFO_REQUEST => { 1008 let sev_cpuid_function = 0x8000_001F; 1009 let cpu_leaf = self 1010 .fd 1011 .get_cpuid_values(sev_cpuid_function, 0, 0, 0) 1012 .unwrap(); 1013 let ebx = cpu_leaf[1]; 1014 // First 6-byte of EBX represents page table encryption bit number 1015 let pbit_encryption = (ebx & 0x3f) as u8; 1016 let mut ghcb_response = GHCB_INFO_SEV_INFO_RESPONSE as u64; 1017 1018 // GHCBData[63:48] specifies the maximum GHCB protocol version supported 1019 ghcb_response |= (GHCB_PROTOCOL_VERSION_MAX as u64) << 48; 1020 // GHCBData[47:32] specifies the minimum GHCB protocol version supported 1021 ghcb_response |= (GHCB_PROTOCOL_VERSION_MIN as u64) << 32; 1022 // GHCBData[31:24] specifies the SEV page table encryption bit number. 1023 ghcb_response |= (pbit_encryption as u64) << 24; 1024 1025 let arr_reg_name_value = 1026 [(hv_register_name_HV_X64_REGISTER_GHCB, ghcb_response)]; 1027 set_registers_64!(self.fd, arr_reg_name_value) 1028 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 1029 } 1030 GHCB_INFO_NORMAL => { 1031 let exit_code = 1032 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_code as u32; 1033 1034 match exit_code { 1035 SVM_EXITCODE_HV_DOORBELL_PAGE => { 1036 let exit_info1 = 1037 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1 as u32; 1038 match exit_info1 { 1039 SVM_NAE_HV_DOORBELL_PAGE_GET_PREFERRED => { 1040 // Hypervisor does not have any preference for doorbell GPA. 1041 let preferred_doorbell_gpa: u64 = 0xFFFFFFFFFFFFFFFF; 1042 set_svm_field_u64_ptr!( 1043 ghcb, 1044 exit_info2, 1045 preferred_doorbell_gpa 1046 ); 1047 } 1048 SVM_NAE_HV_DOORBELL_PAGE_SET => { 1049 let exit_info2 = info 1050 .__bindgen_anon_2 1051 .__bindgen_anon_1 1052 .sw_exit_info2; 1053 let mut ghcb_doorbell_gpa = 1054 hv_x64_register_sev_hv_doorbell::default(); 1055 // SAFETY: Accessing a union element from bindgen generated bindings. 1056 unsafe { 1057 ghcb_doorbell_gpa.__bindgen_anon_1.set_enabled(1); 1058 ghcb_doorbell_gpa 1059 .__bindgen_anon_1 1060 .set_page_number(exit_info2 >> PAGE_SHIFT); 1061 } 1062 // SAFETY: Accessing a union element from bindgen generated bindings. 1063 let reg_names = unsafe { 1064 [( 1065 hv_register_name_HV_X64_REGISTER_SEV_DOORBELL_GPA, 1066 ghcb_doorbell_gpa.as_uint64, 1067 )] 1068 }; 1069 set_registers_64!(self.fd, reg_names).map_err(|e| { 1070 cpu::HypervisorCpuError::SetRegister(e.into()) 1071 })?; 1072 1073 set_svm_field_u64_ptr!(ghcb, exit_info2, exit_info2); 1074 1075 // Clear the SW_EXIT_INFO1 register to indicate no error 1076 self.clear_swexit_info1()?; 1077 } 1078 SVM_NAE_HV_DOORBELL_PAGE_QUERY => { 1079 let mut reg_assocs = [ hv_register_assoc { 1080 name: hv_register_name_HV_X64_REGISTER_SEV_DOORBELL_GPA, 1081 ..Default::default() 1082 } ]; 1083 self.fd.get_reg(&mut reg_assocs).unwrap(); 1084 // SAFETY: Accessing a union element from bindgen generated bindings. 1085 let doorbell_gpa = unsafe { reg_assocs[0].value.reg64 }; 1086 1087 set_svm_field_u64_ptr!(ghcb, exit_info2, doorbell_gpa); 1088 1089 // Clear the SW_EXIT_INFO1 register to indicate no error 1090 self.clear_swexit_info1()?; 1091 } 1092 SVM_NAE_HV_DOORBELL_PAGE_CLEAR => { 1093 set_svm_field_u64_ptr!(ghcb, exit_info2, 0); 1094 } 1095 _ => { 1096 panic!( 1097 "SVM_EXITCODE_HV_DOORBELL_PAGE: Unhandled exit code: {:0x}", 1098 exit_info1 1099 ); 1100 } 1101 } 1102 } 1103 SVM_EXITCODE_IOIO_PROT => { 1104 let exit_info1 = 1105 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1 as u32; 1106 let port_info = hv_sev_vmgexit_port_info { 1107 as_uint32: exit_info1, 1108 }; 1109 1110 let port = 1111 // SAFETY: Accessing a union element from bindgen generated bindings. 1112 unsafe { port_info.__bindgen_anon_1.intercepted_port() }; 1113 let mut len = 4; 1114 // SAFETY: Accessing a union element from bindgen generated bindings. 1115 unsafe { 1116 if port_info.__bindgen_anon_1.operand_size_16bit() == 1 { 1117 len = 2; 1118 } else if port_info.__bindgen_anon_1.operand_size_8bit() 1119 == 1 1120 { 1121 len = 1; 1122 } 1123 } 1124 let is_write = 1125 // SAFETY: Accessing a union element from bindgen generated bindings. 1126 unsafe { port_info.__bindgen_anon_1.access_type() == 0 }; 1127 // SAFETY: Accessing the field from a mapped address 1128 let mut data = unsafe { (*ghcb).rax.to_le_bytes() }; 1129 1130 if is_write { 1131 if let Some(vm_ops) = &self.vm_ops { 1132 vm_ops.pio_write(port.into(), &data[..len]).map_err( 1133 |e| cpu::HypervisorCpuError::RunVcpu(e.into()), 1134 )?; 1135 } 1136 } else { 1137 if let Some(vm_ops) = &self.vm_ops { 1138 vm_ops 1139 .pio_read(port.into(), &mut data[..len]) 1140 .map_err(|e| { 1141 cpu::HypervisorCpuError::RunVcpu(e.into()) 1142 })?; 1143 } 1144 set_svm_field_u64_ptr!(ghcb, rax, u64::from_le_bytes(data)); 1145 } 1146 1147 // Clear the SW_EXIT_INFO1 register to indicate no error 1148 self.clear_swexit_info1()?; 1149 } 1150 SVM_EXITCODE_MMIO_READ => { 1151 let src_gpa = 1152 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1; 1153 let data_len = 1154 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info2 1155 as usize; 1156 // Sanity check to make sure data len is within supported range. 1157 assert!(data_len <= 0x8); 1158 1159 let mut data: Vec<u8> = vec![0; data_len]; 1160 if let Some(vm_ops) = &self.vm_ops { 1161 vm_ops.mmio_read(src_gpa, &mut data).map_err(|e| { 1162 cpu::HypervisorCpuError::RunVcpu(e.into()) 1163 })?; 1164 } 1165 // Copy the data to the shared buffer of the GHCB page 1166 let mut buffer_data = [0; 8]; 1167 buffer_data[..data_len].copy_from_slice(&data[..data_len]); 1168 // SAFETY: Updating the value of mapped area 1169 unsafe { (*ghcb).shared[0] = u64::from_le_bytes(buffer_data) }; 1170 1171 // Clear the SW_EXIT_INFO1 register to indicate no error 1172 self.clear_swexit_info1()?; 1173 } 1174 SVM_EXITCODE_MMIO_WRITE => { 1175 let dst_gpa = 1176 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1; 1177 let data_len = 1178 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info2 1179 as usize; 1180 // Sanity check to make sure data len is within supported range. 1181 assert!(data_len <= 0x8); 1182 1183 let mut data = vec![0; data_len]; 1184 // SAFETY: Accessing data from a mapped address 1185 let bytes_shared_ghcb = 1186 unsafe { (*ghcb).shared[0].to_le_bytes() }; 1187 data.copy_from_slice(&bytes_shared_ghcb[..data_len]); 1188 1189 if let Some(vm_ops) = &self.vm_ops { 1190 vm_ops.mmio_write(dst_gpa, &data).map_err(|e| { 1191 cpu::HypervisorCpuError::RunVcpu(e.into()) 1192 })?; 1193 } 1194 1195 // Clear the SW_EXIT_INFO1 register to indicate no error 1196 self.clear_swexit_info1()?; 1197 } 1198 SVM_EXITCODE_SNP_GUEST_REQUEST 1199 | SVM_EXITCODE_SNP_EXTENDED_GUEST_REQUEST => { 1200 if exit_code == SVM_EXITCODE_SNP_EXTENDED_GUEST_REQUEST { 1201 info!("Fetching extended guest request is not supported"); 1202 // We don't support extended guest request, so we just write empty data. 1203 // This matches the behavior of KVM in Linux 6.11. 1204 1205 // Read RBX from the GHCB. 1206 // SAFETY: Accessing data from a mapped address 1207 let data_gpa = unsafe { (*ghcb).rax }; 1208 // SAFETY: Accessing data from a mapped address 1209 let data_npages = unsafe { (*ghcb).rbx }; 1210 1211 if data_npages > 0 { 1212 // The certificates are terminated by 24 zero bytes. 1213 // TODO: Need to check if data_gpa is the address of the shared buffer in the GHCB page 1214 // in that case we should clear the shared buffer(24 bytes) 1215 self.gpa_write(data_gpa, &[0; 24])?; 1216 } 1217 } 1218 1219 let req_gpa = 1220 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1; 1221 let rsp_gpa = 1222 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info2; 1223 1224 let mshv_psp_req = 1225 mshv_issue_psp_guest_request { req_gpa, rsp_gpa }; 1226 self.vm_fd 1227 .psp_issue_guest_request(&mshv_psp_req) 1228 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 1229 1230 debug!( 1231 "SNP guest request: req_gpa {:0x} rsp_gpa {:0x}", 1232 req_gpa, rsp_gpa 1233 ); 1234 1235 set_svm_field_u64_ptr!(ghcb, exit_info2, 0); 1236 } 1237 SVM_EXITCODE_SNP_AP_CREATION => { 1238 let vmsa_gpa = 1239 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info2; 1240 let apic_id = 1241 info.__bindgen_anon_2.__bindgen_anon_1.sw_exit_info1 >> 32; 1242 debug!( 1243 "SNP AP CREATE REQUEST with VMSA GPA {:0x}, and APIC ID {:?}", 1244 vmsa_gpa, apic_id 1245 ); 1246 1247 let mshv_ap_create_req = mshv_sev_snp_ap_create { 1248 vp_id: apic_id, 1249 vmsa_gpa, 1250 }; 1251 self.vm_fd 1252 .sev_snp_ap_create(&mshv_ap_create_req) 1253 .map_err(|e| cpu::HypervisorCpuError::RunVcpu(e.into()))?; 1254 1255 // Clear the SW_EXIT_INFO1 register to indicate no error 1256 self.clear_swexit_info1()?; 1257 } 1258 _ => panic!( 1259 "GHCB_INFO_NORMAL: Unhandled exit code: {:0x}", 1260 exit_code 1261 ), 1262 } 1263 } 1264 _ => panic!("Unsupported VMGEXIT operation: {:0x}", ghcb_op), 1265 } 1266 1267 Ok(cpu::VmExit::Ignore) 1268 } 1269 exit => Err(cpu::HypervisorCpuError::RunVcpu(anyhow!( 1270 "Unhandled VCPU exit {:?}", 1271 exit 1272 ))), 1273 }, 1274 1275 Err(e) => match e.errno() { 1276 libc::EAGAIN | libc::EINTR => Ok(cpu::VmExit::Ignore), 1277 _ => Err(cpu::HypervisorCpuError::RunVcpu(anyhow!( 1278 "VCPU error {:?}", 1279 e 1280 ))), 1281 }, 1282 } 1283 } 1284 1285 #[cfg(target_arch = "aarch64")] 1286 fn init_pmu(&self, irq: u32) -> cpu::Result<()> { 1287 unimplemented!() 1288 } 1289 1290 #[cfg(target_arch = "aarch64")] 1291 fn has_pmu_support(&self) -> bool { 1292 unimplemented!() 1293 } 1294 1295 #[cfg(target_arch = "aarch64")] 1296 fn setup_regs(&self, cpu_id: u8, boot_ip: u64, fdt_start: u64) -> cpu::Result<()> { 1297 unimplemented!() 1298 } 1299 1300 #[cfg(target_arch = "aarch64")] 1301 fn get_sys_reg(&self, sys_reg: u32) -> cpu::Result<u64> { 1302 unimplemented!() 1303 } 1304 1305 #[cfg(target_arch = "aarch64")] 1306 fn get_reg_list(&self, _reg_list: &mut crate::RegList) -> cpu::Result<()> { 1307 unimplemented!() 1308 } 1309 1310 #[cfg(target_arch = "aarch64")] 1311 fn vcpu_init(&self, _kvi: &crate::VcpuInit) -> cpu::Result<()> { 1312 unimplemented!() 1313 } 1314 1315 #[cfg(target_arch = "aarch64")] 1316 fn vcpu_finalize(&self, _feature: i32) -> cpu::Result<()> { 1317 unimplemented!() 1318 } 1319 1320 #[cfg(target_arch = "aarch64")] 1321 fn vcpu_get_finalized_features(&self) -> i32 { 1322 unimplemented!() 1323 } 1324 1325 #[cfg(target_arch = "aarch64")] 1326 fn vcpu_set_processor_features( 1327 &self, 1328 _vm: &Arc<dyn crate::Vm>, 1329 _kvi: &mut crate::VcpuInit, 1330 _id: u8, 1331 ) -> cpu::Result<()> { 1332 unimplemented!() 1333 } 1334 1335 #[cfg(target_arch = "aarch64")] 1336 fn create_vcpu_init(&self) -> crate::VcpuInit { 1337 unimplemented!(); 1338 } 1339 1340 #[cfg(target_arch = "x86_64")] 1341 /// 1342 /// X86 specific call to setup the CPUID registers. 1343 /// 1344 fn set_cpuid2(&self, cpuid: &[CpuIdEntry]) -> cpu::Result<()> { 1345 let cpuid: Vec<mshv_bindings::hv_cpuid_entry> = cpuid.iter().map(|e| (*e).into()).collect(); 1346 let mshv_cpuid = <CpuId>::from_entries(&cpuid) 1347 .map_err(|_| cpu::HypervisorCpuError::SetCpuid(anyhow!("failed to create CpuId")))?; 1348 1349 self.fd 1350 .register_intercept_result_cpuid(&mshv_cpuid) 1351 .map_err(|e| cpu::HypervisorCpuError::SetCpuid(e.into())) 1352 } 1353 1354 #[cfg(target_arch = "x86_64")] 1355 /// 1356 /// X86 specific call to retrieve the CPUID registers. 1357 /// 1358 fn get_cpuid2(&self, _num_entries: usize) -> cpu::Result<Vec<CpuIdEntry>> { 1359 Ok(self.cpuid.clone()) 1360 } 1361 1362 #[cfg(target_arch = "x86_64")] 1363 /// 1364 /// X86 specific call to retrieve cpuid leaf 1365 /// 1366 fn get_cpuid_values( 1367 &self, 1368 function: u32, 1369 index: u32, 1370 xfem: u64, 1371 xss: u64, 1372 ) -> cpu::Result<[u32; 4]> { 1373 self.fd 1374 .get_cpuid_values(function, index, xfem, xss) 1375 .map_err(|e| cpu::HypervisorCpuError::GetCpuidVales(e.into())) 1376 } 1377 1378 #[cfg(target_arch = "x86_64")] 1379 /// 1380 /// Returns the state of the LAPIC (Local Advanced Programmable Interrupt Controller). 1381 /// 1382 fn get_lapic(&self) -> cpu::Result<crate::arch::x86::LapicState> { 1383 Ok(self 1384 .fd 1385 .get_lapic() 1386 .map_err(|e| cpu::HypervisorCpuError::GetlapicState(e.into()))? 1387 .into()) 1388 } 1389 1390 #[cfg(target_arch = "x86_64")] 1391 /// 1392 /// Sets the state of the LAPIC (Local Advanced Programmable Interrupt Controller). 1393 /// 1394 fn set_lapic(&self, lapic: &crate::arch::x86::LapicState) -> cpu::Result<()> { 1395 let lapic: mshv_bindings::LapicState = (*lapic).clone().into(); 1396 self.fd 1397 .set_lapic(&lapic) 1398 .map_err(|e| cpu::HypervisorCpuError::SetLapicState(e.into())) 1399 } 1400 1401 /// 1402 /// Returns the vcpu's current "multiprocessing state". 1403 /// 1404 fn get_mp_state(&self) -> cpu::Result<MpState> { 1405 Ok(MpState::Mshv) 1406 } 1407 1408 /// 1409 /// Sets the vcpu's current "multiprocessing state". 1410 /// 1411 fn set_mp_state(&self, _mp_state: MpState) -> cpu::Result<()> { 1412 Ok(()) 1413 } 1414 1415 #[cfg(target_arch = "x86_64")] 1416 /// 1417 /// Set CPU state for x86_64 guest. 1418 /// 1419 fn set_state(&self, state: &CpuState) -> cpu::Result<()> { 1420 let mut state: VcpuMshvState = state.clone().into(); 1421 self.set_msrs(&state.msrs)?; 1422 self.set_vcpu_events(&state.vcpu_events)?; 1423 self.set_regs(&state.regs.into())?; 1424 self.set_sregs(&state.sregs.into())?; 1425 self.set_fpu(&state.fpu)?; 1426 self.set_xcrs(&state.xcrs)?; 1427 // These registers are global and needed to be set only for first VCPU 1428 // as Microsoft Hypervisor allows setting this register for only one VCPU 1429 if self.vp_index == 0 { 1430 self.fd 1431 .set_misc_regs(&state.misc) 1432 .map_err(|e| cpu::HypervisorCpuError::SetMiscRegs(e.into()))? 1433 } 1434 self.fd 1435 .set_debug_regs(&state.dbg) 1436 .map_err(|e| cpu::HypervisorCpuError::SetDebugRegs(e.into()))?; 1437 self.fd 1438 .set_all_vp_state_components(&mut state.vp_states) 1439 .map_err(|e| cpu::HypervisorCpuError::SetAllVpStateComponents(e.into()))?; 1440 Ok(()) 1441 } 1442 1443 #[cfg(target_arch = "aarch64")] 1444 /// 1445 /// Set CPU state for aarch64 guest. 1446 /// 1447 fn set_state(&self, state: &CpuState) -> cpu::Result<()> { 1448 unimplemented!() 1449 } 1450 1451 #[cfg(target_arch = "x86_64")] 1452 /// 1453 /// Get CPU State for x86_64 guest 1454 /// 1455 fn state(&self) -> cpu::Result<CpuState> { 1456 let regs = self.get_regs()?; 1457 let sregs = self.get_sregs()?; 1458 let xcrs = self.get_xcrs()?; 1459 let fpu = self.get_fpu()?; 1460 let vcpu_events = self.get_vcpu_events()?; 1461 let mut msrs = self.msrs.clone(); 1462 self.get_msrs(&mut msrs)?; 1463 let misc = self 1464 .fd 1465 .get_misc_regs() 1466 .map_err(|e| cpu::HypervisorCpuError::GetMiscRegs(e.into()))?; 1467 let dbg = self 1468 .fd 1469 .get_debug_regs() 1470 .map_err(|e| cpu::HypervisorCpuError::GetDebugRegs(e.into()))?; 1471 let vp_states = self 1472 .fd 1473 .get_all_vp_state_components() 1474 .map_err(|e| cpu::HypervisorCpuError::GetAllVpStateComponents(e.into()))?; 1475 1476 Ok(VcpuMshvState { 1477 msrs, 1478 vcpu_events, 1479 regs: regs.into(), 1480 sregs: sregs.into(), 1481 fpu, 1482 xcrs, 1483 dbg, 1484 misc, 1485 vp_states, 1486 } 1487 .into()) 1488 } 1489 1490 #[cfg(target_arch = "aarch64")] 1491 /// 1492 /// Get CPU state for aarch64 guest. 1493 /// 1494 fn state(&self) -> cpu::Result<CpuState> { 1495 unimplemented!() 1496 } 1497 1498 #[cfg(target_arch = "x86_64")] 1499 /// 1500 /// Translate guest virtual address to guest physical address 1501 /// 1502 fn translate_gva(&self, gva: u64, flags: u64) -> cpu::Result<(u64, u32)> { 1503 let r = self 1504 .fd 1505 .translate_gva(gva, flags) 1506 .map_err(|e| cpu::HypervisorCpuError::TranslateVirtualAddress(e.into()))?; 1507 1508 let gpa = r.0; 1509 // SAFETY: r is valid, otherwise this function will have returned 1510 let result_code = unsafe { r.1.__bindgen_anon_1.result_code }; 1511 1512 Ok((gpa, result_code)) 1513 } 1514 1515 #[cfg(target_arch = "x86_64")] 1516 /// 1517 /// Return the list of initial MSR entries for a VCPU 1518 /// 1519 fn boot_msr_entries(&self) -> Vec<MsrEntry> { 1520 use crate::arch::x86::{msr_index, MTRR_ENABLE, MTRR_MEM_TYPE_WB}; 1521 1522 [ 1523 msr!(msr_index::MSR_IA32_SYSENTER_CS), 1524 msr!(msr_index::MSR_IA32_SYSENTER_ESP), 1525 msr!(msr_index::MSR_IA32_SYSENTER_EIP), 1526 msr!(msr_index::MSR_STAR), 1527 msr!(msr_index::MSR_CSTAR), 1528 msr!(msr_index::MSR_LSTAR), 1529 msr!(msr_index::MSR_KERNEL_GS_BASE), 1530 msr!(msr_index::MSR_SYSCALL_MASK), 1531 msr_data!(msr_index::MSR_MTRRdefType, MTRR_ENABLE | MTRR_MEM_TYPE_WB), 1532 ] 1533 .to_vec() 1534 } 1535 1536 /// 1537 /// Sets the AMD specific vcpu's sev control register. 1538 /// 1539 #[cfg(feature = "sev_snp")] 1540 fn set_sev_control_register(&self, vmsa_pfn: u64) -> cpu::Result<()> { 1541 let sev_control_reg = snp::get_sev_control_register(vmsa_pfn); 1542 1543 self.fd 1544 .set_sev_control_register(sev_control_reg) 1545 .map_err(|e| cpu::HypervisorCpuError::SetSevControlRegister(e.into())) 1546 } 1547 #[cfg(target_arch = "x86_64")] 1548 /// 1549 /// Trigger NMI interrupt 1550 /// 1551 fn nmi(&self) -> cpu::Result<()> { 1552 let cfg = InterruptRequest { 1553 interrupt_type: hv_interrupt_type_HV_X64_INTERRUPT_TYPE_NMI, 1554 apic_id: self.vp_index as u64, 1555 level_triggered: false, 1556 vector: 0, 1557 logical_destination_mode: false, 1558 long_mode: false, 1559 }; 1560 self.vm_fd 1561 .request_virtual_interrupt(&cfg) 1562 .map_err(|e| cpu::HypervisorCpuError::Nmi(e.into())) 1563 } 1564 } 1565 1566 impl MshvVcpu { 1567 /// 1568 /// Deactivate previously used GHCB page. 1569 /// 1570 #[cfg(feature = "sev_snp")] 1571 fn disable_prev_ghcb_page(&self) -> cpu::Result<()> { 1572 let mut reg_assocs = [hv_register_assoc { 1573 name: hv_register_name_HV_X64_REGISTER_SEV_GHCB_GPA, 1574 ..Default::default() 1575 }]; 1576 self.fd.get_reg(&mut reg_assocs).unwrap(); 1577 // SAFETY: Accessing a union element from bindgen generated bindings. 1578 let prev_ghcb_gpa = unsafe { reg_assocs[0].value.reg64 }; 1579 1580 debug!("Prev GHCB GPA is {:x}", prev_ghcb_gpa); 1581 1582 let mut ghcb_gpa = hv_x64_register_sev_ghcb::default(); 1583 1584 // SAFETY: Accessing a union element from bindgen generated bindings. 1585 unsafe { 1586 ghcb_gpa.__bindgen_anon_1.set_enabled(0); 1587 ghcb_gpa.__bindgen_anon_1.set_page_number(prev_ghcb_gpa); 1588 } 1589 1590 // SAFETY: Accessing a union element from bindgen generated bindings. 1591 let reg_name_value = unsafe { 1592 [( 1593 hv_register_name_HV_X64_REGISTER_SEV_GHCB_GPA, 1594 ghcb_gpa.as_uint64, 1595 )] 1596 }; 1597 1598 set_registers_64!(self.fd, reg_name_value) 1599 .map_err(|e| cpu::HypervisorCpuError::SetRegister(e.into()))?; 1600 1601 Ok(()) 1602 } 1603 #[cfg(target_arch = "x86_64")] 1604 /// 1605 /// X86 specific call that returns the vcpu's current "xcrs". 1606 /// 1607 fn get_xcrs(&self) -> cpu::Result<ExtendedControlRegisters> { 1608 self.fd 1609 .get_xcrs() 1610 .map_err(|e| cpu::HypervisorCpuError::GetXcsr(e.into())) 1611 } 1612 1613 #[cfg(target_arch = "x86_64")] 1614 /// 1615 /// X86 specific call that sets the vcpu's current "xcrs". 1616 /// 1617 fn set_xcrs(&self, xcrs: &ExtendedControlRegisters) -> cpu::Result<()> { 1618 self.fd 1619 .set_xcrs(xcrs) 1620 .map_err(|e| cpu::HypervisorCpuError::SetXcsr(e.into())) 1621 } 1622 1623 #[cfg(target_arch = "x86_64")] 1624 /// 1625 /// Returns currently pending exceptions, interrupts, and NMIs as well as related 1626 /// states of the vcpu. 1627 /// 1628 fn get_vcpu_events(&self) -> cpu::Result<VcpuEvents> { 1629 self.fd 1630 .get_vcpu_events() 1631 .map_err(|e| cpu::HypervisorCpuError::GetVcpuEvents(e.into())) 1632 } 1633 1634 #[cfg(target_arch = "x86_64")] 1635 /// 1636 /// Sets pending exceptions, interrupts, and NMIs as well as related states 1637 /// of the vcpu. 1638 /// 1639 fn set_vcpu_events(&self, events: &VcpuEvents) -> cpu::Result<()> { 1640 self.fd 1641 .set_vcpu_events(events) 1642 .map_err(|e| cpu::HypervisorCpuError::SetVcpuEvents(e.into())) 1643 } 1644 1645 /// 1646 /// Clear SW_EXIT_INFO1 register for SEV-SNP guests. 1647 /// 1648 #[cfg(feature = "sev_snp")] 1649 fn clear_swexit_info1(&self) -> std::result::Result<cpu::VmExit, cpu::HypervisorCpuError> { 1650 // Clear the SW_EXIT_INFO1 register to indicate no error 1651 // Safe to use unwrap, for sev_snp guest we already have the 1652 // GHCB pointer wrapped in the option, otherwise this place is not reached. 1653 let ghcb = self.ghcb.as_ref().unwrap().0; 1654 set_svm_field_u64_ptr!(ghcb, exit_info1, 0); 1655 1656 Ok(cpu::VmExit::Ignore) 1657 } 1658 1659 #[cfg(feature = "sev_snp")] 1660 fn gpa_write(&self, gpa: u64, data: &[u8]) -> cpu::Result<()> { 1661 for (gpa, chunk) in (gpa..) 1662 .step_by(HV_READ_WRITE_GPA_MAX_SIZE as usize) 1663 .zip(data.chunks(HV_READ_WRITE_GPA_MAX_SIZE as usize)) 1664 { 1665 let mut data = [0; HV_READ_WRITE_GPA_MAX_SIZE as usize]; 1666 data[..chunk.len()].copy_from_slice(chunk); 1667 1668 let mut rw_gpa_arg = mshv_bindings::mshv_read_write_gpa { 1669 base_gpa: gpa, 1670 byte_count: chunk.len() as u32, 1671 data, 1672 ..Default::default() 1673 }; 1674 self.fd 1675 .gpa_write(&mut rw_gpa_arg) 1676 .map_err(|e| cpu::HypervisorCpuError::GpaWrite(e.into()))?; 1677 } 1678 1679 Ok(()) 1680 } 1681 } 1682 1683 /// Wrapper over Mshv VM ioctls. 1684 pub struct MshvVm { 1685 fd: Arc<VmFd>, 1686 #[cfg(target_arch = "x86_64")] 1687 msrs: Vec<MsrEntry>, 1688 dirty_log_slots: Arc<RwLock<HashMap<u64, MshvDirtyLogSlot>>>, 1689 #[cfg(feature = "sev_snp")] 1690 sev_snp_enabled: bool, 1691 #[cfg(feature = "sev_snp")] 1692 host_access_pages: ArcSwap<AtomicBitmap>, 1693 } 1694 1695 impl MshvVm { 1696 /// 1697 /// Creates an in-kernel device. 1698 /// 1699 /// See the documentation for `MSHV_CREATE_DEVICE`. 1700 fn create_device(&self, device: &mut CreateDevice) -> vm::Result<VfioDeviceFd> { 1701 let device_fd = self 1702 .fd 1703 .create_device(device) 1704 .map_err(|e| vm::HypervisorVmError::CreateDevice(e.into()))?; 1705 Ok(VfioDeviceFd::new_from_mshv(device_fd)) 1706 } 1707 } 1708 1709 /// 1710 /// Implementation of Vm trait for Mshv 1711 /// 1712 /// # Examples 1713 /// 1714 /// ``` 1715 /// extern crate hypervisor; 1716 /// use hypervisor::mshv::MshvHypervisor; 1717 /// use std::sync::Arc; 1718 /// let mshv = MshvHypervisor::new().unwrap(); 1719 /// let hypervisor = Arc::new(mshv); 1720 /// let vm = hypervisor.create_vm().expect("new VM fd creation failed"); 1721 /// ``` 1722 impl vm::Vm for MshvVm { 1723 #[cfg(target_arch = "x86_64")] 1724 /// 1725 /// Sets the address of the one-page region in the VM's address space. 1726 /// 1727 fn set_identity_map_address(&self, _address: u64) -> vm::Result<()> { 1728 Ok(()) 1729 } 1730 1731 #[cfg(target_arch = "x86_64")] 1732 /// 1733 /// Sets the address of the three-page region in the VM's address space. 1734 /// 1735 fn set_tss_address(&self, _offset: usize) -> vm::Result<()> { 1736 Ok(()) 1737 } 1738 1739 /// 1740 /// Creates an in-kernel interrupt controller. 1741 /// 1742 fn create_irq_chip(&self) -> vm::Result<()> { 1743 Ok(()) 1744 } 1745 1746 /// 1747 /// Registers an event that will, when signaled, trigger the `gsi` IRQ. 1748 /// 1749 fn register_irqfd(&self, fd: &EventFd, gsi: u32) -> vm::Result<()> { 1750 debug!("register_irqfd fd {} gsi {}", fd.as_raw_fd(), gsi); 1751 1752 self.fd 1753 .register_irqfd(fd, gsi) 1754 .map_err(|e| vm::HypervisorVmError::RegisterIrqFd(e.into()))?; 1755 1756 Ok(()) 1757 } 1758 1759 /// 1760 /// Unregisters an event that will, when signaled, trigger the `gsi` IRQ. 1761 /// 1762 fn unregister_irqfd(&self, fd: &EventFd, gsi: u32) -> vm::Result<()> { 1763 debug!("unregister_irqfd fd {} gsi {}", fd.as_raw_fd(), gsi); 1764 1765 self.fd 1766 .unregister_irqfd(fd, gsi) 1767 .map_err(|e| vm::HypervisorVmError::UnregisterIrqFd(e.into()))?; 1768 1769 Ok(()) 1770 } 1771 1772 /// 1773 /// Creates a VcpuFd object from a vcpu RawFd. 1774 /// 1775 fn create_vcpu( 1776 &self, 1777 id: u8, 1778 vm_ops: Option<Arc<dyn VmOps>>, 1779 ) -> vm::Result<Arc<dyn cpu::Vcpu>> { 1780 let vcpu_fd = self 1781 .fd 1782 .create_vcpu(id) 1783 .map_err(|e| vm::HypervisorVmError::CreateVcpu(e.into()))?; 1784 1785 /* Map the GHCB page to the VMM(root) address space 1786 * The map is available after the vcpu creation. This address is mapped 1787 * to the overlay ghcb page of the Microsoft Hypervisor, don't have 1788 * to worry about the scenario when a guest changes the GHCB mapping. 1789 */ 1790 #[cfg(feature = "sev_snp")] 1791 let ghcb = if self.sev_snp_enabled { 1792 // SAFETY: Safe to call as VCPU has this map already available upon creation 1793 let addr = unsafe { 1794 libc::mmap( 1795 std::ptr::null_mut(), 1796 HV_PAGE_SIZE, 1797 libc::PROT_READ | libc::PROT_WRITE, 1798 libc::MAP_SHARED, 1799 vcpu_fd.as_raw_fd(), 1800 MSHV_VP_MMAP_OFFSET_GHCB as i64 * libc::sysconf(libc::_SC_PAGE_SIZE), 1801 ) 1802 }; 1803 if std::ptr::eq(addr, libc::MAP_FAILED) { 1804 // No point of continuing, without this mmap VMGEXIT will fail anyway 1805 // Return error 1806 return Err(vm::HypervisorVmError::MmapToRoot); 1807 } 1808 Some(Ghcb(addr as *mut svm_ghcb_base)) 1809 } else { 1810 None 1811 }; 1812 let vcpu = MshvVcpu { 1813 fd: vcpu_fd, 1814 vp_index: id, 1815 #[cfg(target_arch = "x86_64")] 1816 cpuid: Vec::new(), 1817 #[cfg(target_arch = "x86_64")] 1818 msrs: self.msrs.clone(), 1819 vm_ops, 1820 vm_fd: self.fd.clone(), 1821 #[cfg(feature = "sev_snp")] 1822 ghcb, 1823 #[cfg(feature = "sev_snp")] 1824 host_access_pages: ArcSwap::new(self.host_access_pages.load().clone()), 1825 }; 1826 Ok(Arc::new(vcpu)) 1827 } 1828 1829 #[cfg(target_arch = "x86_64")] 1830 fn enable_split_irq(&self) -> vm::Result<()> { 1831 Ok(()) 1832 } 1833 1834 #[cfg(target_arch = "x86_64")] 1835 fn enable_sgx_attribute(&self, _file: File) -> vm::Result<()> { 1836 Ok(()) 1837 } 1838 1839 fn register_ioevent( 1840 &self, 1841 fd: &EventFd, 1842 addr: &IoEventAddress, 1843 datamatch: Option<DataMatch>, 1844 ) -> vm::Result<()> { 1845 #[cfg(feature = "sev_snp")] 1846 if self.sev_snp_enabled { 1847 return Ok(()); 1848 } 1849 1850 let addr = &mshv_ioctls::IoEventAddress::from(*addr); 1851 debug!( 1852 "register_ioevent fd {} addr {:x?} datamatch {:?}", 1853 fd.as_raw_fd(), 1854 addr, 1855 datamatch 1856 ); 1857 if let Some(dm) = datamatch { 1858 match dm { 1859 vm::DataMatch::DataMatch32(mshv_dm32) => self 1860 .fd 1861 .register_ioevent(fd, addr, mshv_dm32) 1862 .map_err(|e| vm::HypervisorVmError::RegisterIoEvent(e.into())), 1863 vm::DataMatch::DataMatch64(mshv_dm64) => self 1864 .fd 1865 .register_ioevent(fd, addr, mshv_dm64) 1866 .map_err(|e| vm::HypervisorVmError::RegisterIoEvent(e.into())), 1867 } 1868 } else { 1869 self.fd 1870 .register_ioevent(fd, addr, NoDatamatch) 1871 .map_err(|e| vm::HypervisorVmError::RegisterIoEvent(e.into())) 1872 } 1873 } 1874 1875 /// Unregister an event from a certain address it has been previously registered to. 1876 fn unregister_ioevent(&self, fd: &EventFd, addr: &IoEventAddress) -> vm::Result<()> { 1877 #[cfg(feature = "sev_snp")] 1878 if self.sev_snp_enabled { 1879 return Ok(()); 1880 } 1881 1882 let addr = &mshv_ioctls::IoEventAddress::from(*addr); 1883 debug!("unregister_ioevent fd {} addr {:x?}", fd.as_raw_fd(), addr); 1884 1885 self.fd 1886 .unregister_ioevent(fd, addr, NoDatamatch) 1887 .map_err(|e| vm::HypervisorVmError::UnregisterIoEvent(e.into())) 1888 } 1889 1890 /// Creates a guest physical memory region. 1891 fn create_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> vm::Result<()> { 1892 let user_memory_region: mshv_user_mem_region = user_memory_region.into(); 1893 // No matter read only or not we keep track the slots. 1894 // For readonly hypervisor can enable the dirty bits, 1895 // but a VM exit happens before setting the dirty bits 1896 self.dirty_log_slots.write().unwrap().insert( 1897 user_memory_region.guest_pfn, 1898 MshvDirtyLogSlot { 1899 guest_pfn: user_memory_region.guest_pfn, 1900 memory_size: user_memory_region.size, 1901 }, 1902 ); 1903 1904 self.fd 1905 .map_user_memory(user_memory_region) 1906 .map_err(|e| vm::HypervisorVmError::CreateUserMemory(e.into()))?; 1907 Ok(()) 1908 } 1909 1910 /// Removes a guest physical memory region. 1911 fn remove_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> vm::Result<()> { 1912 let user_memory_region: mshv_user_mem_region = user_memory_region.into(); 1913 // Remove the corresponding entry from "self.dirty_log_slots" if needed 1914 self.dirty_log_slots 1915 .write() 1916 .unwrap() 1917 .remove(&user_memory_region.guest_pfn); 1918 1919 self.fd 1920 .unmap_user_memory(user_memory_region) 1921 .map_err(|e| vm::HypervisorVmError::RemoveUserMemory(e.into()))?; 1922 Ok(()) 1923 } 1924 1925 fn make_user_memory_region( 1926 &self, 1927 _slot: u32, 1928 guest_phys_addr: u64, 1929 memory_size: u64, 1930 userspace_addr: u64, 1931 readonly: bool, 1932 _log_dirty_pages: bool, 1933 ) -> UserMemoryRegion { 1934 let mut flags = 1 << MSHV_SET_MEM_BIT_EXECUTABLE; 1935 if !readonly { 1936 flags |= 1 << MSHV_SET_MEM_BIT_WRITABLE; 1937 } 1938 1939 mshv_user_mem_region { 1940 flags, 1941 guest_pfn: guest_phys_addr >> PAGE_SHIFT, 1942 size: memory_size, 1943 userspace_addr, 1944 ..Default::default() 1945 } 1946 .into() 1947 } 1948 1949 fn create_passthrough_device(&self) -> vm::Result<VfioDeviceFd> { 1950 let mut vfio_dev = mshv_create_device { 1951 type_: MSHV_DEV_TYPE_VFIO, 1952 fd: 0, 1953 flags: 0, 1954 }; 1955 1956 self.create_device(&mut vfio_dev) 1957 .map_err(|e| vm::HypervisorVmError::CreatePassthroughDevice(e.into())) 1958 } 1959 1960 /// 1961 /// Constructs a routing entry 1962 /// 1963 fn make_routing_entry(&self, gsi: u32, config: &InterruptSourceConfig) -> IrqRoutingEntry { 1964 match config { 1965 InterruptSourceConfig::MsiIrq(cfg) => mshv_user_irq_entry { 1966 gsi, 1967 address_lo: cfg.low_addr, 1968 address_hi: cfg.high_addr, 1969 data: cfg.data, 1970 } 1971 .into(), 1972 _ => { 1973 unreachable!() 1974 } 1975 } 1976 } 1977 1978 fn set_gsi_routing(&self, entries: &[IrqRoutingEntry]) -> vm::Result<()> { 1979 let mut msi_routing = 1980 vec_with_array_field::<mshv_user_irq_table, mshv_user_irq_entry>(entries.len()); 1981 msi_routing[0].nr = entries.len() as u32; 1982 1983 let entries: Vec<mshv_user_irq_entry> = entries 1984 .iter() 1985 .map(|entry| match entry { 1986 IrqRoutingEntry::Mshv(e) => *e, 1987 #[allow(unreachable_patterns)] 1988 _ => panic!("IrqRoutingEntry type is wrong"), 1989 }) 1990 .collect(); 1991 1992 // SAFETY: msi_routing initialized with entries.len() and now it is being turned into 1993 // entries_slice with entries.len() again. It is guaranteed to be large enough to hold 1994 // everything from entries. 1995 unsafe { 1996 let entries_slice: &mut [mshv_user_irq_entry] = 1997 msi_routing[0].entries.as_mut_slice(entries.len()); 1998 entries_slice.copy_from_slice(&entries); 1999 } 2000 2001 self.fd 2002 .set_msi_routing(&msi_routing[0]) 2003 .map_err(|e| vm::HypervisorVmError::SetGsiRouting(e.into())) 2004 } 2005 2006 /// 2007 /// Start logging dirty pages 2008 /// 2009 fn start_dirty_log(&self) -> vm::Result<()> { 2010 self.fd 2011 .enable_dirty_page_tracking() 2012 .map_err(|e| vm::HypervisorVmError::StartDirtyLog(e.into())) 2013 } 2014 2015 /// 2016 /// Stop logging dirty pages 2017 /// 2018 fn stop_dirty_log(&self) -> vm::Result<()> { 2019 let dirty_log_slots = self.dirty_log_slots.read().unwrap(); 2020 // Before disabling the dirty page tracking we need 2021 // to set the dirty bits in the Hypervisor 2022 // This is a requirement from Microsoft Hypervisor 2023 for (_, s) in dirty_log_slots.iter() { 2024 self.fd 2025 .get_dirty_log( 2026 s.guest_pfn, 2027 s.memory_size as usize, 2028 MSHV_GPAP_ACCESS_OP_SET as u8, 2029 ) 2030 .map_err(|e| vm::HypervisorVmError::StartDirtyLog(e.into()))?; 2031 } 2032 self.fd 2033 .disable_dirty_page_tracking() 2034 .map_err(|e| vm::HypervisorVmError::StartDirtyLog(e.into()))?; 2035 Ok(()) 2036 } 2037 2038 /// 2039 /// Get dirty pages bitmap (one bit per page) 2040 /// 2041 fn get_dirty_log(&self, _slot: u32, base_gpa: u64, memory_size: u64) -> vm::Result<Vec<u64>> { 2042 self.fd 2043 .get_dirty_log( 2044 base_gpa >> PAGE_SHIFT, 2045 memory_size as usize, 2046 MSHV_GPAP_ACCESS_OP_CLEAR as u8, 2047 ) 2048 .map_err(|e| vm::HypervisorVmError::GetDirtyLog(e.into())) 2049 } 2050 2051 /// Retrieve guest clock. 2052 #[cfg(target_arch = "x86_64")] 2053 fn get_clock(&self) -> vm::Result<ClockData> { 2054 let val = self 2055 .fd 2056 .get_partition_property(hv_partition_property_code_HV_PARTITION_PROPERTY_REFERENCE_TIME) 2057 .map_err(|e| vm::HypervisorVmError::GetClock(e.into()))?; 2058 Ok(MshvClockData { ref_time: val }.into()) 2059 } 2060 2061 /// Set guest clock. 2062 #[cfg(target_arch = "x86_64")] 2063 fn set_clock(&self, data: &ClockData) -> vm::Result<()> { 2064 let data: MshvClockData = (*data).into(); 2065 self.fd 2066 .set_partition_property( 2067 hv_partition_property_code_HV_PARTITION_PROPERTY_REFERENCE_TIME, 2068 data.ref_time, 2069 ) 2070 .map_err(|e| vm::HypervisorVmError::SetClock(e.into())) 2071 } 2072 2073 /// Downcast to the underlying MshvVm type 2074 fn as_any(&self) -> &dyn Any { 2075 self 2076 } 2077 2078 /// Initialize the SEV-SNP VM 2079 #[cfg(feature = "sev_snp")] 2080 fn sev_snp_init(&self) -> vm::Result<()> { 2081 self.fd 2082 .set_partition_property( 2083 hv_partition_property_code_HV_PARTITION_PROPERTY_ISOLATION_STATE, 2084 hv_partition_isolation_state_HV_PARTITION_ISOLATION_SECURE as u64, 2085 ) 2086 .map_err(|e| vm::HypervisorVmError::InitializeSevSnp(e.into())) 2087 } 2088 2089 /// 2090 /// Importing isolated pages, these pages will be used 2091 /// for the PSP(Platform Security Processor) measurement. 2092 #[cfg(feature = "sev_snp")] 2093 fn import_isolated_pages( 2094 &self, 2095 page_type: u32, 2096 page_size: u32, 2097 pages: &[u64], 2098 ) -> vm::Result<()> { 2099 debug_assert!(page_size == hv_isolated_page_size_HV_ISOLATED_PAGE_SIZE_4KB); 2100 if pages.is_empty() { 2101 return Ok(()); 2102 } 2103 2104 let mut isolated_pages = 2105 vec_with_array_field::<mshv_import_isolated_pages, u64>(pages.len()); 2106 isolated_pages[0].page_type = page_type as u8; 2107 isolated_pages[0].page_count = pages.len() as u64; 2108 // SAFETY: isolated_pages initialized with pages.len() and now it is being turned into 2109 // pages_slice with pages.len() again. It is guaranteed to be large enough to hold 2110 // everything from pages. 2111 unsafe { 2112 let pages_slice: &mut [u64] = isolated_pages[0].guest_pfns.as_mut_slice(pages.len()); 2113 pages_slice.copy_from_slice(pages); 2114 } 2115 self.fd 2116 .import_isolated_pages(&isolated_pages[0]) 2117 .map_err(|e| vm::HypervisorVmError::ImportIsolatedPages(e.into())) 2118 } 2119 2120 /// 2121 /// Complete isolated import, telling the hypervisor that 2122 /// importing the pages to guest memory is complete. 2123 /// 2124 #[cfg(feature = "sev_snp")] 2125 fn complete_isolated_import( 2126 &self, 2127 snp_id_block: IGVM_VHS_SNP_ID_BLOCK, 2128 host_data: [u8; 32], 2129 id_block_enabled: u8, 2130 ) -> vm::Result<()> { 2131 let mut auth_info = hv_snp_id_auth_info { 2132 id_key_algorithm: snp_id_block.id_key_algorithm, 2133 auth_key_algorithm: snp_id_block.author_key_algorithm, 2134 ..Default::default() 2135 }; 2136 // Each of r/s component is 576 bits long 2137 auth_info.id_block_signature[..SIG_R_COMPONENT_SIZE_IN_BYTES] 2138 .copy_from_slice(snp_id_block.id_key_signature.r_comp.as_ref()); 2139 auth_info.id_block_signature 2140 [SIG_R_COMPONENT_SIZE_IN_BYTES..SIG_R_AND_S_COMPONENT_SIZE_IN_BYTES] 2141 .copy_from_slice(snp_id_block.id_key_signature.s_comp.as_ref()); 2142 auth_info.id_key[..ECDSA_CURVE_ID_SIZE_IN_BYTES] 2143 .copy_from_slice(snp_id_block.id_public_key.curve.to_le_bytes().as_ref()); 2144 auth_info.id_key[ECDSA_SIG_X_COMPONENT_START..ECDSA_SIG_X_COMPONENT_END] 2145 .copy_from_slice(snp_id_block.id_public_key.qx.as_ref()); 2146 auth_info.id_key[ECDSA_SIG_Y_COMPONENT_START..ECDSA_SIG_Y_COMPONENT_END] 2147 .copy_from_slice(snp_id_block.id_public_key.qy.as_ref()); 2148 2149 let data = mshv_complete_isolated_import { 2150 import_data: hv_partition_complete_isolated_import_data { 2151 psp_parameters: hv_psp_launch_finish_data { 2152 id_block: hv_snp_id_block { 2153 launch_digest: snp_id_block.ld, 2154 family_id: snp_id_block.family_id, 2155 image_id: snp_id_block.image_id, 2156 version: snp_id_block.version, 2157 guest_svn: snp_id_block.guest_svn, 2158 policy: get_default_snp_guest_policy(), 2159 }, 2160 id_auth_info: auth_info, 2161 host_data, 2162 id_block_enabled, 2163 author_key_enabled: 0, 2164 }, 2165 }, 2166 }; 2167 self.fd 2168 .complete_isolated_import(&data) 2169 .map_err(|e| vm::HypervisorVmError::CompleteIsolatedImport(e.into())) 2170 } 2171 2172 #[cfg(target_arch = "aarch64")] 2173 fn create_vgic(&self, config: VgicConfig) -> vm::Result<Arc<Mutex<dyn Vgic>>> { 2174 unimplemented!() 2175 } 2176 2177 #[cfg(target_arch = "aarch64")] 2178 fn get_preferred_target(&self, _kvi: &mut crate::VcpuInit) -> vm::Result<()> { 2179 unimplemented!() 2180 } 2181 2182 /// Pause the VM 2183 fn pause(&self) -> vm::Result<()> { 2184 // Freeze the partition 2185 self.fd 2186 .set_partition_property( 2187 hv_partition_property_code_HV_PARTITION_PROPERTY_TIME_FREEZE, 2188 1u64, 2189 ) 2190 .map_err(|e| { 2191 vm::HypervisorVmError::SetVmProperty(anyhow!( 2192 "Failed to set partition property: {}", 2193 e 2194 )) 2195 }) 2196 } 2197 2198 /// Resume the VM 2199 fn resume(&self) -> vm::Result<()> { 2200 // Resuming the partition using TIME_FREEZE property 2201 self.fd 2202 .set_partition_property( 2203 hv_partition_property_code_HV_PARTITION_PROPERTY_TIME_FREEZE, 2204 0u64, 2205 ) 2206 .map_err(|e| { 2207 vm::HypervisorVmError::SetVmProperty(anyhow!( 2208 "Failed to set partition property: {}", 2209 e 2210 )) 2211 }) 2212 } 2213 2214 #[cfg(feature = "sev_snp")] 2215 fn gain_page_access(&self, gpa: u64, size: u32) -> vm::Result<()> { 2216 use mshv_ioctls::set_bits; 2217 const ONE_GB: usize = 1024 * 1024 * 1024; 2218 2219 if !self.sev_snp_enabled { 2220 return Ok(()); 2221 } 2222 2223 let start_gpfn: u64 = gpa >> PAGE_SHIFT; 2224 let end_gpfn: u64 = (gpa + size as u64 - 1) >> PAGE_SHIFT; 2225 2226 // Enlarge the bitmap if the PFN is greater than the bitmap length 2227 if end_gpfn >= self.host_access_pages.load().as_ref().len() as u64 { 2228 self.host_access_pages.rcu(|bitmap| { 2229 let mut bm = bitmap.as_ref().clone(); 2230 bm.enlarge(ONE_GB); 2231 bm 2232 }); 2233 } 2234 2235 let gpas: Vec<u64> = (start_gpfn..=end_gpfn) 2236 .filter(|x| { 2237 !self 2238 .host_access_pages 2239 .load() 2240 .as_ref() 2241 .is_bit_set(*x as usize) 2242 }) 2243 .map(|x| x << PAGE_SHIFT) 2244 .collect(); 2245 2246 if !gpas.is_empty() { 2247 let mut gpa_list = vec_with_array_field::<mshv_modify_gpa_host_access, u64>(gpas.len()); 2248 gpa_list[0].page_count = gpas.len() as u64; 2249 gpa_list[0].flags = set_bits!( 2250 u8, 2251 MSHV_GPA_HOST_ACCESS_BIT_ACQUIRE, 2252 MSHV_GPA_HOST_ACCESS_BIT_READABLE, 2253 MSHV_GPA_HOST_ACCESS_BIT_WRITABLE 2254 ); 2255 2256 // SAFETY: gpa_list initialized with gpas.len() and now it is being turned into 2257 // gpas_slice with gpas.len() again. It is guaranteed to be large enough to hold 2258 // everything from gpas. 2259 unsafe { 2260 let gpas_slice: &mut [u64] = gpa_list[0].guest_pfns.as_mut_slice(gpas.len()); 2261 gpas_slice.copy_from_slice(gpas.as_slice()); 2262 } 2263 2264 self.fd 2265 .modify_gpa_host_access(&gpa_list[0]) 2266 .map_err(|e| vm::HypervisorVmError::ModifyGpaHostAccess(e.into()))?; 2267 2268 for acquired_gpa in gpas { 2269 self.host_access_pages.rcu(|bitmap| { 2270 let bm = bitmap.clone(); 2271 bm.set_bit((acquired_gpa >> PAGE_SHIFT) as usize); 2272 bm 2273 }); 2274 } 2275 } 2276 2277 Ok(()) 2278 } 2279 } 2280