xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision e32effb1507773d32c216d9e77b963786e275c06)
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 use crate::driver::virtio::irq::virtio_irq_manager;
12e2841179SLoGin use crate::exception::irqdata::IrqHandlerData;
13e2841179SLoGin use crate::exception::irqdesc::{IrqHandler, IrqReturn};
14e2841179SLoGin 
15e2841179SLoGin use crate::exception::IrqNumber;
16e2841179SLoGin 
1773c607aaSYJwu2023 use crate::libs::volatile::{
1873c607aaSYJwu2023     volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
1973c607aaSYJwu2023 };
202dd9f0c7SLoGin use crate::mm::VirtAddr;
21e2841179SLoGin 
22e2841179SLoGin use alloc::string::ToString;
23e2841179SLoGin use alloc::sync::Arc;
2426d84a31SYJwu2023 use core::{
2526d84a31SYJwu2023     fmt::{self, Display, Formatter},
2626d84a31SYJwu2023     mem::{align_of, size_of},
2726d84a31SYJwu2023     ptr::{self, addr_of_mut, NonNull},
2826d84a31SYJwu2023 };
29e2841179SLoGin use system_error::SystemError;
3026d84a31SYJwu2023 use virtio_drivers::{
3126d84a31SYJwu2023     transport::{DeviceStatus, DeviceType, Transport},
3273c607aaSYJwu2023     Error, Hal, PhysAddr,
3326d84a31SYJwu2023 };
3426d84a31SYJwu2023 
35*e32effb1SLoGin use super::VIRTIO_VENDOR_ID;
3626d84a31SYJwu2023 
3726d84a31SYJwu2023 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
3826d84a31SYJwu2023 /// PCI Virtio设备的DEVICE_ID 的offset
3926d84a31SYJwu2023 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
4026d84a31SYJwu2023 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型
4126d84a31SYJwu2023 const TRANSITIONAL_NETWORK: u16 = 0x1000;
4226d84a31SYJwu2023 const TRANSITIONAL_BLOCK: u16 = 0x1001;
4326d84a31SYJwu2023 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
4426d84a31SYJwu2023 const TRANSITIONAL_CONSOLE: u16 = 0x1003;
4526d84a31SYJwu2023 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
4626d84a31SYJwu2023 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
4726d84a31SYJwu2023 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
4826d84a31SYJwu2023 
4926d84a31SYJwu2023 /// The offset of the bar field within `virtio_pci_cap`.
5026d84a31SYJwu2023 const CAP_BAR_OFFSET: u8 = 4;
5126d84a31SYJwu2023 /// The offset of the offset field with `virtio_pci_cap`.
5226d84a31SYJwu2023 const CAP_BAR_OFFSET_OFFSET: u8 = 8;
5326d84a31SYJwu2023 /// The offset of the `length` field within `virtio_pci_cap`.
5426d84a31SYJwu2023 const CAP_LENGTH_OFFSET: u8 = 12;
5526d84a31SYJwu2023 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
5626d84a31SYJwu2023 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
5726d84a31SYJwu2023 
5826d84a31SYJwu2023 /// Common configuration.
5926d84a31SYJwu2023 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
6026d84a31SYJwu2023 /// Notifications.
6126d84a31SYJwu2023 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
6226d84a31SYJwu2023 /// ISR Status.
6326d84a31SYJwu2023 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
6426d84a31SYJwu2023 /// Device specific configuration.
6526d84a31SYJwu2023 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
6626d84a31SYJwu2023 
670dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号
68e2841179SLoGin const VIRTIO_RECV_VECTOR: IrqNumber = IrqNumber::new(56);
690dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号的表项号
700dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR_INDEX: u16 = 0;
71afc95d5cSYJwu2023 // 接收的queue号
720dd8ff43SYJwu2023 const QUEUE_RECEIVE: u16 = 0;
7326d84a31SYJwu2023 ///@brief device id 转换为设备类型
7426d84a31SYJwu2023 ///@param pci_device_id,device_id
7526d84a31SYJwu2023 ///@return DeviceType 对应的设备类型
7626d84a31SYJwu2023 fn device_type(pci_device_id: u16) -> DeviceType {
7726d84a31SYJwu2023     match pci_device_id {
7826d84a31SYJwu2023         TRANSITIONAL_NETWORK => DeviceType::Network,
7926d84a31SYJwu2023         TRANSITIONAL_BLOCK => DeviceType::Block,
8026d84a31SYJwu2023         TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
8126d84a31SYJwu2023         TRANSITIONAL_CONSOLE => DeviceType::Console,
8226d84a31SYJwu2023         TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
8326d84a31SYJwu2023         TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
8426d84a31SYJwu2023         TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
8526d84a31SYJwu2023         id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
8626d84a31SYJwu2023         _ => DeviceType::Invalid,
8726d84a31SYJwu2023     }
8826d84a31SYJwu2023 }
8926d84a31SYJwu2023 
9026d84a31SYJwu2023 /// PCI transport for VirtIO.
9126d84a31SYJwu2023 ///
9226d84a31SYJwu2023 /// Ref: 4.1 Virtio Over PCI Bus
93e2841179SLoGin #[allow(dead_code)]
9413776c11Slogin #[derive(Debug, Clone)]
9526d84a31SYJwu2023 pub struct PciTransport {
9626d84a31SYJwu2023     device_type: DeviceType,
9726d84a31SYJwu2023     /// The bus, device and function identifier for the VirtIO device.
981496ba7bSLoGin     _bus_device_function: BusDeviceFunction,
9926d84a31SYJwu2023     /// The common configuration structure within some BAR.
10026d84a31SYJwu2023     common_cfg: NonNull<CommonCfg>,
10126d84a31SYJwu2023     /// The start of the queue notification region within some BAR.
10226d84a31SYJwu2023     notify_region: NonNull<[WriteOnly<u16>]>,
10326d84a31SYJwu2023     notify_off_multiplier: u32,
10426d84a31SYJwu2023     /// The ISR status register within some BAR.
10526d84a31SYJwu2023     isr_status: NonNull<Volatile<u8>>,
10626d84a31SYJwu2023     /// The VirtIO device-specific configuration within some BAR.
10726d84a31SYJwu2023     config_space: Option<NonNull<[u32]>>,
108e2841179SLoGin     irq: IrqNumber,
109e2841179SLoGin     dev_id: Arc<DeviceId>,
1100dd8ff43SYJwu2023 }
1110dd8ff43SYJwu2023 
11226d84a31SYJwu2023 impl PciTransport {
11326d84a31SYJwu2023     /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
11426d84a31SYJwu2023     /// root controller.
11526d84a31SYJwu2023     ///
116e2841179SLoGin     /// ## 参数
11778bf93f0SYJwu2023     ///
118e2841179SLoGin     /// - `device` - The PCI device structure for the VirtIO device.
119e2841179SLoGin     /// - `irq_handler` - An optional handler for the device's interrupt. If `None`, a default
120e2841179SLoGin     ///     handler `DefaultVirtioIrqHandler` will be used.
121b5b571e0SLoGin     #[allow(clippy::extra_unused_type_parameters)]
12278bf93f0SYJwu2023     pub fn new<H: Hal>(
12378bf93f0SYJwu2023         device: &mut PciDeviceStructureGeneralDevice,
124e2841179SLoGin         dev_id: Arc<DeviceId>,
12578bf93f0SYJwu2023     ) -> Result<Self, VirtioPciError> {
126e2841179SLoGin         let irq = VIRTIO_RECV_VECTOR;
12778bf93f0SYJwu2023         let header = &device.common_header;
12878bf93f0SYJwu2023         let bus_device_function = header.bus_device_function;
12978bf93f0SYJwu2023         if header.vendor_id != VIRTIO_VENDOR_ID {
13078bf93f0SYJwu2023             return Err(VirtioPciError::InvalidVendorId(header.vendor_id));
13126d84a31SYJwu2023         }
13278bf93f0SYJwu2023         let device_type = device_type(header.device_id);
13326d84a31SYJwu2023         // Find the PCI capabilities we need.
13413776c11Slogin         let mut common_cfg: Option<VirtioCapabilityInfo> = None;
13513776c11Slogin         let mut notify_cfg: Option<VirtioCapabilityInfo> = None;
13626d84a31SYJwu2023         let mut notify_off_multiplier = 0;
13726d84a31SYJwu2023         let mut isr_cfg = None;
13826d84a31SYJwu2023         let mut device_cfg = None;
139cc36cf4aSYJwu2023         device.bar_ioremap().unwrap()?;
14078bf93f0SYJwu2023         device.enable_master();
1410dd8ff43SYJwu2023         let standard_device = device.as_standard_device_mut().unwrap();
1420dd8ff43SYJwu2023         // 目前缺少对PCI设备中断号的统一管理,所以这里需要指定一个中断号。不能与其他中断重复
1430dd8ff43SYJwu2023         let irq_vector = standard_device.irq_vector_mut().unwrap();
144e2841179SLoGin         irq_vector.push(irq);
1450dd8ff43SYJwu2023         standard_device
1460dd8ff43SYJwu2023             .irq_init(IRQ::PCI_IRQ_MSIX)
1470dd8ff43SYJwu2023             .expect("IRQ init failed");
1480dd8ff43SYJwu2023         // 中断相关信息
149ce5850adSLoGin         let msg = PciIrqMsg {
150afc95d5cSYJwu2023             irq_common_message: IrqCommonMsg::init_from(
151afc95d5cSYJwu2023                 0,
152e2841179SLoGin                 "Virtio_IRQ".to_string(),
153e2841179SLoGin                 &DefaultVirtioIrqHandler,
154e2841179SLoGin                 dev_id.clone(),
155afc95d5cSYJwu2023             ),
1560dd8ff43SYJwu2023             irq_specific_message: IrqSpecificMsg::msi_default(),
1570dd8ff43SYJwu2023         };
1580dd8ff43SYJwu2023         standard_device.irq_install(msg)?;
1590dd8ff43SYJwu2023         standard_device.irq_enable(true)?;
16026d84a31SYJwu2023         //device_capability为迭代器,遍历其相当于遍历所有的cap空间
16178bf93f0SYJwu2023         for capability in device.capabilities().unwrap() {
16226d84a31SYJwu2023             if capability.id != PCI_CAP_ID_VNDR {
16326d84a31SYJwu2023                 continue;
16426d84a31SYJwu2023             }
16526d84a31SYJwu2023             let cap_len = capability.private_header as u8;
16626d84a31SYJwu2023             let cfg_type = (capability.private_header >> 8) as u8;
16726d84a31SYJwu2023             if cap_len < 16 {
16826d84a31SYJwu2023                 continue;
16926d84a31SYJwu2023             }
17026d84a31SYJwu2023             let struct_info = VirtioCapabilityInfo {
1712709e017SLoGin                 bar: pci_root_0().read_config(
1722709e017SLoGin                     bus_device_function,
1732709e017SLoGin                     (capability.offset + CAP_BAR_OFFSET).into(),
1742709e017SLoGin                 ) as u8,
1752709e017SLoGin                 offset: pci_root_0().read_config(
1762709e017SLoGin                     bus_device_function,
1772709e017SLoGin                     (capability.offset + CAP_BAR_OFFSET_OFFSET).into(),
17878bf93f0SYJwu2023                 ),
1792709e017SLoGin                 length: pci_root_0().read_config(
1802709e017SLoGin                     bus_device_function,
1812709e017SLoGin                     (capability.offset + CAP_LENGTH_OFFSET).into(),
18278bf93f0SYJwu2023                 ),
18326d84a31SYJwu2023             };
18426d84a31SYJwu2023 
18526d84a31SYJwu2023             match cfg_type {
18626d84a31SYJwu2023                 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
18726d84a31SYJwu2023                     common_cfg = Some(struct_info);
18826d84a31SYJwu2023                 }
18926d84a31SYJwu2023                 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
19026d84a31SYJwu2023                     notify_cfg = Some(struct_info);
1912709e017SLoGin                     notify_off_multiplier = pci_root_0().read_config(
1922709e017SLoGin                         bus_device_function,
1932709e017SLoGin                         (capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET).into(),
19426d84a31SYJwu2023                     );
19526d84a31SYJwu2023                 }
19626d84a31SYJwu2023                 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
19726d84a31SYJwu2023                     isr_cfg = Some(struct_info);
19826d84a31SYJwu2023                 }
19926d84a31SYJwu2023                 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
20026d84a31SYJwu2023                     device_cfg = Some(struct_info);
20126d84a31SYJwu2023                 }
20226d84a31SYJwu2023                 _ => {}
20326d84a31SYJwu2023             }
20426d84a31SYJwu2023         }
20526d84a31SYJwu2023 
20626d84a31SYJwu2023         let common_cfg = get_bar_region::<_>(
20778bf93f0SYJwu2023             &device.standard_device_bar,
20826d84a31SYJwu2023             &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
20926d84a31SYJwu2023         )?;
21026d84a31SYJwu2023 
21126d84a31SYJwu2023         let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
21226d84a31SYJwu2023         if notify_off_multiplier % 2 != 0 {
21326d84a31SYJwu2023             return Err(VirtioPciError::InvalidNotifyOffMultiplier(
21426d84a31SYJwu2023                 notify_off_multiplier,
21526d84a31SYJwu2023             ));
21626d84a31SYJwu2023         }
21773c607aaSYJwu2023         //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length);
21878bf93f0SYJwu2023         let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, &notify_cfg)?;
21926d84a31SYJwu2023         let isr_status = get_bar_region::<_>(
22078bf93f0SYJwu2023             &device.standard_device_bar,
22126d84a31SYJwu2023             &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
22226d84a31SYJwu2023         )?;
22326d84a31SYJwu2023         let config_space = if let Some(device_cfg) = device_cfg {
22478bf93f0SYJwu2023             Some(get_bar_region_slice::<_>(
22578bf93f0SYJwu2023                 &device.standard_device_bar,
22678bf93f0SYJwu2023                 &device_cfg,
22778bf93f0SYJwu2023             )?)
22826d84a31SYJwu2023         } else {
22926d84a31SYJwu2023             None
23026d84a31SYJwu2023         };
23126d84a31SYJwu2023         Ok(Self {
23226d84a31SYJwu2023             device_type,
2331496ba7bSLoGin             _bus_device_function: bus_device_function,
23426d84a31SYJwu2023             common_cfg,
23526d84a31SYJwu2023             notify_region,
23626d84a31SYJwu2023             notify_off_multiplier,
23726d84a31SYJwu2023             isr_status,
23826d84a31SYJwu2023             config_space,
239e2841179SLoGin             irq,
240e2841179SLoGin             dev_id,
24126d84a31SYJwu2023         })
24226d84a31SYJwu2023     }
24326d84a31SYJwu2023 }
24426d84a31SYJwu2023 
24526d84a31SYJwu2023 impl Transport for PciTransport {
24626d84a31SYJwu2023     fn device_type(&self) -> DeviceType {
24726d84a31SYJwu2023         self.device_type
24826d84a31SYJwu2023     }
24926d84a31SYJwu2023 
25026d84a31SYJwu2023     fn read_device_features(&mut self) -> u64 {
25126d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
25226d84a31SYJwu2023         // was aligned.
25326d84a31SYJwu2023         unsafe {
25426d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 0);
25526d84a31SYJwu2023             let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
25626d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 1);
25726d84a31SYJwu2023             device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
25826d84a31SYJwu2023             device_features_bits
25926d84a31SYJwu2023         }
26026d84a31SYJwu2023     }
26126d84a31SYJwu2023 
26226d84a31SYJwu2023     fn write_driver_features(&mut self, driver_features: u64) {
26326d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
26426d84a31SYJwu2023         // was aligned.
26526d84a31SYJwu2023         unsafe {
26626d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 0);
26726d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature, driver_features as u32);
26826d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 1);
26926d84a31SYJwu2023             volwrite!(
27026d84a31SYJwu2023                 self.common_cfg,
27126d84a31SYJwu2023                 driver_feature,
27226d84a31SYJwu2023                 (driver_features >> 32) as u32
27326d84a31SYJwu2023             );
27426d84a31SYJwu2023         }
27526d84a31SYJwu2023     }
27626d84a31SYJwu2023 
277b502fbf0SLoGin     fn max_queue_size(&mut self, queue: u16) -> u32 {
278b502fbf0SLoGin         unsafe {
279b502fbf0SLoGin             volwrite!(self.common_cfg, queue_select, queue);
280b502fbf0SLoGin             volread!(self.common_cfg, queue_size).into()
281b502fbf0SLoGin         }
28226d84a31SYJwu2023     }
28326d84a31SYJwu2023 
28426d84a31SYJwu2023     fn notify(&mut self, queue: u16) {
28526d84a31SYJwu2023         // Safe because the common config and notify region pointers are valid and we checked in
28626d84a31SYJwu2023         // get_bar_region that they were aligned.
28726d84a31SYJwu2023         unsafe {
28826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
28926d84a31SYJwu2023             // TODO: Consider caching this somewhere (per queue).
29026d84a31SYJwu2023             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
29126d84a31SYJwu2023 
29226d84a31SYJwu2023             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
29326d84a31SYJwu2023             let index = offset_bytes / size_of::<u16>();
29426d84a31SYJwu2023             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
29526d84a31SYJwu2023         }
29626d84a31SYJwu2023     }
29726d84a31SYJwu2023 
29826d84a31SYJwu2023     fn set_status(&mut self, status: DeviceStatus) {
29926d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
30026d84a31SYJwu2023         // was aligned.
30126d84a31SYJwu2023         unsafe {
30226d84a31SYJwu2023             volwrite!(self.common_cfg, device_status, status.bits() as u8);
30326d84a31SYJwu2023         }
30426d84a31SYJwu2023     }
30526d84a31SYJwu2023 
306b502fbf0SLoGin     fn get_status(&self) -> DeviceStatus {
307b502fbf0SLoGin         // Safe because the common config pointer is valid and we checked in get_bar_region that it
308b502fbf0SLoGin         // was aligned.
309b502fbf0SLoGin         unsafe { DeviceStatus::from_bits_truncate(volread!(self.common_cfg, device_status).into()) }
310b502fbf0SLoGin     }
311b502fbf0SLoGin 
31226d84a31SYJwu2023     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
31326d84a31SYJwu2023         // No-op, the PCI transport doesn't care.
31426d84a31SYJwu2023     }
31573c607aaSYJwu2023     fn requires_legacy_layout(&self) -> bool {
31673c607aaSYJwu2023         false
31773c607aaSYJwu2023     }
31826d84a31SYJwu2023     fn queue_set(
31926d84a31SYJwu2023         &mut self,
32026d84a31SYJwu2023         queue: u16,
32126d84a31SYJwu2023         size: u32,
32226d84a31SYJwu2023         descriptors: PhysAddr,
32326d84a31SYJwu2023         driver_area: PhysAddr,
32426d84a31SYJwu2023         device_area: PhysAddr,
32526d84a31SYJwu2023     ) {
32626d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
32726d84a31SYJwu2023         // was aligned.
32826d84a31SYJwu2023         unsafe {
32926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
33026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, size as u16);
33126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
33226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
33326d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, device_area as u64);
334afc95d5cSYJwu2023             // 这里设置队列中断对应的中断项
3350dd8ff43SYJwu2023             if queue == QUEUE_RECEIVE {
3360dd8ff43SYJwu2023                 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX);
3370dd8ff43SYJwu2023                 let vector = volread!(self.common_cfg, queue_msix_vector);
3380dd8ff43SYJwu2023                 if vector != VIRTIO_RECV_VECTOR_INDEX {
3390dd8ff43SYJwu2023                     panic!("Vector set failed");
3400dd8ff43SYJwu2023                 }
3410dd8ff43SYJwu2023             }
34226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_enable, 1);
34326d84a31SYJwu2023         }
34426d84a31SYJwu2023     }
34526d84a31SYJwu2023 
34626d84a31SYJwu2023     fn queue_unset(&mut self, queue: u16) {
34726d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
34826d84a31SYJwu2023         // was aligned.
34926d84a31SYJwu2023         unsafe {
35026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
35126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, 0);
35226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, 0);
35326d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, 0);
35426d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, 0);
35526d84a31SYJwu2023         }
35626d84a31SYJwu2023     }
35726d84a31SYJwu2023 
35826d84a31SYJwu2023     fn queue_used(&mut self, queue: u16) -> bool {
35926d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
36026d84a31SYJwu2023         // was aligned.
36126d84a31SYJwu2023         unsafe {
36226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
36326d84a31SYJwu2023             volread!(self.common_cfg, queue_enable) == 1
36426d84a31SYJwu2023         }
36526d84a31SYJwu2023     }
36626d84a31SYJwu2023 
36726d84a31SYJwu2023     fn ack_interrupt(&mut self) -> bool {
36826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
36926d84a31SYJwu2023         // was aligned.
37026d84a31SYJwu2023         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
37126d84a31SYJwu2023         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
37226d84a31SYJwu2023         // TODO: Distinguish between queue interrupt and device configuration interrupt.
37326d84a31SYJwu2023         isr_status & 0x3 != 0
37426d84a31SYJwu2023     }
37526d84a31SYJwu2023 
37626d84a31SYJwu2023     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
37726d84a31SYJwu2023         if let Some(config_space) = self.config_space {
37826d84a31SYJwu2023             if size_of::<T>() > config_space.len() * size_of::<u32>() {
37926d84a31SYJwu2023                 Err(Error::ConfigSpaceTooSmall)
38026d84a31SYJwu2023             } else if align_of::<T>() > 4 {
38126d84a31SYJwu2023                 // Panic as this should only happen if the driver is written incorrectly.
38226d84a31SYJwu2023                 panic!(
38326d84a31SYJwu2023                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
38426d84a31SYJwu2023                     align_of::<T>()
38526d84a31SYJwu2023                 );
38626d84a31SYJwu2023             } else {
38726d84a31SYJwu2023                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
38826d84a31SYJwu2023                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
38926d84a31SYJwu2023                 Ok(config_space_ptr.cast())
39026d84a31SYJwu2023             }
39126d84a31SYJwu2023         } else {
39226d84a31SYJwu2023             Err(Error::ConfigSpaceMissing)
39326d84a31SYJwu2023         }
39426d84a31SYJwu2023     }
39526d84a31SYJwu2023 }
39626d84a31SYJwu2023 
39773c607aaSYJwu2023 impl Drop for PciTransport {
39873c607aaSYJwu2023     fn drop(&mut self) {
39973c607aaSYJwu2023         // Reset the device when the transport is dropped.
400e2841179SLoGin         self.set_status(DeviceStatus::empty());
401e2841179SLoGin 
402e2841179SLoGin         // todo: 调用pci的中断释放函数,并且在virtio_irq_manager里面删除对应的设备的中断
40373c607aaSYJwu2023     }
40473c607aaSYJwu2023 }
40573c607aaSYJwu2023 
40626d84a31SYJwu2023 #[repr(C)]
40726d84a31SYJwu2023 struct CommonCfg {
40826d84a31SYJwu2023     device_feature_select: Volatile<u32>,
40926d84a31SYJwu2023     device_feature: ReadOnly<u32>,
41026d84a31SYJwu2023     driver_feature_select: Volatile<u32>,
41126d84a31SYJwu2023     driver_feature: Volatile<u32>,
41226d84a31SYJwu2023     msix_config: Volatile<u16>,
41326d84a31SYJwu2023     num_queues: ReadOnly<u16>,
41426d84a31SYJwu2023     device_status: Volatile<u8>,
41526d84a31SYJwu2023     config_generation: ReadOnly<u8>,
41626d84a31SYJwu2023     queue_select: Volatile<u16>,
41726d84a31SYJwu2023     queue_size: Volatile<u16>,
41826d84a31SYJwu2023     queue_msix_vector: Volatile<u16>,
41926d84a31SYJwu2023     queue_enable: Volatile<u16>,
42026d84a31SYJwu2023     queue_notify_off: Volatile<u16>,
42126d84a31SYJwu2023     queue_desc: Volatile<u64>,
42226d84a31SYJwu2023     queue_driver: Volatile<u64>,
42326d84a31SYJwu2023     queue_device: Volatile<u64>,
42426d84a31SYJwu2023 }
42526d84a31SYJwu2023 
42626d84a31SYJwu2023 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
42726d84a31SYJwu2023 /// cfg空间在哪个bar的多少偏移处,长度多少
42826d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
42926d84a31SYJwu2023 struct VirtioCapabilityInfo {
43026d84a31SYJwu2023     /// The bar in which the structure can be found.
43126d84a31SYJwu2023     bar: u8,
43226d84a31SYJwu2023     /// The offset within the bar.
43326d84a31SYJwu2023     offset: u32,
43426d84a31SYJwu2023     /// The length in bytes of the structure within the bar.
43526d84a31SYJwu2023     length: u32,
43626d84a31SYJwu2023 }
43726d84a31SYJwu2023 
43826d84a31SYJwu2023 /// An error encountered initialising a VirtIO PCI transport.
43926d84a31SYJwu2023 /// VirtIO PCI transport 初始化时的错误
44026d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
44126d84a31SYJwu2023 pub enum VirtioPciError {
44226d84a31SYJwu2023     /// PCI device vender ID was not the VirtIO vendor ID.
44326d84a31SYJwu2023     InvalidVendorId(u16),
44426d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
44526d84a31SYJwu2023     MissingCommonConfig,
44626d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
44726d84a31SYJwu2023     MissingNotifyConfig,
44826d84a31SYJwu2023     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
44926d84a31SYJwu2023     /// of 2.
45026d84a31SYJwu2023     InvalidNotifyOffMultiplier(u32),
45126d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
45226d84a31SYJwu2023     MissingIsrConfig,
45326d84a31SYJwu2023     /// An IO BAR was provided rather than a memory BAR.
45426d84a31SYJwu2023     UnexpectedBarType,
45526d84a31SYJwu2023     /// A BAR which we need was not allocated an address.
45626d84a31SYJwu2023     BarNotAllocated(u8),
45726d84a31SYJwu2023     /// The offset for some capability was greater than the length of the BAR.
45826d84a31SYJwu2023     BarOffsetOutOfRange,
45926d84a31SYJwu2023     /// The virtual address was not aligned as expected.
46026d84a31SYJwu2023     Misaligned {
46126d84a31SYJwu2023         /// The virtual address in question.
46226d84a31SYJwu2023         vaddr: VirtAddr,
46326d84a31SYJwu2023         /// The expected alignment in bytes.
46426d84a31SYJwu2023         alignment: usize,
46526d84a31SYJwu2023     },
46626d84a31SYJwu2023     ///获取虚拟地址失败
46726d84a31SYJwu2023     BarGetVaddrFailed,
46826d84a31SYJwu2023     /// A generic PCI error,
46926d84a31SYJwu2023     Pci(PciError),
47026d84a31SYJwu2023 }
47126d84a31SYJwu2023 
47226d84a31SYJwu2023 impl Display for VirtioPciError {
47326d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
47426d84a31SYJwu2023         match self {
47526d84a31SYJwu2023             Self::InvalidVendorId(vendor_id) => write!(
47626d84a31SYJwu2023                 f,
47726d84a31SYJwu2023                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
47826d84a31SYJwu2023                 vendor_id, VIRTIO_VENDOR_ID
47926d84a31SYJwu2023             ),
48026d84a31SYJwu2023             Self::MissingCommonConfig => write!(
48126d84a31SYJwu2023                 f,
48226d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
48326d84a31SYJwu2023             ),
48426d84a31SYJwu2023             Self::MissingNotifyConfig => write!(
48526d84a31SYJwu2023                 f,
48626d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
48726d84a31SYJwu2023             ),
48826d84a31SYJwu2023             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
48926d84a31SYJwu2023                 write!(
49026d84a31SYJwu2023                     f,
49126d84a31SYJwu2023                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
49226d84a31SYJwu2023                     notify_off_multiplier
49326d84a31SYJwu2023                 )
49426d84a31SYJwu2023             }
49526d84a31SYJwu2023             Self::MissingIsrConfig => {
49626d84a31SYJwu2023                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
49726d84a31SYJwu2023             }
49826d84a31SYJwu2023             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
49926d84a31SYJwu2023             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
50026d84a31SYJwu2023             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
50126d84a31SYJwu2023             Self::Misaligned { vaddr, alignment } => write!(
50226d84a31SYJwu2023                 f,
5032dd9f0c7SLoGin                 "Virtual address {:?} was not aligned to a {} byte boundary as expected.",
50426d84a31SYJwu2023                 vaddr, alignment
50526d84a31SYJwu2023             ),
50626d84a31SYJwu2023             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
50726d84a31SYJwu2023             Self::Pci(pci_error) => pci_error.fmt(f),
50826d84a31SYJwu2023         }
50926d84a31SYJwu2023     }
51026d84a31SYJwu2023 }
51113776c11Slogin 
51226d84a31SYJwu2023 /// PCI error到VirtioPciError的转换,层层上报
51326d84a31SYJwu2023 impl From<PciError> for VirtioPciError {
51426d84a31SYJwu2023     fn from(error: PciError) -> Self {
51526d84a31SYJwu2023         Self::Pci(error)
51626d84a31SYJwu2023     }
51726d84a31SYJwu2023 }
51826d84a31SYJwu2023 
51926d84a31SYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的指针
52026d84a31SYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
52126d84a31SYJwu2023 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
52226d84a31SYJwu2023 fn get_bar_region<T>(
52378bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
52426d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
52526d84a31SYJwu2023 ) -> Result<NonNull<T>, VirtioPciError> {
52626d84a31SYJwu2023     let bar_info = device_bar.get_bar(struct_info.bar)?;
52726d84a31SYJwu2023     let (bar_address, bar_size) = bar_info
52826d84a31SYJwu2023         .memory_address_size()
52926d84a31SYJwu2023         .ok_or(VirtioPciError::UnexpectedBarType)?;
53026d84a31SYJwu2023     if bar_address == 0 {
53126d84a31SYJwu2023         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
53226d84a31SYJwu2023     }
53326d84a31SYJwu2023     if struct_info.offset + struct_info.length > bar_size
53426d84a31SYJwu2023         || size_of::<T>() > struct_info.length as usize
53526d84a31SYJwu2023     {
53626d84a31SYJwu2023         return Err(VirtioPciError::BarOffsetOutOfRange);
53726d84a31SYJwu2023     }
53873c607aaSYJwu2023     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
53926d84a31SYJwu2023     let vaddr = (bar_info
54026d84a31SYJwu2023         .virtual_address()
5412dd9f0c7SLoGin         .ok_or(VirtioPciError::BarGetVaddrFailed)?)
54226d84a31SYJwu2023         + struct_info.offset as usize;
5432dd9f0c7SLoGin     if vaddr.data() % align_of::<T>() != 0 {
54426d84a31SYJwu2023         return Err(VirtioPciError::Misaligned {
54526d84a31SYJwu2023             vaddr,
54626d84a31SYJwu2023             alignment: align_of::<T>(),
54726d84a31SYJwu2023         });
54826d84a31SYJwu2023     }
5492dd9f0c7SLoGin     let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap();
55073c607aaSYJwu2023     Ok(vaddr.cast())
55126d84a31SYJwu2023 }
55226d84a31SYJwu2023 
553cc36cf4aSYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针
55473c607aaSYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
55526d84a31SYJwu2023 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
55626d84a31SYJwu2023 fn get_bar_region_slice<T>(
55778bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
55826d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
55926d84a31SYJwu2023 ) -> Result<NonNull<[T]>, VirtioPciError> {
56026d84a31SYJwu2023     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
56173c607aaSYJwu2023     // let raw_slice =
56273c607aaSYJwu2023     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
56373c607aaSYJwu2023     Ok(nonnull_slice_from_raw_parts(
56473c607aaSYJwu2023         ptr,
56573c607aaSYJwu2023         struct_info.length as usize / size_of::<T>(),
56673c607aaSYJwu2023     ))
56773c607aaSYJwu2023 }
56813776c11Slogin 
56973c607aaSYJwu2023 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
57073c607aaSYJwu2023     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
57126d84a31SYJwu2023 }
572e2841179SLoGin 
573e2841179SLoGin /// `DefaultVirtioIrqHandler` 是一个默认的virtio设备中断处理程序。
574e2841179SLoGin ///
575e2841179SLoGin /// 当虚拟设备产生中断时,该处理程序会被调用。
576e2841179SLoGin ///
577e2841179SLoGin /// 它首先检查设备ID是否存在,然后尝试查找与设备ID关联的设备。
578e2841179SLoGin /// 如果找到设备,它会调用设备的 `handle_irq` 方法来处理中断。
579e2841179SLoGin /// 如果没有找到设备,它会记录一条警告并返回 `IrqReturn::NotHandled`,表示中断未被处理。
580e2841179SLoGin #[derive(Debug)]
581e2841179SLoGin struct DefaultVirtioIrqHandler;
582e2841179SLoGin 
583e2841179SLoGin impl IrqHandler for DefaultVirtioIrqHandler {
584e2841179SLoGin     fn handle(
585e2841179SLoGin         &self,
586e2841179SLoGin         irq: IrqNumber,
587e2841179SLoGin         _static_data: Option<&dyn IrqHandlerData>,
588e2841179SLoGin         dev_id: Option<Arc<dyn IrqHandlerData>>,
589e2841179SLoGin     ) -> Result<IrqReturn, SystemError> {
590e2841179SLoGin         let dev_id = dev_id.ok_or(SystemError::EINVAL)?;
591e2841179SLoGin         let dev_id = dev_id
592e2841179SLoGin             .arc_any()
593e2841179SLoGin             .downcast::<DeviceId>()
594e2841179SLoGin             .map_err(|_| SystemError::EINVAL)?;
595e2841179SLoGin 
596e2841179SLoGin         if let Some(dev) = virtio_irq_manager().lookup_device(&dev_id) {
597e2841179SLoGin             return dev.handle_irq(irq);
598e2841179SLoGin         } else {
599e2841179SLoGin             // 未绑定具体设备,因此无法处理中断
600e2841179SLoGin 
601e2841179SLoGin             return Ok(IrqReturn::NotHandled);
602e2841179SLoGin         }
603e2841179SLoGin     }
604e2841179SLoGin }
605