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