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