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