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