xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision afc95d5c2541c27c762091ad38fdffabe355db5a)
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 
80dd8ff43SYJwu2023 use crate::driver::pci::pci_irq::{IrqCommonMsg, IrqMsg, IrqSpecificMsg, PciInterrupt, IRQ};
90dd8ff43SYJwu2023 use crate::include::bindings::bindings::pt_regs;
1073c607aaSYJwu2023 use crate::libs::volatile::{
1173c607aaSYJwu2023     volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
1273c607aaSYJwu2023 };
132dd9f0c7SLoGin use crate::mm::VirtAddr;
140dd8ff43SYJwu2023 use crate::net::net_core::poll_ifaces_try_lock_onetime;
1526d84a31SYJwu2023 use core::{
1626d84a31SYJwu2023     fmt::{self, Display, Formatter},
1726d84a31SYJwu2023     mem::{align_of, size_of},
1826d84a31SYJwu2023     ptr::{self, addr_of_mut, NonNull},
1926d84a31SYJwu2023 };
2026d84a31SYJwu2023 use virtio_drivers::{
2126d84a31SYJwu2023     transport::{DeviceStatus, DeviceType, Transport},
2273c607aaSYJwu2023     Error, Hal, PhysAddr,
2326d84a31SYJwu2023 };
2426d84a31SYJwu2023 
2526d84a31SYJwu2023 /// The PCI vendor ID for VirtIO devices.
2626d84a31SYJwu2023 /// PCI Virtio设备的vendor ID
2726d84a31SYJwu2023 const VIRTIO_VENDOR_ID: u16 = 0x1af4;
2826d84a31SYJwu2023 
2926d84a31SYJwu2023 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
3026d84a31SYJwu2023 /// PCI Virtio设备的DEVICE_ID 的offset
3126d84a31SYJwu2023 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
3226d84a31SYJwu2023 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型
3326d84a31SYJwu2023 const TRANSITIONAL_NETWORK: u16 = 0x1000;
3426d84a31SYJwu2023 const TRANSITIONAL_BLOCK: u16 = 0x1001;
3526d84a31SYJwu2023 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
3626d84a31SYJwu2023 const TRANSITIONAL_CONSOLE: u16 = 0x1003;
3726d84a31SYJwu2023 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
3826d84a31SYJwu2023 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
3926d84a31SYJwu2023 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
4026d84a31SYJwu2023 
4126d84a31SYJwu2023 /// The offset of the bar field within `virtio_pci_cap`.
4226d84a31SYJwu2023 const CAP_BAR_OFFSET: u8 = 4;
4326d84a31SYJwu2023 /// The offset of the offset field with `virtio_pci_cap`.
4426d84a31SYJwu2023 const CAP_BAR_OFFSET_OFFSET: u8 = 8;
4526d84a31SYJwu2023 /// The offset of the `length` field within `virtio_pci_cap`.
4626d84a31SYJwu2023 const CAP_LENGTH_OFFSET: u8 = 12;
4726d84a31SYJwu2023 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
4826d84a31SYJwu2023 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
4926d84a31SYJwu2023 
5026d84a31SYJwu2023 /// Common configuration.
5126d84a31SYJwu2023 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
5226d84a31SYJwu2023 /// Notifications.
5326d84a31SYJwu2023 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
5426d84a31SYJwu2023 /// ISR Status.
5526d84a31SYJwu2023 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
5626d84a31SYJwu2023 /// Device specific configuration.
5726d84a31SYJwu2023 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
5826d84a31SYJwu2023 
590dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号
600dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR: u16 = 56;
610dd8ff43SYJwu2023 /// Virtio设备接收中断的设备号的表项号
620dd8ff43SYJwu2023 const VIRTIO_RECV_VECTOR_INDEX: u16 = 0;
63*afc95d5cSYJwu2023 // 接收的queue号
640dd8ff43SYJwu2023 const QUEUE_RECEIVE: u16 = 0;
6526d84a31SYJwu2023 ///@brief device id 转换为设备类型
6626d84a31SYJwu2023 ///@param pci_device_id,device_id
6726d84a31SYJwu2023 ///@return DeviceType 对应的设备类型
6826d84a31SYJwu2023 fn device_type(pci_device_id: u16) -> DeviceType {
6926d84a31SYJwu2023     match pci_device_id {
7026d84a31SYJwu2023         TRANSITIONAL_NETWORK => DeviceType::Network,
7126d84a31SYJwu2023         TRANSITIONAL_BLOCK => DeviceType::Block,
7226d84a31SYJwu2023         TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
7326d84a31SYJwu2023         TRANSITIONAL_CONSOLE => DeviceType::Console,
7426d84a31SYJwu2023         TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
7526d84a31SYJwu2023         TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
7626d84a31SYJwu2023         TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
7726d84a31SYJwu2023         id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
7826d84a31SYJwu2023         _ => DeviceType::Invalid,
7926d84a31SYJwu2023     }
8026d84a31SYJwu2023 }
8126d84a31SYJwu2023 
8226d84a31SYJwu2023 /// PCI transport for VirtIO.
8326d84a31SYJwu2023 ///
8426d84a31SYJwu2023 /// Ref: 4.1 Virtio Over PCI Bus
8513776c11Slogin #[derive(Debug, Clone)]
8626d84a31SYJwu2023 pub struct PciTransport {
8726d84a31SYJwu2023     device_type: DeviceType,
8826d84a31SYJwu2023     /// The bus, device and function identifier for the VirtIO device.
891496ba7bSLoGin     _bus_device_function: BusDeviceFunction,
9026d84a31SYJwu2023     /// The common configuration structure within some BAR.
9126d84a31SYJwu2023     common_cfg: NonNull<CommonCfg>,
9226d84a31SYJwu2023     /// The start of the queue notification region within some BAR.
9326d84a31SYJwu2023     notify_region: NonNull<[WriteOnly<u16>]>,
9426d84a31SYJwu2023     notify_off_multiplier: u32,
9526d84a31SYJwu2023     /// The ISR status register within some BAR.
9626d84a31SYJwu2023     isr_status: NonNull<Volatile<u8>>,
9726d84a31SYJwu2023     /// The VirtIO device-specific configuration within some BAR.
9826d84a31SYJwu2023     config_space: Option<NonNull<[u32]>>,
9926d84a31SYJwu2023 }
10026d84a31SYJwu2023 
1010dd8ff43SYJwu2023 unsafe extern "C" fn virtio_irq_hander(_irq_num: u64, _irq_paramer: u64, _regs: *mut pt_regs) {
1020dd8ff43SYJwu2023     // kdebug!("12345");
1030dd8ff43SYJwu2023     poll_ifaces_try_lock_onetime().ok();
1040dd8ff43SYJwu2023 }
1050dd8ff43SYJwu2023 
10626d84a31SYJwu2023 impl PciTransport {
10726d84a31SYJwu2023     /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
10826d84a31SYJwu2023     /// root controller.
10926d84a31SYJwu2023     ///
11078bf93f0SYJwu2023     ///
11178bf93f0SYJwu2023     pub fn new<H: Hal>(
11278bf93f0SYJwu2023         device: &mut PciDeviceStructureGeneralDevice,
11378bf93f0SYJwu2023     ) -> Result<Self, VirtioPciError> {
11478bf93f0SYJwu2023         let header = &device.common_header;
11578bf93f0SYJwu2023         let bus_device_function = header.bus_device_function;
11678bf93f0SYJwu2023         if header.vendor_id != VIRTIO_VENDOR_ID {
11778bf93f0SYJwu2023             return Err(VirtioPciError::InvalidVendorId(header.vendor_id));
11826d84a31SYJwu2023         }
11978bf93f0SYJwu2023         let device_type = device_type(header.device_id);
12026d84a31SYJwu2023         // Find the PCI capabilities we need.
12113776c11Slogin         let mut common_cfg: Option<VirtioCapabilityInfo> = None;
12213776c11Slogin         let mut notify_cfg: Option<VirtioCapabilityInfo> = None;
12326d84a31SYJwu2023         let mut notify_off_multiplier = 0;
12426d84a31SYJwu2023         let mut isr_cfg = None;
12526d84a31SYJwu2023         let mut device_cfg = None;
126cc36cf4aSYJwu2023         device.bar_ioremap().unwrap()?;
12778bf93f0SYJwu2023         device.enable_master();
1280dd8ff43SYJwu2023         let standard_device = device.as_standard_device_mut().unwrap();
1290dd8ff43SYJwu2023         // 目前缺少对PCI设备中断号的统一管理,所以这里需要指定一个中断号。不能与其他中断重复
1300dd8ff43SYJwu2023         let irq_vector = standard_device.irq_vector_mut().unwrap();
1310dd8ff43SYJwu2023         irq_vector.push(VIRTIO_RECV_VECTOR);
1320dd8ff43SYJwu2023         standard_device
1330dd8ff43SYJwu2023             .irq_init(IRQ::PCI_IRQ_MSIX)
1340dd8ff43SYJwu2023             .expect("IRQ init failed");
1350dd8ff43SYJwu2023         // 中断相关信息
1360dd8ff43SYJwu2023         let msg = IrqMsg {
137*afc95d5cSYJwu2023             irq_common_message: IrqCommonMsg::init_from(
138*afc95d5cSYJwu2023                 0,
139*afc95d5cSYJwu2023                 "Virtio_Recv_IRQ",
140*afc95d5cSYJwu2023                 0,
141*afc95d5cSYJwu2023                 virtio_irq_hander,
142*afc95d5cSYJwu2023                 None,
143*afc95d5cSYJwu2023             ),
1440dd8ff43SYJwu2023             irq_specific_message: IrqSpecificMsg::msi_default(),
1450dd8ff43SYJwu2023         };
1460dd8ff43SYJwu2023         standard_device.irq_install(msg)?;
1470dd8ff43SYJwu2023         standard_device.irq_enable(true)?;
14826d84a31SYJwu2023         //device_capability为迭代器,遍历其相当于遍历所有的cap空间
14978bf93f0SYJwu2023         for capability in device.capabilities().unwrap() {
15026d84a31SYJwu2023             if capability.id != PCI_CAP_ID_VNDR {
15126d84a31SYJwu2023                 continue;
15226d84a31SYJwu2023             }
15326d84a31SYJwu2023             let cap_len = capability.private_header as u8;
15426d84a31SYJwu2023             let cfg_type = (capability.private_header >> 8) as u8;
15526d84a31SYJwu2023             if cap_len < 16 {
15626d84a31SYJwu2023                 continue;
15726d84a31SYJwu2023             }
15826d84a31SYJwu2023             let struct_info = VirtioCapabilityInfo {
15978bf93f0SYJwu2023                 bar: PciArch::read_config(&bus_device_function, capability.offset + CAP_BAR_OFFSET)
16078bf93f0SYJwu2023                     as u8,
16178bf93f0SYJwu2023                 offset: PciArch::read_config(
16278bf93f0SYJwu2023                     &bus_device_function,
16326d84a31SYJwu2023                     capability.offset + CAP_BAR_OFFSET_OFFSET,
16478bf93f0SYJwu2023                 ),
16578bf93f0SYJwu2023                 length: PciArch::read_config(
16678bf93f0SYJwu2023                     &bus_device_function,
16726d84a31SYJwu2023                     capability.offset + CAP_LENGTH_OFFSET,
16878bf93f0SYJwu2023                 ),
16926d84a31SYJwu2023             };
17026d84a31SYJwu2023 
17126d84a31SYJwu2023             match cfg_type {
17226d84a31SYJwu2023                 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
17326d84a31SYJwu2023                     common_cfg = Some(struct_info);
17426d84a31SYJwu2023                 }
17526d84a31SYJwu2023                 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
17626d84a31SYJwu2023                     notify_cfg = Some(struct_info);
17778bf93f0SYJwu2023                     notify_off_multiplier = PciArch::read_config(
17878bf93f0SYJwu2023                         &bus_device_function,
17926d84a31SYJwu2023                         capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET,
18026d84a31SYJwu2023                     );
18126d84a31SYJwu2023                 }
18226d84a31SYJwu2023                 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
18326d84a31SYJwu2023                     isr_cfg = Some(struct_info);
18426d84a31SYJwu2023                 }
18526d84a31SYJwu2023                 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
18626d84a31SYJwu2023                     device_cfg = Some(struct_info);
18726d84a31SYJwu2023                 }
18826d84a31SYJwu2023                 _ => {}
18926d84a31SYJwu2023             }
19026d84a31SYJwu2023         }
19126d84a31SYJwu2023 
19226d84a31SYJwu2023         let common_cfg = get_bar_region::<_>(
19378bf93f0SYJwu2023             &device.standard_device_bar,
19426d84a31SYJwu2023             &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
19526d84a31SYJwu2023         )?;
19626d84a31SYJwu2023 
19726d84a31SYJwu2023         let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
19826d84a31SYJwu2023         if notify_off_multiplier % 2 != 0 {
19926d84a31SYJwu2023             return Err(VirtioPciError::InvalidNotifyOffMultiplier(
20026d84a31SYJwu2023                 notify_off_multiplier,
20126d84a31SYJwu2023             ));
20226d84a31SYJwu2023         }
20373c607aaSYJwu2023         //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length);
20478bf93f0SYJwu2023         let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, &notify_cfg)?;
20526d84a31SYJwu2023         let isr_status = get_bar_region::<_>(
20678bf93f0SYJwu2023             &device.standard_device_bar,
20726d84a31SYJwu2023             &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
20826d84a31SYJwu2023         )?;
20926d84a31SYJwu2023         let config_space = if let Some(device_cfg) = device_cfg {
21078bf93f0SYJwu2023             Some(get_bar_region_slice::<_>(
21178bf93f0SYJwu2023                 &device.standard_device_bar,
21278bf93f0SYJwu2023                 &device_cfg,
21378bf93f0SYJwu2023             )?)
21426d84a31SYJwu2023         } else {
21526d84a31SYJwu2023             None
21626d84a31SYJwu2023         };
21726d84a31SYJwu2023         Ok(Self {
21826d84a31SYJwu2023             device_type,
2191496ba7bSLoGin             _bus_device_function: bus_device_function,
22026d84a31SYJwu2023             common_cfg,
22126d84a31SYJwu2023             notify_region,
22226d84a31SYJwu2023             notify_off_multiplier,
22326d84a31SYJwu2023             isr_status,
22426d84a31SYJwu2023             config_space,
22526d84a31SYJwu2023         })
22626d84a31SYJwu2023     }
22726d84a31SYJwu2023 }
22826d84a31SYJwu2023 
22926d84a31SYJwu2023 impl Transport for PciTransport {
23026d84a31SYJwu2023     fn device_type(&self) -> DeviceType {
23126d84a31SYJwu2023         self.device_type
23226d84a31SYJwu2023     }
23326d84a31SYJwu2023 
23426d84a31SYJwu2023     fn read_device_features(&mut self) -> u64 {
23526d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
23626d84a31SYJwu2023         // was aligned.
23726d84a31SYJwu2023         unsafe {
23826d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 0);
23926d84a31SYJwu2023             let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
24026d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 1);
24126d84a31SYJwu2023             device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
24226d84a31SYJwu2023             device_features_bits
24326d84a31SYJwu2023         }
24426d84a31SYJwu2023     }
24526d84a31SYJwu2023 
24626d84a31SYJwu2023     fn write_driver_features(&mut self, driver_features: u64) {
24726d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
24826d84a31SYJwu2023         // was aligned.
24926d84a31SYJwu2023         unsafe {
25026d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 0);
25126d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature, driver_features as u32);
25226d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 1);
25326d84a31SYJwu2023             volwrite!(
25426d84a31SYJwu2023                 self.common_cfg,
25526d84a31SYJwu2023                 driver_feature,
25626d84a31SYJwu2023                 (driver_features >> 32) as u32
25726d84a31SYJwu2023             );
25826d84a31SYJwu2023         }
25926d84a31SYJwu2023     }
26026d84a31SYJwu2023 
26126d84a31SYJwu2023     fn max_queue_size(&self) -> u32 {
26226d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
26326d84a31SYJwu2023         // was aligned.
26426d84a31SYJwu2023         unsafe { volread!(self.common_cfg, queue_size) }.into()
26526d84a31SYJwu2023     }
26626d84a31SYJwu2023 
26726d84a31SYJwu2023     fn notify(&mut self, queue: u16) {
26826d84a31SYJwu2023         // Safe because the common config and notify region pointers are valid and we checked in
26926d84a31SYJwu2023         // get_bar_region that they were aligned.
27026d84a31SYJwu2023         unsafe {
27126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
27226d84a31SYJwu2023             // TODO: Consider caching this somewhere (per queue).
27326d84a31SYJwu2023             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
27426d84a31SYJwu2023 
27526d84a31SYJwu2023             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
27626d84a31SYJwu2023             let index = offset_bytes / size_of::<u16>();
27726d84a31SYJwu2023             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
27826d84a31SYJwu2023         }
27926d84a31SYJwu2023     }
28026d84a31SYJwu2023 
28126d84a31SYJwu2023     fn set_status(&mut self, status: DeviceStatus) {
28226d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
28326d84a31SYJwu2023         // was aligned.
28426d84a31SYJwu2023         unsafe {
28526d84a31SYJwu2023             volwrite!(self.common_cfg, device_status, status.bits() as u8);
28626d84a31SYJwu2023         }
28726d84a31SYJwu2023     }
28826d84a31SYJwu2023 
28926d84a31SYJwu2023     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
29026d84a31SYJwu2023         // No-op, the PCI transport doesn't care.
29126d84a31SYJwu2023     }
29273c607aaSYJwu2023     fn requires_legacy_layout(&self) -> bool {
29373c607aaSYJwu2023         false
29473c607aaSYJwu2023     }
29526d84a31SYJwu2023     fn queue_set(
29626d84a31SYJwu2023         &mut self,
29726d84a31SYJwu2023         queue: u16,
29826d84a31SYJwu2023         size: u32,
29926d84a31SYJwu2023         descriptors: PhysAddr,
30026d84a31SYJwu2023         driver_area: PhysAddr,
30126d84a31SYJwu2023         device_area: PhysAddr,
30226d84a31SYJwu2023     ) {
30326d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
30426d84a31SYJwu2023         // was aligned.
30526d84a31SYJwu2023         unsafe {
30626d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
30726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, size as u16);
30826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
30926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
31026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, device_area as u64);
311*afc95d5cSYJwu2023             // 这里设置队列中断对应的中断项
3120dd8ff43SYJwu2023             if queue == QUEUE_RECEIVE {
3130dd8ff43SYJwu2023                 volwrite!(self.common_cfg, queue_msix_vector, VIRTIO_RECV_VECTOR_INDEX);
3140dd8ff43SYJwu2023                 let vector = volread!(self.common_cfg, queue_msix_vector);
3150dd8ff43SYJwu2023                 if vector != VIRTIO_RECV_VECTOR_INDEX {
3160dd8ff43SYJwu2023                     panic!("Vector set failed");
3170dd8ff43SYJwu2023                 }
3180dd8ff43SYJwu2023             }
31926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_enable, 1);
32026d84a31SYJwu2023         }
32126d84a31SYJwu2023     }
32226d84a31SYJwu2023 
32326d84a31SYJwu2023     fn queue_unset(&mut self, queue: u16) {
32426d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
32526d84a31SYJwu2023         // was aligned.
32626d84a31SYJwu2023         unsafe {
32726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
32826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, 0);
32926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, 0);
33026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, 0);
33126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, 0);
33226d84a31SYJwu2023         }
33326d84a31SYJwu2023     }
33426d84a31SYJwu2023 
33526d84a31SYJwu2023     fn queue_used(&mut self, queue: u16) -> bool {
33626d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
33726d84a31SYJwu2023         // was aligned.
33826d84a31SYJwu2023         unsafe {
33926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
34026d84a31SYJwu2023             volread!(self.common_cfg, queue_enable) == 1
34126d84a31SYJwu2023         }
34226d84a31SYJwu2023     }
34326d84a31SYJwu2023 
34426d84a31SYJwu2023     fn ack_interrupt(&mut self) -> bool {
34526d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
34626d84a31SYJwu2023         // was aligned.
34726d84a31SYJwu2023         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
34826d84a31SYJwu2023         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
34926d84a31SYJwu2023         // TODO: Distinguish between queue interrupt and device configuration interrupt.
35026d84a31SYJwu2023         isr_status & 0x3 != 0
35126d84a31SYJwu2023     }
35226d84a31SYJwu2023 
35326d84a31SYJwu2023     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
35426d84a31SYJwu2023         if let Some(config_space) = self.config_space {
35526d84a31SYJwu2023             if size_of::<T>() > config_space.len() * size_of::<u32>() {
35626d84a31SYJwu2023                 Err(Error::ConfigSpaceTooSmall)
35726d84a31SYJwu2023             } else if align_of::<T>() > 4 {
35826d84a31SYJwu2023                 // Panic as this should only happen if the driver is written incorrectly.
35926d84a31SYJwu2023                 panic!(
36026d84a31SYJwu2023                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
36126d84a31SYJwu2023                     align_of::<T>()
36226d84a31SYJwu2023                 );
36326d84a31SYJwu2023             } else {
36426d84a31SYJwu2023                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
36526d84a31SYJwu2023                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
36626d84a31SYJwu2023                 Ok(config_space_ptr.cast())
36726d84a31SYJwu2023             }
36826d84a31SYJwu2023         } else {
36926d84a31SYJwu2023             Err(Error::ConfigSpaceMissing)
37026d84a31SYJwu2023         }
37126d84a31SYJwu2023     }
37226d84a31SYJwu2023 }
37326d84a31SYJwu2023 
37473c607aaSYJwu2023 impl Drop for PciTransport {
37573c607aaSYJwu2023     fn drop(&mut self) {
37673c607aaSYJwu2023         // Reset the device when the transport is dropped.
37773c607aaSYJwu2023         self.set_status(DeviceStatus::empty())
37873c607aaSYJwu2023     }
37973c607aaSYJwu2023 }
38073c607aaSYJwu2023 
38126d84a31SYJwu2023 #[repr(C)]
38226d84a31SYJwu2023 struct CommonCfg {
38326d84a31SYJwu2023     device_feature_select: Volatile<u32>,
38426d84a31SYJwu2023     device_feature: ReadOnly<u32>,
38526d84a31SYJwu2023     driver_feature_select: Volatile<u32>,
38626d84a31SYJwu2023     driver_feature: Volatile<u32>,
38726d84a31SYJwu2023     msix_config: Volatile<u16>,
38826d84a31SYJwu2023     num_queues: ReadOnly<u16>,
38926d84a31SYJwu2023     device_status: Volatile<u8>,
39026d84a31SYJwu2023     config_generation: ReadOnly<u8>,
39126d84a31SYJwu2023     queue_select: Volatile<u16>,
39226d84a31SYJwu2023     queue_size: Volatile<u16>,
39326d84a31SYJwu2023     queue_msix_vector: Volatile<u16>,
39426d84a31SYJwu2023     queue_enable: Volatile<u16>,
39526d84a31SYJwu2023     queue_notify_off: Volatile<u16>,
39626d84a31SYJwu2023     queue_desc: Volatile<u64>,
39726d84a31SYJwu2023     queue_driver: Volatile<u64>,
39826d84a31SYJwu2023     queue_device: Volatile<u64>,
39926d84a31SYJwu2023 }
40026d84a31SYJwu2023 
40126d84a31SYJwu2023 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
40226d84a31SYJwu2023 /// cfg空间在哪个bar的多少偏移处,长度多少
40326d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
40426d84a31SYJwu2023 struct VirtioCapabilityInfo {
40526d84a31SYJwu2023     /// The bar in which the structure can be found.
40626d84a31SYJwu2023     bar: u8,
40726d84a31SYJwu2023     /// The offset within the bar.
40826d84a31SYJwu2023     offset: u32,
40926d84a31SYJwu2023     /// The length in bytes of the structure within the bar.
41026d84a31SYJwu2023     length: u32,
41126d84a31SYJwu2023 }
41226d84a31SYJwu2023 
41326d84a31SYJwu2023 /// An error encountered initialising a VirtIO PCI transport.
41426d84a31SYJwu2023 /// VirtIO PCI transport 初始化时的错误
41526d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
41626d84a31SYJwu2023 pub enum VirtioPciError {
41726d84a31SYJwu2023     /// PCI device vender ID was not the VirtIO vendor ID.
41826d84a31SYJwu2023     InvalidVendorId(u16),
41926d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
42026d84a31SYJwu2023     MissingCommonConfig,
42126d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
42226d84a31SYJwu2023     MissingNotifyConfig,
42326d84a31SYJwu2023     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
42426d84a31SYJwu2023     /// of 2.
42526d84a31SYJwu2023     InvalidNotifyOffMultiplier(u32),
42626d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
42726d84a31SYJwu2023     MissingIsrConfig,
42826d84a31SYJwu2023     /// An IO BAR was provided rather than a memory BAR.
42926d84a31SYJwu2023     UnexpectedBarType,
43026d84a31SYJwu2023     /// A BAR which we need was not allocated an address.
43126d84a31SYJwu2023     BarNotAllocated(u8),
43226d84a31SYJwu2023     /// The offset for some capability was greater than the length of the BAR.
43326d84a31SYJwu2023     BarOffsetOutOfRange,
43426d84a31SYJwu2023     /// The virtual address was not aligned as expected.
43526d84a31SYJwu2023     Misaligned {
43626d84a31SYJwu2023         /// The virtual address in question.
43726d84a31SYJwu2023         vaddr: VirtAddr,
43826d84a31SYJwu2023         /// The expected alignment in bytes.
43926d84a31SYJwu2023         alignment: usize,
44026d84a31SYJwu2023     },
44126d84a31SYJwu2023     ///获取虚拟地址失败
44226d84a31SYJwu2023     BarGetVaddrFailed,
44326d84a31SYJwu2023     /// A generic PCI error,
44426d84a31SYJwu2023     Pci(PciError),
44526d84a31SYJwu2023 }
44626d84a31SYJwu2023 
44726d84a31SYJwu2023 impl Display for VirtioPciError {
44826d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
44926d84a31SYJwu2023         match self {
45026d84a31SYJwu2023             Self::InvalidVendorId(vendor_id) => write!(
45126d84a31SYJwu2023                 f,
45226d84a31SYJwu2023                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
45326d84a31SYJwu2023                 vendor_id, VIRTIO_VENDOR_ID
45426d84a31SYJwu2023             ),
45526d84a31SYJwu2023             Self::MissingCommonConfig => write!(
45626d84a31SYJwu2023                 f,
45726d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
45826d84a31SYJwu2023             ),
45926d84a31SYJwu2023             Self::MissingNotifyConfig => write!(
46026d84a31SYJwu2023                 f,
46126d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
46226d84a31SYJwu2023             ),
46326d84a31SYJwu2023             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
46426d84a31SYJwu2023                 write!(
46526d84a31SYJwu2023                     f,
46626d84a31SYJwu2023                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
46726d84a31SYJwu2023                     notify_off_multiplier
46826d84a31SYJwu2023                 )
46926d84a31SYJwu2023             }
47026d84a31SYJwu2023             Self::MissingIsrConfig => {
47126d84a31SYJwu2023                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
47226d84a31SYJwu2023             }
47326d84a31SYJwu2023             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
47426d84a31SYJwu2023             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
47526d84a31SYJwu2023             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
47626d84a31SYJwu2023             Self::Misaligned { vaddr, alignment } => write!(
47726d84a31SYJwu2023                 f,
4782dd9f0c7SLoGin                 "Virtual address {:?} was not aligned to a {} byte boundary as expected.",
47926d84a31SYJwu2023                 vaddr, alignment
48026d84a31SYJwu2023             ),
48126d84a31SYJwu2023             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
48226d84a31SYJwu2023             Self::Pci(pci_error) => pci_error.fmt(f),
48326d84a31SYJwu2023         }
48426d84a31SYJwu2023     }
48526d84a31SYJwu2023 }
48613776c11Slogin 
48726d84a31SYJwu2023 /// PCI error到VirtioPciError的转换,层层上报
48826d84a31SYJwu2023 impl From<PciError> for VirtioPciError {
48926d84a31SYJwu2023     fn from(error: PciError) -> Self {
49026d84a31SYJwu2023         Self::Pci(error)
49126d84a31SYJwu2023     }
49226d84a31SYJwu2023 }
49326d84a31SYJwu2023 
49426d84a31SYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的指针
49526d84a31SYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
49626d84a31SYJwu2023 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
49726d84a31SYJwu2023 fn get_bar_region<T>(
49878bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
49926d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
50026d84a31SYJwu2023 ) -> Result<NonNull<T>, VirtioPciError> {
50126d84a31SYJwu2023     let bar_info = device_bar.get_bar(struct_info.bar)?;
50226d84a31SYJwu2023     let (bar_address, bar_size) = bar_info
50326d84a31SYJwu2023         .memory_address_size()
50426d84a31SYJwu2023         .ok_or(VirtioPciError::UnexpectedBarType)?;
50526d84a31SYJwu2023     if bar_address == 0 {
50626d84a31SYJwu2023         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
50726d84a31SYJwu2023     }
50826d84a31SYJwu2023     if struct_info.offset + struct_info.length > bar_size
50926d84a31SYJwu2023         || size_of::<T>() > struct_info.length as usize
51026d84a31SYJwu2023     {
51126d84a31SYJwu2023         return Err(VirtioPciError::BarOffsetOutOfRange);
51226d84a31SYJwu2023     }
51373c607aaSYJwu2023     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
51426d84a31SYJwu2023     let vaddr = (bar_info
51526d84a31SYJwu2023         .virtual_address()
5162dd9f0c7SLoGin         .ok_or(VirtioPciError::BarGetVaddrFailed)?)
51726d84a31SYJwu2023         + struct_info.offset as usize;
5182dd9f0c7SLoGin     if vaddr.data() % align_of::<T>() != 0 {
51926d84a31SYJwu2023         return Err(VirtioPciError::Misaligned {
52026d84a31SYJwu2023             vaddr,
52126d84a31SYJwu2023             alignment: align_of::<T>(),
52226d84a31SYJwu2023         });
52326d84a31SYJwu2023     }
5242dd9f0c7SLoGin     let vaddr = NonNull::new(vaddr.data() as *mut u8).unwrap();
52573c607aaSYJwu2023     Ok(vaddr.cast())
52626d84a31SYJwu2023 }
52726d84a31SYJwu2023 
528cc36cf4aSYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的切片的指针
52973c607aaSYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
53026d84a31SYJwu2023 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
53126d84a31SYJwu2023 fn get_bar_region_slice<T>(
53278bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
53326d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
53426d84a31SYJwu2023 ) -> Result<NonNull<[T]>, VirtioPciError> {
53526d84a31SYJwu2023     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
53673c607aaSYJwu2023     // let raw_slice =
53773c607aaSYJwu2023     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
53873c607aaSYJwu2023     Ok(nonnull_slice_from_raw_parts(
53973c607aaSYJwu2023         ptr,
54073c607aaSYJwu2023         struct_info.length as usize / size_of::<T>(),
54173c607aaSYJwu2023     ))
54273c607aaSYJwu2023 }
54313776c11Slogin 
54473c607aaSYJwu2023 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
54573c607aaSYJwu2023     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
54626d84a31SYJwu2023 }
547