xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision 370472f7288b568c7b80815f5b150daf4496446c)
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, &notify_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(&self) -> u32 {
280         // Safe because the common config pointer is valid and we checked in get_bar_region that it
281         // was aligned.
282         unsafe { volread!(self.common_cfg, queue_size) }.into()
283     }
284 
285     fn notify(&mut self, queue: u16) {
286         // Safe because the common config and notify region pointers are valid and we checked in
287         // get_bar_region that they were aligned.
288         unsafe {
289             volwrite!(self.common_cfg, queue_select, queue);
290             // TODO: Consider caching this somewhere (per queue).
291             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
292 
293             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
294             let index = offset_bytes / size_of::<u16>();
295             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
296         }
297     }
298 
299     fn set_status(&mut self, status: DeviceStatus) {
300         // Safe because the common config pointer is valid and we checked in get_bar_region that it
301         // was aligned.
302         unsafe {
303             volwrite!(self.common_cfg, device_status, status.bits() as u8);
304         }
305     }
306 
307     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
308         // No-op, the PCI transport doesn't care.
309     }
310     fn requires_legacy_layout(&self) -> bool {
311         false
312     }
313     fn queue_set(
314         &mut self,
315         queue: u16,
316         size: u32,
317         descriptors: PhysAddr,
318         driver_area: PhysAddr,
319         device_area: PhysAddr,
320     ) {
321         // Safe because the common config pointer is valid and we checked in get_bar_region that it
322         // was aligned.
323         unsafe {
324             volwrite!(self.common_cfg, queue_select, queue);
325             volwrite!(self.common_cfg, queue_size, size as u16);
326             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
327             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
328             volwrite!(self.common_cfg, queue_device, device_area as u64);
329             // 这里设置队列中断对应的中断项
330             if queue == QUEUE_RECEIVE {
331                 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX);
332                 let vector = volread!(self.common_cfg, queue_msix_vector);
333                 if vector != VIRTIO_RECV_VECTOR_INDEX {
334                     panic!("Vector set failed");
335                 }
336             }
337             volwrite!(self.common_cfg, queue_enable, 1);
338         }
339     }
340 
341     fn queue_unset(&mut self, queue: u16) {
342         // Safe because the common config pointer is valid and we checked in get_bar_region that it
343         // was aligned.
344         unsafe {
345             volwrite!(self.common_cfg, queue_select, queue);
346             volwrite!(self.common_cfg, queue_size, 0);
347             volwrite!(self.common_cfg, queue_desc, 0);
348             volwrite!(self.common_cfg, queue_driver, 0);
349             volwrite!(self.common_cfg, queue_device, 0);
350         }
351     }
352 
353     fn queue_used(&mut self, queue: u16) -> bool {
354         // Safe because the common config pointer is valid and we checked in get_bar_region that it
355         // was aligned.
356         unsafe {
357             volwrite!(self.common_cfg, queue_select, queue);
358             volread!(self.common_cfg, queue_enable) == 1
359         }
360     }
361 
362     fn ack_interrupt(&mut self) -> bool {
363         // Safe because the common config pointer is valid and we checked in get_bar_region that it
364         // was aligned.
365         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
366         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
367         // TODO: Distinguish between queue interrupt and device configuration interrupt.
368         isr_status & 0x3 != 0
369     }
370 
371     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
372         if let Some(config_space) = self.config_space {
373             if size_of::<T>() > config_space.len() * size_of::<u32>() {
374                 Err(Error::ConfigSpaceTooSmall)
375             } else if align_of::<T>() > 4 {
376                 // Panic as this should only happen if the driver is written incorrectly.
377                 panic!(
378                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
379                     align_of::<T>()
380                 );
381             } else {
382                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
383                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
384                 Ok(config_space_ptr.cast())
385             }
386         } else {
387             Err(Error::ConfigSpaceMissing)
388         }
389     }
390 }
391 
392 impl Drop for PciTransport {
393     fn drop(&mut self) {
394         // Reset the device when the transport is dropped.
395         self.set_status(DeviceStatus::empty());
396 
397         // todo: 调用pci的中断释放函数,并且在virtio_irq_manager里面删除对应的设备的中断
398     }
399 }
400 
401 #[repr(C)]
402 struct CommonCfg {
403     device_feature_select: Volatile<u32>,
404     device_feature: ReadOnly<u32>,
405     driver_feature_select: Volatile<u32>,
406     driver_feature: Volatile<u32>,
407     msix_config: Volatile<u16>,
408     num_queues: ReadOnly<u16>,
409     device_status: Volatile<u8>,
410     config_generation: ReadOnly<u8>,
411     queue_select: Volatile<u16>,
412     queue_size: Volatile<u16>,
413     queue_msix_vector: Volatile<u16>,
414     queue_enable: Volatile<u16>,
415     queue_notify_off: Volatile<u16>,
416     queue_desc: Volatile<u64>,
417     queue_driver: Volatile<u64>,
418     queue_device: Volatile<u64>,
419 }
420 
421 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
422 /// cfg空间在哪个bar的多少偏移处,长度多少
423 #[derive(Clone, Debug, Eq, PartialEq)]
424 struct VirtioCapabilityInfo {
425     /// The bar in which the structure can be found.
426     bar: u8,
427     /// The offset within the bar.
428     offset: u32,
429     /// The length in bytes of the structure within the bar.
430     length: u32,
431 }
432 
433 /// An error encountered initialising a VirtIO PCI transport.
434 /// VirtIO PCI transport 初始化时的错误
435 #[derive(Clone, Debug, Eq, PartialEq)]
436 pub enum VirtioPciError {
437     /// PCI device vender ID was not the VirtIO vendor ID.
438     InvalidVendorId(u16),
439     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
440     MissingCommonConfig,
441     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
442     MissingNotifyConfig,
443     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
444     /// of 2.
445     InvalidNotifyOffMultiplier(u32),
446     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
447     MissingIsrConfig,
448     /// An IO BAR was provided rather than a memory BAR.
449     UnexpectedBarType,
450     /// A BAR which we need was not allocated an address.
451     BarNotAllocated(u8),
452     /// The offset for some capability was greater than the length of the BAR.
453     BarOffsetOutOfRange,
454     /// The virtual address was not aligned as expected.
455     Misaligned {
456         /// The virtual address in question.
457         vaddr: VirtAddr,
458         /// The expected alignment in bytes.
459         alignment: usize,
460     },
461     ///获取虚拟地址失败
462     BarGetVaddrFailed,
463     /// A generic PCI error,
464     Pci(PciError),
465 }
466 
467 impl Display for VirtioPciError {
468     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
469         match self {
470             Self::InvalidVendorId(vendor_id) => write!(
471                 f,
472                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
473                 vendor_id, VIRTIO_VENDOR_ID
474             ),
475             Self::MissingCommonConfig => write!(
476                 f,
477                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
478             ),
479             Self::MissingNotifyConfig => write!(
480                 f,
481                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
482             ),
483             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
484                 write!(
485                     f,
486                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
487                     notify_off_multiplier
488                 )
489             }
490             Self::MissingIsrConfig => {
491                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
492             }
493             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
494             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
495             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
496             Self::Misaligned { vaddr, alignment } => write!(
497                 f,
498                 "Virtual address {:?} was not aligned to a {} byte boundary as expected.",
499                 vaddr, alignment
500             ),
501             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
502             Self::Pci(pci_error) => pci_error.fmt(f),
503         }
504     }
505 }
506 
507 /// PCI error到VirtioPciError的转换,层层上报
508 impl From<PciError> for VirtioPciError {
509     fn from(error: PciError) -> Self {
510         Self::Pci(error)
511     }
512 }
513 
514 /// @brief 获取虚拟地址并将其转化为对应类型的指针
515 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
516 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
517 fn get_bar_region<T>(
518     device_bar: &PciStandardDeviceBar,
519     struct_info: &VirtioCapabilityInfo,
520 ) -> Result<NonNull<T>, VirtioPciError> {
521     let bar_info = device_bar.get_bar(struct_info.bar)?;
522     let (bar_address, bar_size) = bar_info
523         .memory_address_size()
524         .ok_or(VirtioPciError::UnexpectedBarType)?;
525     if bar_address == 0 {
526         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
527     }
528     if struct_info.offset + struct_info.length > bar_size
529         || size_of::<T>() > struct_info.length as usize
530     {
531         return Err(VirtioPciError::BarOffsetOutOfRange);
532     }
533     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
534     let vaddr = (bar_info
535         .virtual_address()
536         .ok_or(VirtioPciError::BarGetVaddrFailed)?)
537         + struct_info.offset as usize;
538     if vaddr.data() % align_of::<T>() != 0 {
539         return Err(VirtioPciError::Misaligned {
540             vaddr,
541             alignment: align_of::<T>(),
542         });
543     }
544     let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap();
545     Ok(vaddr.cast())
546 }
547 
548 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针
549 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
550 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
551 fn get_bar_region_slice<T>(
552     device_bar: &PciStandardDeviceBar,
553     struct_info: &VirtioCapabilityInfo,
554 ) -> Result<NonNull<[T]>, VirtioPciError> {
555     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
556     // let raw_slice =
557     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
558     Ok(nonnull_slice_from_raw_parts(
559         ptr,
560         struct_info.length as usize / size_of::<T>(),
561     ))
562 }
563 
564 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
565     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
566 }
567 
568 /// `DefaultVirtioIrqHandler` 是一个默认的virtio设备中断处理程序。
569 ///
570 /// 当虚拟设备产生中断时,该处理程序会被调用。
571 ///
572 /// 它首先检查设备ID是否存在,然后尝试查找与设备ID关联的设备。
573 /// 如果找到设备,它会调用设备的 `handle_irq` 方法来处理中断。
574 /// 如果没有找到设备,它会记录一条警告并返回 `IrqReturn::NotHandled`,表示中断未被处理。
575 #[derive(Debug)]
576 struct DefaultVirtioIrqHandler;
577 
578 impl IrqHandler for DefaultVirtioIrqHandler {
579     fn handle(
580         &self,
581         irq: IrqNumber,
582         _static_data: Option<&dyn IrqHandlerData>,
583         dev_id: Option<Arc<dyn IrqHandlerData>>,
584     ) -> Result<IrqReturn, SystemError> {
585         let dev_id = dev_id.ok_or(SystemError::EINVAL)?;
586         let dev_id = dev_id
587             .arc_any()
588             .downcast::<DeviceId>()
589             .map_err(|_| SystemError::EINVAL)?;
590 
591         if let Some(dev) = virtio_irq_manager().lookup_device(&dev_id) {
592             return dev.handle_irq(irq);
593         } else {
594             // 未绑定具体设备,因此无法处理中断
595 
596             return Ok(IrqReturn::NotHandled);
597         }
598     }
599 }
600