1 // Copyright © 2019 Intel Corporation 2 // 3 // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause 4 // 5 6 use std::any::Any; 7 use std::collections::{BTreeMap, HashMap}; 8 use std::io; 9 use std::os::unix::io::AsRawFd; 10 use std::ptr::null_mut; 11 use std::sync::{Arc, Barrier, Mutex}; 12 13 use anyhow::anyhow; 14 use byteorder::{ByteOrder, LittleEndian}; 15 use hypervisor::HypervisorVmError; 16 use libc::{sysconf, _SC_PAGESIZE}; 17 use serde::{Deserialize, Serialize}; 18 use thiserror::Error; 19 use vfio_bindings::bindings::vfio::*; 20 use vfio_ioctls::{ 21 VfioContainer, VfioDevice, VfioIrq, VfioRegionInfoCap, VfioRegionSparseMmapArea, 22 }; 23 use vm_allocator::page_size::{ 24 align_page_size_down, align_page_size_up, is_4k_aligned, is_4k_multiple, is_page_size_aligned, 25 }; 26 use vm_allocator::{AddressAllocator, MemorySlotAllocator, SystemAllocator}; 27 use vm_device::dma_mapping::ExternalDmaMapping; 28 use vm_device::interrupt::{ 29 InterruptIndex, InterruptManager, InterruptSourceGroup, MsiIrqGroupConfig, 30 }; 31 use vm_device::{BusDevice, Resource}; 32 use vm_memory::{Address, GuestAddress, GuestAddressSpace, GuestMemory, GuestUsize}; 33 use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; 34 use vmm_sys_util::eventfd::EventFd; 35 36 use crate::msi::{MsiConfigState, MSI_CONFIG_ID}; 37 use crate::msix::MsixConfigState; 38 use crate::{ 39 msi_num_enabled_vectors, BarReprogrammingParams, MsiCap, MsiConfig, MsixCap, MsixConfig, 40 PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciCapabilityId, 41 PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciExpressCapabilityId, 42 PciHeaderType, PciSubclass, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, PCI_CONFIGURATION_ID, 43 }; 44 45 pub(crate) const VFIO_COMMON_ID: &str = "vfio_common"; 46 47 #[derive(Debug, Error)] 48 pub enum VfioPciError { 49 #[error("Failed to create user memory region: {0}")] 50 CreateUserMemoryRegion(#[source] HypervisorVmError), 51 #[error("Failed to DMA map: {0}")] 52 DmaMap(#[source] vfio_ioctls::VfioError), 53 #[error("Failed to DMA unmap: {0}")] 54 DmaUnmap(#[source] vfio_ioctls::VfioError), 55 #[error("Failed to enable INTx: {0}")] 56 EnableIntx(#[source] VfioError), 57 #[error("Failed to enable MSI: {0}")] 58 EnableMsi(#[source] VfioError), 59 #[error("Failed to enable MSI-x: {0}")] 60 EnableMsix(#[source] VfioError), 61 #[error("Failed to mmap the area")] 62 MmapArea, 63 #[error("Failed to notifier's eventfd")] 64 MissingNotifier, 65 #[error("Invalid region alignment")] 66 RegionAlignment, 67 #[error("Invalid region size")] 68 RegionSize, 69 #[error("Failed to retrieve MsiConfigState: {0}")] 70 RetrieveMsiConfigState(#[source] anyhow::Error), 71 #[error("Failed to retrieve MsixConfigState: {0}")] 72 RetrieveMsixConfigState(#[source] anyhow::Error), 73 #[error("Failed to retrieve PciConfigurationState: {0}")] 74 RetrievePciConfigurationState(#[source] anyhow::Error), 75 #[error("Failed to retrieve VfioCommonState: {0}")] 76 RetrieveVfioCommonState(#[source] anyhow::Error), 77 } 78 79 #[derive(Copy, Clone)] 80 enum PciVfioSubclass { 81 VfioSubclass = 0xff, 82 } 83 84 impl PciSubclass for PciVfioSubclass { 85 fn get_register_value(&self) -> u8 { 86 *self as u8 87 } 88 } 89 90 enum InterruptUpdateAction { 91 EnableMsi, 92 DisableMsi, 93 EnableMsix, 94 DisableMsix, 95 } 96 97 #[derive(Serialize, Deserialize)] 98 struct IntxState { 99 enabled: bool, 100 } 101 102 pub(crate) struct VfioIntx { 103 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 104 enabled: bool, 105 } 106 107 #[derive(Serialize, Deserialize)] 108 struct MsiState { 109 cap: MsiCap, 110 cap_offset: u32, 111 } 112 113 pub(crate) struct VfioMsi { 114 pub(crate) cfg: MsiConfig, 115 cap_offset: u32, 116 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 117 } 118 119 impl VfioMsi { 120 fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 121 let old_enabled = self.cfg.enabled(); 122 123 self.cfg.update(offset, data); 124 125 let new_enabled = self.cfg.enabled(); 126 127 if !old_enabled && new_enabled { 128 return Some(InterruptUpdateAction::EnableMsi); 129 } 130 131 if old_enabled && !new_enabled { 132 return Some(InterruptUpdateAction::DisableMsi); 133 } 134 135 None 136 } 137 } 138 139 #[derive(Serialize, Deserialize)] 140 struct MsixState { 141 cap: MsixCap, 142 cap_offset: u32, 143 bdf: u32, 144 } 145 146 pub(crate) struct VfioMsix { 147 pub(crate) bar: MsixConfig, 148 cap: MsixCap, 149 cap_offset: u32, 150 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 151 } 152 153 impl VfioMsix { 154 fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 155 let old_enabled = self.bar.enabled(); 156 157 // Update "Message Control" word 158 if offset == 2 && data.len() == 2 { 159 self.bar.set_msg_ctl(LittleEndian::read_u16(data)); 160 } 161 162 let new_enabled = self.bar.enabled(); 163 164 if !old_enabled && new_enabled { 165 return Some(InterruptUpdateAction::EnableMsix); 166 } 167 168 if old_enabled && !new_enabled { 169 return Some(InterruptUpdateAction::DisableMsix); 170 } 171 172 None 173 } 174 175 fn table_accessed(&self, bar_index: u32, offset: u64) -> bool { 176 let table_offset: u64 = u64::from(self.cap.table_offset()); 177 let table_size: u64 = u64::from(self.cap.table_size()) * (MSIX_TABLE_ENTRY_SIZE as u64); 178 let table_bir: u32 = self.cap.table_bir(); 179 180 bar_index == table_bir && offset >= table_offset && offset < table_offset + table_size 181 } 182 } 183 184 pub(crate) struct Interrupt { 185 pub(crate) intx: Option<VfioIntx>, 186 pub(crate) msi: Option<VfioMsi>, 187 pub(crate) msix: Option<VfioMsix>, 188 } 189 190 impl Interrupt { 191 fn update_msi(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 192 if let Some(ref mut msi) = &mut self.msi { 193 let action = msi.update(offset, data); 194 return action; 195 } 196 197 None 198 } 199 200 fn update_msix(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 201 if let Some(ref mut msix) = &mut self.msix { 202 let action = msix.update(offset, data); 203 return action; 204 } 205 206 None 207 } 208 209 fn accessed(&self, offset: u64) -> Option<(PciCapabilityId, u64)> { 210 if let Some(msi) = &self.msi { 211 if offset >= u64::from(msi.cap_offset) 212 && offset < u64::from(msi.cap_offset) + msi.cfg.size() 213 { 214 return Some(( 215 PciCapabilityId::MessageSignalledInterrupts, 216 u64::from(msi.cap_offset), 217 )); 218 } 219 } 220 221 if let Some(msix) = &self.msix { 222 if offset == u64::from(msix.cap_offset) { 223 return Some((PciCapabilityId::MsiX, u64::from(msix.cap_offset))); 224 } 225 } 226 227 None 228 } 229 230 fn msix_table_accessed(&self, bar_index: u32, offset: u64) -> bool { 231 if let Some(msix) = &self.msix { 232 return msix.table_accessed(bar_index, offset); 233 } 234 235 false 236 } 237 238 fn msix_write_table(&mut self, offset: u64, data: &[u8]) { 239 if let Some(ref mut msix) = &mut self.msix { 240 let offset = offset - u64::from(msix.cap.table_offset()); 241 msix.bar.write_table(offset, data) 242 } 243 } 244 245 fn msix_read_table(&self, offset: u64, data: &mut [u8]) { 246 if let Some(msix) = &self.msix { 247 let offset = offset - u64::from(msix.cap.table_offset()); 248 msix.bar.read_table(offset, data) 249 } 250 } 251 252 pub(crate) fn intx_in_use(&self) -> bool { 253 if let Some(intx) = &self.intx { 254 return intx.enabled; 255 } 256 257 false 258 } 259 } 260 261 #[derive(Copy, Clone)] 262 pub struct UserMemoryRegion { 263 pub slot: u32, 264 pub start: u64, 265 pub size: u64, 266 pub host_addr: u64, 267 } 268 269 #[derive(Clone)] 270 pub struct MmioRegion { 271 pub start: GuestAddress, 272 pub length: GuestUsize, 273 pub(crate) type_: PciBarRegionType, 274 pub(crate) index: u32, 275 pub(crate) user_memory_regions: Vec<UserMemoryRegion>, 276 } 277 278 trait MmioRegionRange { 279 fn check_range(&self, guest_addr: u64, size: u64) -> bool; 280 fn find_user_address(&self, guest_addr: u64) -> Result<u64, io::Error>; 281 } 282 283 impl MmioRegionRange for Vec<MmioRegion> { 284 // Check if a guest address is within the range of mmio regions 285 fn check_range(&self, guest_addr: u64, size: u64) -> bool { 286 for region in self.iter() { 287 let Some(guest_addr_end) = guest_addr.checked_add(size) else { 288 return false; 289 }; 290 let Some(region_end) = region.start.raw_value().checked_add(region.length) else { 291 return false; 292 }; 293 if guest_addr >= region.start.raw_value() && guest_addr_end <= region_end { 294 return true; 295 } 296 } 297 false 298 } 299 300 // Locate the user region address for a guest address within all mmio regions 301 fn find_user_address(&self, guest_addr: u64) -> Result<u64, io::Error> { 302 for region in self.iter() { 303 for user_region in region.user_memory_regions.iter() { 304 if guest_addr >= user_region.start 305 && guest_addr < user_region.start + user_region.size 306 { 307 return Ok(user_region.host_addr + (guest_addr - user_region.start)); 308 } 309 } 310 } 311 312 Err(io::Error::new( 313 io::ErrorKind::Other, 314 format!("unable to find user address: 0x{guest_addr:x}"), 315 )) 316 } 317 } 318 319 #[derive(Debug, Error)] 320 pub enum VfioError { 321 #[error("Kernel VFIO error: {0}")] 322 KernelVfio(#[source] vfio_ioctls::VfioError), 323 #[error("VFIO user error: {0}")] 324 VfioUser(#[source] vfio_user::Error), 325 } 326 327 pub(crate) trait Vfio: Send + Sync { 328 fn read_config_byte(&self, offset: u32) -> u8 { 329 let mut data: [u8; 1] = [0]; 330 self.read_config(offset, &mut data); 331 data[0] 332 } 333 334 fn read_config_word(&self, offset: u32) -> u16 { 335 let mut data: [u8; 2] = [0, 0]; 336 self.read_config(offset, &mut data); 337 u16::from_le_bytes(data) 338 } 339 340 fn read_config_dword(&self, offset: u32) -> u32 { 341 let mut data: [u8; 4] = [0, 0, 0, 0]; 342 self.read_config(offset, &mut data); 343 u32::from_le_bytes(data) 344 } 345 346 fn write_config_dword(&self, offset: u32, buf: u32) { 347 let data: [u8; 4] = buf.to_le_bytes(); 348 self.write_config(offset, &data) 349 } 350 351 fn read_config(&self, offset: u32, data: &mut [u8]) { 352 self.region_read(VFIO_PCI_CONFIG_REGION_INDEX, offset.into(), data.as_mut()); 353 } 354 355 fn write_config(&self, offset: u32, data: &[u8]) { 356 self.region_write(VFIO_PCI_CONFIG_REGION_INDEX, offset.into(), data) 357 } 358 359 fn enable_msi(&self, fds: Vec<&EventFd>) -> Result<(), VfioError> { 360 self.enable_irq(VFIO_PCI_MSI_IRQ_INDEX, fds) 361 } 362 363 fn disable_msi(&self) -> Result<(), VfioError> { 364 self.disable_irq(VFIO_PCI_MSI_IRQ_INDEX) 365 } 366 367 fn enable_msix(&self, fds: Vec<&EventFd>) -> Result<(), VfioError> { 368 self.enable_irq(VFIO_PCI_MSIX_IRQ_INDEX, fds) 369 } 370 371 fn disable_msix(&self) -> Result<(), VfioError> { 372 self.disable_irq(VFIO_PCI_MSIX_IRQ_INDEX) 373 } 374 375 fn region_read(&self, _index: u32, _offset: u64, _data: &mut [u8]) { 376 unimplemented!() 377 } 378 379 fn region_write(&self, _index: u32, _offset: u64, _data: &[u8]) { 380 unimplemented!() 381 } 382 383 fn get_irq_info(&self, _irq_index: u32) -> Option<VfioIrq> { 384 unimplemented!() 385 } 386 387 fn enable_irq(&self, _irq_index: u32, _event_fds: Vec<&EventFd>) -> Result<(), VfioError> { 388 unimplemented!() 389 } 390 391 fn disable_irq(&self, _irq_index: u32) -> Result<(), VfioError> { 392 unimplemented!() 393 } 394 395 fn unmask_irq(&self, _irq_index: u32) -> Result<(), VfioError> { 396 unimplemented!() 397 } 398 } 399 400 struct VfioDeviceWrapper { 401 device: Arc<VfioDevice>, 402 } 403 404 impl VfioDeviceWrapper { 405 fn new(device: Arc<VfioDevice>) -> Self { 406 Self { device } 407 } 408 } 409 410 impl Vfio for VfioDeviceWrapper { 411 fn region_read(&self, index: u32, offset: u64, data: &mut [u8]) { 412 self.device.region_read(index, data, offset) 413 } 414 415 fn region_write(&self, index: u32, offset: u64, data: &[u8]) { 416 self.device.region_write(index, data, offset) 417 } 418 419 fn get_irq_info(&self, irq_index: u32) -> Option<VfioIrq> { 420 self.device.get_irq_info(irq_index).copied() 421 } 422 423 fn enable_irq(&self, irq_index: u32, event_fds: Vec<&EventFd>) -> Result<(), VfioError> { 424 self.device 425 .enable_irq(irq_index, event_fds) 426 .map_err(VfioError::KernelVfio) 427 } 428 429 fn disable_irq(&self, irq_index: u32) -> Result<(), VfioError> { 430 self.device 431 .disable_irq(irq_index) 432 .map_err(VfioError::KernelVfio) 433 } 434 435 fn unmask_irq(&self, irq_index: u32) -> Result<(), VfioError> { 436 self.device 437 .unmask_irq(irq_index) 438 .map_err(VfioError::KernelVfio) 439 } 440 } 441 442 #[derive(Serialize, Deserialize)] 443 struct VfioCommonState { 444 intx_state: Option<IntxState>, 445 msi_state: Option<MsiState>, 446 msix_state: Option<MsixState>, 447 } 448 449 pub(crate) struct ConfigPatch { 450 mask: u32, 451 patch: u32, 452 } 453 454 pub(crate) struct VfioCommon { 455 pub(crate) configuration: PciConfiguration, 456 pub(crate) mmio_regions: Vec<MmioRegion>, 457 pub(crate) interrupt: Interrupt, 458 pub(crate) msi_interrupt_manager: Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, 459 pub(crate) legacy_interrupt_group: Option<Arc<dyn InterruptSourceGroup>>, 460 pub(crate) vfio_wrapper: Arc<dyn Vfio>, 461 pub(crate) patches: HashMap<usize, ConfigPatch>, 462 x_nv_gpudirect_clique: Option<u8>, 463 } 464 465 impl VfioCommon { 466 pub(crate) fn new( 467 msi_interrupt_manager: Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, 468 legacy_interrupt_group: Option<Arc<dyn InterruptSourceGroup>>, 469 vfio_wrapper: Arc<dyn Vfio>, 470 subclass: &dyn PciSubclass, 471 bdf: PciBdf, 472 snapshot: Option<Snapshot>, 473 x_nv_gpudirect_clique: Option<u8>, 474 ) -> Result<Self, VfioPciError> { 475 let pci_configuration_state = 476 vm_migration::state_from_id(snapshot.as_ref(), PCI_CONFIGURATION_ID).map_err(|e| { 477 VfioPciError::RetrievePciConfigurationState(anyhow!( 478 "Failed to get PciConfigurationState from Snapshot: {}", 479 e 480 )) 481 })?; 482 483 let configuration = PciConfiguration::new( 484 0, 485 0, 486 0, 487 PciClassCode::Other, 488 subclass, 489 None, 490 PciHeaderType::Device, 491 0, 492 0, 493 None, 494 pci_configuration_state, 495 ); 496 497 let mut vfio_common = VfioCommon { 498 mmio_regions: Vec::new(), 499 configuration, 500 interrupt: Interrupt { 501 intx: None, 502 msi: None, 503 msix: None, 504 }, 505 msi_interrupt_manager, 506 legacy_interrupt_group, 507 vfio_wrapper, 508 patches: HashMap::new(), 509 x_nv_gpudirect_clique, 510 }; 511 512 let state: Option<VfioCommonState> = snapshot 513 .as_ref() 514 .map(|s| s.to_state()) 515 .transpose() 516 .map_err(|e| { 517 VfioPciError::RetrieveVfioCommonState(anyhow!( 518 "Failed to get VfioCommonState from Snapshot: {}", 519 e 520 )) 521 })?; 522 let msi_state = 523 vm_migration::state_from_id(snapshot.as_ref(), MSI_CONFIG_ID).map_err(|e| { 524 VfioPciError::RetrieveMsiConfigState(anyhow!( 525 "Failed to get MsiConfigState from Snapshot: {}", 526 e 527 )) 528 })?; 529 let msix_state = 530 vm_migration::state_from_id(snapshot.as_ref(), MSIX_CONFIG_ID).map_err(|e| { 531 VfioPciError::RetrieveMsixConfigState(anyhow!( 532 "Failed to get MsixConfigState from Snapshot: {}", 533 e 534 )) 535 })?; 536 537 if let Some(state) = state.as_ref() { 538 vfio_common.set_state(state, msi_state, msix_state)?; 539 } else { 540 vfio_common.parse_capabilities(bdf); 541 vfio_common.initialize_legacy_interrupt()?; 542 } 543 544 Ok(vfio_common) 545 } 546 547 /// In case msix table offset is not page size aligned, we need do some fixup to achieve it. 548 /// Because we don't want the MMIO RW region and trap region overlap each other. 549 fn fixup_msix_region(&mut self, bar_id: u32, region_size: u64) -> u64 { 550 if let Some(msix) = self.interrupt.msix.as_mut() { 551 let msix_cap = &mut msix.cap; 552 553 // Suppose table_bir equals to pba_bir here. Am I right? 554 let (table_offset, table_size) = msix_cap.table_range(); 555 if is_page_size_aligned(table_offset) || msix_cap.table_bir() != bar_id { 556 return region_size; 557 } 558 559 let (pba_offset, pba_size) = msix_cap.pba_range(); 560 let msix_sz = align_page_size_up(table_size + pba_size); 561 // Expand region to hold RW and trap region which both page size aligned 562 let size = std::cmp::max(region_size * 2, msix_sz * 2); 563 // let table starts from the middle of the region 564 msix_cap.table_set_offset((size / 2) as u32); 565 msix_cap.pba_set_offset((size / 2 + pba_offset - table_offset) as u32); 566 567 size 568 } else { 569 // MSI-X not supported for this device 570 region_size 571 } 572 } 573 574 // The `allocator` argument is unused on `aarch64` 575 #[allow(unused_variables)] 576 pub(crate) fn allocate_bars( 577 &mut self, 578 allocator: &Arc<Mutex<SystemAllocator>>, 579 mmio32_allocator: &mut AddressAllocator, 580 mmio64_allocator: &mut AddressAllocator, 581 resources: Option<Vec<Resource>>, 582 ) -> Result<Vec<PciBarConfiguration>, PciDeviceError> { 583 let mut bars = Vec::new(); 584 let mut bar_id = VFIO_PCI_BAR0_REGION_INDEX; 585 586 // Going through all regular regions to compute the BAR size. 587 // We're not saving the BAR address to restore it, because we 588 // are going to allocate a guest address for each BAR and write 589 // that new address back. 590 while bar_id < VFIO_PCI_CONFIG_REGION_INDEX { 591 let mut region_size: u64 = 0; 592 let mut region_type = PciBarRegionType::Memory32BitRegion; 593 let mut prefetchable = PciBarPrefetchable::NotPrefetchable; 594 let mut flags: u32 = 0; 595 596 let mut restored_bar_addr = None; 597 if let Some(resources) = &resources { 598 for resource in resources { 599 if let Resource::PciBar { 600 index, 601 base, 602 size, 603 type_, 604 .. 605 } = resource 606 { 607 if *index == bar_id as usize { 608 restored_bar_addr = Some(GuestAddress(*base)); 609 region_size = *size; 610 region_type = PciBarRegionType::from(*type_); 611 break; 612 } 613 } 614 } 615 if restored_bar_addr.is_none() { 616 bar_id += 1; 617 continue; 618 } 619 } else { 620 let bar_offset = if bar_id == VFIO_PCI_ROM_REGION_INDEX { 621 (PCI_ROM_EXP_BAR_INDEX * 4) as u32 622 } else { 623 PCI_CONFIG_BAR_OFFSET + bar_id * 4 624 }; 625 626 // First read flags 627 flags = self.vfio_wrapper.read_config_dword(bar_offset); 628 629 // Is this an IO BAR? 630 let io_bar = if bar_id != VFIO_PCI_ROM_REGION_INDEX { 631 matches!(flags & PCI_CONFIG_IO_BAR, PCI_CONFIG_IO_BAR) 632 } else { 633 false 634 }; 635 636 // Is this a 64-bit BAR? 637 let is_64bit_bar = if bar_id != VFIO_PCI_ROM_REGION_INDEX { 638 matches!( 639 flags & PCI_CONFIG_MEMORY_BAR_64BIT, 640 PCI_CONFIG_MEMORY_BAR_64BIT 641 ) 642 } else { 643 false 644 }; 645 646 if matches!( 647 flags & PCI_CONFIG_BAR_PREFETCHABLE, 648 PCI_CONFIG_BAR_PREFETCHABLE 649 ) { 650 prefetchable = PciBarPrefetchable::Prefetchable 651 }; 652 653 // To get size write all 1s 654 self.vfio_wrapper 655 .write_config_dword(bar_offset, 0xffff_ffff); 656 657 // And read back BAR value. The device will write zeros for bits it doesn't care about 658 let mut lower = self.vfio_wrapper.read_config_dword(bar_offset); 659 660 if io_bar { 661 // Mask flag bits (lowest 2 for I/O bars) 662 lower &= !0b11; 663 664 // BAR is not enabled 665 if lower == 0 { 666 bar_id += 1; 667 continue; 668 } 669 670 // IO BAR 671 region_type = PciBarRegionType::IoRegion; 672 673 // Invert bits and add 1 to calculate size 674 region_size = (!lower + 1) as u64; 675 } else if is_64bit_bar { 676 // 64 bits Memory BAR 677 region_type = PciBarRegionType::Memory64BitRegion; 678 679 // Query size of upper BAR of 64-bit BAR 680 let upper_offset: u32 = PCI_CONFIG_BAR_OFFSET + (bar_id + 1) * 4; 681 self.vfio_wrapper 682 .write_config_dword(upper_offset, 0xffff_ffff); 683 let upper = self.vfio_wrapper.read_config_dword(upper_offset); 684 685 let mut combined_size = (u64::from(upper) << 32) | u64::from(lower); 686 687 // Mask out flag bits (lowest 4 for memory bars) 688 combined_size &= !0b1111; 689 690 // BAR is not enabled 691 if combined_size == 0 { 692 bar_id += 1; 693 continue; 694 } 695 696 // Invert and add 1 to to find size 697 region_size = !combined_size + 1; 698 } else { 699 region_type = PciBarRegionType::Memory32BitRegion; 700 701 // Mask out flag bits (lowest 4 for memory bars) 702 lower &= !0b1111; 703 704 if lower == 0 { 705 bar_id += 1; 706 continue; 707 } 708 709 // Invert and add 1 to to find size 710 region_size = (!lower + 1) as u64; 711 } 712 } 713 714 let bar_addr = match region_type { 715 PciBarRegionType::IoRegion => { 716 // The address needs to be 4 bytes aligned. 717 allocator 718 .lock() 719 .unwrap() 720 .allocate_io_addresses(restored_bar_addr, region_size, Some(0x4)) 721 .ok_or(PciDeviceError::IoAllocationFailed(region_size))? 722 } 723 PciBarRegionType::Memory32BitRegion => { 724 // BAR allocation must be naturally aligned 725 mmio32_allocator 726 .allocate(restored_bar_addr, region_size, Some(region_size)) 727 .ok_or(PciDeviceError::IoAllocationFailed(region_size))? 728 } 729 PciBarRegionType::Memory64BitRegion => { 730 // We need do some fixup to keep MMIO RW region and msix cap region page size 731 // aligned. 732 region_size = self.fixup_msix_region(bar_id, region_size); 733 mmio64_allocator 734 .allocate( 735 restored_bar_addr, 736 region_size, 737 Some(std::cmp::max( 738 // SAFETY: FFI call. Trivially safe. 739 unsafe { sysconf(_SC_PAGESIZE) as GuestUsize }, 740 region_size, 741 )), 742 ) 743 .ok_or(PciDeviceError::IoAllocationFailed(region_size))? 744 } 745 }; 746 747 // We can now build our BAR configuration block. 748 let bar = PciBarConfiguration::default() 749 .set_index(bar_id as usize) 750 .set_address(bar_addr.raw_value()) 751 .set_size(region_size) 752 .set_region_type(region_type) 753 .set_prefetchable(prefetchable); 754 755 if bar_id == VFIO_PCI_ROM_REGION_INDEX { 756 self.configuration 757 .add_pci_rom_bar(&bar, flags & 0x1) 758 .map_err(|e| PciDeviceError::IoRegistrationFailed(bar_addr.raw_value(), e))?; 759 } else { 760 self.configuration 761 .add_pci_bar(&bar) 762 .map_err(|e| PciDeviceError::IoRegistrationFailed(bar_addr.raw_value(), e))?; 763 } 764 765 bars.push(bar); 766 self.mmio_regions.push(MmioRegion { 767 start: bar_addr, 768 length: region_size, 769 type_: region_type, 770 index: bar_id, 771 user_memory_regions: Vec::new(), 772 }); 773 774 bar_id += 1; 775 if region_type == PciBarRegionType::Memory64BitRegion { 776 bar_id += 1; 777 } 778 } 779 780 Ok(bars) 781 } 782 783 // The `allocator` argument is unused on `aarch64` 784 #[allow(unused_variables)] 785 pub(crate) fn free_bars( 786 &mut self, 787 allocator: &mut SystemAllocator, 788 mmio32_allocator: &mut AddressAllocator, 789 mmio64_allocator: &mut AddressAllocator, 790 ) -> Result<(), PciDeviceError> { 791 for region in self.mmio_regions.iter() { 792 match region.type_ { 793 PciBarRegionType::IoRegion => { 794 allocator.free_io_addresses(region.start, region.length); 795 } 796 PciBarRegionType::Memory32BitRegion => { 797 mmio32_allocator.free(region.start, region.length); 798 } 799 PciBarRegionType::Memory64BitRegion => { 800 mmio64_allocator.free(region.start, region.length); 801 } 802 } 803 } 804 Ok(()) 805 } 806 807 pub(crate) fn parse_msix_capabilities(&mut self, cap: u8) -> MsixCap { 808 let msg_ctl = self.vfio_wrapper.read_config_word((cap + 2).into()); 809 810 let table = self.vfio_wrapper.read_config_dword((cap + 4).into()); 811 812 let pba = self.vfio_wrapper.read_config_dword((cap + 8).into()); 813 814 MsixCap { 815 msg_ctl, 816 table, 817 pba, 818 } 819 } 820 821 pub(crate) fn initialize_msix( 822 &mut self, 823 msix_cap: MsixCap, 824 cap_offset: u32, 825 bdf: PciBdf, 826 state: Option<MsixConfigState>, 827 ) { 828 let interrupt_source_group = self 829 .msi_interrupt_manager 830 .create_group(MsiIrqGroupConfig { 831 base: 0, 832 count: msix_cap.table_size() as InterruptIndex, 833 }) 834 .unwrap(); 835 836 let msix_config = MsixConfig::new( 837 msix_cap.table_size(), 838 interrupt_source_group.clone(), 839 bdf.into(), 840 state, 841 ) 842 .unwrap(); 843 844 self.interrupt.msix = Some(VfioMsix { 845 bar: msix_config, 846 cap: msix_cap, 847 cap_offset, 848 interrupt_source_group, 849 }); 850 } 851 852 pub(crate) fn parse_msi_capabilities(&mut self, cap: u8) -> u16 { 853 self.vfio_wrapper.read_config_word((cap + 2).into()) 854 } 855 856 pub(crate) fn initialize_msi( 857 &mut self, 858 msg_ctl: u16, 859 cap_offset: u32, 860 state: Option<MsiConfigState>, 861 ) { 862 let interrupt_source_group = self 863 .msi_interrupt_manager 864 .create_group(MsiIrqGroupConfig { 865 base: 0, 866 count: msi_num_enabled_vectors(msg_ctl) as InterruptIndex, 867 }) 868 .unwrap(); 869 870 let msi_config = MsiConfig::new(msg_ctl, interrupt_source_group.clone(), state).unwrap(); 871 872 self.interrupt.msi = Some(VfioMsi { 873 cfg: msi_config, 874 cap_offset, 875 interrupt_source_group, 876 }); 877 } 878 879 pub(crate) fn get_msix_cap_idx(&self) -> Option<usize> { 880 let mut cap_next = self 881 .vfio_wrapper 882 .read_config_byte(PCI_CONFIG_CAPABILITY_OFFSET); 883 884 while cap_next != 0 { 885 let cap_id = self.vfio_wrapper.read_config_byte(cap_next.into()); 886 if PciCapabilityId::from(cap_id) == PciCapabilityId::MsiX { 887 return Some(cap_next as usize); 888 } else { 889 cap_next = self.vfio_wrapper.read_config_byte((cap_next + 1).into()); 890 } 891 } 892 893 None 894 } 895 896 pub(crate) fn parse_capabilities(&mut self, bdf: PciBdf) { 897 let mut cap_iter = self 898 .vfio_wrapper 899 .read_config_byte(PCI_CONFIG_CAPABILITY_OFFSET); 900 901 let mut pci_express_cap_found = false; 902 let mut power_management_cap_found = false; 903 904 while cap_iter != 0 { 905 let cap_id = self.vfio_wrapper.read_config_byte(cap_iter.into()); 906 907 match PciCapabilityId::from(cap_id) { 908 PciCapabilityId::MessageSignalledInterrupts => { 909 if let Some(irq_info) = self.vfio_wrapper.get_irq_info(VFIO_PCI_MSI_IRQ_INDEX) { 910 if irq_info.count > 0 { 911 // Parse capability only if the VFIO device 912 // supports MSI. 913 let msg_ctl = self.parse_msi_capabilities(cap_iter); 914 self.initialize_msi(msg_ctl, cap_iter as u32, None); 915 } 916 } 917 } 918 PciCapabilityId::MsiX => { 919 if let Some(irq_info) = self.vfio_wrapper.get_irq_info(VFIO_PCI_MSIX_IRQ_INDEX) 920 { 921 if irq_info.count > 0 { 922 // Parse capability only if the VFIO device 923 // supports MSI-X. 924 let msix_cap = self.parse_msix_capabilities(cap_iter); 925 self.initialize_msix(msix_cap, cap_iter as u32, bdf, None); 926 } 927 } 928 } 929 PciCapabilityId::PciExpress => pci_express_cap_found = true, 930 PciCapabilityId::PowerManagement => power_management_cap_found = true, 931 _ => {} 932 }; 933 934 let cap_next = self.vfio_wrapper.read_config_byte((cap_iter + 1).into()); 935 if cap_next == 0 { 936 break; 937 } 938 939 cap_iter = cap_next; 940 } 941 942 if let Some(clique_id) = self.x_nv_gpudirect_clique { 943 self.add_nv_gpudirect_clique_cap(cap_iter, clique_id); 944 } 945 946 if pci_express_cap_found && power_management_cap_found { 947 self.parse_extended_capabilities(); 948 } 949 } 950 951 fn add_nv_gpudirect_clique_cap(&mut self, cap_iter: u8, clique_id: u8) { 952 // Turing, Ampere, Hopper, and Lovelace GPUs have dedicated space 953 // at 0xD4 for this capability. 954 let cap_offset = 0xd4u32; 955 956 let reg_idx = (cap_iter / 4) as usize; 957 self.patches.insert( 958 reg_idx, 959 ConfigPatch { 960 mask: 0x0000_ff00, 961 patch: cap_offset << 8, 962 }, 963 ); 964 965 let reg_idx = (cap_offset / 4) as usize; 966 self.patches.insert( 967 reg_idx, 968 ConfigPatch { 969 mask: 0xffff_ffff, 970 patch: 0x50080009u32, 971 }, 972 ); 973 self.patches.insert( 974 reg_idx + 1, 975 ConfigPatch { 976 mask: 0xffff_ffff, 977 patch: (u32::from(clique_id) << 19) | 0x5032, 978 }, 979 ); 980 } 981 982 fn parse_extended_capabilities(&mut self) { 983 let mut current_offset = PCI_CONFIG_EXTENDED_CAPABILITY_OFFSET; 984 985 loop { 986 let ext_cap_hdr = self.vfio_wrapper.read_config_dword(current_offset); 987 988 let cap_id: u16 = (ext_cap_hdr & 0xffff) as u16; 989 let cap_next: u16 = ((ext_cap_hdr >> 20) & 0xfff) as u16; 990 991 match PciExpressCapabilityId::from(cap_id) { 992 PciExpressCapabilityId::AlternativeRoutingIdentificationInterpretation 993 | PciExpressCapabilityId::ResizeableBar 994 | PciExpressCapabilityId::SingleRootIoVirtualization => { 995 let reg_idx = (current_offset / 4) as usize; 996 self.patches.insert( 997 reg_idx, 998 ConfigPatch { 999 mask: 0x0000_ffff, 1000 patch: PciExpressCapabilityId::NullCapability as u32, 1001 }, 1002 ); 1003 } 1004 _ => {} 1005 } 1006 1007 if cap_next == 0 { 1008 break; 1009 } 1010 1011 current_offset = cap_next.into(); 1012 } 1013 } 1014 1015 pub(crate) fn enable_intx(&mut self) -> Result<(), VfioPciError> { 1016 if let Some(intx) = &mut self.interrupt.intx { 1017 if !intx.enabled { 1018 if let Some(eventfd) = intx.interrupt_source_group.notifier(0) { 1019 self.vfio_wrapper 1020 .enable_irq(VFIO_PCI_INTX_IRQ_INDEX, vec![&eventfd]) 1021 .map_err(VfioPciError::EnableIntx)?; 1022 1023 intx.enabled = true; 1024 } else { 1025 return Err(VfioPciError::MissingNotifier); 1026 } 1027 } 1028 } 1029 1030 Ok(()) 1031 } 1032 1033 pub(crate) fn disable_intx(&mut self) { 1034 if let Some(intx) = &mut self.interrupt.intx { 1035 if intx.enabled { 1036 if let Err(e) = self.vfio_wrapper.disable_irq(VFIO_PCI_INTX_IRQ_INDEX) { 1037 error!("Could not disable INTx: {}", e); 1038 } else { 1039 intx.enabled = false; 1040 } 1041 } 1042 } 1043 } 1044 1045 pub(crate) fn enable_msi(&self) -> Result<(), VfioPciError> { 1046 if let Some(msi) = &self.interrupt.msi { 1047 let mut irq_fds: Vec<EventFd> = Vec::new(); 1048 for i in 0..msi.cfg.num_enabled_vectors() { 1049 if let Some(eventfd) = msi.interrupt_source_group.notifier(i as InterruptIndex) { 1050 irq_fds.push(eventfd); 1051 } else { 1052 return Err(VfioPciError::MissingNotifier); 1053 } 1054 } 1055 1056 self.vfio_wrapper 1057 .enable_msi(irq_fds.iter().collect()) 1058 .map_err(VfioPciError::EnableMsi)?; 1059 } 1060 1061 Ok(()) 1062 } 1063 1064 pub(crate) fn disable_msi(&self) { 1065 if let Err(e) = self.vfio_wrapper.disable_msi() { 1066 error!("Could not disable MSI: {}", e); 1067 } 1068 } 1069 1070 pub(crate) fn enable_msix(&self) -> Result<(), VfioPciError> { 1071 if let Some(msix) = &self.interrupt.msix { 1072 let mut irq_fds: Vec<EventFd> = Vec::new(); 1073 for i in 0..msix.bar.table_entries.len() { 1074 if let Some(eventfd) = msix.interrupt_source_group.notifier(i as InterruptIndex) { 1075 irq_fds.push(eventfd); 1076 } else { 1077 return Err(VfioPciError::MissingNotifier); 1078 } 1079 } 1080 1081 self.vfio_wrapper 1082 .enable_msix(irq_fds.iter().collect()) 1083 .map_err(VfioPciError::EnableMsix)?; 1084 } 1085 1086 Ok(()) 1087 } 1088 1089 pub(crate) fn disable_msix(&self) { 1090 if let Err(e) = self.vfio_wrapper.disable_msix() { 1091 error!("Could not disable MSI-X: {}", e); 1092 } 1093 } 1094 1095 pub(crate) fn initialize_legacy_interrupt(&mut self) -> Result<(), VfioPciError> { 1096 if let Some(irq_info) = self.vfio_wrapper.get_irq_info(VFIO_PCI_INTX_IRQ_INDEX) { 1097 if irq_info.count == 0 { 1098 // A count of 0 means the INTx IRQ is not supported, therefore 1099 // it shouldn't be initialized. 1100 return Ok(()); 1101 } 1102 } 1103 1104 if let Some(interrupt_source_group) = self.legacy_interrupt_group.clone() { 1105 self.interrupt.intx = Some(VfioIntx { 1106 interrupt_source_group, 1107 enabled: false, 1108 }); 1109 1110 self.enable_intx()?; 1111 } 1112 1113 Ok(()) 1114 } 1115 1116 pub(crate) fn update_msi_capabilities( 1117 &mut self, 1118 offset: u64, 1119 data: &[u8], 1120 ) -> Result<(), VfioPciError> { 1121 match self.interrupt.update_msi(offset, data) { 1122 Some(InterruptUpdateAction::EnableMsi) => { 1123 // Disable INTx before we can enable MSI 1124 self.disable_intx(); 1125 self.enable_msi()?; 1126 } 1127 Some(InterruptUpdateAction::DisableMsi) => { 1128 // Fallback onto INTx when disabling MSI 1129 self.disable_msi(); 1130 self.enable_intx()?; 1131 } 1132 _ => {} 1133 } 1134 1135 Ok(()) 1136 } 1137 1138 pub(crate) fn update_msix_capabilities( 1139 &mut self, 1140 offset: u64, 1141 data: &[u8], 1142 ) -> Result<(), VfioPciError> { 1143 match self.interrupt.update_msix(offset, data) { 1144 Some(InterruptUpdateAction::EnableMsix) => { 1145 // Disable INTx before we can enable MSI-X 1146 self.disable_intx(); 1147 self.enable_msix()?; 1148 } 1149 Some(InterruptUpdateAction::DisableMsix) => { 1150 // Fallback onto INTx when disabling MSI-X 1151 self.disable_msix(); 1152 self.enable_intx()?; 1153 } 1154 _ => {} 1155 } 1156 1157 Ok(()) 1158 } 1159 1160 pub(crate) fn find_region(&self, addr: u64) -> Option<MmioRegion> { 1161 for region in self.mmio_regions.iter() { 1162 if addr >= region.start.raw_value() 1163 && addr < region.start.unchecked_add(region.length).raw_value() 1164 { 1165 return Some(region.clone()); 1166 } 1167 } 1168 None 1169 } 1170 1171 pub(crate) fn read_bar(&mut self, base: u64, offset: u64, data: &mut [u8]) { 1172 let addr = base + offset; 1173 if let Some(region) = self.find_region(addr) { 1174 let offset = addr - region.start.raw_value(); 1175 1176 if self.interrupt.msix_table_accessed(region.index, offset) { 1177 self.interrupt.msix_read_table(offset, data); 1178 } else { 1179 self.vfio_wrapper.region_read(region.index, offset, data); 1180 } 1181 } 1182 1183 // INTx EOI 1184 // The guest reading from the BAR potentially means the interrupt has 1185 // been received and can be acknowledged. 1186 if self.interrupt.intx_in_use() { 1187 if let Err(e) = self.vfio_wrapper.unmask_irq(VFIO_PCI_INTX_IRQ_INDEX) { 1188 error!("Failed unmasking INTx IRQ: {}", e); 1189 } 1190 } 1191 } 1192 1193 pub(crate) fn write_bar( 1194 &mut self, 1195 base: u64, 1196 offset: u64, 1197 data: &[u8], 1198 ) -> Option<Arc<Barrier>> { 1199 let addr = base + offset; 1200 if let Some(region) = self.find_region(addr) { 1201 let offset = addr - region.start.raw_value(); 1202 1203 // If the MSI-X table is written to, we need to update our cache. 1204 if self.interrupt.msix_table_accessed(region.index, offset) { 1205 self.interrupt.msix_write_table(offset, data); 1206 } else { 1207 self.vfio_wrapper.region_write(region.index, offset, data); 1208 } 1209 } 1210 1211 // INTx EOI 1212 // The guest writing to the BAR potentially means the interrupt has 1213 // been received and can be acknowledged. 1214 if self.interrupt.intx_in_use() { 1215 if let Err(e) = self.vfio_wrapper.unmask_irq(VFIO_PCI_INTX_IRQ_INDEX) { 1216 error!("Failed unmasking INTx IRQ: {}", e); 1217 } 1218 } 1219 1220 None 1221 } 1222 1223 pub(crate) fn write_config_register( 1224 &mut self, 1225 reg_idx: usize, 1226 offset: u64, 1227 data: &[u8], 1228 ) -> Option<Arc<Barrier>> { 1229 // When the guest wants to write to a BAR, we trap it into 1230 // our local configuration space. We're not reprogramming 1231 // VFIO device. 1232 if (PCI_CONFIG_BAR0_INDEX..PCI_CONFIG_BAR0_INDEX + BAR_NUMS).contains(®_idx) 1233 || reg_idx == PCI_ROM_EXP_BAR_INDEX 1234 { 1235 // We keep our local cache updated with the BARs. 1236 // We'll read it back from there when the guest is asking 1237 // for BARs (see read_config_register()). 1238 self.configuration 1239 .write_config_register(reg_idx, offset, data); 1240 return None; 1241 } 1242 1243 let reg = (reg_idx * PCI_CONFIG_REGISTER_SIZE) as u64; 1244 1245 // If the MSI or MSI-X capabilities are accessed, we need to 1246 // update our local cache accordingly. 1247 // Depending on how the capabilities are modified, this could 1248 // trigger a VFIO MSI or MSI-X toggle. 1249 if let Some((cap_id, cap_base)) = self.interrupt.accessed(reg) { 1250 let cap_offset: u64 = reg - cap_base + offset; 1251 match cap_id { 1252 PciCapabilityId::MessageSignalledInterrupts => { 1253 if let Err(e) = self.update_msi_capabilities(cap_offset, data) { 1254 error!("Could not update MSI capabilities: {}", e); 1255 } 1256 } 1257 PciCapabilityId::MsiX => { 1258 if let Err(e) = self.update_msix_capabilities(cap_offset, data) { 1259 error!("Could not update MSI-X capabilities: {}", e); 1260 } 1261 } 1262 _ => {} 1263 } 1264 } 1265 1266 // Make sure to write to the device's PCI config space after MSI/MSI-X 1267 // interrupts have been enabled/disabled. In case of MSI, when the 1268 // interrupts are enabled through VFIO (using VFIO_DEVICE_SET_IRQS), 1269 // the MSI Enable bit in the MSI capability structure found in the PCI 1270 // config space is disabled by default. That's why when the guest is 1271 // enabling this bit, we first need to enable the MSI interrupts with 1272 // VFIO through VFIO_DEVICE_SET_IRQS ioctl, and only after we can write 1273 // to the device region to update the MSI Enable bit. 1274 self.vfio_wrapper.write_config((reg + offset) as u32, data); 1275 1276 None 1277 } 1278 1279 pub(crate) fn read_config_register(&mut self, reg_idx: usize) -> u32 { 1280 // When reading the BARs, we trap it and return what comes 1281 // from our local configuration space. We want the guest to 1282 // use that and not the VFIO device BARs as it does not map 1283 // with the guest address space. 1284 if (PCI_CONFIG_BAR0_INDEX..PCI_CONFIG_BAR0_INDEX + BAR_NUMS).contains(®_idx) 1285 || reg_idx == PCI_ROM_EXP_BAR_INDEX 1286 { 1287 return self.configuration.read_reg(reg_idx); 1288 } 1289 1290 if let Some(id) = self.get_msix_cap_idx() { 1291 let msix = self.interrupt.msix.as_mut().unwrap(); 1292 if reg_idx * 4 == id + 4 { 1293 return msix.cap.table; 1294 } else if reg_idx * 4 == id + 8 { 1295 return msix.cap.pba; 1296 } 1297 } 1298 1299 // Since we don't support passing multi-functions devices, we should 1300 // mask the multi-function bit, bit 7 of the Header Type byte on the 1301 // register 3. 1302 let mask = if reg_idx == PCI_HEADER_TYPE_REG_INDEX { 1303 0xff7f_ffff 1304 } else { 1305 0xffff_ffff 1306 }; 1307 1308 // The config register read comes from the VFIO device itself. 1309 let mut value = self.vfio_wrapper.read_config_dword((reg_idx * 4) as u32) & mask; 1310 1311 if let Some(config_patch) = self.patches.get(®_idx) { 1312 value = (value & !config_patch.mask) | config_patch.patch; 1313 } 1314 1315 value 1316 } 1317 1318 fn state(&self) -> VfioCommonState { 1319 let intx_state = self.interrupt.intx.as_ref().map(|intx| IntxState { 1320 enabled: intx.enabled, 1321 }); 1322 1323 let msi_state = self.interrupt.msi.as_ref().map(|msi| MsiState { 1324 cap: msi.cfg.cap, 1325 cap_offset: msi.cap_offset, 1326 }); 1327 1328 let msix_state = self.interrupt.msix.as_ref().map(|msix| MsixState { 1329 cap: msix.cap, 1330 cap_offset: msix.cap_offset, 1331 bdf: msix.bar.devid, 1332 }); 1333 1334 VfioCommonState { 1335 intx_state, 1336 msi_state, 1337 msix_state, 1338 } 1339 } 1340 1341 fn set_state( 1342 &mut self, 1343 state: &VfioCommonState, 1344 msi_state: Option<MsiConfigState>, 1345 msix_state: Option<MsixConfigState>, 1346 ) -> Result<(), VfioPciError> { 1347 if let (Some(intx), Some(interrupt_source_group)) = 1348 (&state.intx_state, self.legacy_interrupt_group.clone()) 1349 { 1350 self.interrupt.intx = Some(VfioIntx { 1351 interrupt_source_group, 1352 enabled: false, 1353 }); 1354 1355 if intx.enabled { 1356 self.enable_intx()?; 1357 } 1358 } 1359 1360 if let Some(msi) = &state.msi_state { 1361 self.initialize_msi(msi.cap.msg_ctl, msi.cap_offset, msi_state); 1362 } 1363 1364 if let Some(msix) = &state.msix_state { 1365 self.initialize_msix(msix.cap, msix.cap_offset, msix.bdf.into(), msix_state); 1366 } 1367 1368 Ok(()) 1369 } 1370 } 1371 1372 impl Pausable for VfioCommon {} 1373 1374 impl Snapshottable for VfioCommon { 1375 fn id(&self) -> String { 1376 String::from(VFIO_COMMON_ID) 1377 } 1378 1379 fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> { 1380 let mut vfio_common_snapshot = Snapshot::new_from_state(&self.state())?; 1381 1382 // Snapshot PciConfiguration 1383 vfio_common_snapshot.add_snapshot(self.configuration.id(), self.configuration.snapshot()?); 1384 1385 // Snapshot MSI 1386 if let Some(msi) = &mut self.interrupt.msi { 1387 vfio_common_snapshot.add_snapshot(msi.cfg.id(), msi.cfg.snapshot()?); 1388 } 1389 1390 // Snapshot MSI-X 1391 if let Some(msix) = &mut self.interrupt.msix { 1392 vfio_common_snapshot.add_snapshot(msix.bar.id(), msix.bar.snapshot()?); 1393 } 1394 1395 Ok(vfio_common_snapshot) 1396 } 1397 } 1398 1399 /// VfioPciDevice represents a VFIO PCI device. 1400 /// This structure implements the BusDevice and PciDevice traits. 1401 /// 1402 /// A VfioPciDevice is bound to a VfioDevice and is also a PCI device. 1403 /// The VMM creates a VfioDevice, then assigns it to a VfioPciDevice, 1404 /// which then gets added to the PCI bus. 1405 pub struct VfioPciDevice { 1406 id: String, 1407 vm: Arc<dyn hypervisor::Vm>, 1408 device: Arc<VfioDevice>, 1409 container: Arc<VfioContainer>, 1410 common: VfioCommon, 1411 iommu_attached: bool, 1412 memory_slot_allocator: MemorySlotAllocator, 1413 } 1414 1415 impl VfioPciDevice { 1416 /// Constructs a new Vfio Pci device for the given Vfio device 1417 #[allow(clippy::too_many_arguments)] 1418 pub fn new( 1419 id: String, 1420 vm: &Arc<dyn hypervisor::Vm>, 1421 device: VfioDevice, 1422 container: Arc<VfioContainer>, 1423 msi_interrupt_manager: Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, 1424 legacy_interrupt_group: Option<Arc<dyn InterruptSourceGroup>>, 1425 iommu_attached: bool, 1426 bdf: PciBdf, 1427 memory_slot_allocator: MemorySlotAllocator, 1428 snapshot: Option<Snapshot>, 1429 x_nv_gpudirect_clique: Option<u8>, 1430 ) -> Result<Self, VfioPciError> { 1431 let device = Arc::new(device); 1432 device.reset(); 1433 1434 let vfio_wrapper = VfioDeviceWrapper::new(Arc::clone(&device)); 1435 1436 let common = VfioCommon::new( 1437 msi_interrupt_manager, 1438 legacy_interrupt_group, 1439 Arc::new(vfio_wrapper) as Arc<dyn Vfio>, 1440 &PciVfioSubclass::VfioSubclass, 1441 bdf, 1442 vm_migration::snapshot_from_id(snapshot.as_ref(), VFIO_COMMON_ID), 1443 x_nv_gpudirect_clique, 1444 )?; 1445 1446 let vfio_pci_device = VfioPciDevice { 1447 id, 1448 vm: vm.clone(), 1449 device, 1450 container, 1451 common, 1452 iommu_attached, 1453 memory_slot_allocator, 1454 }; 1455 1456 Ok(vfio_pci_device) 1457 } 1458 1459 pub fn iommu_attached(&self) -> bool { 1460 self.iommu_attached 1461 } 1462 1463 fn generate_sparse_areas( 1464 caps: &[VfioRegionInfoCap], 1465 region_index: u32, 1466 region_start: u64, 1467 region_size: u64, 1468 vfio_msix: Option<&VfioMsix>, 1469 ) -> Result<Vec<VfioRegionSparseMmapArea>, VfioPciError> { 1470 for cap in caps { 1471 match cap { 1472 VfioRegionInfoCap::SparseMmap(sparse_mmap) => return Ok(sparse_mmap.areas.clone()), 1473 VfioRegionInfoCap::MsixMappable => { 1474 if !is_4k_aligned(region_start) { 1475 error!( 1476 "Region start address 0x{:x} must be at least aligned on 4KiB", 1477 region_start 1478 ); 1479 return Err(VfioPciError::RegionAlignment); 1480 } 1481 if !is_4k_multiple(region_size) { 1482 error!( 1483 "Region size 0x{:x} must be at least a multiple of 4KiB", 1484 region_size 1485 ); 1486 return Err(VfioPciError::RegionSize); 1487 } 1488 1489 // In case the region contains the MSI-X vectors table or 1490 // the MSI-X PBA table, we must calculate the subregions 1491 // around them, leading to a list of sparse areas. 1492 // We want to make sure we will still trap MMIO accesses 1493 // to these MSI-X specific ranges. If these region don't align 1494 // with pagesize, we can achieve it by enlarging its range. 1495 // 1496 // Using a BtreeMap as the list provided through the iterator is sorted 1497 // by key. This ensures proper split of the whole region. 1498 let mut inter_ranges = BTreeMap::new(); 1499 if let Some(msix) = vfio_msix { 1500 if region_index == msix.cap.table_bir() { 1501 let (offset, size) = msix.cap.table_range(); 1502 let offset = align_page_size_down(offset); 1503 let size = align_page_size_up(size); 1504 inter_ranges.insert(offset, size); 1505 } 1506 if region_index == msix.cap.pba_bir() { 1507 let (offset, size) = msix.cap.pba_range(); 1508 let offset = align_page_size_down(offset); 1509 let size = align_page_size_up(size); 1510 inter_ranges.insert(offset, size); 1511 } 1512 } 1513 1514 let mut sparse_areas = Vec::new(); 1515 let mut current_offset = 0; 1516 for (range_offset, range_size) in inter_ranges { 1517 if range_offset > current_offset { 1518 sparse_areas.push(VfioRegionSparseMmapArea { 1519 offset: current_offset, 1520 size: range_offset - current_offset, 1521 }); 1522 } 1523 current_offset = align_page_size_down(range_offset + range_size); 1524 } 1525 1526 if region_size > current_offset { 1527 sparse_areas.push(VfioRegionSparseMmapArea { 1528 offset: current_offset, 1529 size: region_size - current_offset, 1530 }); 1531 } 1532 1533 return Ok(sparse_areas); 1534 } 1535 _ => {} 1536 } 1537 } 1538 1539 // In case no relevant capabilities have been found, create a single 1540 // sparse area corresponding to the entire MMIO region. 1541 Ok(vec![VfioRegionSparseMmapArea { 1542 offset: 0, 1543 size: region_size, 1544 }]) 1545 } 1546 1547 /// Map MMIO regions into the guest, and avoid VM exits when the guest tries 1548 /// to reach those regions. 1549 /// 1550 /// # Arguments 1551 /// 1552 /// * `vm` - The VM object. It is used to set the VFIO MMIO regions 1553 /// as user memory regions. 1554 /// * `mem_slot` - The closure to return a memory slot. 1555 pub fn map_mmio_regions(&mut self) -> Result<(), VfioPciError> { 1556 let fd = self.device.as_raw_fd(); 1557 1558 for region in self.common.mmio_regions.iter_mut() { 1559 let region_flags = self.device.get_region_flags(region.index); 1560 if region_flags & VFIO_REGION_INFO_FLAG_MMAP != 0 { 1561 let mut prot = 0; 1562 if region_flags & VFIO_REGION_INFO_FLAG_READ != 0 { 1563 prot |= libc::PROT_READ; 1564 } 1565 if region_flags & VFIO_REGION_INFO_FLAG_WRITE != 0 { 1566 prot |= libc::PROT_WRITE; 1567 } 1568 1569 // Retrieve the list of capabilities found on the region 1570 let caps = if region_flags & VFIO_REGION_INFO_FLAG_CAPS != 0 { 1571 self.device.get_region_caps(region.index) 1572 } else { 1573 Vec::new() 1574 }; 1575 1576 // Don't try to mmap the region if it contains MSI-X table or 1577 // MSI-X PBA subregion, and if we couldn't find MSIX_MAPPABLE 1578 // in the list of supported capabilities. 1579 if let Some(msix) = self.common.interrupt.msix.as_ref() { 1580 if (region.index == msix.cap.table_bir() || region.index == msix.cap.pba_bir()) 1581 && !caps.contains(&VfioRegionInfoCap::MsixMappable) 1582 { 1583 continue; 1584 } 1585 } 1586 1587 let mmap_size = self.device.get_region_size(region.index); 1588 let mmap_offset = self.device.get_region_offset(region.index); 1589 1590 let sparse_areas = Self::generate_sparse_areas( 1591 &caps, 1592 region.index, 1593 region.start.0, 1594 mmap_size, 1595 self.common.interrupt.msix.as_ref(), 1596 )?; 1597 1598 for area in sparse_areas.iter() { 1599 // SAFETY: FFI call with correct arguments 1600 let host_addr = unsafe { 1601 libc::mmap( 1602 null_mut(), 1603 area.size as usize, 1604 prot, 1605 libc::MAP_SHARED, 1606 fd, 1607 mmap_offset as libc::off_t + area.offset as libc::off_t, 1608 ) 1609 }; 1610 1611 if host_addr == libc::MAP_FAILED { 1612 error!( 1613 "Could not mmap sparse area (offset = 0x{:x}, size = 0x{:x}): {}", 1614 area.offset, 1615 area.size, 1616 std::io::Error::last_os_error() 1617 ); 1618 return Err(VfioPciError::MmapArea); 1619 } 1620 1621 if !is_page_size_aligned(area.size) || !is_page_size_aligned(area.offset) { 1622 warn!( 1623 "Could not mmap sparse area that is not page size aligned (offset = 0x{:x}, size = 0x{:x})", 1624 area.offset, 1625 area.size, 1626 ); 1627 return Ok(()); 1628 } 1629 1630 let user_memory_region = UserMemoryRegion { 1631 slot: self.memory_slot_allocator.next_memory_slot(), 1632 start: region.start.0 + area.offset, 1633 size: area.size, 1634 host_addr: host_addr as u64, 1635 }; 1636 1637 region.user_memory_regions.push(user_memory_region); 1638 1639 let mem_region = self.vm.make_user_memory_region( 1640 user_memory_region.slot, 1641 user_memory_region.start, 1642 user_memory_region.size, 1643 user_memory_region.host_addr, 1644 false, 1645 false, 1646 ); 1647 1648 self.vm 1649 .create_user_memory_region(mem_region) 1650 .map_err(VfioPciError::CreateUserMemoryRegion)?; 1651 1652 if !self.iommu_attached { 1653 self.container 1654 .vfio_dma_map( 1655 user_memory_region.start, 1656 user_memory_region.size, 1657 user_memory_region.host_addr, 1658 ) 1659 .map_err(VfioPciError::DmaMap)?; 1660 } 1661 } 1662 } 1663 } 1664 1665 Ok(()) 1666 } 1667 1668 pub fn unmap_mmio_regions(&mut self) { 1669 for region in self.common.mmio_regions.iter() { 1670 for user_memory_region in region.user_memory_regions.iter() { 1671 // Unmap from vfio container 1672 if !self.iommu_attached { 1673 if let Err(e) = self 1674 .container 1675 .vfio_dma_unmap(user_memory_region.start, user_memory_region.size) 1676 { 1677 error!("Could not unmap mmio region from vfio container: {}", e); 1678 } 1679 } 1680 1681 // Remove region 1682 let r = self.vm.make_user_memory_region( 1683 user_memory_region.slot, 1684 user_memory_region.start, 1685 user_memory_region.size, 1686 user_memory_region.host_addr, 1687 false, 1688 false, 1689 ); 1690 1691 if let Err(e) = self.vm.remove_user_memory_region(r) { 1692 error!("Could not remove the userspace memory region: {}", e); 1693 } 1694 1695 self.memory_slot_allocator 1696 .free_memory_slot(user_memory_region.slot); 1697 1698 // SAFETY: FFI call with correct arguments 1699 let ret = unsafe { 1700 libc::munmap( 1701 user_memory_region.host_addr as *mut libc::c_void, 1702 user_memory_region.size as usize, 1703 ) 1704 }; 1705 if ret != 0 { 1706 error!( 1707 "Could not unmap region {}, error:{}", 1708 region.index, 1709 io::Error::last_os_error() 1710 ); 1711 } 1712 } 1713 } 1714 } 1715 1716 pub fn dma_map(&self, iova: u64, size: u64, user_addr: u64) -> Result<(), VfioPciError> { 1717 if !self.iommu_attached { 1718 self.container 1719 .vfio_dma_map(iova, size, user_addr) 1720 .map_err(VfioPciError::DmaMap)?; 1721 } 1722 1723 Ok(()) 1724 } 1725 1726 pub fn dma_unmap(&self, iova: u64, size: u64) -> Result<(), VfioPciError> { 1727 if !self.iommu_attached { 1728 self.container 1729 .vfio_dma_unmap(iova, size) 1730 .map_err(VfioPciError::DmaUnmap)?; 1731 } 1732 1733 Ok(()) 1734 } 1735 1736 pub fn mmio_regions(&self) -> Vec<MmioRegion> { 1737 self.common.mmio_regions.clone() 1738 } 1739 } 1740 1741 impl Drop for VfioPciDevice { 1742 fn drop(&mut self) { 1743 self.unmap_mmio_regions(); 1744 1745 if let Some(msix) = &self.common.interrupt.msix { 1746 if msix.bar.enabled() { 1747 self.common.disable_msix(); 1748 } 1749 } 1750 1751 if let Some(msi) = &self.common.interrupt.msi { 1752 if msi.cfg.enabled() { 1753 self.common.disable_msi() 1754 } 1755 } 1756 1757 if self.common.interrupt.intx_in_use() { 1758 self.common.disable_intx(); 1759 } 1760 } 1761 } 1762 1763 impl BusDevice for VfioPciDevice { 1764 fn read(&mut self, base: u64, offset: u64, data: &mut [u8]) { 1765 self.read_bar(base, offset, data) 1766 } 1767 1768 fn write(&mut self, base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> { 1769 self.write_bar(base, offset, data) 1770 } 1771 } 1772 1773 // First BAR offset in the PCI config space. 1774 const PCI_CONFIG_BAR_OFFSET: u32 = 0x10; 1775 // Capability register offset in the PCI config space. 1776 const PCI_CONFIG_CAPABILITY_OFFSET: u32 = 0x34; 1777 // Extended capabilities register offset in the PCI config space. 1778 const PCI_CONFIG_EXTENDED_CAPABILITY_OFFSET: u32 = 0x100; 1779 // IO BAR when first BAR bit is 1. 1780 const PCI_CONFIG_IO_BAR: u32 = 0x1; 1781 // 64-bit memory bar flag. 1782 const PCI_CONFIG_MEMORY_BAR_64BIT: u32 = 0x4; 1783 // Prefetchable BAR bit 1784 const PCI_CONFIG_BAR_PREFETCHABLE: u32 = 0x8; 1785 // PCI config register size (4 bytes). 1786 const PCI_CONFIG_REGISTER_SIZE: usize = 4; 1787 // Number of BARs for a PCI device 1788 const BAR_NUMS: usize = 6; 1789 // PCI Header Type register index 1790 const PCI_HEADER_TYPE_REG_INDEX: usize = 3; 1791 // First BAR register index 1792 const PCI_CONFIG_BAR0_INDEX: usize = 4; 1793 // PCI ROM expansion BAR register index 1794 const PCI_ROM_EXP_BAR_INDEX: usize = 12; 1795 1796 impl PciDevice for VfioPciDevice { 1797 fn allocate_bars( 1798 &mut self, 1799 allocator: &Arc<Mutex<SystemAllocator>>, 1800 mmio32_allocator: &mut AddressAllocator, 1801 mmio64_allocator: &mut AddressAllocator, 1802 resources: Option<Vec<Resource>>, 1803 ) -> Result<Vec<PciBarConfiguration>, PciDeviceError> { 1804 self.common 1805 .allocate_bars(allocator, mmio32_allocator, mmio64_allocator, resources) 1806 } 1807 1808 fn free_bars( 1809 &mut self, 1810 allocator: &mut SystemAllocator, 1811 mmio32_allocator: &mut AddressAllocator, 1812 mmio64_allocator: &mut AddressAllocator, 1813 ) -> Result<(), PciDeviceError> { 1814 self.common 1815 .free_bars(allocator, mmio32_allocator, mmio64_allocator) 1816 } 1817 1818 fn write_config_register( 1819 &mut self, 1820 reg_idx: usize, 1821 offset: u64, 1822 data: &[u8], 1823 ) -> Option<Arc<Barrier>> { 1824 self.common.write_config_register(reg_idx, offset, data) 1825 } 1826 1827 fn read_config_register(&mut self, reg_idx: usize) -> u32 { 1828 self.common.read_config_register(reg_idx) 1829 } 1830 1831 fn detect_bar_reprogramming( 1832 &mut self, 1833 reg_idx: usize, 1834 data: &[u8], 1835 ) -> Option<BarReprogrammingParams> { 1836 self.common 1837 .configuration 1838 .detect_bar_reprogramming(reg_idx, data) 1839 } 1840 1841 fn read_bar(&mut self, base: u64, offset: u64, data: &mut [u8]) { 1842 self.common.read_bar(base, offset, data) 1843 } 1844 1845 fn write_bar(&mut self, base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> { 1846 self.common.write_bar(base, offset, data) 1847 } 1848 1849 fn move_bar(&mut self, old_base: u64, new_base: u64) -> Result<(), io::Error> { 1850 for region in self.common.mmio_regions.iter_mut() { 1851 if region.start.raw_value() == old_base { 1852 region.start = GuestAddress(new_base); 1853 1854 for user_memory_region in region.user_memory_regions.iter_mut() { 1855 // Remove old region 1856 let old_mem_region = self.vm.make_user_memory_region( 1857 user_memory_region.slot, 1858 user_memory_region.start, 1859 user_memory_region.size, 1860 user_memory_region.host_addr, 1861 false, 1862 false, 1863 ); 1864 1865 self.vm 1866 .remove_user_memory_region(old_mem_region) 1867 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; 1868 1869 // Update the user memory region with the correct start address. 1870 if new_base > old_base { 1871 user_memory_region.start += new_base - old_base; 1872 } else { 1873 user_memory_region.start -= old_base - new_base; 1874 } 1875 1876 // Insert new region 1877 let new_mem_region = self.vm.make_user_memory_region( 1878 user_memory_region.slot, 1879 user_memory_region.start, 1880 user_memory_region.size, 1881 user_memory_region.host_addr, 1882 false, 1883 false, 1884 ); 1885 1886 self.vm 1887 .create_user_memory_region(new_mem_region) 1888 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; 1889 } 1890 } 1891 } 1892 1893 Ok(()) 1894 } 1895 1896 fn as_any(&mut self) -> &mut dyn Any { 1897 self 1898 } 1899 1900 fn id(&self) -> Option<String> { 1901 Some(self.id.clone()) 1902 } 1903 } 1904 1905 impl Pausable for VfioPciDevice {} 1906 1907 impl Snapshottable for VfioPciDevice { 1908 fn id(&self) -> String { 1909 self.id.clone() 1910 } 1911 1912 fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> { 1913 let mut vfio_pci_dev_snapshot = Snapshot::default(); 1914 1915 // Snapshot VfioCommon 1916 vfio_pci_dev_snapshot.add_snapshot(self.common.id(), self.common.snapshot()?); 1917 1918 Ok(vfio_pci_dev_snapshot) 1919 } 1920 } 1921 impl Transportable for VfioPciDevice {} 1922 impl Migratable for VfioPciDevice {} 1923 1924 /// This structure implements the ExternalDmaMapping trait. It is meant to 1925 /// be used when the caller tries to provide a way to update the mappings 1926 /// associated with a specific VFIO container. 1927 pub struct VfioDmaMapping<M: GuestAddressSpace> { 1928 container: Arc<VfioContainer>, 1929 memory: Arc<M>, 1930 mmio_regions: Arc<Mutex<Vec<MmioRegion>>>, 1931 } 1932 1933 impl<M: GuestAddressSpace> VfioDmaMapping<M> { 1934 /// Create a DmaMapping object. 1935 /// # Parameters 1936 /// * `container`: VFIO container object. 1937 /// * `memory`: guest memory to mmap. 1938 /// * `mmio_regions`: mmio_regions to mmap. 1939 pub fn new( 1940 container: Arc<VfioContainer>, 1941 memory: Arc<M>, 1942 mmio_regions: Arc<Mutex<Vec<MmioRegion>>>, 1943 ) -> Self { 1944 VfioDmaMapping { 1945 container, 1946 memory, 1947 mmio_regions, 1948 } 1949 } 1950 } 1951 1952 impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioDmaMapping<M> { 1953 fn map(&self, iova: u64, gpa: u64, size: u64) -> std::result::Result<(), io::Error> { 1954 let mem = self.memory.memory(); 1955 let guest_addr = GuestAddress(gpa); 1956 let user_addr = if mem.check_range(guest_addr, size as usize) { 1957 match mem.get_host_address(guest_addr) { 1958 Ok(t) => t as u64, 1959 Err(e) => { 1960 return Err(io::Error::new( 1961 io::ErrorKind::Other, 1962 format!("unable to retrieve user address for gpa 0x{gpa:x} from guest memory region: {e}") 1963 )); 1964 } 1965 } 1966 } else if self.mmio_regions.lock().unwrap().check_range(gpa, size) { 1967 self.mmio_regions.lock().unwrap().find_user_address(gpa)? 1968 } else { 1969 return Err(io::Error::new( 1970 io::ErrorKind::Other, 1971 format!("failed to locate guest address 0x{gpa:x} in guest memory"), 1972 )); 1973 }; 1974 1975 self.container 1976 .vfio_dma_map(iova, size, user_addr) 1977 .map_err(|e| { 1978 io::Error::new( 1979 io::ErrorKind::Other, 1980 format!( 1981 "failed to map memory for VFIO container, \ 1982 iova 0x{iova:x}, gpa 0x{gpa:x}, size 0x{size:x}: {e:?}" 1983 ), 1984 ) 1985 }) 1986 } 1987 1988 fn unmap(&self, iova: u64, size: u64) -> std::result::Result<(), io::Error> { 1989 self.container.vfio_dma_unmap(iova, size).map_err(|e| { 1990 io::Error::new( 1991 io::ErrorKind::Other, 1992 format!( 1993 "failed to unmap memory for VFIO container, \ 1994 iova 0x{iova:x}, size 0x{size:x}: {e:?}" 1995 ), 1996 ) 1997 }) 1998 } 1999 } 2000