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