1 //! PCI transport for VirtIO. 2 3 use crate::driver::base::device::DeviceId; 4 use crate::driver::pci::pci::{ 5 BusDeviceFunction, PciDeviceStructure, PciDeviceStructureGeneralDevice, PciError, 6 PciStandardDeviceBar, PCI_CAP_ID_VNDR, 7 }; 8 9 use crate::driver::pci::root::pci_root_0; 10 11 use crate::exception::IrqNumber; 12 13 use crate::libs::spinlock::{SpinLock, SpinLockGuard}; 14 use crate::libs::volatile::{ 15 volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly, 16 }; 17 use crate::mm::VirtAddr; 18 19 use alloc::sync::Arc; 20 use core::{ 21 fmt::{self, Display, Formatter}, 22 mem::{align_of, size_of}, 23 ptr::{self, addr_of_mut, NonNull}, 24 }; 25 use virtio_drivers::{ 26 transport::{DeviceStatus, DeviceType, Transport}, 27 Error, Hal, PhysAddr, 28 }; 29 30 use super::VIRTIO_VENDOR_ID; 31 32 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID. 33 /// PCI Virtio设备的DEVICE_ID 的offset 34 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040; 35 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型 36 const TRANSITIONAL_NETWORK: u16 = 0x1000; 37 const TRANSITIONAL_BLOCK: u16 = 0x1001; 38 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002; 39 const TRANSITIONAL_CONSOLE: u16 = 0x1003; 40 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004; 41 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005; 42 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009; 43 44 /// The offset of the bar field within `virtio_pci_cap`. 45 const CAP_BAR_OFFSET: u8 = 4; 46 /// The offset of the offset field with `virtio_pci_cap`. 47 const CAP_BAR_OFFSET_OFFSET: u8 = 8; 48 /// The offset of the `length` field within `virtio_pci_cap`. 49 const CAP_LENGTH_OFFSET: u8 = 12; 50 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`. 51 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16; 52 53 /// Common configuration. 54 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1; 55 /// Notifications. 56 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2; 57 /// ISR Status. 58 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3; 59 /// Device specific configuration. 60 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4; 61 62 /// Virtio设备接收中断的设备号 63 const VIRTIO_RECV_VECTOR: IrqNumber = IrqNumber::new(56); 64 /// Virtio设备接收中断的设备号的表项号 65 const VIRTIO_RECV_VECTOR_INDEX: u16 = 0; 66 // 接收的queue号 67 const QUEUE_RECEIVE: u16 = 0; 68 ///@brief device id 转换为设备类型 69 ///@param pci_device_id,device_id 70 ///@return DeviceType 对应的设备类型 71 fn device_type(pci_device_id: u16) -> DeviceType { 72 match pci_device_id { 73 TRANSITIONAL_NETWORK => DeviceType::Network, 74 TRANSITIONAL_BLOCK => DeviceType::Block, 75 TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon, 76 TRANSITIONAL_CONSOLE => DeviceType::Console, 77 TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost, 78 TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource, 79 TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P, 80 id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET), 81 _ => DeviceType::Invalid, 82 } 83 } 84 85 /// PCI transport for VirtIO. 86 /// 87 /// Ref: 4.1 Virtio Over PCI Bus 88 #[allow(dead_code)] 89 #[derive(Debug, Clone)] 90 pub struct PciTransport { 91 device_type: DeviceType, 92 /// The bus, device and function identifier for the VirtIO device. 93 _bus_device_function: BusDeviceFunction, 94 /// The common configuration structure within some BAR. 95 common_cfg: NonNull<CommonCfg>, 96 /// The start of the queue notification region within some BAR. 97 notify_region: NonNull<[WriteOnly<u16>]>, 98 notify_off_multiplier: u32, 99 /// The ISR status register within some BAR. 100 isr_status: NonNull<Volatile<u8>>, 101 /// The VirtIO device-specific configuration within some BAR. 102 config_space: Option<NonNull<[u32]>>, 103 irq: IrqNumber, 104 dev_id: Arc<DeviceId>, 105 device: Arc<SpinLock<PciDeviceStructureGeneralDevice>>, 106 } 107 108 impl PciTransport { 109 /// Construct a new PCI VirtIO device driver for the given device function on the given PCI 110 /// root controller. 111 /// 112 /// ## 参数 113 /// 114 /// - `device` - The PCI device structure for the VirtIO device. 115 /// - `irq_handler` - An optional handler for the device's interrupt. If `None`, a default 116 /// handler `DefaultVirtioIrqHandler` will be used. 117 /// - `irq_number_offset` - Currently, this parameter is just simple make a offset to the irq number, cause it's not be allowed to have the same irq number within different device 118 #[allow(clippy::extra_unused_type_parameters)] 119 pub fn new<H: Hal>( 120 device: &mut PciDeviceStructureGeneralDevice, 121 dev_id: Arc<DeviceId>, 122 ) -> Result<Self, VirtioPciError> { 123 let irq = VIRTIO_RECV_VECTOR; 124 let header = &device.common_header; 125 let bus_device_function = header.bus_device_function; 126 if header.vendor_id != VIRTIO_VENDOR_ID { 127 return Err(VirtioPciError::InvalidVendorId(header.vendor_id)); 128 } 129 let device_type = device_type(header.device_id); 130 // Find the PCI capabilities we need. 131 let mut common_cfg: Option<VirtioCapabilityInfo> = None; 132 let mut notify_cfg: Option<VirtioCapabilityInfo> = None; 133 let mut notify_off_multiplier = 0; 134 let mut isr_cfg = None; 135 let mut device_cfg = None; 136 device.bar_ioremap().unwrap()?; 137 device.enable_master(); 138 let standard_device = device.as_standard_device_mut().unwrap(); 139 // 目前缺少对PCI设备中断号的统一管理,所以这里需要指定一个中断号。不能与其他中断重复 140 let irq_vector = standard_device.irq_vector_mut().unwrap(); 141 irq_vector.push(irq); 142 143 //device_capability为迭代器,遍历其相当于遍历所有的cap空间 144 for capability in device.capabilities().unwrap() { 145 if capability.id != PCI_CAP_ID_VNDR { 146 continue; 147 } 148 let cap_len = capability.private_header as u8; 149 let cfg_type = (capability.private_header >> 8) as u8; 150 if cap_len < 16 { 151 continue; 152 } 153 let struct_info = VirtioCapabilityInfo { 154 bar: pci_root_0().read_config( 155 bus_device_function, 156 (capability.offset + CAP_BAR_OFFSET).into(), 157 ) as u8, 158 offset: pci_root_0().read_config( 159 bus_device_function, 160 (capability.offset + CAP_BAR_OFFSET_OFFSET).into(), 161 ), 162 length: pci_root_0().read_config( 163 bus_device_function, 164 (capability.offset + CAP_LENGTH_OFFSET).into(), 165 ), 166 }; 167 168 match cfg_type { 169 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => { 170 common_cfg = Some(struct_info); 171 } 172 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => { 173 notify_cfg = Some(struct_info); 174 notify_off_multiplier = pci_root_0().read_config( 175 bus_device_function, 176 (capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET).into(), 177 ); 178 } 179 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => { 180 isr_cfg = Some(struct_info); 181 } 182 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => { 183 device_cfg = Some(struct_info); 184 } 185 _ => {} 186 } 187 } 188 189 let common_cfg = get_bar_region::<_>( 190 &device.standard_device_bar, 191 &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?, 192 )?; 193 194 let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?; 195 if notify_off_multiplier % 2 != 0 { 196 return Err(VirtioPciError::InvalidNotifyOffMultiplier( 197 notify_off_multiplier, 198 )); 199 } 200 //debug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length); 201 let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, ¬ify_cfg)?; 202 let isr_status = get_bar_region::<_>( 203 &device.standard_device_bar, 204 &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?, 205 )?; 206 let config_space = if let Some(device_cfg) = device_cfg { 207 Some(get_bar_region_slice::<_>( 208 &device.standard_device_bar, 209 &device_cfg, 210 )?) 211 } else { 212 None 213 }; 214 Ok(Self { 215 device_type, 216 _bus_device_function: bus_device_function, 217 common_cfg, 218 notify_region, 219 notify_off_multiplier, 220 isr_status, 221 config_space, 222 irq, 223 dev_id, 224 device: Arc::new(SpinLock::new(device.clone())), 225 }) 226 } 227 228 pub fn pci_device(&self) -> SpinLockGuard<PciDeviceStructureGeneralDevice> { 229 self.device.lock() 230 } 231 232 pub fn irq(&self) -> IrqNumber { 233 self.irq 234 } 235 } 236 237 impl Transport for PciTransport { 238 fn device_type(&self) -> DeviceType { 239 self.device_type 240 } 241 242 fn read_device_features(&mut self) -> u64 { 243 // Safe because the common config pointer is valid and we checked in get_bar_region that it 244 // was aligned. 245 unsafe { 246 volwrite!(self.common_cfg, device_feature_select, 0); 247 let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64; 248 volwrite!(self.common_cfg, device_feature_select, 1); 249 device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32; 250 device_features_bits 251 } 252 } 253 254 fn write_driver_features(&mut self, driver_features: u64) { 255 // Safe because the common config pointer is valid and we checked in get_bar_region that it 256 // was aligned. 257 unsafe { 258 volwrite!(self.common_cfg, driver_feature_select, 0); 259 volwrite!(self.common_cfg, driver_feature, driver_features as u32); 260 volwrite!(self.common_cfg, driver_feature_select, 1); 261 volwrite!( 262 self.common_cfg, 263 driver_feature, 264 (driver_features >> 32) as u32 265 ); 266 } 267 } 268 269 fn max_queue_size(&mut self, queue: u16) -> u32 { 270 unsafe { 271 volwrite!(self.common_cfg, queue_select, queue); 272 volread!(self.common_cfg, queue_size).into() 273 } 274 } 275 276 fn notify(&mut self, queue: u16) { 277 // Safe because the common config and notify region pointers are valid and we checked in 278 // get_bar_region that they were aligned. 279 unsafe { 280 volwrite!(self.common_cfg, queue_select, queue); 281 // TODO: Consider caching this somewhere (per queue). 282 let queue_notify_off = volread!(self.common_cfg, queue_notify_off); 283 284 let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize; 285 let index = offset_bytes / size_of::<u16>(); 286 addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue); 287 } 288 } 289 290 fn set_status(&mut self, status: DeviceStatus) { 291 // Safe because the common config pointer is valid and we checked in get_bar_region that it 292 // was aligned. 293 unsafe { 294 volwrite!(self.common_cfg, device_status, status.bits() as u8); 295 } 296 } 297 298 fn get_status(&self) -> DeviceStatus { 299 // Safe because the common config pointer is valid and we checked in get_bar_region that it 300 // was aligned. 301 unsafe { DeviceStatus::from_bits_truncate(volread!(self.common_cfg, device_status).into()) } 302 } 303 304 fn set_guest_page_size(&mut self, _guest_page_size: u32) { 305 // No-op, the PCI transport doesn't care. 306 } 307 fn requires_legacy_layout(&self) -> bool { 308 false 309 } 310 fn queue_set( 311 &mut self, 312 queue: u16, 313 size: u32, 314 descriptors: PhysAddr, 315 driver_area: PhysAddr, 316 device_area: PhysAddr, 317 ) { 318 // Safe because the common config pointer is valid and we checked in get_bar_region that it 319 // was aligned. 320 unsafe { 321 volwrite!(self.common_cfg, queue_select, queue); 322 volwrite!(self.common_cfg, queue_size, size as u16); 323 volwrite!(self.common_cfg, queue_desc, descriptors as u64); 324 volwrite!(self.common_cfg, queue_driver, driver_area as u64); 325 volwrite!(self.common_cfg, queue_device, device_area as u64); 326 // 这里设置队列中断对应的中断项 327 if queue == QUEUE_RECEIVE { 328 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX); 329 let vector = volread!(self.common_cfg, queue_msix_vector); 330 if vector != VIRTIO_RECV_VECTOR_INDEX { 331 panic!("Vector set failed"); 332 } 333 } 334 volwrite!(self.common_cfg, queue_enable, 1); 335 } 336 } 337 338 fn queue_unset(&mut self, queue: u16) { 339 // Safe because the common config pointer is valid and we checked in get_bar_region that it 340 // was aligned. 341 unsafe { 342 volwrite!(self.common_cfg, queue_select, queue); 343 volwrite!(self.common_cfg, queue_size, 0); 344 volwrite!(self.common_cfg, queue_desc, 0); 345 volwrite!(self.common_cfg, queue_driver, 0); 346 volwrite!(self.common_cfg, queue_device, 0); 347 } 348 } 349 350 fn queue_used(&mut self, queue: u16) -> bool { 351 // Safe because the common config pointer is valid and we checked in get_bar_region that it 352 // was aligned. 353 unsafe { 354 volwrite!(self.common_cfg, queue_select, queue); 355 volread!(self.common_cfg, queue_enable) == 1 356 } 357 } 358 359 fn ack_interrupt(&mut self) -> bool { 360 // Safe because the common config pointer is valid and we checked in get_bar_region that it 361 // was aligned. 362 // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt. 363 let isr_status = unsafe { self.isr_status.as_ptr().vread() }; 364 // TODO: Distinguish between queue interrupt and device configuration interrupt. 365 isr_status & 0x3 != 0 366 } 367 368 fn config_space<T>(&self) -> Result<NonNull<T>, Error> { 369 if let Some(config_space) = self.config_space { 370 if size_of::<T>() > config_space.len() * size_of::<u32>() { 371 Err(Error::ConfigSpaceTooSmall) 372 } else if align_of::<T>() > 4 { 373 // Panic as this should only happen if the driver is written incorrectly. 374 panic!( 375 "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.", 376 align_of::<T>() 377 ); 378 } else { 379 // TODO: Use NonNull::as_non_null_ptr once it is stable. 380 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap(); 381 Ok(config_space_ptr.cast()) 382 } 383 } else { 384 Err(Error::ConfigSpaceMissing) 385 } 386 } 387 } 388 389 impl Drop for PciTransport { 390 fn drop(&mut self) { 391 // Reset the device when the transport is dropped. 392 self.set_status(DeviceStatus::empty()); 393 394 // todo: 调用pci的中断释放函数,并且在virtio_irq_manager里面删除对应的设备的中断 395 } 396 } 397 398 #[repr(C)] 399 struct CommonCfg { 400 device_feature_select: Volatile<u32>, 401 device_feature: ReadOnly<u32>, 402 driver_feature_select: Volatile<u32>, 403 driver_feature: Volatile<u32>, 404 msix_config: Volatile<u16>, 405 num_queues: ReadOnly<u16>, 406 device_status: Volatile<u8>, 407 config_generation: ReadOnly<u8>, 408 queue_select: Volatile<u16>, 409 queue_size: Volatile<u16>, 410 queue_msix_vector: Volatile<u16>, 411 queue_enable: Volatile<u16>, 412 queue_notify_off: Volatile<u16>, 413 queue_desc: Volatile<u64>, 414 queue_driver: Volatile<u64>, 415 queue_device: Volatile<u64>, 416 } 417 418 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`. 419 /// cfg空间在哪个bar的多少偏移处,长度多少 420 #[derive(Clone, Debug, Eq, PartialEq)] 421 struct VirtioCapabilityInfo { 422 /// The bar in which the structure can be found. 423 bar: u8, 424 /// The offset within the bar. 425 offset: u32, 426 /// The length in bytes of the structure within the bar. 427 length: u32, 428 } 429 430 /// An error encountered initialising a VirtIO PCI transport. 431 /// VirtIO PCI transport 初始化时的错误 432 #[derive(Clone, Debug, Eq, PartialEq)] 433 pub enum VirtioPciError { 434 /// PCI device vender ID was not the VirtIO vendor ID. 435 InvalidVendorId(u16), 436 /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found. 437 MissingCommonConfig, 438 /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found. 439 MissingNotifyConfig, 440 /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple 441 /// of 2. 442 InvalidNotifyOffMultiplier(u32), 443 /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found. 444 MissingIsrConfig, 445 /// An IO BAR was provided rather than a memory BAR. 446 UnexpectedBarType, 447 /// A BAR which we need was not allocated an address. 448 BarNotAllocated(u8), 449 /// The offset for some capability was greater than the length of the BAR. 450 BarOffsetOutOfRange, 451 /// The virtual address was not aligned as expected. 452 Misaligned { 453 /// The virtual address in question. 454 vaddr: VirtAddr, 455 /// The expected alignment in bytes. 456 alignment: usize, 457 }, 458 ///获取虚拟地址失败 459 BarGetVaddrFailed, 460 /// A generic PCI error, 461 Pci(PciError), 462 } 463 464 impl Display for VirtioPciError { 465 fn fmt(&self, f: &mut Formatter) -> fmt::Result { 466 match self { 467 Self::InvalidVendorId(vendor_id) => write!( 468 f, 469 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.", 470 vendor_id, VIRTIO_VENDOR_ID 471 ), 472 Self::MissingCommonConfig => write!( 473 f, 474 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found." 475 ), 476 Self::MissingNotifyConfig => write!( 477 f, 478 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found." 479 ), 480 Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => { 481 write!( 482 f, 483 "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}", 484 notify_off_multiplier 485 ) 486 } 487 Self::MissingIsrConfig => { 488 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.") 489 } 490 Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."), 491 Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index), 492 Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."), 493 Self::Misaligned { vaddr, alignment } => write!( 494 f, 495 "Virtual address {:?} was not aligned to a {} byte boundary as expected.", 496 vaddr, alignment 497 ), 498 Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"), 499 Self::Pci(pci_error) => pci_error.fmt(f), 500 } 501 } 502 } 503 504 /// PCI error到VirtioPciError的转换,层层上报 505 impl From<PciError> for VirtioPciError { 506 fn from(error: PciError) -> Self { 507 Self::Pci(error) 508 } 509 } 510 511 /// @brief 获取虚拟地址并将其转化为对应类型的指针 512 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息 513 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error 514 fn get_bar_region<T>( 515 device_bar: &PciStandardDeviceBar, 516 struct_info: &VirtioCapabilityInfo, 517 ) -> Result<NonNull<T>, VirtioPciError> { 518 let bar_info = device_bar.get_bar(struct_info.bar)?; 519 let (bar_address, bar_size) = bar_info 520 .memory_address_size() 521 .ok_or(VirtioPciError::UnexpectedBarType)?; 522 if bar_address == 0 { 523 return Err(VirtioPciError::BarNotAllocated(struct_info.bar)); 524 } 525 if struct_info.offset + struct_info.length > bar_size 526 || size_of::<T>() > struct_info.length as usize 527 { 528 return Err(VirtioPciError::BarOffsetOutOfRange); 529 } 530 //debug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length); 531 let vaddr = (bar_info 532 .virtual_address() 533 .ok_or(VirtioPciError::BarGetVaddrFailed)?) 534 + struct_info.offset as usize; 535 if vaddr.data() % align_of::<T>() != 0 { 536 return Err(VirtioPciError::Misaligned { 537 vaddr, 538 alignment: align_of::<T>(), 539 }); 540 } 541 let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap(); 542 Ok(vaddr.cast()) 543 } 544 545 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针 546 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针 547 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error 548 fn get_bar_region_slice<T>( 549 device_bar: &PciStandardDeviceBar, 550 struct_info: &VirtioCapabilityInfo, 551 ) -> Result<NonNull<[T]>, VirtioPciError> { 552 let ptr = get_bar_region::<T>(device_bar, struct_info)?; 553 // let raw_slice = 554 // ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>()); 555 Ok(nonnull_slice_from_raw_parts( 556 ptr, 557 struct_info.length as usize / size_of::<T>(), 558 )) 559 } 560 561 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> { 562 NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap() 563 } 564