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