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::path::PathBuf; 11 use std::ptr::null_mut; 12 use std::sync::{Arc, Barrier, Mutex}; 13 14 use anyhow::anyhow; 15 use byteorder::{ByteOrder, LittleEndian}; 16 use hypervisor::HypervisorVmError; 17 use libc::{sysconf, _SC_PAGESIZE}; 18 use serde::{Deserialize, Serialize}; 19 use thiserror::Error; 20 use vfio_bindings::bindings::vfio::*; 21 use vfio_ioctls::{ 22 VfioContainer, VfioDevice, VfioIrq, VfioRegionInfoCap, VfioRegionSparseMmapArea, 23 }; 24 use vm_allocator::page_size::{ 25 align_page_size_down, align_page_size_up, is_4k_aligned, is_4k_multiple, is_page_size_aligned, 26 }; 27 use vm_allocator::{AddressAllocator, MemorySlotAllocator, SystemAllocator}; 28 use vm_device::dma_mapping::ExternalDmaMapping; 29 use vm_device::interrupt::{ 30 InterruptIndex, InterruptManager, InterruptSourceGroup, MsiIrqGroupConfig, 31 }; 32 use vm_device::{BusDevice, Resource}; 33 use vm_memory::{Address, GuestAddress, GuestAddressSpace, GuestMemory, GuestUsize}; 34 use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; 35 use vmm_sys_util::eventfd::EventFd; 36 37 use crate::msi::{MsiConfigState, MSI_CONFIG_ID}; 38 use crate::msix::MsixConfigState; 39 use crate::{ 40 msi_num_enabled_vectors, BarReprogrammingParams, MsiCap, MsiConfig, MsixCap, MsixConfig, 41 PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciCapabilityId, 42 PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciExpressCapabilityId, 43 PciHeaderType, PciSubclass, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, PCI_CONFIGURATION_ID, 44 }; 45 46 pub(crate) const VFIO_COMMON_ID: &str = "vfio_common"; 47 48 #[derive(Debug, Error)] 49 pub enum VfioPciError { 50 #[error("Failed to create user memory region: {0}")] 51 CreateUserMemoryRegion(#[source] HypervisorVmError), 52 #[error("Failed to DMA map: {0} for device {1} (guest BDF: {2})")] 53 DmaMap(#[source] vfio_ioctls::VfioError, PathBuf, PciBdf), 54 #[error("Failed to DMA unmap: {0} for device {1} (guest BDF: {2})")] 55 DmaUnmap(#[source] vfio_ioctls::VfioError, PathBuf, PciBdf), 56 #[error("Failed to enable INTx: {0}")] 57 EnableIntx(#[source] VfioError), 58 #[error("Failed to enable MSI: {0}")] 59 EnableMsi(#[source] VfioError), 60 #[error("Failed to enable MSI-x: {0}")] 61 EnableMsix(#[source] VfioError), 62 #[error("Failed to mmap the area")] 63 MmapArea, 64 #[error("Failed to notifier's eventfd")] 65 MissingNotifier, 66 #[error("Invalid region alignment")] 67 RegionAlignment, 68 #[error("Invalid region size")] 69 RegionSize, 70 #[error("Failed to retrieve MsiConfigState: {0}")] 71 RetrieveMsiConfigState(#[source] anyhow::Error), 72 #[error("Failed to retrieve MsixConfigState: {0}")] 73 RetrieveMsixConfigState(#[source] anyhow::Error), 74 #[error("Failed to retrieve PciConfigurationState: {0}")] 75 RetrievePciConfigurationState(#[source] anyhow::Error), 76 #[error("Failed to retrieve VfioCommonState: {0}")] 77 RetrieveVfioCommonState(#[source] anyhow::Error), 78 } 79 80 #[derive(Copy, Clone)] 81 enum PciVfioSubclass { 82 VfioSubclass = 0xff, 83 } 84 85 impl PciSubclass for PciVfioSubclass { 86 fn get_register_value(&self) -> u8 { 87 *self as u8 88 } 89 } 90 91 enum InterruptUpdateAction { 92 EnableMsi, 93 DisableMsi, 94 EnableMsix, 95 DisableMsix, 96 } 97 98 #[derive(Serialize, Deserialize)] 99 struct IntxState { 100 enabled: bool, 101 } 102 103 pub(crate) struct VfioIntx { 104 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 105 enabled: bool, 106 } 107 108 #[derive(Serialize, Deserialize)] 109 struct MsiState { 110 cap: MsiCap, 111 cap_offset: u32, 112 } 113 114 pub(crate) struct VfioMsi { 115 pub(crate) cfg: MsiConfig, 116 cap_offset: u32, 117 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 118 } 119 120 impl VfioMsi { 121 fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 122 let old_enabled = self.cfg.enabled(); 123 124 self.cfg.update(offset, data); 125 126 let new_enabled = self.cfg.enabled(); 127 128 if !old_enabled && new_enabled { 129 return Some(InterruptUpdateAction::EnableMsi); 130 } 131 132 if old_enabled && !new_enabled { 133 return Some(InterruptUpdateAction::DisableMsi); 134 } 135 136 None 137 } 138 } 139 140 #[derive(Serialize, Deserialize)] 141 struct MsixState { 142 cap: MsixCap, 143 cap_offset: u32, 144 bdf: u32, 145 } 146 147 pub(crate) struct VfioMsix { 148 pub(crate) bar: MsixConfig, 149 cap: MsixCap, 150 cap_offset: u32, 151 interrupt_source_group: Arc<dyn InterruptSourceGroup>, 152 } 153 154 impl VfioMsix { 155 fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 156 let old_enabled = self.bar.enabled(); 157 158 // Update "Message Control" word 159 if offset == 2 && data.len() == 2 { 160 self.bar.set_msg_ctl(LittleEndian::read_u16(data)); 161 } 162 163 let new_enabled = self.bar.enabled(); 164 165 if !old_enabled && new_enabled { 166 return Some(InterruptUpdateAction::EnableMsix); 167 } 168 169 if old_enabled && !new_enabled { 170 return Some(InterruptUpdateAction::DisableMsix); 171 } 172 173 None 174 } 175 176 fn table_accessed(&self, bar_index: u32, offset: u64) -> bool { 177 let table_offset: u64 = u64::from(self.cap.table_offset()); 178 let table_size: u64 = u64::from(self.cap.table_size()) * (MSIX_TABLE_ENTRY_SIZE as u64); 179 let table_bir: u32 = self.cap.table_bir(); 180 181 bar_index == table_bir && offset >= table_offset && offset < table_offset + table_size 182 } 183 } 184 185 pub(crate) struct Interrupt { 186 pub(crate) intx: Option<VfioIntx>, 187 pub(crate) msi: Option<VfioMsi>, 188 pub(crate) msix: Option<VfioMsix>, 189 } 190 191 impl Interrupt { 192 fn update_msi(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 193 if let Some(ref mut msi) = &mut self.msi { 194 let action = msi.update(offset, data); 195 return action; 196 } 197 198 None 199 } 200 201 fn update_msix(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { 202 if let Some(ref mut msix) = &mut self.msix { 203 let action = msix.update(offset, data); 204 return action; 205 } 206 207 None 208 } 209 210 fn accessed(&self, offset: u64) -> Option<(PciCapabilityId, u64)> { 211 if let Some(msi) = &self.msi { 212 if offset >= u64::from(msi.cap_offset) 213 && offset < u64::from(msi.cap_offset) + msi.cfg.size() 214 { 215 return Some(( 216 PciCapabilityId::MessageSignalledInterrupts, 217 u64::from(msi.cap_offset), 218 )); 219 } 220 } 221 222 if let Some(msix) = &self.msix { 223 if offset == u64::from(msix.cap_offset) { 224 return Some((PciCapabilityId::MsiX, u64::from(msix.cap_offset))); 225 } 226 } 227 228 None 229 } 230 231 fn msix_table_accessed(&self, bar_index: u32, offset: u64) -> bool { 232 if let Some(msix) = &self.msix { 233 return msix.table_accessed(bar_index, offset); 234 } 235 236 false 237 } 238 239 fn msix_write_table(&mut self, offset: u64, data: &[u8]) { 240 if let Some(ref mut msix) = &mut self.msix { 241 let offset = offset - u64::from(msix.cap.table_offset()); 242 msix.bar.write_table(offset, data) 243 } 244 } 245 246 fn msix_read_table(&self, offset: u64, data: &mut [u8]) { 247 if let Some(msix) = &self.msix { 248 let offset = offset - u64::from(msix.cap.table_offset()); 249 msix.bar.read_table(offset, data) 250 } 251 } 252 253 pub(crate) fn intx_in_use(&self) -> bool { 254 if let Some(intx) = &self.intx { 255 return intx.enabled; 256 } 257 258 false 259 } 260 } 261 262 #[derive(Copy, Clone)] 263 pub struct UserMemoryRegion { 264 pub slot: u32, 265 pub start: u64, 266 pub size: u64, 267 pub host_addr: u64, 268 } 269 270 #[derive(Clone)] 271 pub struct MmioRegion { 272 pub start: GuestAddress, 273 pub length: GuestUsize, 274 pub(crate) type_: PciBarRegionType, 275 pub(crate) index: u32, 276 pub(crate) user_memory_regions: Vec<UserMemoryRegion>, 277 } 278 279 trait MmioRegionRange { 280 fn check_range(&self, guest_addr: u64, size: u64) -> bool; 281 fn find_user_address(&self, guest_addr: u64) -> Result<u64, io::Error>; 282 } 283 284 impl MmioRegionRange for Vec<MmioRegion> { 285 // Check if a guest address is within the range of mmio regions 286 fn check_range(&self, guest_addr: u64, size: u64) -> bool { 287 for region in self.iter() { 288 let Some(guest_addr_end) = guest_addr.checked_add(size) else { 289 return false; 290 }; 291 let Some(region_end) = region.start.raw_value().checked_add(region.length) else { 292 return false; 293 }; 294 if guest_addr >= region.start.raw_value() && guest_addr_end <= region_end { 295 return true; 296 } 297 } 298 false 299 } 300 301 // Locate the user region address for a guest address within all mmio regions 302 fn find_user_address(&self, guest_addr: u64) -> Result<u64, io::Error> { 303 for region in self.iter() { 304 for user_region in region.user_memory_regions.iter() { 305 if guest_addr >= user_region.start 306 && guest_addr < user_region.start + user_region.size 307 { 308 return Ok(user_region.host_addr + (guest_addr - user_region.start)); 309 } 310 } 311 } 312 313 Err(io::Error::other(format!( 314 "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 bdf: PciBdf, 1414 device_path: PathBuf, 1415 } 1416 1417 impl VfioPciDevice { 1418 /// Constructs a new Vfio Pci device for the given Vfio device 1419 #[allow(clippy::too_many_arguments)] 1420 pub fn new( 1421 id: String, 1422 vm: &Arc<dyn hypervisor::Vm>, 1423 device: VfioDevice, 1424 container: Arc<VfioContainer>, 1425 msi_interrupt_manager: Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, 1426 legacy_interrupt_group: Option<Arc<dyn InterruptSourceGroup>>, 1427 iommu_attached: bool, 1428 bdf: PciBdf, 1429 memory_slot_allocator: MemorySlotAllocator, 1430 snapshot: Option<Snapshot>, 1431 x_nv_gpudirect_clique: Option<u8>, 1432 device_path: PathBuf, 1433 ) -> Result<Self, VfioPciError> { 1434 let device = Arc::new(device); 1435 device.reset(); 1436 1437 let vfio_wrapper = VfioDeviceWrapper::new(Arc::clone(&device)); 1438 1439 let common = VfioCommon::new( 1440 msi_interrupt_manager, 1441 legacy_interrupt_group, 1442 Arc::new(vfio_wrapper) as Arc<dyn Vfio>, 1443 &PciVfioSubclass::VfioSubclass, 1444 bdf, 1445 vm_migration::snapshot_from_id(snapshot.as_ref(), VFIO_COMMON_ID), 1446 x_nv_gpudirect_clique, 1447 )?; 1448 1449 let vfio_pci_device = VfioPciDevice { 1450 id, 1451 vm: vm.clone(), 1452 device, 1453 container, 1454 common, 1455 iommu_attached, 1456 memory_slot_allocator, 1457 bdf, 1458 device_path: device_path.clone(), 1459 }; 1460 1461 Ok(vfio_pci_device) 1462 } 1463 1464 pub fn iommu_attached(&self) -> bool { 1465 self.iommu_attached 1466 } 1467 1468 fn generate_sparse_areas( 1469 caps: &[VfioRegionInfoCap], 1470 region_index: u32, 1471 region_start: u64, 1472 region_size: u64, 1473 vfio_msix: Option<&VfioMsix>, 1474 ) -> Result<Vec<VfioRegionSparseMmapArea>, VfioPciError> { 1475 for cap in caps { 1476 match cap { 1477 VfioRegionInfoCap::SparseMmap(sparse_mmap) => return Ok(sparse_mmap.areas.clone()), 1478 VfioRegionInfoCap::MsixMappable => { 1479 if !is_4k_aligned(region_start) { 1480 error!( 1481 "Region start address 0x{:x} must be at least aligned on 4KiB", 1482 region_start 1483 ); 1484 return Err(VfioPciError::RegionAlignment); 1485 } 1486 if !is_4k_multiple(region_size) { 1487 error!( 1488 "Region size 0x{:x} must be at least a multiple of 4KiB", 1489 region_size 1490 ); 1491 return Err(VfioPciError::RegionSize); 1492 } 1493 1494 // In case the region contains the MSI-X vectors table or 1495 // the MSI-X PBA table, we must calculate the subregions 1496 // around them, leading to a list of sparse areas. 1497 // We want to make sure we will still trap MMIO accesses 1498 // to these MSI-X specific ranges. If these region don't align 1499 // with pagesize, we can achieve it by enlarging its range. 1500 // 1501 // Using a BtreeMap as the list provided through the iterator is sorted 1502 // by key. This ensures proper split of the whole region. 1503 let mut inter_ranges = BTreeMap::new(); 1504 if let Some(msix) = vfio_msix { 1505 if region_index == msix.cap.table_bir() { 1506 let (offset, size) = msix.cap.table_range(); 1507 let offset = align_page_size_down(offset); 1508 let size = align_page_size_up(size); 1509 inter_ranges.insert(offset, size); 1510 } 1511 if region_index == msix.cap.pba_bir() { 1512 let (offset, size) = msix.cap.pba_range(); 1513 let offset = align_page_size_down(offset); 1514 let size = align_page_size_up(size); 1515 inter_ranges.insert(offset, size); 1516 } 1517 } 1518 1519 let mut sparse_areas = Vec::new(); 1520 let mut current_offset = 0; 1521 for (range_offset, range_size) in inter_ranges { 1522 if range_offset > current_offset { 1523 sparse_areas.push(VfioRegionSparseMmapArea { 1524 offset: current_offset, 1525 size: range_offset - current_offset, 1526 }); 1527 } 1528 current_offset = align_page_size_down(range_offset + range_size); 1529 } 1530 1531 if region_size > current_offset { 1532 sparse_areas.push(VfioRegionSparseMmapArea { 1533 offset: current_offset, 1534 size: region_size - current_offset, 1535 }); 1536 } 1537 1538 return Ok(sparse_areas); 1539 } 1540 _ => {} 1541 } 1542 } 1543 1544 // In case no relevant capabilities have been found, create a single 1545 // sparse area corresponding to the entire MMIO region. 1546 Ok(vec![VfioRegionSparseMmapArea { 1547 offset: 0, 1548 size: region_size, 1549 }]) 1550 } 1551 1552 /// Map MMIO regions into the guest, and avoid VM exits when the guest tries 1553 /// to reach those regions. 1554 /// 1555 /// # Arguments 1556 /// 1557 /// * `vm` - The VM object. It is used to set the VFIO MMIO regions 1558 /// as user memory regions. 1559 /// * `mem_slot` - The closure to return a memory slot. 1560 pub fn map_mmio_regions(&mut self) -> Result<(), VfioPciError> { 1561 let fd = self.device.as_raw_fd(); 1562 1563 for region in self.common.mmio_regions.iter_mut() { 1564 let region_flags = self.device.get_region_flags(region.index); 1565 if region_flags & VFIO_REGION_INFO_FLAG_MMAP != 0 { 1566 let mut prot = 0; 1567 if region_flags & VFIO_REGION_INFO_FLAG_READ != 0 { 1568 prot |= libc::PROT_READ; 1569 } 1570 if region_flags & VFIO_REGION_INFO_FLAG_WRITE != 0 { 1571 prot |= libc::PROT_WRITE; 1572 } 1573 1574 // Retrieve the list of capabilities found on the region 1575 let caps = if region_flags & VFIO_REGION_INFO_FLAG_CAPS != 0 { 1576 self.device.get_region_caps(region.index) 1577 } else { 1578 Vec::new() 1579 }; 1580 1581 // Don't try to mmap the region if it contains MSI-X table or 1582 // MSI-X PBA subregion, and if we couldn't find MSIX_MAPPABLE 1583 // in the list of supported capabilities. 1584 if let Some(msix) = self.common.interrupt.msix.as_ref() { 1585 if (region.index == msix.cap.table_bir() || region.index == msix.cap.pba_bir()) 1586 && !caps.contains(&VfioRegionInfoCap::MsixMappable) 1587 { 1588 continue; 1589 } 1590 } 1591 1592 let mmap_size = self.device.get_region_size(region.index); 1593 let mmap_offset = self.device.get_region_offset(region.index); 1594 1595 let sparse_areas = Self::generate_sparse_areas( 1596 &caps, 1597 region.index, 1598 region.start.0, 1599 mmap_size, 1600 self.common.interrupt.msix.as_ref(), 1601 )?; 1602 1603 for area in sparse_areas.iter() { 1604 // SAFETY: FFI call with correct arguments 1605 let host_addr = unsafe { 1606 libc::mmap( 1607 null_mut(), 1608 area.size as usize, 1609 prot, 1610 libc::MAP_SHARED, 1611 fd, 1612 mmap_offset as libc::off_t + area.offset as libc::off_t, 1613 ) 1614 }; 1615 1616 if std::ptr::eq(host_addr, libc::MAP_FAILED) { 1617 error!( 1618 "Could not mmap sparse area (offset = 0x{:x}, size = 0x{:x}): {}", 1619 area.offset, 1620 area.size, 1621 std::io::Error::last_os_error() 1622 ); 1623 return Err(VfioPciError::MmapArea); 1624 } 1625 1626 if !is_page_size_aligned(area.size) || !is_page_size_aligned(area.offset) { 1627 warn!( 1628 "Could not mmap sparse area that is not page size aligned (offset = 0x{:x}, size = 0x{:x})", 1629 area.offset, 1630 area.size, 1631 ); 1632 return Ok(()); 1633 } 1634 1635 let user_memory_region = UserMemoryRegion { 1636 slot: self.memory_slot_allocator.next_memory_slot(), 1637 start: region.start.0 + area.offset, 1638 size: area.size, 1639 host_addr: host_addr as u64, 1640 }; 1641 1642 region.user_memory_regions.push(user_memory_region); 1643 1644 let mem_region = self.vm.make_user_memory_region( 1645 user_memory_region.slot, 1646 user_memory_region.start, 1647 user_memory_region.size, 1648 user_memory_region.host_addr, 1649 false, 1650 false, 1651 ); 1652 1653 self.vm 1654 .create_user_memory_region(mem_region) 1655 .map_err(VfioPciError::CreateUserMemoryRegion)?; 1656 1657 if !self.iommu_attached { 1658 self.container 1659 .vfio_dma_map( 1660 user_memory_region.start, 1661 user_memory_region.size, 1662 user_memory_region.host_addr, 1663 ) 1664 .map_err(|e| { 1665 VfioPciError::DmaMap(e, self.device_path.clone(), self.bdf) 1666 })?; 1667 } 1668 } 1669 } 1670 } 1671 1672 Ok(()) 1673 } 1674 1675 pub fn unmap_mmio_regions(&mut self) { 1676 for region in self.common.mmio_regions.iter() { 1677 for user_memory_region in region.user_memory_regions.iter() { 1678 // Unmap from vfio container 1679 if !self.iommu_attached { 1680 if let Err(e) = self 1681 .container 1682 .vfio_dma_unmap(user_memory_region.start, user_memory_region.size) 1683 { 1684 error!("Could not unmap mmio region from vfio container: {}", e); 1685 } 1686 } 1687 1688 // Remove region 1689 let r = self.vm.make_user_memory_region( 1690 user_memory_region.slot, 1691 user_memory_region.start, 1692 user_memory_region.size, 1693 user_memory_region.host_addr, 1694 false, 1695 false, 1696 ); 1697 1698 if let Err(e) = self.vm.remove_user_memory_region(r) { 1699 error!("Could not remove the userspace memory region: {}", e); 1700 } 1701 1702 self.memory_slot_allocator 1703 .free_memory_slot(user_memory_region.slot); 1704 1705 // SAFETY: FFI call with correct arguments 1706 let ret = unsafe { 1707 libc::munmap( 1708 user_memory_region.host_addr as *mut libc::c_void, 1709 user_memory_region.size as usize, 1710 ) 1711 }; 1712 if ret != 0 { 1713 error!( 1714 "Could not unmap region {}, error:{}", 1715 region.index, 1716 io::Error::last_os_error() 1717 ); 1718 } 1719 } 1720 } 1721 } 1722 1723 pub fn dma_map(&self, iova: u64, size: u64, user_addr: u64) -> Result<(), VfioPciError> { 1724 if !self.iommu_attached { 1725 self.container 1726 .vfio_dma_map(iova, size, user_addr) 1727 .map_err(|e| VfioPciError::DmaMap(e, self.device_path.clone(), self.bdf))?; 1728 } 1729 1730 Ok(()) 1731 } 1732 1733 pub fn dma_unmap(&self, iova: u64, size: u64) -> Result<(), VfioPciError> { 1734 if !self.iommu_attached { 1735 self.container 1736 .vfio_dma_unmap(iova, size) 1737 .map_err(|e| VfioPciError::DmaUnmap(e, self.device_path.clone(), self.bdf))?; 1738 } 1739 1740 Ok(()) 1741 } 1742 1743 pub fn mmio_regions(&self) -> Vec<MmioRegion> { 1744 self.common.mmio_regions.clone() 1745 } 1746 } 1747 1748 impl Drop for VfioPciDevice { 1749 fn drop(&mut self) { 1750 self.unmap_mmio_regions(); 1751 1752 if let Some(msix) = &self.common.interrupt.msix { 1753 if msix.bar.enabled() { 1754 self.common.disable_msix(); 1755 } 1756 } 1757 1758 if let Some(msi) = &self.common.interrupt.msi { 1759 if msi.cfg.enabled() { 1760 self.common.disable_msi() 1761 } 1762 } 1763 1764 if self.common.interrupt.intx_in_use() { 1765 self.common.disable_intx(); 1766 } 1767 } 1768 } 1769 1770 impl BusDevice for VfioPciDevice { 1771 fn read(&mut self, base: u64, offset: u64, data: &mut [u8]) { 1772 self.read_bar(base, offset, data) 1773 } 1774 1775 fn write(&mut self, base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> { 1776 self.write_bar(base, offset, data) 1777 } 1778 } 1779 1780 // First BAR offset in the PCI config space. 1781 const PCI_CONFIG_BAR_OFFSET: u32 = 0x10; 1782 // Capability register offset in the PCI config space. 1783 const PCI_CONFIG_CAPABILITY_OFFSET: u32 = 0x34; 1784 // Extended capabilities register offset in the PCI config space. 1785 const PCI_CONFIG_EXTENDED_CAPABILITY_OFFSET: u32 = 0x100; 1786 // IO BAR when first BAR bit is 1. 1787 const PCI_CONFIG_IO_BAR: u32 = 0x1; 1788 // 64-bit memory bar flag. 1789 const PCI_CONFIG_MEMORY_BAR_64BIT: u32 = 0x4; 1790 // Prefetchable BAR bit 1791 const PCI_CONFIG_BAR_PREFETCHABLE: u32 = 0x8; 1792 // PCI config register size (4 bytes). 1793 const PCI_CONFIG_REGISTER_SIZE: usize = 4; 1794 // Number of BARs for a PCI device 1795 const BAR_NUMS: usize = 6; 1796 // PCI Header Type register index 1797 const PCI_HEADER_TYPE_REG_INDEX: usize = 3; 1798 // First BAR register index 1799 const PCI_CONFIG_BAR0_INDEX: usize = 4; 1800 // PCI ROM expansion BAR register index 1801 const PCI_ROM_EXP_BAR_INDEX: usize = 12; 1802 1803 impl PciDevice for VfioPciDevice { 1804 fn allocate_bars( 1805 &mut self, 1806 allocator: &Arc<Mutex<SystemAllocator>>, 1807 mmio32_allocator: &mut AddressAllocator, 1808 mmio64_allocator: &mut AddressAllocator, 1809 resources: Option<Vec<Resource>>, 1810 ) -> Result<Vec<PciBarConfiguration>, PciDeviceError> { 1811 self.common 1812 .allocate_bars(allocator, mmio32_allocator, mmio64_allocator, resources) 1813 } 1814 1815 fn free_bars( 1816 &mut self, 1817 allocator: &mut SystemAllocator, 1818 mmio32_allocator: &mut AddressAllocator, 1819 mmio64_allocator: &mut AddressAllocator, 1820 ) -> Result<(), PciDeviceError> { 1821 self.common 1822 .free_bars(allocator, mmio32_allocator, mmio64_allocator) 1823 } 1824 1825 fn write_config_register( 1826 &mut self, 1827 reg_idx: usize, 1828 offset: u64, 1829 data: &[u8], 1830 ) -> Option<Arc<Barrier>> { 1831 self.common.write_config_register(reg_idx, offset, data) 1832 } 1833 1834 fn read_config_register(&mut self, reg_idx: usize) -> u32 { 1835 self.common.read_config_register(reg_idx) 1836 } 1837 1838 fn detect_bar_reprogramming( 1839 &mut self, 1840 reg_idx: usize, 1841 data: &[u8], 1842 ) -> Option<BarReprogrammingParams> { 1843 self.common 1844 .configuration 1845 .detect_bar_reprogramming(reg_idx, data) 1846 } 1847 1848 fn read_bar(&mut self, base: u64, offset: u64, data: &mut [u8]) { 1849 self.common.read_bar(base, offset, data) 1850 } 1851 1852 fn write_bar(&mut self, base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> { 1853 self.common.write_bar(base, offset, data) 1854 } 1855 1856 fn move_bar(&mut self, old_base: u64, new_base: u64) -> Result<(), io::Error> { 1857 for region in self.common.mmio_regions.iter_mut() { 1858 if region.start.raw_value() == old_base { 1859 region.start = GuestAddress(new_base); 1860 1861 for user_memory_region in region.user_memory_regions.iter_mut() { 1862 // Remove old region 1863 let old_mem_region = self.vm.make_user_memory_region( 1864 user_memory_region.slot, 1865 user_memory_region.start, 1866 user_memory_region.size, 1867 user_memory_region.host_addr, 1868 false, 1869 false, 1870 ); 1871 1872 self.vm 1873 .remove_user_memory_region(old_mem_region) 1874 .map_err(io::Error::other)?; 1875 1876 // Update the user memory region with the correct start address. 1877 if new_base > old_base { 1878 user_memory_region.start += new_base - old_base; 1879 } else { 1880 user_memory_region.start -= old_base - new_base; 1881 } 1882 1883 // Insert new region 1884 let new_mem_region = self.vm.make_user_memory_region( 1885 user_memory_region.slot, 1886 user_memory_region.start, 1887 user_memory_region.size, 1888 user_memory_region.host_addr, 1889 false, 1890 false, 1891 ); 1892 1893 self.vm 1894 .create_user_memory_region(new_mem_region) 1895 .map_err(io::Error::other)?; 1896 } 1897 } 1898 } 1899 1900 Ok(()) 1901 } 1902 1903 fn as_any_mut(&mut self) -> &mut dyn Any { 1904 self 1905 } 1906 1907 fn id(&self) -> Option<String> { 1908 Some(self.id.clone()) 1909 } 1910 } 1911 1912 impl Pausable for VfioPciDevice {} 1913 1914 impl Snapshottable for VfioPciDevice { 1915 fn id(&self) -> String { 1916 self.id.clone() 1917 } 1918 1919 fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> { 1920 let mut vfio_pci_dev_snapshot = Snapshot::default(); 1921 1922 // Snapshot VfioCommon 1923 vfio_pci_dev_snapshot.add_snapshot(self.common.id(), self.common.snapshot()?); 1924 1925 Ok(vfio_pci_dev_snapshot) 1926 } 1927 } 1928 impl Transportable for VfioPciDevice {} 1929 impl Migratable for VfioPciDevice {} 1930 1931 /// This structure implements the ExternalDmaMapping trait. It is meant to 1932 /// be used when the caller tries to provide a way to update the mappings 1933 /// associated with a specific VFIO container. 1934 pub struct VfioDmaMapping<M: GuestAddressSpace> { 1935 container: Arc<VfioContainer>, 1936 memory: Arc<M>, 1937 mmio_regions: Arc<Mutex<Vec<MmioRegion>>>, 1938 } 1939 1940 impl<M: GuestAddressSpace> VfioDmaMapping<M> { 1941 /// Create a DmaMapping object. 1942 /// # Parameters 1943 /// * `container`: VFIO container object. 1944 /// * `memory`: guest memory to mmap. 1945 /// * `mmio_regions`: mmio_regions to mmap. 1946 pub fn new( 1947 container: Arc<VfioContainer>, 1948 memory: Arc<M>, 1949 mmio_regions: Arc<Mutex<Vec<MmioRegion>>>, 1950 ) -> Self { 1951 VfioDmaMapping { 1952 container, 1953 memory, 1954 mmio_regions, 1955 } 1956 } 1957 } 1958 1959 impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioDmaMapping<M> { 1960 fn map(&self, iova: u64, gpa: u64, size: u64) -> std::result::Result<(), io::Error> { 1961 let mem = self.memory.memory(); 1962 let guest_addr = GuestAddress(gpa); 1963 let user_addr = if mem.check_range(guest_addr, size as usize) { 1964 match mem.get_host_address(guest_addr) { 1965 Ok(t) => t as u64, 1966 Err(e) => { 1967 return Err(io::Error::other( 1968 format!("unable to retrieve user address for gpa 0x{gpa:x} from guest memory region: {e}") 1969 )); 1970 } 1971 } 1972 } else if self.mmio_regions.lock().unwrap().check_range(gpa, size) { 1973 self.mmio_regions.lock().unwrap().find_user_address(gpa)? 1974 } else { 1975 return Err(io::Error::other(format!( 1976 "failed to locate guest address 0x{gpa:x} in guest memory" 1977 ))); 1978 }; 1979 1980 self.container 1981 .vfio_dma_map(iova, size, user_addr) 1982 .map_err(|e| { 1983 io::Error::other(format!( 1984 "failed to map memory for VFIO container, \ 1985 iova 0x{iova:x}, gpa 0x{gpa:x}, size 0x{size:x}: {e:?}" 1986 )) 1987 }) 1988 } 1989 1990 fn unmap(&self, iova: u64, size: u64) -> std::result::Result<(), io::Error> { 1991 self.container.vfio_dma_unmap(iova, size).map_err(|e| { 1992 io::Error::other(format!( 1993 "failed to unmap memory for VFIO container, \ 1994 iova 0x{iova:x}, size 0x{size:x}: {e:?}" 1995 )) 1996 }) 1997 } 1998 } 1999