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