xref: /DragonOS/kernel/src/driver/virtio/transport_pci.rs (revision 13776c114b15c406b1e0aaeeb71812ea6e471d2e)
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 
873c607aaSYJwu2023 use crate::libs::volatile::{
973c607aaSYJwu2023     volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
1073c607aaSYJwu2023 };
1126d84a31SYJwu2023 use core::{
1226d84a31SYJwu2023     fmt::{self, Display, Formatter},
1326d84a31SYJwu2023     mem::{align_of, size_of},
1426d84a31SYJwu2023     ptr::{self, addr_of_mut, NonNull},
1526d84a31SYJwu2023 };
1626d84a31SYJwu2023 use virtio_drivers::{
1726d84a31SYJwu2023     transport::{DeviceStatus, DeviceType, Transport},
1873c607aaSYJwu2023     Error, Hal, PhysAddr,
1926d84a31SYJwu2023 };
2026d84a31SYJwu2023 
2173c607aaSYJwu2023 type VirtAddr = usize;
2226d84a31SYJwu2023 /// The PCI vendor ID for VirtIO devices.
2326d84a31SYJwu2023 /// PCI Virtio设备的vendor ID
2426d84a31SYJwu2023 const VIRTIO_VENDOR_ID: u16 = 0x1af4;
2526d84a31SYJwu2023 
2626d84a31SYJwu2023 /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
2726d84a31SYJwu2023 /// PCI Virtio设备的DEVICE_ID 的offset
2826d84a31SYJwu2023 const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
2926d84a31SYJwu2023 /// PCI Virtio 设备的DEVICE_ID及其对应的设备类型
3026d84a31SYJwu2023 const TRANSITIONAL_NETWORK: u16 = 0x1000;
3126d84a31SYJwu2023 const TRANSITIONAL_BLOCK: u16 = 0x1001;
3226d84a31SYJwu2023 const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
3326d84a31SYJwu2023 const TRANSITIONAL_CONSOLE: u16 = 0x1003;
3426d84a31SYJwu2023 const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
3526d84a31SYJwu2023 const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
3626d84a31SYJwu2023 const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
3726d84a31SYJwu2023 
3826d84a31SYJwu2023 /// The offset of the bar field within `virtio_pci_cap`.
3926d84a31SYJwu2023 const CAP_BAR_OFFSET: u8 = 4;
4026d84a31SYJwu2023 /// The offset of the offset field with `virtio_pci_cap`.
4126d84a31SYJwu2023 const CAP_BAR_OFFSET_OFFSET: u8 = 8;
4226d84a31SYJwu2023 /// The offset of the `length` field within `virtio_pci_cap`.
4326d84a31SYJwu2023 const CAP_LENGTH_OFFSET: u8 = 12;
4426d84a31SYJwu2023 /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
4526d84a31SYJwu2023 const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
4626d84a31SYJwu2023 
4726d84a31SYJwu2023 /// Common configuration.
4826d84a31SYJwu2023 const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
4926d84a31SYJwu2023 /// Notifications.
5026d84a31SYJwu2023 const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
5126d84a31SYJwu2023 /// ISR Status.
5226d84a31SYJwu2023 const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
5326d84a31SYJwu2023 /// Device specific configuration.
5426d84a31SYJwu2023 const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
5526d84a31SYJwu2023 
5626d84a31SYJwu2023 ///@brief device id 转换为设备类型
5726d84a31SYJwu2023 ///@param pci_device_id,device_id
5826d84a31SYJwu2023 ///@return DeviceType 对应的设备类型
5926d84a31SYJwu2023 fn device_type(pci_device_id: u16) -> DeviceType {
6026d84a31SYJwu2023     match pci_device_id {
6126d84a31SYJwu2023         TRANSITIONAL_NETWORK => DeviceType::Network,
6226d84a31SYJwu2023         TRANSITIONAL_BLOCK => DeviceType::Block,
6326d84a31SYJwu2023         TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
6426d84a31SYJwu2023         TRANSITIONAL_CONSOLE => DeviceType::Console,
6526d84a31SYJwu2023         TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
6626d84a31SYJwu2023         TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
6726d84a31SYJwu2023         TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
6826d84a31SYJwu2023         id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
6926d84a31SYJwu2023         _ => DeviceType::Invalid,
7026d84a31SYJwu2023     }
7126d84a31SYJwu2023 }
7226d84a31SYJwu2023 
7326d84a31SYJwu2023 /// PCI transport for VirtIO.
7426d84a31SYJwu2023 ///
7526d84a31SYJwu2023 /// Ref: 4.1 Virtio Over PCI Bus
76*13776c11Slogin #[derive(Debug, Clone)]
7726d84a31SYJwu2023 pub struct PciTransport {
7826d84a31SYJwu2023     device_type: DeviceType,
7926d84a31SYJwu2023     /// The bus, device and function identifier for the VirtIO device.
8078bf93f0SYJwu2023     bus_device_function: BusDeviceFunction,
8126d84a31SYJwu2023     /// The common configuration structure within some BAR.
8226d84a31SYJwu2023     common_cfg: NonNull<CommonCfg>,
8326d84a31SYJwu2023     /// The start of the queue notification region within some BAR.
8426d84a31SYJwu2023     notify_region: NonNull<[WriteOnly<u16>]>,
8526d84a31SYJwu2023     notify_off_multiplier: u32,
8626d84a31SYJwu2023     /// The ISR status register within some BAR.
8726d84a31SYJwu2023     isr_status: NonNull<Volatile<u8>>,
8826d84a31SYJwu2023     /// The VirtIO device-specific configuration within some BAR.
8926d84a31SYJwu2023     config_space: Option<NonNull<[u32]>>,
9026d84a31SYJwu2023 }
9126d84a31SYJwu2023 
9226d84a31SYJwu2023 impl PciTransport {
9326d84a31SYJwu2023     /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
9426d84a31SYJwu2023     /// root controller.
9526d84a31SYJwu2023     ///
9678bf93f0SYJwu2023     ///
9778bf93f0SYJwu2023     pub fn new<H: Hal>(
9878bf93f0SYJwu2023         device: &mut PciDeviceStructureGeneralDevice,
9978bf93f0SYJwu2023     ) -> Result<Self, VirtioPciError> {
10078bf93f0SYJwu2023         let header = &device.common_header;
10178bf93f0SYJwu2023         let bus_device_function = header.bus_device_function;
10278bf93f0SYJwu2023         if header.vendor_id != VIRTIO_VENDOR_ID {
10378bf93f0SYJwu2023             return Err(VirtioPciError::InvalidVendorId(header.vendor_id));
10426d84a31SYJwu2023         }
10578bf93f0SYJwu2023         let device_type = device_type(header.device_id);
10626d84a31SYJwu2023         // Find the PCI capabilities we need.
107*13776c11Slogin         let mut common_cfg: Option<VirtioCapabilityInfo> = None;
108*13776c11Slogin         let mut notify_cfg: Option<VirtioCapabilityInfo> = None;
10926d84a31SYJwu2023         let mut notify_off_multiplier = 0;
11026d84a31SYJwu2023         let mut isr_cfg = None;
11126d84a31SYJwu2023         let mut device_cfg = None;
11278bf93f0SYJwu2023         device.bar_init().unwrap()?;
11378bf93f0SYJwu2023         device.enable_master();
11426d84a31SYJwu2023         //device_capability为迭代器,遍历其相当于遍历所有的cap空间
11578bf93f0SYJwu2023         for capability in device.capabilities().unwrap() {
11626d84a31SYJwu2023             if capability.id != PCI_CAP_ID_VNDR {
11726d84a31SYJwu2023                 continue;
11826d84a31SYJwu2023             }
11926d84a31SYJwu2023             let cap_len = capability.private_header as u8;
12026d84a31SYJwu2023             let cfg_type = (capability.private_header >> 8) as u8;
12126d84a31SYJwu2023             if cap_len < 16 {
12226d84a31SYJwu2023                 continue;
12326d84a31SYJwu2023             }
12426d84a31SYJwu2023             let struct_info = VirtioCapabilityInfo {
12578bf93f0SYJwu2023                 bar: PciArch::read_config(&bus_device_function, capability.offset + CAP_BAR_OFFSET)
12678bf93f0SYJwu2023                     as u8,
12778bf93f0SYJwu2023                 offset: PciArch::read_config(
12878bf93f0SYJwu2023                     &bus_device_function,
12926d84a31SYJwu2023                     capability.offset + CAP_BAR_OFFSET_OFFSET,
13078bf93f0SYJwu2023                 ),
13178bf93f0SYJwu2023                 length: PciArch::read_config(
13278bf93f0SYJwu2023                     &bus_device_function,
13326d84a31SYJwu2023                     capability.offset + CAP_LENGTH_OFFSET,
13478bf93f0SYJwu2023                 ),
13526d84a31SYJwu2023             };
13626d84a31SYJwu2023 
13726d84a31SYJwu2023             match cfg_type {
13826d84a31SYJwu2023                 VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
13926d84a31SYJwu2023                     common_cfg = Some(struct_info);
14026d84a31SYJwu2023                 }
14126d84a31SYJwu2023                 VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
14226d84a31SYJwu2023                     notify_cfg = Some(struct_info);
14378bf93f0SYJwu2023                     notify_off_multiplier = PciArch::read_config(
14478bf93f0SYJwu2023                         &bus_device_function,
14526d84a31SYJwu2023                         capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET,
14626d84a31SYJwu2023                     );
14726d84a31SYJwu2023                 }
14826d84a31SYJwu2023                 VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
14926d84a31SYJwu2023                     isr_cfg = Some(struct_info);
15026d84a31SYJwu2023                 }
15126d84a31SYJwu2023                 VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
15226d84a31SYJwu2023                     device_cfg = Some(struct_info);
15326d84a31SYJwu2023                 }
15426d84a31SYJwu2023                 _ => {}
15526d84a31SYJwu2023             }
15626d84a31SYJwu2023         }
15726d84a31SYJwu2023 
15826d84a31SYJwu2023         let common_cfg = get_bar_region::<_>(
15978bf93f0SYJwu2023             &device.standard_device_bar,
16026d84a31SYJwu2023             &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
16126d84a31SYJwu2023         )?;
16226d84a31SYJwu2023 
16326d84a31SYJwu2023         let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
16426d84a31SYJwu2023         if notify_off_multiplier % 2 != 0 {
16526d84a31SYJwu2023             return Err(VirtioPciError::InvalidNotifyOffMultiplier(
16626d84a31SYJwu2023                 notify_off_multiplier,
16726d84a31SYJwu2023             ));
16826d84a31SYJwu2023         }
16973c607aaSYJwu2023         //kdebug!("notify.offset={},notify.length={}",notify_cfg.offset,notify_cfg.length);
17078bf93f0SYJwu2023         let notify_region = get_bar_region_slice::<_>(&device.standard_device_bar, &notify_cfg)?;
17126d84a31SYJwu2023         let isr_status = get_bar_region::<_>(
17278bf93f0SYJwu2023             &device.standard_device_bar,
17326d84a31SYJwu2023             &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
17426d84a31SYJwu2023         )?;
17526d84a31SYJwu2023         let config_space = if let Some(device_cfg) = device_cfg {
17678bf93f0SYJwu2023             Some(get_bar_region_slice::<_>(
17778bf93f0SYJwu2023                 &device.standard_device_bar,
17878bf93f0SYJwu2023                 &device_cfg,
17978bf93f0SYJwu2023             )?)
18026d84a31SYJwu2023         } else {
18126d84a31SYJwu2023             None
18226d84a31SYJwu2023         };
18326d84a31SYJwu2023         Ok(Self {
18426d84a31SYJwu2023             device_type,
18578bf93f0SYJwu2023             bus_device_function,
18626d84a31SYJwu2023             common_cfg,
18726d84a31SYJwu2023             notify_region,
18826d84a31SYJwu2023             notify_off_multiplier,
18926d84a31SYJwu2023             isr_status,
19026d84a31SYJwu2023             config_space,
19126d84a31SYJwu2023         })
19226d84a31SYJwu2023     }
19326d84a31SYJwu2023 }
19426d84a31SYJwu2023 
19526d84a31SYJwu2023 impl Transport for PciTransport {
19626d84a31SYJwu2023     fn device_type(&self) -> DeviceType {
19726d84a31SYJwu2023         self.device_type
19826d84a31SYJwu2023     }
19926d84a31SYJwu2023 
20026d84a31SYJwu2023     fn read_device_features(&mut self) -> u64 {
20126d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
20226d84a31SYJwu2023         // was aligned.
20326d84a31SYJwu2023         unsafe {
20426d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 0);
20526d84a31SYJwu2023             let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
20626d84a31SYJwu2023             volwrite!(self.common_cfg, device_feature_select, 1);
20726d84a31SYJwu2023             device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
20826d84a31SYJwu2023             device_features_bits
20926d84a31SYJwu2023         }
21026d84a31SYJwu2023     }
21126d84a31SYJwu2023 
21226d84a31SYJwu2023     fn write_driver_features(&mut self, driver_features: u64) {
21326d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
21426d84a31SYJwu2023         // was aligned.
21526d84a31SYJwu2023         unsafe {
21626d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 0);
21726d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature, driver_features as u32);
21826d84a31SYJwu2023             volwrite!(self.common_cfg, driver_feature_select, 1);
21926d84a31SYJwu2023             volwrite!(
22026d84a31SYJwu2023                 self.common_cfg,
22126d84a31SYJwu2023                 driver_feature,
22226d84a31SYJwu2023                 (driver_features >> 32) as u32
22326d84a31SYJwu2023             );
22426d84a31SYJwu2023         }
22526d84a31SYJwu2023     }
22626d84a31SYJwu2023 
22726d84a31SYJwu2023     fn max_queue_size(&self) -> u32 {
22826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
22926d84a31SYJwu2023         // was aligned.
23026d84a31SYJwu2023         unsafe { volread!(self.common_cfg, queue_size) }.into()
23126d84a31SYJwu2023     }
23226d84a31SYJwu2023 
23326d84a31SYJwu2023     fn notify(&mut self, queue: u16) {
23426d84a31SYJwu2023         // Safe because the common config and notify region pointers are valid and we checked in
23526d84a31SYJwu2023         // get_bar_region that they were aligned.
23626d84a31SYJwu2023         unsafe {
23726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
23826d84a31SYJwu2023             // TODO: Consider caching this somewhere (per queue).
23926d84a31SYJwu2023             let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
24026d84a31SYJwu2023 
24126d84a31SYJwu2023             let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
24226d84a31SYJwu2023             let index = offset_bytes / size_of::<u16>();
24326d84a31SYJwu2023             addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
24426d84a31SYJwu2023         }
24526d84a31SYJwu2023     }
24626d84a31SYJwu2023 
24726d84a31SYJwu2023     fn set_status(&mut self, status: DeviceStatus) {
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_status, status.bits() as u8);
25226d84a31SYJwu2023         }
25326d84a31SYJwu2023     }
25426d84a31SYJwu2023 
25526d84a31SYJwu2023     fn set_guest_page_size(&mut self, _guest_page_size: u32) {
25626d84a31SYJwu2023         // No-op, the PCI transport doesn't care.
25726d84a31SYJwu2023     }
25873c607aaSYJwu2023     fn requires_legacy_layout(&self) -> bool {
25973c607aaSYJwu2023         false
26073c607aaSYJwu2023     }
26126d84a31SYJwu2023     fn queue_set(
26226d84a31SYJwu2023         &mut self,
26326d84a31SYJwu2023         queue: u16,
26426d84a31SYJwu2023         size: u32,
26526d84a31SYJwu2023         descriptors: PhysAddr,
26626d84a31SYJwu2023         driver_area: PhysAddr,
26726d84a31SYJwu2023         device_area: PhysAddr,
26826d84a31SYJwu2023     ) {
26926d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
27026d84a31SYJwu2023         // was aligned.
27173c607aaSYJwu2023         // kdebug!("queue_select={}",queue);
27273c607aaSYJwu2023         // kdebug!("queue_size={}",size as u16);
27373c607aaSYJwu2023         // kdebug!("queue_desc={:#x}",descriptors as u64);
27473c607aaSYJwu2023         // kdebug!("driver_area={:#x}",driver_area);
27526d84a31SYJwu2023         unsafe {
27626d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
27726d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, size as u16);
27826d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, descriptors as u64);
27926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, driver_area as u64);
28026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, device_area as u64);
28126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_enable, 1);
28226d84a31SYJwu2023         }
28326d84a31SYJwu2023     }
28426d84a31SYJwu2023 
28526d84a31SYJwu2023     fn queue_unset(&mut self, queue: u16) {
28626d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
28726d84a31SYJwu2023         // was aligned.
28826d84a31SYJwu2023         unsafe {
28926d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
29026d84a31SYJwu2023             volwrite!(self.common_cfg, queue_size, 0);
29126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_desc, 0);
29226d84a31SYJwu2023             volwrite!(self.common_cfg, queue_driver, 0);
29326d84a31SYJwu2023             volwrite!(self.common_cfg, queue_device, 0);
29426d84a31SYJwu2023         }
29526d84a31SYJwu2023     }
29626d84a31SYJwu2023 
29726d84a31SYJwu2023     fn queue_used(&mut self, queue: u16) -> bool {
29826d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
29926d84a31SYJwu2023         // was aligned.
30026d84a31SYJwu2023         unsafe {
30126d84a31SYJwu2023             volwrite!(self.common_cfg, queue_select, queue);
30226d84a31SYJwu2023             volread!(self.common_cfg, queue_enable) == 1
30326d84a31SYJwu2023         }
30426d84a31SYJwu2023     }
30526d84a31SYJwu2023 
30626d84a31SYJwu2023     fn ack_interrupt(&mut self) -> bool {
30726d84a31SYJwu2023         // Safe because the common config pointer is valid and we checked in get_bar_region that it
30826d84a31SYJwu2023         // was aligned.
30926d84a31SYJwu2023         // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
31026d84a31SYJwu2023         let isr_status = unsafe { self.isr_status.as_ptr().vread() };
31126d84a31SYJwu2023         // TODO: Distinguish between queue interrupt and device configuration interrupt.
31226d84a31SYJwu2023         isr_status & 0x3 != 0
31326d84a31SYJwu2023     }
31426d84a31SYJwu2023 
31526d84a31SYJwu2023     fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
31626d84a31SYJwu2023         if let Some(config_space) = self.config_space {
31726d84a31SYJwu2023             if size_of::<T>() > config_space.len() * size_of::<u32>() {
31826d84a31SYJwu2023                 Err(Error::ConfigSpaceTooSmall)
31926d84a31SYJwu2023             } else if align_of::<T>() > 4 {
32026d84a31SYJwu2023                 // Panic as this should only happen if the driver is written incorrectly.
32126d84a31SYJwu2023                 panic!(
32226d84a31SYJwu2023                     "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
32326d84a31SYJwu2023                     align_of::<T>()
32426d84a31SYJwu2023                 );
32526d84a31SYJwu2023             } else {
32626d84a31SYJwu2023                 // TODO: Use NonNull::as_non_null_ptr once it is stable.
32726d84a31SYJwu2023                 let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
32826d84a31SYJwu2023                 Ok(config_space_ptr.cast())
32926d84a31SYJwu2023             }
33026d84a31SYJwu2023         } else {
33126d84a31SYJwu2023             Err(Error::ConfigSpaceMissing)
33226d84a31SYJwu2023         }
33326d84a31SYJwu2023     }
33426d84a31SYJwu2023 }
33526d84a31SYJwu2023 
33673c607aaSYJwu2023 impl Drop for PciTransport {
33773c607aaSYJwu2023     fn drop(&mut self) {
33873c607aaSYJwu2023         // Reset the device when the transport is dropped.
33973c607aaSYJwu2023         self.set_status(DeviceStatus::empty())
34073c607aaSYJwu2023     }
34173c607aaSYJwu2023 }
34273c607aaSYJwu2023 
34326d84a31SYJwu2023 #[repr(C)]
34426d84a31SYJwu2023 struct CommonCfg {
34526d84a31SYJwu2023     device_feature_select: Volatile<u32>,
34626d84a31SYJwu2023     device_feature: ReadOnly<u32>,
34726d84a31SYJwu2023     driver_feature_select: Volatile<u32>,
34826d84a31SYJwu2023     driver_feature: Volatile<u32>,
34926d84a31SYJwu2023     msix_config: Volatile<u16>,
35026d84a31SYJwu2023     num_queues: ReadOnly<u16>,
35126d84a31SYJwu2023     device_status: Volatile<u8>,
35226d84a31SYJwu2023     config_generation: ReadOnly<u8>,
35326d84a31SYJwu2023     queue_select: Volatile<u16>,
35426d84a31SYJwu2023     queue_size: Volatile<u16>,
35526d84a31SYJwu2023     queue_msix_vector: Volatile<u16>,
35626d84a31SYJwu2023     queue_enable: Volatile<u16>,
35726d84a31SYJwu2023     queue_notify_off: Volatile<u16>,
35826d84a31SYJwu2023     queue_desc: Volatile<u64>,
35926d84a31SYJwu2023     queue_driver: Volatile<u64>,
36026d84a31SYJwu2023     queue_device: Volatile<u64>,
36126d84a31SYJwu2023 }
36226d84a31SYJwu2023 
36326d84a31SYJwu2023 /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
36426d84a31SYJwu2023 /// cfg空间在哪个bar的多少偏移处,长度多少
36526d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
36626d84a31SYJwu2023 struct VirtioCapabilityInfo {
36726d84a31SYJwu2023     /// The bar in which the structure can be found.
36826d84a31SYJwu2023     bar: u8,
36926d84a31SYJwu2023     /// The offset within the bar.
37026d84a31SYJwu2023     offset: u32,
37126d84a31SYJwu2023     /// The length in bytes of the structure within the bar.
37226d84a31SYJwu2023     length: u32,
37326d84a31SYJwu2023 }
37426d84a31SYJwu2023 
37526d84a31SYJwu2023 /// An error encountered initialising a VirtIO PCI transport.
37626d84a31SYJwu2023 /// VirtIO PCI transport 初始化时的错误
37726d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
37826d84a31SYJwu2023 pub enum VirtioPciError {
37926d84a31SYJwu2023     /// PCI device vender ID was not the VirtIO vendor ID.
38026d84a31SYJwu2023     InvalidVendorId(u16),
38126d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
38226d84a31SYJwu2023     MissingCommonConfig,
38326d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
38426d84a31SYJwu2023     MissingNotifyConfig,
38526d84a31SYJwu2023     /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
38626d84a31SYJwu2023     /// of 2.
38726d84a31SYJwu2023     InvalidNotifyOffMultiplier(u32),
38826d84a31SYJwu2023     /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
38926d84a31SYJwu2023     MissingIsrConfig,
39026d84a31SYJwu2023     /// An IO BAR was provided rather than a memory BAR.
39126d84a31SYJwu2023     UnexpectedBarType,
39226d84a31SYJwu2023     /// A BAR which we need was not allocated an address.
39326d84a31SYJwu2023     BarNotAllocated(u8),
39426d84a31SYJwu2023     /// The offset for some capability was greater than the length of the BAR.
39526d84a31SYJwu2023     BarOffsetOutOfRange,
39626d84a31SYJwu2023     /// The virtual address was not aligned as expected.
39726d84a31SYJwu2023     Misaligned {
39826d84a31SYJwu2023         /// The virtual address in question.
39926d84a31SYJwu2023         vaddr: VirtAddr,
40026d84a31SYJwu2023         /// The expected alignment in bytes.
40126d84a31SYJwu2023         alignment: usize,
40226d84a31SYJwu2023     },
40326d84a31SYJwu2023     ///获取虚拟地址失败
40426d84a31SYJwu2023     BarGetVaddrFailed,
40526d84a31SYJwu2023     /// A generic PCI error,
40626d84a31SYJwu2023     Pci(PciError),
40726d84a31SYJwu2023 }
40826d84a31SYJwu2023 
40926d84a31SYJwu2023 impl Display for VirtioPciError {
41026d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
41126d84a31SYJwu2023         match self {
41226d84a31SYJwu2023             Self::InvalidVendorId(vendor_id) => write!(
41326d84a31SYJwu2023                 f,
41426d84a31SYJwu2023                 "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
41526d84a31SYJwu2023                 vendor_id, VIRTIO_VENDOR_ID
41626d84a31SYJwu2023             ),
41726d84a31SYJwu2023             Self::MissingCommonConfig => write!(
41826d84a31SYJwu2023                 f,
41926d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
42026d84a31SYJwu2023             ),
42126d84a31SYJwu2023             Self::MissingNotifyConfig => write!(
42226d84a31SYJwu2023                 f,
42326d84a31SYJwu2023                 "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
42426d84a31SYJwu2023             ),
42526d84a31SYJwu2023             Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
42626d84a31SYJwu2023                 write!(
42726d84a31SYJwu2023                     f,
42826d84a31SYJwu2023                     "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
42926d84a31SYJwu2023                     notify_off_multiplier
43026d84a31SYJwu2023                 )
43126d84a31SYJwu2023             }
43226d84a31SYJwu2023             Self::MissingIsrConfig => {
43326d84a31SYJwu2023                 write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
43426d84a31SYJwu2023             }
43526d84a31SYJwu2023             Self::UnexpectedBarType => write!(f, "Unexpected BAR (expected memory BAR)."),
43626d84a31SYJwu2023             Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
43726d84a31SYJwu2023             Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
43826d84a31SYJwu2023             Self::Misaligned { vaddr, alignment } => write!(
43926d84a31SYJwu2023                 f,
44026d84a31SYJwu2023                 "Virtual address {:#018x} was not aligned to a {} byte boundary as expected.",
44126d84a31SYJwu2023                 vaddr, alignment
44226d84a31SYJwu2023             ),
44326d84a31SYJwu2023             Self::BarGetVaddrFailed => write!(f, "Get bar virtaddress failed"),
44426d84a31SYJwu2023             Self::Pci(pci_error) => pci_error.fmt(f),
44526d84a31SYJwu2023         }
44626d84a31SYJwu2023     }
44726d84a31SYJwu2023 }
448*13776c11Slogin 
44926d84a31SYJwu2023 /// PCI error到VirtioPciError的转换,层层上报
45026d84a31SYJwu2023 impl From<PciError> for VirtioPciError {
45126d84a31SYJwu2023     fn from(error: PciError) -> Self {
45226d84a31SYJwu2023         Self::Pci(error)
45326d84a31SYJwu2023     }
45426d84a31SYJwu2023 }
45526d84a31SYJwu2023 
45626d84a31SYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的指针
45726d84a31SYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息
45826d84a31SYJwu2023 /// @return Result<NonNull<T>, VirtioPciError> 成功则返回对应类型的指针,失败则返回Error
45926d84a31SYJwu2023 fn get_bar_region<T>(
46078bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
46126d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
46226d84a31SYJwu2023 ) -> Result<NonNull<T>, VirtioPciError> {
46326d84a31SYJwu2023     let bar_info = device_bar.get_bar(struct_info.bar)?;
46426d84a31SYJwu2023     let (bar_address, bar_size) = bar_info
46526d84a31SYJwu2023         .memory_address_size()
46626d84a31SYJwu2023         .ok_or(VirtioPciError::UnexpectedBarType)?;
46726d84a31SYJwu2023     if bar_address == 0 {
46826d84a31SYJwu2023         return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
46926d84a31SYJwu2023     }
47026d84a31SYJwu2023     if struct_info.offset + struct_info.length > bar_size
47126d84a31SYJwu2023         || size_of::<T>() > struct_info.length as usize
47226d84a31SYJwu2023     {
47326d84a31SYJwu2023         return Err(VirtioPciError::BarOffsetOutOfRange);
47426d84a31SYJwu2023     }
47573c607aaSYJwu2023     //kdebug!("Chossed bar ={},used={}",struct_info.bar,struct_info.offset + struct_info.length);
47626d84a31SYJwu2023     let vaddr = (bar_info
47726d84a31SYJwu2023         .virtual_address()
47826d84a31SYJwu2023         .ok_or(VirtioPciError::BarGetVaddrFailed)?) as usize
47926d84a31SYJwu2023         + struct_info.offset as usize;
48026d84a31SYJwu2023     if vaddr % align_of::<T>() != 0 {
48126d84a31SYJwu2023         return Err(VirtioPciError::Misaligned {
48226d84a31SYJwu2023             vaddr,
48326d84a31SYJwu2023             alignment: align_of::<T>(),
48426d84a31SYJwu2023         });
48526d84a31SYJwu2023     }
48673c607aaSYJwu2023     let vaddr = NonNull::new(vaddr as *mut u8).unwrap();
48773c607aaSYJwu2023     Ok(vaddr.cast())
48826d84a31SYJwu2023 }
48926d84a31SYJwu2023 
49073c607aaSYJwu2023 /// @brief 获取虚拟地址并将其转化为对应类型的
49173c607aaSYJwu2023 /// @param device_bar 存储bar信息的结构体 struct_info 存储cfg空间的位置信息切片的指针
49226d84a31SYJwu2023 /// @return Result<NonNull<[T]>, VirtioPciError> 成功则返回对应类型的指针切片,失败则返回Error
49326d84a31SYJwu2023 fn get_bar_region_slice<T>(
49478bf93f0SYJwu2023     device_bar: &PciStandardDeviceBar,
49526d84a31SYJwu2023     struct_info: &VirtioCapabilityInfo,
49626d84a31SYJwu2023 ) -> Result<NonNull<[T]>, VirtioPciError> {
49726d84a31SYJwu2023     let ptr = get_bar_region::<T>(device_bar, struct_info)?;
49873c607aaSYJwu2023     // let raw_slice =
49973c607aaSYJwu2023     //     ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
50073c607aaSYJwu2023     Ok(nonnull_slice_from_raw_parts(
50173c607aaSYJwu2023         ptr,
50273c607aaSYJwu2023         struct_info.length as usize / size_of::<T>(),
50373c607aaSYJwu2023     ))
50473c607aaSYJwu2023 }
505*13776c11Slogin 
50673c607aaSYJwu2023 fn nonnull_slice_from_raw_parts<T>(data: NonNull<T>, len: usize) -> NonNull<[T]> {
50773c607aaSYJwu2023     NonNull::new(ptr::slice_from_raw_parts_mut(data.as_ptr(), len)).unwrap()
50826d84a31SYJwu2023 }
509