xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision 0102d69fdd231e472d7bb3d609a41ae56a3799ee)
126d84a31SYJwu2023 //! PCI transport for VirtIO.
22709e017SLoGin 
3e2841179SLoGin use crate::driver::base::device::DeviceId;
426d84a31SYJwu2023 use crate::driver::pci::pci::{
5370472f7SLoGin     BusDeviceFunction, PciDeviceStructure, PciDeviceStructureGeneralDevice, PciError,
678bf93f0SYJwu2023     PciStandardDeviceBar, PCI_CAP_ID_VNDR,
726d84a31SYJwu2023 };
873c607aaSYJwu2023 
9ce5850adSLoGin use crate::driver::pci::pci_irq::{IrqCommonMsg, IrqSpecificMsg, PciInterrupt, PciIrqMsg, IRQ};
10370472f7SLoGin use crate::driver::pci::root::pci_root_0;
11e2841179SLoGin 
12e2841179SLoGin use crate::exception::IrqNumber;
13e2841179SLoGin 
1473c607aaSYJwu2023 use crate::libs::volatile::{
1573c607aaSYJwu2023     volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
1673c607aaSYJwu2023 };
172dd9f0c7SLoGin use crate::mm::VirtAddr;
18e2841179SLoGin 
19e2841179SLoGin use alloc::string::ToString;
20e2841179SLoGin use alloc::sync::Arc;
2126d84a31SYJwu2023 use core::{
2226d84a31SYJwu2023     fmt::{self, Display, Formatter},
2326d84a31SYJwu2023     mem::{align_of, size_of},
2426d84a31SYJwu2023     ptr::{self, addr_of_mut, NonNull},
2526d84a31SYJwu2023 };
2626d84a31SYJwu2023 use virtio_drivers::{
2726d84a31SYJwu2023     transport::{DeviceStatus, DeviceType, Transport},
2873c607aaSYJwu2023     Error, Hal, PhysAddr,
2926d84a31SYJwu2023 };
3026d84a31SYJwu2023 
31*0102d69fSLoGin use super::irq::DefaultVirtioIrqHandler;
32e32effb1SLoGin use super::VIRTIO_VENDOR_ID;
3326d84a31SYJwu2023 
3426d84a31SYJwu2023 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
3526d84a31SYJwu2023 /// PCI Virtio设备的DEVICE_ID 的offset
3626d84a31SYJwu2023 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
3726d84a31SYJwu2023 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型
3826d84a31SYJwu2023 const TRANSITIONAL_NETWORK: u16 = 0x1000;
3926d84a31SYJwu2023 const TRANSITIONAL_BLOCK: u16 = 0x1001;
4026d84a31SYJwu2023 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
4126d84a31SYJwu2023 const TRANSITIONAL_CONSOLE: u16 = 0x1003;
4226d84a31SYJwu2023 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
4326d84a31SYJwu2023 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
4426d84a31SYJwu2023 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
4526d84a31SYJwu2023 
4626d84a31SYJwu2023 /// The offset of the bar field within `virtio_pci_cap`.
4726d84a31SYJwu2023 const CAP_BAR_OFFSET: u8 = 4;
4826d84a31SYJwu2023 /// The offset of the offset field with `virtio_pci_cap`.
4926d84a31SYJwu2023 const CAP_BAR_OFFSET_OFFSET: u8 = 8;
5026d84a31SYJwu2023 /// The offset of the `length` field within `virtio_pci_cap`.
5126d84a31SYJwu2023 const CAP_LENGTH_OFFSET: u8 = 12;
5226d84a31SYJwu2023 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
5326d84a31SYJwu2023 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
5426d84a31SYJwu2023 
5526d84a31SYJwu2023 /// Common configuration.
5626d84a31SYJwu2023 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
5726d84a31SYJwu2023 /// Notifications.
5826d84a31SYJwu2023 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
5926d84a31SYJwu2023 /// ISR Status.
6026d84a31SYJwu2023 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
6126d84a31SYJwu2023 /// Device specific configuration.
6226d84a31SYJwu2023 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
6326d84a31SYJwu2023 
640dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号
65e2841179SLoGin const VIRTIO_RECV_VECTOR: IrqNumber = IrqNumber::new(56);
660dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号的表项号
670dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR_INDEX: u16 = 0;
68afc95d5cSYJwu2023 // 接收的queue号
690dd8ff43SYJwu2023 const QUEUE_RECEIVE: u16 = 0;
7026d84a31SYJwu2023 ///@brief device id 转换为设备类型
7126d84a31SYJwu2023 ///@param pci_device_id,device_id
7226d84a31SYJwu2023 ///@return DeviceType 对应的设备类型
7326d84a31SYJwu2023 fn device_type(pci_device_id: u16) -> DeviceType {
7426d84a31SYJwu2023     match pci_device_id {
7526d84a31SYJwu2023         TRANSITIONAL_NETWORK => DeviceType::Network,
7626d84a31SYJwu2023         TRANSITIONAL_BLOCK => DeviceType::Block,
7726d84a31SYJwu2023         TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
7826d84a31SYJwu2023         TRANSITIONAL_CONSOLE => DeviceType::Console,
7926d84a31SYJwu2023         TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
8026d84a31SYJwu2023         TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
8126d84a31SYJwu2023         TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
8226d84a31SYJwu2023         id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
8326d84a31SYJwu2023         _ => DeviceType::Invalid,
8426d84a31SYJwu2023     }
8526d84a31SYJwu2023 }
8626d84a31SYJwu2023 
8726d84a31SYJwu2023 /// PCI transport for VirtIO.
8826d84a31SYJwu2023 ///
8926d84a31SYJwu2023 /// Ref: 4.1 Virtio Over PCI Bus
90e2841179SLoGin #[allow(dead_code)]
9113776c11Slogin #[derive(Debug, Clone)]
9226d84a31SYJwu2023 pub struct PciTransport {
9326d84a31SYJwu2023     device_type: DeviceType,
9426d84a31SYJwu2023     /// The bus, device and function identifier for the VirtIO device.
951496ba7bSLoGin     _bus_device_function: BusDeviceFunction,
9626d84a31SYJwu2023     /// The common configuration structure within some BAR.
9726d84a31SYJwu2023     common_cfg: NonNull<CommonCfg>,
9826d84a31SYJwu2023     /// The start of the queue notification region within some BAR.
9926d84a31SYJwu2023     notify_region: NonNull<[WriteOnly<u16>]>,
10026d84a31SYJwu2023     notify_off_multiplier: u32,
10126d84a31SYJwu2023     /// The ISR status register within some BAR.
10226d84a31SYJwu2023     isr_status: NonNull<Volatile<u8>>,
10326d84a31SYJwu2023     /// The VirtIO device-specific configuration within some BAR.
10426d84a31SYJwu2023     config_space: Option<NonNull<[u32]>>,
105e2841179SLoGin     irq: IrqNumber,
106e2841179SLoGin     dev_id: Arc<DeviceId>,
1070dd8ff43SYJwu2023 }
1080dd8ff43SYJwu2023 
10926d84a31SYJwu2023 impl PciTransport {
11026d84a31SYJwu2023     /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
11126d84a31SYJwu2023     /// root controller.
11226d84a31SYJwu2023     ///
113e2841179SLoGin     /// ## 参数
11478bf93f0SYJwu2023     ///
115e2841179SLoGin     /// - `device` - The PCI device structure for the VirtIO device.
116e2841179SLoGin     /// - `irq_handler` - An optional handler for the device's interrupt. If `None`, a default
117e2841179SLoGin     ///     handler `DefaultVirtioIrqHandler` will be used.
118b5b571e0SLoGin     #[allow(clippy::extra_unused_type_parameters)]
11978bf93f0SYJwu2023     pub fn new<H: Hal>(
12078bf93f0SYJwu2023         device: &mut PciDeviceStructureGeneralDevice,
121e2841179SLoGin         dev_id: Arc<DeviceId>,
12278bf93f0SYJwu2023     ) -> Result<Self, VirtioPciError> {
123e2841179SLoGin         let irq = VIRTIO_RECV_VECTOR;
12478bf93f0SYJwu2023         let header = &device.common_header;
12578bf93f0SYJwu2023         let bus_device_function = header.bus_device_function;
12678bf93f0SYJwu2023         if header.vendor_id != VIRTIO_VENDOR_ID {
12778bf93f0SYJwu2023             return Err(VirtioPciError::InvalidVendorId(header.vendor_id));
12826d84a31SYJwu2023         }
12978bf93f0SYJwu2023         let device_type = device_type(header.device_id);
13026d84a31SYJwu2023         // Find the PCI capabilities we need.
13113776c11Slogin         let mut common_cfg: Option<VirtioCapabilityInfo> = None;
13213776c11Slogin         let mut notify_cfg: Option<VirtioCapabilityInfo> = None;
13326d84a31SYJwu2023         let mut notify_off_multiplier = 0;
13426d84a31SYJwu2023         let mut isr_cfg = None;
13526d84a31SYJwu2023         let mut device_cfg = None;
136cc36cf4aSYJwu2023         device.bar_ioremap().unwrap()?;
13778bf93f0SYJwu2023         device.enable_master();
1380dd8ff43SYJwu2023         let standard_device = device.as_standard_device_mut().unwrap();
1390dd8ff43SYJwu2023         // 目前缺少对PCI设备中断号的统一管理,所以这里需要指定一个中断号。不能与其他中断重复
1400dd8ff43SYJwu2023         let irq_vector = standard_device.irq_vector_mut().unwrap();
141e2841179SLoGin         irq_vector.push(irq);
1420dd8ff43SYJwu2023         standard_device
1430dd8ff43SYJwu2023             .irq_init(IRQ::PCI_IRQ_MSIX)
1440dd8ff43SYJwu2023             .expect("IRQ init failed");
1450dd8ff43SYJwu2023         // 中断相关信息
146ce5850adSLoGin         let msg = PciIrqMsg {
147afc95d5cSYJwu2023             irq_common_message: IrqCommonMsg::init_from(
148afc95d5cSYJwu2023                 0,
149e2841179SLoGin                 "Virtio_IRQ".to_string(),
150e2841179SLoGin                 &DefaultVirtioIrqHandler,
151e2841179SLoGin                 dev_id.clone(),
152afc95d5cSYJwu2023             ),
1530dd8ff43SYJwu2023             irq_specific_message: IrqSpecificMsg::msi_default(),
1540dd8ff43SYJwu2023         };
1550dd8ff43SYJwu2023         standard_device.irq_install(msg)?;
1560dd8ff43SYJwu2023         standard_device.irq_enable(true)?;
15726d84a31SYJwu2023         //device_capability为迭代器,遍历其相当于遍历所有的cap空间
15878bf93f0SYJwu2023         for capability in device.capabilities().unwrap() {
15926d84a31SYJwu2023             if capability.id != PCI_CAP_ID_VNDR {
16026d84a31SYJwu2023                 continue;
16126d84a31SYJwu2023             }
16226d84a31SYJwu2023             let cap_len = capability.private_header as u8;
16326d84a31SYJwu2023             let cfg_type = (capability.private_header >> 8) as u8;
16426d84a31SYJwu2023             if cap_len < 16 {
16526d84a31SYJwu2023                 continue;
16626d84a31SYJwu2023             }
16726d84a31SYJwu2023             let struct_info = VirtioCapabilityInfo {
1682709e017SLoGin                 bar: pci_root_0().read_config(
1692709e017SLoGin                     bus_device_function,
1702709e017SLoGin                     (capability.offset + CAP_BAR_OFFSET).into(),
1712709e017SLoGin                 ) as u8,
1722709e017SLoGin                 offset: pci_root_0().read_config(
1732709e017SLoGin                     bus_device_function,
1742709e017SLoGin                     (capability.offset + CAP_BAR_OFFSET_OFFSET).into(),
17578bf93f0SYJwu2023                 ),
1762709e017SLoGin                 length: pci_root_0().read_config(
1772709e017SLoGin                     bus_device_function,
1782709e017SLoGin                     (capability.offset + CAP_LENGTH_OFFSET).into(),
17978bf93f0SYJwu2023                 ),
18026d84a31SYJwu2023             };
18126d84a31SYJwu2023 
18226d84a31SYJwu2023             match cfg_type {
18326d84a31SYJwu2023                 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
18426d84a31SYJwu2023                     common_cfg = Some(struct_info);
18526d84a31SYJwu2023                 }
18626d84a31SYJwu2023                 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
18726d84a31SYJwu2023                     notify_cfg = Some(struct_info);
1882709e017SLoGin                     notify_off_multiplier = pci_root_0().read_config(
1892709e017SLoGin                         bus_device_function,
1902709e017SLoGin                         (capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET).into(),
19126d84a31SYJwu2023                     );
19226d84a31SYJwu2023                 }
19326d84a31SYJwu2023                 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
19426d84a31SYJwu2023                     isr_cfg = Some(struct_info);
19526d84a31SYJwu2023                 }
19626d84a31SYJwu2023                 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
19726d84a31SYJwu2023                     device_cfg = Some(struct_info);
19826d84a31SYJwu2023                 }
19926d84a31SYJwu2023                 _ => {}
20026d84a31SYJwu2023             }
20126d84a31SYJwu2023         }
20226d84a31SYJwu2023 
20326d84a31SYJwu2023         let common_cfg = get_bar_region::<_>(
20478bf93f0SYJwu2023             &device.standard_device_bar,
20526d84a31SYJwu2023             &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
20626d84a31SYJwu2023         )?;
20726d84a31SYJwu2023 
20826d84a31SYJwu2023         let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
20926d84a31SYJwu2023         if notify_off_multiplier % 2 != 0 {
21026d84a31SYJwu2023             return Err(VirtioPciError::InvalidNotifyOffMultiplier(
21126d84a31SYJwu2023                 notify_off_multiplier,
21226d84a31SYJwu2023             ));
21326d84a31SYJwu2023         }
21473c607aaSYJwu2023         //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length);
21578bf93f0SYJwu2023         let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, &notify_cfg)?;
21626d84a31SYJwu2023         let isr_status = get_bar_region::<_>(
21778bf93f0SYJwu2023             &device.standard_device_bar,
21826d84a31SYJwu2023             &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
21926d84a31SYJwu2023         )?;
22026d84a31SYJwu2023         let config_space = if let Some(device_cfg) = device_cfg {
22178bf93f0SYJwu2023             Some(get_bar_region_slice::<_>(
22278bf93f0SYJwu2023                 &device.standard_device_bar,
22378bf93f0SYJwu2023                 &device_cfg,
22478bf93f0SYJwu2023             )?)
22526d84a31SYJwu2023         } else {
22626d84a31SYJwu2023             None
22726d84a31SYJwu2023         };
22826d84a31SYJwu2023         Ok(Self {
22926d84a31SYJwu2023             device_type,
2301496ba7bSLoGin             _bus_device_function: bus_device_function,
23126d84a31SYJwu2023             common_cfg,
23226d84a31SYJwu2023             notify_region,
23326d84a31SYJwu2023             notify_off_multiplier,
23426d84a31SYJwu2023             isr_status,
23526d84a31SYJwu2023             config_space,
236e2841179SLoGin             irq,
237e2841179SLoGin             dev_id,
23826d84a31SYJwu2023         })
23926d84a31SYJwu2023     }
24026d84a31SYJwu2023 }
24126d84a31SYJwu2023 
24226d84a31SYJwu2023 impl Transport for PciTransport {
24326d84a31SYJwu2023     fn device_type(&self) -> DeviceType {
24426d84a31SYJwu2023         self.device_type
24526d84a31SYJwu2023     }
24626d84a31SYJwu2023 
24726d84a31SYJwu2023     fn read_device_features(&mut self) -> u64 {
24826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
24926d84a31SYJwu2023         // was aligned.
25026d84a31SYJwu2023         unsafe {
25126d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 0);
25226d84a31SYJwu2023             let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
25326d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 1);
25426d84a31SYJwu2023             device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
25526d84a31SYJwu2023             device_features_bits
25626d84a31SYJwu2023         }
25726d84a31SYJwu2023     }
25826d84a31SYJwu2023 
25926d84a31SYJwu2023     fn write_driver_features(&mut self, driver_features: u64) {
26026d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
26126d84a31SYJwu2023         // was aligned.
26226d84a31SYJwu2023         unsafe {
26326d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 0);
26426d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature, driver_features as u32);
26526d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 1);
26626d84a31SYJwu2023             volwrite!(
26726d84a31SYJwu2023                 self.common_cfg,
26826d84a31SYJwu2023                 driver_feature,
26926d84a31SYJwu2023                 (driver_features >> 32) as u32
27026d84a31SYJwu2023             );
27126d84a31SYJwu2023         }
27226d84a31SYJwu2023     }
27326d84a31SYJwu2023 
274b502fbf0SLoGin     fn max_queue_size(&mut self, queue: u16) -> u32 {
275b502fbf0SLoGin         unsafe {
276b502fbf0SLoGin             volwrite!(self.common_cfg, queue_select, queue);
277b502fbf0SLoGin             volread!(self.common_cfg, queue_size).into()
278b502fbf0SLoGin         }
27926d84a31SYJwu2023     }
28026d84a31SYJwu2023 
28126d84a31SYJwu2023     fn notify(&mut self, queue: u16) {
28226d84a31SYJwu2023         // Safe because the common config and notify region pointers are valid and we checked in
28326d84a31SYJwu2023         // get_bar_region that they were aligned.
28426d84a31SYJwu2023         unsafe {
28526d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
28626d84a31SYJwu2023             // TODO: Consider caching this somewhere (per queue).
28726d84a31SYJwu2023             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
28826d84a31SYJwu2023 
28926d84a31SYJwu2023             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
29026d84a31SYJwu2023             let index = offset_bytes / size_of::<u16>();
29126d84a31SYJwu2023             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
29226d84a31SYJwu2023         }
29326d84a31SYJwu2023     }
29426d84a31SYJwu2023 
29526d84a31SYJwu2023     fn set_status(&mut self, status: DeviceStatus) {
29626d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
29726d84a31SYJwu2023         // was aligned.
29826d84a31SYJwu2023         unsafe {
29926d84a31SYJwu2023             volwrite!(self.common_cfg, device_status, status.bits() as u8);
30026d84a31SYJwu2023         }
30126d84a31SYJwu2023     }
30226d84a31SYJwu2023 
303b502fbf0SLoGin     fn get_status(&self) -> DeviceStatus {
304b502fbf0SLoGin         // Safe because the common config pointer is valid and we checked in get_bar_region that it
305b502fbf0SLoGin         // was aligned.
306b502fbf0SLoGin         unsafe { DeviceStatus::from_bits_truncate(volread!(self.common_cfg, device_status).into()) }
307b502fbf0SLoGin     }
308b502fbf0SLoGin 
30926d84a31SYJwu2023     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
31026d84a31SYJwu2023         // No-op, the PCI transport doesn't care.
31126d84a31SYJwu2023     }
31273c607aaSYJwu2023     fn requires_legacy_layout(&self) -> bool {
31373c607aaSYJwu2023         false
31473c607aaSYJwu2023     }
31526d84a31SYJwu2023     fn queue_set(
31626d84a31SYJwu2023         &mut self,
31726d84a31SYJwu2023         queue: u16,
31826d84a31SYJwu2023         size: u32,
31926d84a31SYJwu2023         descriptors: PhysAddr,
32026d84a31SYJwu2023         driver_area: PhysAddr,
32126d84a31SYJwu2023         device_area: PhysAddr,
32226d84a31SYJwu2023     ) {
32326d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
32426d84a31SYJwu2023         // was aligned.
32526d84a31SYJwu2023         unsafe {
32626d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
32726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, size as u16);
32826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
32926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
33026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, device_area as u64);
331afc95d5cSYJwu2023             // 这里设置队列中断对应的中断项
3320dd8ff43SYJwu2023             if queue == QUEUE_RECEIVE {
3330dd8ff43SYJwu2023                 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX);
3340dd8ff43SYJwu2023                 let vector = volread!(self.common_cfg, queue_msix_vector);
3350dd8ff43SYJwu2023                 if vector != VIRTIO_RECV_VECTOR_INDEX {
3360dd8ff43SYJwu2023                     panic!("Vector set failed");
3370dd8ff43SYJwu2023                 }
3380dd8ff43SYJwu2023             }
33926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_enable, 1);
34026d84a31SYJwu2023         }
34126d84a31SYJwu2023     }
34226d84a31SYJwu2023 
34326d84a31SYJwu2023     fn queue_unset(&mut self, queue: u16) {
34426d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
34526d84a31SYJwu2023         // was aligned.
34626d84a31SYJwu2023         unsafe {
34726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
34826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, 0);
34926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, 0);
35026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, 0);
35126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, 0);
35226d84a31SYJwu2023         }
35326d84a31SYJwu2023     }
35426d84a31SYJwu2023 
35526d84a31SYJwu2023     fn queue_used(&mut self, queue: u16) -> bool {
35626d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
35726d84a31SYJwu2023         // was aligned.
35826d84a31SYJwu2023         unsafe {
35926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
36026d84a31SYJwu2023             volread!(self.common_cfg, queue_enable) == 1
36126d84a31SYJwu2023         }
36226d84a31SYJwu2023     }
36326d84a31SYJwu2023 
36426d84a31SYJwu2023     fn ack_interrupt(&mut self) -> bool {
36526d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
36626d84a31SYJwu2023         // was aligned.
36726d84a31SYJwu2023         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
36826d84a31SYJwu2023         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
36926d84a31SYJwu2023         // TODO: Distinguish between queue interrupt and device configuration interrupt.
37026d84a31SYJwu2023         isr_status & 0x3 != 0
37126d84a31SYJwu2023     }
37226d84a31SYJwu2023 
37326d84a31SYJwu2023     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
37426d84a31SYJwu2023         if let Some(config_space) = self.config_space {
37526d84a31SYJwu2023             if size_of::<T>() > config_space.len() * size_of::<u32>() {
37626d84a31SYJwu2023                 Err(Error::ConfigSpaceTooSmall)
37726d84a31SYJwu2023             } else if align_of::<T>() > 4 {
37826d84a31SYJwu2023                 // Panic as this should only happen if the driver is written incorrectly.
37926d84a31SYJwu2023                 panic!(
38026d84a31SYJwu2023                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
38126d84a31SYJwu2023                     align_of::<T>()
38226d84a31SYJwu2023                 );
38326d84a31SYJwu2023             } else {
38426d84a31SYJwu2023                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
38526d84a31SYJwu2023                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
38626d84a31SYJwu2023                 Ok(config_space_ptr.cast())
38726d84a31SYJwu2023             }
38826d84a31SYJwu2023         } else {
38926d84a31SYJwu2023             Err(Error::ConfigSpaceMissing)
39026d84a31SYJwu2023         }
39126d84a31SYJwu2023     }
39226d84a31SYJwu2023 }
39326d84a31SYJwu2023 
39473c607aaSYJwu2023 impl Drop for PciTransport {
39573c607aaSYJwu2023     fn drop(&mut self) {
39673c607aaSYJwu2023         // Reset the device when the transport is dropped.
397e2841179SLoGin         self.set_status(DeviceStatus::empty());
398e2841179SLoGin 
399e2841179SLoGin         // todo: 调用pci的中断释放函数,并且在virtio_irq_manager里面删除对应的设备的中断
40073c607aaSYJwu2023     }
40173c607aaSYJwu2023 }
40273c607aaSYJwu2023 
40326d84a31SYJwu2023 #[repr(C)]
40426d84a31SYJwu2023 struct CommonCfg {
40526d84a31SYJwu2023     device_feature_select: Volatile<u32>,
40626d84a31SYJwu2023     device_feature: ReadOnly<u32>,
40726d84a31SYJwu2023     driver_feature_select: Volatile<u32>,
40826d84a31SYJwu2023     driver_feature: Volatile<u32>,
40926d84a31SYJwu2023     msix_config: Volatile<u16>,
41026d84a31SYJwu2023     num_queues: ReadOnly<u16>,
41126d84a31SYJwu2023     device_status: Volatile<u8>,
41226d84a31SYJwu2023     config_generation: ReadOnly<u8>,
41326d84a31SYJwu2023     queue_select: Volatile<u16>,
41426d84a31SYJwu2023     queue_size: Volatile<u16>,
41526d84a31SYJwu2023     queue_msix_vector: Volatile<u16>,
41626d84a31SYJwu2023     queue_enable: Volatile<u16>,
41726d84a31SYJwu2023     queue_notify_off: Volatile<u16>,
41826d84a31SYJwu2023     queue_desc: Volatile<u64>,
41926d84a31SYJwu2023     queue_driver: Volatile<u64>,
42026d84a31SYJwu2023     queue_device: Volatile<u64>,
42126d84a31SYJwu2023 }
42226d84a31SYJwu2023 
42326d84a31SYJwu2023 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
42426d84a31SYJwu2023 /// cfg空间在哪个bar的多少偏移处,长度多少
42526d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
42626d84a31SYJwu2023 struct VirtioCapabilityInfo {
42726d84a31SYJwu2023     /// The bar in which the structure can be found.
42826d84a31SYJwu2023     bar: u8,
42926d84a31SYJwu2023     /// The offset within the bar.
43026d84a31SYJwu2023     offset: u32,
43126d84a31SYJwu2023     /// The length in bytes of the structure within the bar.
43226d84a31SYJwu2023     length: u32,
43326d84a31SYJwu2023 }
43426d84a31SYJwu2023 
43526d84a31SYJwu2023 /// An error encountered initialising a VirtIO PCI transport.
43626d84a31SYJwu2023 /// VirtIO PCI transport 初始化时的错误
43726d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
43826d84a31SYJwu2023 pub enum VirtioPciError {
43926d84a31SYJwu2023     /// PCI device vender ID was not the VirtIO vendor ID.
44026d84a31SYJwu2023     InvalidVendorId(u16),
44126d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
44226d84a31SYJwu2023     MissingCommonConfig,
44326d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
44426d84a31SYJwu2023     MissingNotifyConfig,
44526d84a31SYJwu2023     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
44626d84a31SYJwu2023     /// of 2.
44726d84a31SYJwu2023     InvalidNotifyOffMultiplier(u32),
44826d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
44926d84a31SYJwu2023     MissingIsrConfig,
45026d84a31SYJwu2023     /// An IO BAR was provided rather than a memory BAR.
45126d84a31SYJwu2023     UnexpectedBarType,
45226d84a31SYJwu2023     /// A BAR which we need was not allocated an address.
45326d84a31SYJwu2023     BarNotAllocated(u8),
45426d84a31SYJwu2023     /// The offset for some capability was greater than the length of the BAR.
45526d84a31SYJwu2023     BarOffsetOutOfRange,
45626d84a31SYJwu2023     /// The virtual address was not aligned as expected.
45726d84a31SYJwu2023     Misaligned {
45826d84a31SYJwu2023         /// The virtual address in question.
45926d84a31SYJwu2023         vaddr: VirtAddr,
46026d84a31SYJwu2023         /// The expected alignment in bytes.
46126d84a31SYJwu2023         alignment: usize,
46226d84a31SYJwu2023     },
46326d84a31SYJwu2023     ///获取虚拟地址失败
46426d84a31SYJwu2023     BarGetVaddrFailed,
46526d84a31SYJwu2023     /// A generic PCI error,
46626d84a31SYJwu2023     Pci(PciError),
46726d84a31SYJwu2023 }
46826d84a31SYJwu2023 
46926d84a31SYJwu2023 impl Display for VirtioPciError {
47026d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
47126d84a31SYJwu2023         match self {
47226d84a31SYJwu2023             Self::InvalidVendorId(vendor_id) => write!(
47326d84a31SYJwu2023                 f,
47426d84a31SYJwu2023                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
47526d84a31SYJwu2023                 vendor_id, VIRTIO_VENDOR_ID
47626d84a31SYJwu2023             ),
47726d84a31SYJwu2023             Self::MissingCommonConfig => write!(
47826d84a31SYJwu2023                 f,
47926d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
48026d84a31SYJwu2023             ),
48126d84a31SYJwu2023             Self::MissingNotifyConfig => write!(
48226d84a31SYJwu2023                 f,
48326d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
48426d84a31SYJwu2023             ),
48526d84a31SYJwu2023             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
48626d84a31SYJwu2023                 write!(
48726d84a31SYJwu2023                     f,
48826d84a31SYJwu2023                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
48926d84a31SYJwu2023                     notify_off_multiplier
49026d84a31SYJwu2023                 )
49126d84a31SYJwu2023             }
49226d84a31SYJwu2023             Self::MissingIsrConfig => {
49326d84a31SYJwu2023                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
49426d84a31SYJwu2023             }
49526d84a31SYJwu2023             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
49626d84a31SYJwu2023             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
49726d84a31SYJwu2023             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
49826d84a31SYJwu2023             Self::Misaligned { vaddr, alignment } => write!(
49926d84a31SYJwu2023                 f,
5002dd9f0c7SLoGin                 "Virtual address {:?} was not aligned to a {} byte boundary as expected.",
50126d84a31SYJwu2023                 vaddr, alignment
50226d84a31SYJwu2023             ),
50326d84a31SYJwu2023             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
50426d84a31SYJwu2023             Self::Pci(pci_error) => pci_error.fmt(f),
50526d84a31SYJwu2023         }
50626d84a31SYJwu2023     }
50726d84a31SYJwu2023 }
50813776c11Slogin 
50926d84a31SYJwu2023 /// PCI error到VirtioPciError的转换,层层上报
51026d84a31SYJwu2023 impl From<PciError> for VirtioPciError {
51126d84a31SYJwu2023     fn from(error: PciError) -> Self {
51226d84a31SYJwu2023         Self::Pci(error)
51326d84a31SYJwu2023     }
51426d84a31SYJwu2023 }
51526d84a31SYJwu2023 
51626d84a31SYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的指针
51726d84a31SYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
51826d84a31SYJwu2023 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
51926d84a31SYJwu2023 fn get_bar_region<T>(
52078bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
52126d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
52226d84a31SYJwu2023 ) -> Result<NonNull<T>, VirtioPciError> {
52326d84a31SYJwu2023     let bar_info = device_bar.get_bar(struct_info.bar)?;
52426d84a31SYJwu2023     let (bar_address, bar_size) = bar_info
52526d84a31SYJwu2023         .memory_address_size()
52626d84a31SYJwu2023         .ok_or(VirtioPciError::UnexpectedBarType)?;
52726d84a31SYJwu2023     if bar_address == 0 {
52826d84a31SYJwu2023         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
52926d84a31SYJwu2023     }
53026d84a31SYJwu2023     if struct_info.offset + struct_info.length > bar_size
53126d84a31SYJwu2023         || size_of::<T>() > struct_info.length as usize
53226d84a31SYJwu2023     {
53326d84a31SYJwu2023         return Err(VirtioPciError::BarOffsetOutOfRange);
53426d84a31SYJwu2023     }
53573c607aaSYJwu2023     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
53626d84a31SYJwu2023     let vaddr = (bar_info
53726d84a31SYJwu2023         .virtual_address()
5382dd9f0c7SLoGin         .ok_or(VirtioPciError::BarGetVaddrFailed)?)
53926d84a31SYJwu2023         + struct_info.offset as usize;
5402dd9f0c7SLoGin     if vaddr.data() % align_of::<T>() != 0 {
54126d84a31SYJwu2023         return Err(VirtioPciError::Misaligned {
54226d84a31SYJwu2023             vaddr,
54326d84a31SYJwu2023             alignment: align_of::<T>(),
54426d84a31SYJwu2023         });
54526d84a31SYJwu2023     }
5462dd9f0c7SLoGin     let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap();
54773c607aaSYJwu2023     Ok(vaddr.cast())
54826d84a31SYJwu2023 }
54926d84a31SYJwu2023 
550cc36cf4aSYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针
55173c607aaSYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
55226d84a31SYJwu2023 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
55326d84a31SYJwu2023 fn get_bar_region_slice<T>(
55478bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
55526d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
55626d84a31SYJwu2023 ) -> Result<NonNull<[T]>, VirtioPciError> {
55726d84a31SYJwu2023     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
55873c607aaSYJwu2023     // let raw_slice =
55973c607aaSYJwu2023     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
56073c607aaSYJwu2023     Ok(nonnull_slice_from_raw_parts(
56173c607aaSYJwu2023         ptr,
56273c607aaSYJwu2023         struct_info.length as usize / size_of::<T>(),
56373c607aaSYJwu2023     ))
56473c607aaSYJwu2023 }
56513776c11Slogin 
56673c607aaSYJwu2023 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
56773c607aaSYJwu2023     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
56826d84a31SYJwu2023 }
569