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