xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision 0dd8ff43325b494ea777dbe6e552fdc77b9dabc8)
126d84a31SYJwu2023 //! PCI transport for VirtIO.
278bf93f0SYJwu2023 use crate::arch::{PciArch, TraitPciArch};
326d84a31SYJwu2023 use crate::driver::pci::pci::{
478bf93f0SYJwu2023     BusDeviceFunction, PciDeviceStructure, PciDeviceStructureGeneralDevice, PciError,
578bf93f0SYJwu2023     PciStandardDeviceBar, PCI_CAP_ID_VNDR,
626d84a31SYJwu2023 };
773c607aaSYJwu2023 
8*0dd8ff43SYJwu2023 use crate::driver::pci::pci_irq::{IrqCommonMsg, IrqMsg, IrqSpecificMsg, PciInterrupt, IRQ};
9*0dd8ff43SYJwu2023 use crate::include::bindings::bindings::pt_regs;
10*0dd8ff43SYJwu2023 use crate::kdebug;
1173c607aaSYJwu2023 use crate::libs::volatile::{
1273c607aaSYJwu2023     volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
1373c607aaSYJwu2023 };
142dd9f0c7SLoGin use crate::mm::VirtAddr;
15*0dd8ff43SYJwu2023 use crate::net::net_core::poll_ifaces_try_lock_onetime;
16*0dd8ff43SYJwu2023 use alloc::ffi::CString;
1726d84a31SYJwu2023 use core::{
1826d84a31SYJwu2023     fmt::{self, Display, Formatter},
1926d84a31SYJwu2023     mem::{align_of, size_of},
2026d84a31SYJwu2023     ptr::{self, addr_of_mut, NonNull},
2126d84a31SYJwu2023 };
2226d84a31SYJwu2023 use virtio_drivers::{
2326d84a31SYJwu2023     transport::{DeviceStatus, DeviceType, Transport},
2473c607aaSYJwu2023     Error, Hal, PhysAddr,
2526d84a31SYJwu2023 };
2626d84a31SYJwu2023 
2726d84a31SYJwu2023 /// The PCI vendor ID for VirtIO devices.
2826d84a31SYJwu2023 /// PCI Virtio设备的vendor ID
2926d84a31SYJwu2023 const VIRTIO_VENDOR_ID: u16 = 0x1af4;
3026d84a31SYJwu2023 
3126d84a31SYJwu2023 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
3226d84a31SYJwu2023 /// PCI Virtio设备的DEVICE_ID 的offset
3326d84a31SYJwu2023 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
3426d84a31SYJwu2023 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型
3526d84a31SYJwu2023 const TRANSITIONAL_NETWORK: u16 = 0x1000;
3626d84a31SYJwu2023 const TRANSITIONAL_BLOCK: u16 = 0x1001;
3726d84a31SYJwu2023 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
3826d84a31SYJwu2023 const TRANSITIONAL_CONSOLE: u16 = 0x1003;
3926d84a31SYJwu2023 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
4026d84a31SYJwu2023 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
4126d84a31SYJwu2023 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
4226d84a31SYJwu2023 
4326d84a31SYJwu2023 /// The offset of the bar field within `virtio_pci_cap`.
4426d84a31SYJwu2023 const CAP_BAR_OFFSET: u8 = 4;
4526d84a31SYJwu2023 /// The offset of the offset field with `virtio_pci_cap`.
4626d84a31SYJwu2023 const CAP_BAR_OFFSET_OFFSET: u8 = 8;
4726d84a31SYJwu2023 /// The offset of the `length` field within `virtio_pci_cap`.
4826d84a31SYJwu2023 const CAP_LENGTH_OFFSET: u8 = 12;
4926d84a31SYJwu2023 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
5026d84a31SYJwu2023 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
5126d84a31SYJwu2023 
5226d84a31SYJwu2023 /// Common configuration.
5326d84a31SYJwu2023 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
5426d84a31SYJwu2023 /// Notifications.
5526d84a31SYJwu2023 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
5626d84a31SYJwu2023 /// ISR Status.
5726d84a31SYJwu2023 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
5826d84a31SYJwu2023 /// Device specific configuration.
5926d84a31SYJwu2023 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
6026d84a31SYJwu2023 
61*0dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号
62*0dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR: u16 = 56;
63*0dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号的表项号
64*0dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR_INDEX: u16 = 0;
65*0dd8ff43SYJwu2023 // 接收的queue
66*0dd8ff43SYJwu2023 const QUEUE_RECEIVE: u16 = 0;
6726d84a31SYJwu2023 ///@brief device id 转换为设备类型
6826d84a31SYJwu2023 ///@param pci_device_id,device_id
6926d84a31SYJwu2023 ///@return DeviceType 对应的设备类型
7026d84a31SYJwu2023 fn device_type(pci_device_id: u16) -> DeviceType {
7126d84a31SYJwu2023     match pci_device_id {
7226d84a31SYJwu2023         TRANSITIONAL_NETWORK => DeviceType::Network,
7326d84a31SYJwu2023         TRANSITIONAL_BLOCK => DeviceType::Block,
7426d84a31SYJwu2023         TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
7526d84a31SYJwu2023         TRANSITIONAL_CONSOLE => DeviceType::Console,
7626d84a31SYJwu2023         TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
7726d84a31SYJwu2023         TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
7826d84a31SYJwu2023         TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
7926d84a31SYJwu2023         id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
8026d84a31SYJwu2023         _ => DeviceType::Invalid,
8126d84a31SYJwu2023     }
8226d84a31SYJwu2023 }
8326d84a31SYJwu2023 
8426d84a31SYJwu2023 /// PCI transport for VirtIO.
8526d84a31SYJwu2023 ///
8626d84a31SYJwu2023 /// Ref: 4.1 Virtio Over PCI Bus
8713776c11Slogin #[derive(Debug, Clone)]
8826d84a31SYJwu2023 pub struct PciTransport {
8926d84a31SYJwu2023     device_type: DeviceType,
9026d84a31SYJwu2023     /// The bus, device and function identifier for the VirtIO device.
911496ba7bSLoGin     _bus_device_function: BusDeviceFunction,
9226d84a31SYJwu2023     /// The common configuration structure within some BAR.
9326d84a31SYJwu2023     common_cfg: NonNull<CommonCfg>,
9426d84a31SYJwu2023     /// The start of the queue notification region within some BAR.
9526d84a31SYJwu2023     notify_region: NonNull<[WriteOnly<u16>]>,
9626d84a31SYJwu2023     notify_off_multiplier: u32,
9726d84a31SYJwu2023     /// The ISR status register within some BAR.
9826d84a31SYJwu2023     isr_status: NonNull<Volatile<u8>>,
9926d84a31SYJwu2023     /// The VirtIO device-specific configuration within some BAR.
10026d84a31SYJwu2023     config_space: Option<NonNull<[u32]>>,
10126d84a31SYJwu2023 }
10226d84a31SYJwu2023 
103*0dd8ff43SYJwu2023 unsafe extern "C" fn virtio_irq_hander(_irq_num: u64, _irq_paramer: u64, _regs: *mut pt_regs) {
104*0dd8ff43SYJwu2023     // kdebug!("12345");
105*0dd8ff43SYJwu2023     poll_ifaces_try_lock_onetime().ok();
106*0dd8ff43SYJwu2023 }
107*0dd8ff43SYJwu2023 
10826d84a31SYJwu2023 impl PciTransport {
10926d84a31SYJwu2023     /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
11026d84a31SYJwu2023     /// root controller.
11126d84a31SYJwu2023     ///
11278bf93f0SYJwu2023     ///
11378bf93f0SYJwu2023     pub fn new<H: Hal>(
11478bf93f0SYJwu2023         device: &mut PciDeviceStructureGeneralDevice,
11578bf93f0SYJwu2023     ) -> Result<Self, VirtioPciError> {
11678bf93f0SYJwu2023         let header = &device.common_header;
11778bf93f0SYJwu2023         let bus_device_function = header.bus_device_function;
11878bf93f0SYJwu2023         if header.vendor_id != VIRTIO_VENDOR_ID {
11978bf93f0SYJwu2023             return Err(VirtioPciError::InvalidVendorId(header.vendor_id));
12026d84a31SYJwu2023         }
12178bf93f0SYJwu2023         let device_type = device_type(header.device_id);
12226d84a31SYJwu2023         // Find the PCI capabilities we need.
12313776c11Slogin         let mut common_cfg: Option<VirtioCapabilityInfo> = None;
12413776c11Slogin         let mut notify_cfg: Option<VirtioCapabilityInfo> = None;
12526d84a31SYJwu2023         let mut notify_off_multiplier = 0;
12626d84a31SYJwu2023         let mut isr_cfg = None;
12726d84a31SYJwu2023         let mut device_cfg = None;
128cc36cf4aSYJwu2023         device.bar_ioremap().unwrap()?;
12978bf93f0SYJwu2023         device.enable_master();
130*0dd8ff43SYJwu2023         let standard_device = device.as_standard_device_mut().unwrap();
131*0dd8ff43SYJwu2023         // 目前缺少对PCI设备中断号的统一管理,所以这里需要指定一个中断号。不能与其他中断重复
132*0dd8ff43SYJwu2023         let irq_vector = standard_device.irq_vector_mut().unwrap();
133*0dd8ff43SYJwu2023         irq_vector.push(VIRTIO_RECV_VECTOR);
134*0dd8ff43SYJwu2023         standard_device
135*0dd8ff43SYJwu2023             .irq_init(IRQ::PCI_IRQ_MSIX)
136*0dd8ff43SYJwu2023             .expect("IRQ init failed");
137*0dd8ff43SYJwu2023         // 中断相关信息
138*0dd8ff43SYJwu2023         let msg = IrqMsg {
139*0dd8ff43SYJwu2023             irq_common_message: IrqCommonMsg {
140*0dd8ff43SYJwu2023                 irq_index: 0,
141*0dd8ff43SYJwu2023                 irq_name: CString::new(
142*0dd8ff43SYJwu2023                     "Virtio_Recv_
143*0dd8ff43SYJwu2023                 IRQ",
144*0dd8ff43SYJwu2023                 )
145*0dd8ff43SYJwu2023                 .expect("CString::new failed"),
146*0dd8ff43SYJwu2023                 irq_parameter: 0,
147*0dd8ff43SYJwu2023                 irq_hander: virtio_irq_hander,
148*0dd8ff43SYJwu2023                 irq_ack: None,
149*0dd8ff43SYJwu2023             },
150*0dd8ff43SYJwu2023             irq_specific_message: IrqSpecificMsg::msi_default(),
151*0dd8ff43SYJwu2023         };
152*0dd8ff43SYJwu2023         standard_device.irq_install(msg)?;
153*0dd8ff43SYJwu2023         standard_device.irq_enable(true)?;
15426d84a31SYJwu2023         //device_capability为迭代器,遍历其相当于遍历所有的cap空间
15578bf93f0SYJwu2023         for capability in device.capabilities().unwrap() {
15626d84a31SYJwu2023             if capability.id != PCI_CAP_ID_VNDR {
15726d84a31SYJwu2023                 continue;
15826d84a31SYJwu2023             }
15926d84a31SYJwu2023             let cap_len = capability.private_header as u8;
16026d84a31SYJwu2023             let cfg_type = (capability.private_header >> 8) as u8;
16126d84a31SYJwu2023             if cap_len < 16 {
16226d84a31SYJwu2023                 continue;
16326d84a31SYJwu2023             }
16426d84a31SYJwu2023             let struct_info = VirtioCapabilityInfo {
16578bf93f0SYJwu2023                 bar: PciArch::read_config(&bus_device_function, capability.offset + CAP_BAR_OFFSET)
16678bf93f0SYJwu2023                     as u8,
16778bf93f0SYJwu2023                 offset: PciArch::read_config(
16878bf93f0SYJwu2023                     &bus_device_function,
16926d84a31SYJwu2023                     capability.offset + CAP_BAR_OFFSET_OFFSET,
17078bf93f0SYJwu2023                 ),
17178bf93f0SYJwu2023                 length: PciArch::read_config(
17278bf93f0SYJwu2023                     &bus_device_function,
17326d84a31SYJwu2023                     capability.offset + CAP_LENGTH_OFFSET,
17478bf93f0SYJwu2023                 ),
17526d84a31SYJwu2023             };
17626d84a31SYJwu2023 
17726d84a31SYJwu2023             match cfg_type {
17826d84a31SYJwu2023                 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
17926d84a31SYJwu2023                     common_cfg = Some(struct_info);
18026d84a31SYJwu2023                 }
18126d84a31SYJwu2023                 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
18226d84a31SYJwu2023                     notify_cfg = Some(struct_info);
18378bf93f0SYJwu2023                     notify_off_multiplier = PciArch::read_config(
18478bf93f0SYJwu2023                         &bus_device_function,
18526d84a31SYJwu2023                         capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET,
18626d84a31SYJwu2023                     );
18726d84a31SYJwu2023                 }
18826d84a31SYJwu2023                 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
18926d84a31SYJwu2023                     isr_cfg = Some(struct_info);
19026d84a31SYJwu2023                 }
19126d84a31SYJwu2023                 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
19226d84a31SYJwu2023                     device_cfg = Some(struct_info);
19326d84a31SYJwu2023                 }
19426d84a31SYJwu2023                 _ => {}
19526d84a31SYJwu2023             }
19626d84a31SYJwu2023         }
19726d84a31SYJwu2023 
19826d84a31SYJwu2023         let common_cfg = get_bar_region::<_>(
19978bf93f0SYJwu2023             &device.standard_device_bar,
20026d84a31SYJwu2023             &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
20126d84a31SYJwu2023         )?;
20226d84a31SYJwu2023 
20326d84a31SYJwu2023         let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
20426d84a31SYJwu2023         if notify_off_multiplier % 2 != 0 {
20526d84a31SYJwu2023             return Err(VirtioPciError::InvalidNotifyOffMultiplier(
20626d84a31SYJwu2023                 notify_off_multiplier,
20726d84a31SYJwu2023             ));
20826d84a31SYJwu2023         }
20973c607aaSYJwu2023         //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length);
21078bf93f0SYJwu2023         let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, &notify_cfg)?;
21126d84a31SYJwu2023         let isr_status = get_bar_region::<_>(
21278bf93f0SYJwu2023             &device.standard_device_bar,
21326d84a31SYJwu2023             &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
21426d84a31SYJwu2023         )?;
21526d84a31SYJwu2023         let config_space = if let Some(device_cfg) = device_cfg {
21678bf93f0SYJwu2023             Some(get_bar_region_slice::<_>(
21778bf93f0SYJwu2023                 &device.standard_device_bar,
21878bf93f0SYJwu2023                 &device_cfg,
21978bf93f0SYJwu2023             )?)
22026d84a31SYJwu2023         } else {
22126d84a31SYJwu2023             None
22226d84a31SYJwu2023         };
22326d84a31SYJwu2023         Ok(Self {
22426d84a31SYJwu2023             device_type,
2251496ba7bSLoGin             _bus_device_function: bus_device_function,
22626d84a31SYJwu2023             common_cfg,
22726d84a31SYJwu2023             notify_region,
22826d84a31SYJwu2023             notify_off_multiplier,
22926d84a31SYJwu2023             isr_status,
23026d84a31SYJwu2023             config_space,
23126d84a31SYJwu2023         })
23226d84a31SYJwu2023     }
23326d84a31SYJwu2023 }
23426d84a31SYJwu2023 
23526d84a31SYJwu2023 impl Transport for PciTransport {
23626d84a31SYJwu2023     fn device_type(&self) -> DeviceType {
23726d84a31SYJwu2023         self.device_type
23826d84a31SYJwu2023     }
23926d84a31SYJwu2023 
24026d84a31SYJwu2023     fn read_device_features(&mut self) -> u64 {
24126d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
24226d84a31SYJwu2023         // was aligned.
24326d84a31SYJwu2023         unsafe {
24426d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 0);
24526d84a31SYJwu2023             let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
24626d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 1);
24726d84a31SYJwu2023             device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
24826d84a31SYJwu2023             device_features_bits
24926d84a31SYJwu2023         }
25026d84a31SYJwu2023     }
25126d84a31SYJwu2023 
25226d84a31SYJwu2023     fn write_driver_features(&mut self, driver_features: u64) {
25326d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
25426d84a31SYJwu2023         // was aligned.
25526d84a31SYJwu2023         unsafe {
25626d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 0);
25726d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature, driver_features as u32);
25826d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 1);
25926d84a31SYJwu2023             volwrite!(
26026d84a31SYJwu2023                 self.common_cfg,
26126d84a31SYJwu2023                 driver_feature,
26226d84a31SYJwu2023                 (driver_features >> 32) as u32
26326d84a31SYJwu2023             );
26426d84a31SYJwu2023         }
26526d84a31SYJwu2023     }
26626d84a31SYJwu2023 
26726d84a31SYJwu2023     fn max_queue_size(&self) -> u32 {
26826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
26926d84a31SYJwu2023         // was aligned.
27026d84a31SYJwu2023         unsafe { volread!(self.common_cfg, queue_size) }.into()
27126d84a31SYJwu2023     }
27226d84a31SYJwu2023 
27326d84a31SYJwu2023     fn notify(&mut self, queue: u16) {
27426d84a31SYJwu2023         // Safe because the common config and notify region pointers are valid and we checked in
27526d84a31SYJwu2023         // get_bar_region that they were aligned.
27626d84a31SYJwu2023         unsafe {
27726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
27826d84a31SYJwu2023             // TODO: Consider caching this somewhere (per queue).
27926d84a31SYJwu2023             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
28026d84a31SYJwu2023 
28126d84a31SYJwu2023             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
28226d84a31SYJwu2023             let index = offset_bytes / size_of::<u16>();
28326d84a31SYJwu2023             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
28426d84a31SYJwu2023         }
28526d84a31SYJwu2023     }
28626d84a31SYJwu2023 
28726d84a31SYJwu2023     fn set_status(&mut self, status: DeviceStatus) {
28826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
28926d84a31SYJwu2023         // was aligned.
29026d84a31SYJwu2023         unsafe {
29126d84a31SYJwu2023             volwrite!(self.common_cfg, device_status, status.bits() as u8);
29226d84a31SYJwu2023         }
29326d84a31SYJwu2023     }
29426d84a31SYJwu2023 
29526d84a31SYJwu2023     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
29626d84a31SYJwu2023         // No-op, the PCI transport doesn't care.
29726d84a31SYJwu2023     }
29873c607aaSYJwu2023     fn requires_legacy_layout(&self) -> bool {
29973c607aaSYJwu2023         false
30073c607aaSYJwu2023     }
30126d84a31SYJwu2023     fn queue_set(
30226d84a31SYJwu2023         &mut self,
30326d84a31SYJwu2023         queue: u16,
30426d84a31SYJwu2023         size: u32,
30526d84a31SYJwu2023         descriptors: PhysAddr,
30626d84a31SYJwu2023         driver_area: PhysAddr,
30726d84a31SYJwu2023         device_area: PhysAddr,
30826d84a31SYJwu2023     ) {
30926d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
31026d84a31SYJwu2023         // was aligned.
31126d84a31SYJwu2023         unsafe {
31226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
31326d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, size as u16);
31426d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
31526d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
31626d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, device_area as u64);
317*0dd8ff43SYJwu2023             if queue == QUEUE_RECEIVE {
318*0dd8ff43SYJwu2023                 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX);
319*0dd8ff43SYJwu2023                 let vector = volread!(self.common_cfg, queue_msix_vector);
320*0dd8ff43SYJwu2023                 if vector != VIRTIO_RECV_VECTOR_INDEX {
321*0dd8ff43SYJwu2023                     panic!("Vector set failed");
322*0dd8ff43SYJwu2023                 }
323*0dd8ff43SYJwu2023             }
32426d84a31SYJwu2023             volwrite!(self.common_cfg, queue_enable, 1);
32526d84a31SYJwu2023         }
32626d84a31SYJwu2023     }
32726d84a31SYJwu2023 
32826d84a31SYJwu2023     fn queue_unset(&mut self, queue: u16) {
32926d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
33026d84a31SYJwu2023         // was aligned.
33126d84a31SYJwu2023         unsafe {
33226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
33326d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, 0);
33426d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, 0);
33526d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, 0);
33626d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, 0);
33726d84a31SYJwu2023         }
33826d84a31SYJwu2023     }
33926d84a31SYJwu2023 
34026d84a31SYJwu2023     fn queue_used(&mut self, queue: u16) -> bool {
34126d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
34226d84a31SYJwu2023         // was aligned.
34326d84a31SYJwu2023         unsafe {
34426d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
34526d84a31SYJwu2023             volread!(self.common_cfg, queue_enable) == 1
34626d84a31SYJwu2023         }
34726d84a31SYJwu2023     }
34826d84a31SYJwu2023 
34926d84a31SYJwu2023     fn ack_interrupt(&mut self) -> bool {
35026d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
35126d84a31SYJwu2023         // was aligned.
35226d84a31SYJwu2023         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
35326d84a31SYJwu2023         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
35426d84a31SYJwu2023         // TODO: Distinguish between queue interrupt and device configuration interrupt.
35526d84a31SYJwu2023         isr_status & 0x3 != 0
35626d84a31SYJwu2023     }
35726d84a31SYJwu2023 
35826d84a31SYJwu2023     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
35926d84a31SYJwu2023         if let Some(config_space) = self.config_space {
36026d84a31SYJwu2023             if size_of::<T>() > config_space.len() * size_of::<u32>() {
36126d84a31SYJwu2023                 Err(Error::ConfigSpaceTooSmall)
36226d84a31SYJwu2023             } else if align_of::<T>() > 4 {
36326d84a31SYJwu2023                 // Panic as this should only happen if the driver is written incorrectly.
36426d84a31SYJwu2023                 panic!(
36526d84a31SYJwu2023                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
36626d84a31SYJwu2023                     align_of::<T>()
36726d84a31SYJwu2023                 );
36826d84a31SYJwu2023             } else {
36926d84a31SYJwu2023                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
37026d84a31SYJwu2023                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
37126d84a31SYJwu2023                 Ok(config_space_ptr.cast())
37226d84a31SYJwu2023             }
37326d84a31SYJwu2023         } else {
37426d84a31SYJwu2023             Err(Error::ConfigSpaceMissing)
37526d84a31SYJwu2023         }
37626d84a31SYJwu2023     }
37726d84a31SYJwu2023 }
37826d84a31SYJwu2023 
37973c607aaSYJwu2023 impl Drop for PciTransport {
38073c607aaSYJwu2023     fn drop(&mut self) {
38173c607aaSYJwu2023         // Reset the device when the transport is dropped.
38273c607aaSYJwu2023         self.set_status(DeviceStatus::empty())
38373c607aaSYJwu2023     }
38473c607aaSYJwu2023 }
38573c607aaSYJwu2023 
38626d84a31SYJwu2023 #[repr(C)]
38726d84a31SYJwu2023 struct CommonCfg {
38826d84a31SYJwu2023     device_feature_select: Volatile<u32>,
38926d84a31SYJwu2023     device_feature: ReadOnly<u32>,
39026d84a31SYJwu2023     driver_feature_select: Volatile<u32>,
39126d84a31SYJwu2023     driver_feature: Volatile<u32>,
39226d84a31SYJwu2023     msix_config: Volatile<u16>,
39326d84a31SYJwu2023     num_queues: ReadOnly<u16>,
39426d84a31SYJwu2023     device_status: Volatile<u8>,
39526d84a31SYJwu2023     config_generation: ReadOnly<u8>,
39626d84a31SYJwu2023     queue_select: Volatile<u16>,
39726d84a31SYJwu2023     queue_size: Volatile<u16>,
39826d84a31SYJwu2023     queue_msix_vector: Volatile<u16>,
39926d84a31SYJwu2023     queue_enable: Volatile<u16>,
40026d84a31SYJwu2023     queue_notify_off: Volatile<u16>,
40126d84a31SYJwu2023     queue_desc: Volatile<u64>,
40226d84a31SYJwu2023     queue_driver: Volatile<u64>,
40326d84a31SYJwu2023     queue_device: Volatile<u64>,
40426d84a31SYJwu2023 }
40526d84a31SYJwu2023 
40626d84a31SYJwu2023 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
40726d84a31SYJwu2023 /// cfg空间在哪个bar的多少偏移处,长度多少
40826d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
40926d84a31SYJwu2023 struct VirtioCapabilityInfo {
41026d84a31SYJwu2023     /// The bar in which the structure can be found.
41126d84a31SYJwu2023     bar: u8,
41226d84a31SYJwu2023     /// The offset within the bar.
41326d84a31SYJwu2023     offset: u32,
41426d84a31SYJwu2023     /// The length in bytes of the structure within the bar.
41526d84a31SYJwu2023     length: u32,
41626d84a31SYJwu2023 }
41726d84a31SYJwu2023 
41826d84a31SYJwu2023 /// An error encountered initialising a VirtIO PCI transport.
41926d84a31SYJwu2023 /// VirtIO PCI transport 初始化时的错误
42026d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
42126d84a31SYJwu2023 pub enum VirtioPciError {
42226d84a31SYJwu2023     /// PCI device vender ID was not the VirtIO vendor ID.
42326d84a31SYJwu2023     InvalidVendorId(u16),
42426d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
42526d84a31SYJwu2023     MissingCommonConfig,
42626d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
42726d84a31SYJwu2023     MissingNotifyConfig,
42826d84a31SYJwu2023     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
42926d84a31SYJwu2023     /// of 2.
43026d84a31SYJwu2023     InvalidNotifyOffMultiplier(u32),
43126d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
43226d84a31SYJwu2023     MissingIsrConfig,
43326d84a31SYJwu2023     /// An IO BAR was provided rather than a memory BAR.
43426d84a31SYJwu2023     UnexpectedBarType,
43526d84a31SYJwu2023     /// A BAR which we need was not allocated an address.
43626d84a31SYJwu2023     BarNotAllocated(u8),
43726d84a31SYJwu2023     /// The offset for some capability was greater than the length of the BAR.
43826d84a31SYJwu2023     BarOffsetOutOfRange,
43926d84a31SYJwu2023     /// The virtual address was not aligned as expected.
44026d84a31SYJwu2023     Misaligned {
44126d84a31SYJwu2023         /// The virtual address in question.
44226d84a31SYJwu2023         vaddr: VirtAddr,
44326d84a31SYJwu2023         /// The expected alignment in bytes.
44426d84a31SYJwu2023         alignment: usize,
44526d84a31SYJwu2023     },
44626d84a31SYJwu2023     ///获取虚拟地址失败
44726d84a31SYJwu2023     BarGetVaddrFailed,
44826d84a31SYJwu2023     /// A generic PCI error,
44926d84a31SYJwu2023     Pci(PciError),
45026d84a31SYJwu2023 }
45126d84a31SYJwu2023 
45226d84a31SYJwu2023 impl Display for VirtioPciError {
45326d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
45426d84a31SYJwu2023         match self {
45526d84a31SYJwu2023             Self::InvalidVendorId(vendor_id) => write!(
45626d84a31SYJwu2023                 f,
45726d84a31SYJwu2023                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
45826d84a31SYJwu2023                 vendor_id, VIRTIO_VENDOR_ID
45926d84a31SYJwu2023             ),
46026d84a31SYJwu2023             Self::MissingCommonConfig => write!(
46126d84a31SYJwu2023                 f,
46226d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
46326d84a31SYJwu2023             ),
46426d84a31SYJwu2023             Self::MissingNotifyConfig => write!(
46526d84a31SYJwu2023                 f,
46626d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
46726d84a31SYJwu2023             ),
46826d84a31SYJwu2023             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
46926d84a31SYJwu2023                 write!(
47026d84a31SYJwu2023                     f,
47126d84a31SYJwu2023                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
47226d84a31SYJwu2023                     notify_off_multiplier
47326d84a31SYJwu2023                 )
47426d84a31SYJwu2023             }
47526d84a31SYJwu2023             Self::MissingIsrConfig => {
47626d84a31SYJwu2023                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
47726d84a31SYJwu2023             }
47826d84a31SYJwu2023             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
47926d84a31SYJwu2023             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
48026d84a31SYJwu2023             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
48126d84a31SYJwu2023             Self::Misaligned { vaddr, alignment } => write!(
48226d84a31SYJwu2023                 f,
4832dd9f0c7SLoGin                 "Virtual address {:?} was not aligned to a {} byte boundary as expected.",
48426d84a31SYJwu2023                 vaddr, alignment
48526d84a31SYJwu2023             ),
48626d84a31SYJwu2023             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
48726d84a31SYJwu2023             Self::Pci(pci_error) => pci_error.fmt(f),
48826d84a31SYJwu2023         }
48926d84a31SYJwu2023     }
49026d84a31SYJwu2023 }
49113776c11Slogin 
49226d84a31SYJwu2023 /// PCI error到VirtioPciError的转换,层层上报
49326d84a31SYJwu2023 impl From<PciError> for VirtioPciError {
49426d84a31SYJwu2023     fn from(error: PciError) -> Self {
49526d84a31SYJwu2023         Self::Pci(error)
49626d84a31SYJwu2023     }
49726d84a31SYJwu2023 }
49826d84a31SYJwu2023 
49926d84a31SYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的指针
50026d84a31SYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
50126d84a31SYJwu2023 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
50226d84a31SYJwu2023 fn get_bar_region<T>(
50378bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
50426d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
50526d84a31SYJwu2023 ) -> Result<NonNull<T>, VirtioPciError> {
50626d84a31SYJwu2023     let bar_info = device_bar.get_bar(struct_info.bar)?;
50726d84a31SYJwu2023     let (bar_address, bar_size) = bar_info
50826d84a31SYJwu2023         .memory_address_size()
50926d84a31SYJwu2023         .ok_or(VirtioPciError::UnexpectedBarType)?;
51026d84a31SYJwu2023     if bar_address == 0 {
51126d84a31SYJwu2023         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
51226d84a31SYJwu2023     }
51326d84a31SYJwu2023     if struct_info.offset + struct_info.length > bar_size
51426d84a31SYJwu2023         || size_of::<T>() > struct_info.length as usize
51526d84a31SYJwu2023     {
51626d84a31SYJwu2023         return Err(VirtioPciError::BarOffsetOutOfRange);
51726d84a31SYJwu2023     }
51873c607aaSYJwu2023     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
51926d84a31SYJwu2023     let vaddr = (bar_info
52026d84a31SYJwu2023         .virtual_address()
5212dd9f0c7SLoGin         .ok_or(VirtioPciError::BarGetVaddrFailed)?)
52226d84a31SYJwu2023         + struct_info.offset as usize;
5232dd9f0c7SLoGin     if vaddr.data() % align_of::<T>() != 0 {
52426d84a31SYJwu2023         return Err(VirtioPciError::Misaligned {
52526d84a31SYJwu2023             vaddr,
52626d84a31SYJwu2023             alignment: align_of::<T>(),
52726d84a31SYJwu2023         });
52826d84a31SYJwu2023     }
5292dd9f0c7SLoGin     let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap();
53073c607aaSYJwu2023     Ok(vaddr.cast())
53126d84a31SYJwu2023 }
53226d84a31SYJwu2023 
533cc36cf4aSYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针
53473c607aaSYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
53526d84a31SYJwu2023 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
53626d84a31SYJwu2023 fn get_bar_region_slice<T>(
53778bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
53826d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
53926d84a31SYJwu2023 ) -> Result<NonNull<[T]>, VirtioPciError> {
54026d84a31SYJwu2023     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
54173c607aaSYJwu2023     // let raw_slice =
54273c607aaSYJwu2023     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
54373c607aaSYJwu2023     Ok(nonnull_slice_from_raw_parts(
54473c607aaSYJwu2023         ptr,
54573c607aaSYJwu2023         struct_info.length as usize / size_of::<T>(),
54673c607aaSYJwu2023     ))
54773c607aaSYJwu2023 }
54813776c11Slogin 
54973c607aaSYJwu2023 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
55073c607aaSYJwu2023     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
55126d84a31SYJwu2023 }
552