xref: /DragonOS/kernel/src/driver/pci/pci.rs (revision cc36cf4a186be834e6c2ab857b9b9501ddb8b1eb)
178bf93f0SYJwu2023 #![allow(dead_code)]
278bf93f0SYJwu2023 // 目前仅支持单主桥单Segment
378bf93f0SYJwu2023 
4*cc36cf4aSYJwu2023 use super::pci_irq::{IrqType, PciIrqError};
578bf93f0SYJwu2023 use crate::arch::{PciArch, TraitPciArch};
626d84a31SYJwu2023 use crate::include::bindings::bindings::{
778bf93f0SYJwu2023     initial_mm, mm_map, mm_struct, PAGE_2M_SIZE, VM_DONTCOPY, VM_IO,
826d84a31SYJwu2023 };
978bf93f0SYJwu2023 use crate::libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
1026d84a31SYJwu2023 use crate::mm::mmio_buddy::MMIO_POOL;
1178bf93f0SYJwu2023 use crate::{kdebug, kerror, kinfo, kwarn};
1278bf93f0SYJwu2023 use alloc::vec::Vec;
1378bf93f0SYJwu2023 use alloc::{boxed::Box, collections::LinkedList};
1426d84a31SYJwu2023 use bitflags::bitflags;
1526d84a31SYJwu2023 use core::{
1626d84a31SYJwu2023     convert::TryFrom,
175c1e552cSYJwu2023     fmt::{self, Debug, Display, Formatter},
1826d84a31SYJwu2023 };
1978bf93f0SYJwu2023 // PCI_DEVICE_LINKEDLIST 添加了读写锁的全局链表,里面存储了检索到的PCI设备结构体
2078bf93f0SYJwu2023 // PCI_ROOT_0 Segment为0的全局PciRoot
2178bf93f0SYJwu2023 lazy_static! {
2278bf93f0SYJwu2023     pub static ref PCI_DEVICE_LINKEDLIST: PciDeviceLinkedList = PciDeviceLinkedList::new();
2378bf93f0SYJwu2023     pub static ref PCI_ROOT_0: Option<PciRoot> = {
2478bf93f0SYJwu2023         match PciRoot::new(0) {
2578bf93f0SYJwu2023             Ok(root) => Some(root),
2678bf93f0SYJwu2023             Err(err) => {
2778bf93f0SYJwu2023                 kerror!("Pci_root init failed because of error: {}", err);
2878bf93f0SYJwu2023                 None
2978bf93f0SYJwu2023             }
3078bf93f0SYJwu2023         }
3178bf93f0SYJwu2023     };
3278bf93f0SYJwu2023 }
335c1e552cSYJwu2023 /// PCI域地址
345c1e552cSYJwu2023 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
355c1e552cSYJwu2023 #[repr(transparent)]
365c1e552cSYJwu2023 pub struct PciAddr(usize);
375c1e552cSYJwu2023 
385c1e552cSYJwu2023 impl PciAddr {
395c1e552cSYJwu2023     #[inline(always)]
405c1e552cSYJwu2023     pub const fn new(address: usize) -> Self {
415c1e552cSYJwu2023         Self(address)
425c1e552cSYJwu2023     }
435c1e552cSYJwu2023 
445c1e552cSYJwu2023     /// @brief 获取PCI域地址的值
455c1e552cSYJwu2023     #[inline(always)]
465c1e552cSYJwu2023     pub fn data(&self) -> usize {
475c1e552cSYJwu2023         self.0
485c1e552cSYJwu2023     }
495c1e552cSYJwu2023 
505c1e552cSYJwu2023     /// @brief 将PCI域地址加上一个偏移量
515c1e552cSYJwu2023     #[inline(always)]
525c1e552cSYJwu2023     pub fn add(self, offset: usize) -> Self {
535c1e552cSYJwu2023         Self(self.0 + offset)
545c1e552cSYJwu2023     }
555c1e552cSYJwu2023 
565c1e552cSYJwu2023     /// @brief 判断PCI域地址是否按照指定要求对齐
575c1e552cSYJwu2023     #[inline(always)]
585c1e552cSYJwu2023     pub fn check_aligned(&self, align: usize) -> bool {
595c1e552cSYJwu2023         return self.0 & (align - 1) == 0;
605c1e552cSYJwu2023     }
615c1e552cSYJwu2023 }
625c1e552cSYJwu2023 impl Debug for PciAddr {
635c1e552cSYJwu2023     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
645c1e552cSYJwu2023         write!(f, "PciAddr({:#x})", self.0)
655c1e552cSYJwu2023     }
665c1e552cSYJwu2023 }
6778bf93f0SYJwu2023 
6878bf93f0SYJwu2023 /// 添加了读写锁的链表,存储PCI设备结构体
6978bf93f0SYJwu2023 pub struct PciDeviceLinkedList {
7078bf93f0SYJwu2023     list: RwLock<LinkedList<Box<dyn PciDeviceStructure>>>,
7178bf93f0SYJwu2023 }
7278bf93f0SYJwu2023 
7378bf93f0SYJwu2023 impl PciDeviceLinkedList {
7478bf93f0SYJwu2023     /// @brief 初始化结构体
7578bf93f0SYJwu2023     fn new() -> Self {
7678bf93f0SYJwu2023         PciDeviceLinkedList {
7778bf93f0SYJwu2023             list: RwLock::new(LinkedList::new()),
7878bf93f0SYJwu2023         }
7978bf93f0SYJwu2023     }
8078bf93f0SYJwu2023     /// @brief 获取可读的linkedlist(读锁守卫)
8178bf93f0SYJwu2023     /// @return RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>>  读锁守卫
8213776c11Slogin     pub fn read(&self) -> RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
8378bf93f0SYJwu2023         self.list.read()
8478bf93f0SYJwu2023     }
8578bf93f0SYJwu2023     /// @brief 获取可写的linkedlist(写锁守卫)
8678bf93f0SYJwu2023     /// @return RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>>  写锁守卫
8713776c11Slogin     pub fn write(&self) -> RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
8878bf93f0SYJwu2023         self.list.write()
8978bf93f0SYJwu2023     }
9078bf93f0SYJwu2023     /// @brief 获取链表中PCI结构体数目
9178bf93f0SYJwu2023     /// @return usize 链表中PCI结构体数目
9278bf93f0SYJwu2023     pub fn num(&self) -> usize {
9378bf93f0SYJwu2023         let list = self.list.read();
9478bf93f0SYJwu2023         list.len()
9578bf93f0SYJwu2023     }
9678bf93f0SYJwu2023     /// @brief 添加Pci设备结构体到链表中
9778bf93f0SYJwu2023     pub fn add(&self, device: Box<dyn PciDeviceStructure>) {
9878bf93f0SYJwu2023         let mut list = self.list.write();
9978bf93f0SYJwu2023         list.push_back(device);
10078bf93f0SYJwu2023     }
10178bf93f0SYJwu2023 }
10278bf93f0SYJwu2023 
10378bf93f0SYJwu2023 /// @brief 在链表中寻找满足条件的PCI设备结构体并返回其可变引用
10478bf93f0SYJwu2023 /// @param list 链表的写锁守卫
10578bf93f0SYJwu2023 /// @param class_code 寄存器值
10678bf93f0SYJwu2023 /// @param subclass 寄存器值,与class_code一起确定设备类型
10778bf93f0SYJwu2023 /// @return Vec<&'a mut Box<(dyn PciDeviceStructure)  包含链表中所有满足条件的PCI结构体的可变引用的容器
10878bf93f0SYJwu2023 pub fn get_pci_device_structure_mut<'a>(
10978bf93f0SYJwu2023     list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
11078bf93f0SYJwu2023     class_code: u8,
11178bf93f0SYJwu2023     subclass: u8,
11278bf93f0SYJwu2023 ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
11378bf93f0SYJwu2023     let mut result = Vec::new();
11478bf93f0SYJwu2023     for box_pci_device_structure in list.iter_mut() {
11578bf93f0SYJwu2023         let common_header = (*box_pci_device_structure).common_header();
11678bf93f0SYJwu2023         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
11778bf93f0SYJwu2023             result.push(box_pci_device_structure);
11878bf93f0SYJwu2023         }
11978bf93f0SYJwu2023     }
12078bf93f0SYJwu2023     result
12178bf93f0SYJwu2023 }
12278bf93f0SYJwu2023 /// @brief 在链表中寻找满足条件的PCI设备结构体并返回其不可变引用
12378bf93f0SYJwu2023 /// @param list 链表的读锁守卫
12478bf93f0SYJwu2023 /// @param class_code 寄存器值
12578bf93f0SYJwu2023 /// @param subclass 寄存器值,与class_code一起确定设备类型
12678bf93f0SYJwu2023 /// @return Vec<&'a Box<(dyn PciDeviceStructure)  包含链表中所有满足条件的PCI结构体的不可变引用的容器
12778bf93f0SYJwu2023 pub fn get_pci_device_structure<'a>(
12878bf93f0SYJwu2023     list: &'a mut RwLockReadGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
12978bf93f0SYJwu2023     class_code: u8,
13078bf93f0SYJwu2023     subclass: u8,
13178bf93f0SYJwu2023 ) -> Vec<&'a Box<(dyn PciDeviceStructure)>> {
13278bf93f0SYJwu2023     let mut result = Vec::new();
13378bf93f0SYJwu2023     for box_pci_device_structure in list.iter() {
13478bf93f0SYJwu2023         let common_header = (*box_pci_device_structure).common_header();
13578bf93f0SYJwu2023         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
13678bf93f0SYJwu2023             result.push(box_pci_device_structure);
13778bf93f0SYJwu2023         }
13878bf93f0SYJwu2023     }
13978bf93f0SYJwu2023     result
14078bf93f0SYJwu2023 }
14178bf93f0SYJwu2023 
14226d84a31SYJwu2023 //Bar0寄存器的offset
14326d84a31SYJwu2023 const BAR0_OFFSET: u8 = 0x10;
14426d84a31SYJwu2023 //Status、Command寄存器的offset
14526d84a31SYJwu2023 const STATUS_COMMAND_OFFSET: u8 = 0x04;
14626d84a31SYJwu2023 /// ID for vendor-specific PCI capabilities.(Virtio Capabilities)
14726d84a31SYJwu2023 pub const PCI_CAP_ID_VNDR: u8 = 0x09;
148*cc36cf4aSYJwu2023 pub const PCI_CAP_ID_MSI: u8 = 0x05;
149*cc36cf4aSYJwu2023 pub const PCI_CAP_ID_MSIX: u8 = 0x11;
15078bf93f0SYJwu2023 pub const PORT_PCI_CONFIG_ADDRESS: u16 = 0xcf8;
15178bf93f0SYJwu2023 pub const PORT_PCI_CONFIG_DATA: u16 = 0xcfc;
15278bf93f0SYJwu2023 // pci设备分组的id
15378bf93f0SYJwu2023 pub type SegmentGroupNumber = u16; //理论上最多支持65535个Segment_Group
15426d84a31SYJwu2023 
15526d84a31SYJwu2023 bitflags! {
15626d84a31SYJwu2023     /// The status register in PCI configuration space.
15726d84a31SYJwu2023     pub struct Status: u16 {
15826d84a31SYJwu2023         // Bits 0-2 are reserved.
15926d84a31SYJwu2023         /// The state of the device's INTx# signal.
16026d84a31SYJwu2023         const INTERRUPT_STATUS = 1 << 3;
16126d84a31SYJwu2023         /// The device has a linked list of capabilities.
16226d84a31SYJwu2023         const CAPABILITIES_LIST = 1 << 4;
16326d84a31SYJwu2023         /// The device is capabile of running at 66 MHz rather than 33 MHz.
16426d84a31SYJwu2023         const MHZ_66_CAPABLE = 1 << 5;
16526d84a31SYJwu2023         // Bit 6 is reserved.
16626d84a31SYJwu2023         /// The device can accept fast back-to-back transactions not from the same agent.
16726d84a31SYJwu2023         const FAST_BACK_TO_BACK_CAPABLE = 1 << 7;
16826d84a31SYJwu2023         /// The bus agent observed a parity error (if parity error handling is enabled).
16926d84a31SYJwu2023         const MASTER_DATA_PARITY_ERROR = 1 << 8;
17026d84a31SYJwu2023         // Bits 9-10 are DEVSEL timing.
17126d84a31SYJwu2023         /// A target device terminated a transaction with target-abort.
17226d84a31SYJwu2023         const SIGNALED_TARGET_ABORT = 1 << 11;
17326d84a31SYJwu2023         /// A master device transaction was terminated with target-abort.
17426d84a31SYJwu2023         const RECEIVED_TARGET_ABORT = 1 << 12;
17526d84a31SYJwu2023         /// A master device transaction was terminated with master-abort.
17626d84a31SYJwu2023         const RECEIVED_MASTER_ABORT = 1 << 13;
17726d84a31SYJwu2023         /// A device asserts SERR#.
17826d84a31SYJwu2023         const SIGNALED_SYSTEM_ERROR = 1 << 14;
17926d84a31SYJwu2023         /// The device detects a parity error, even if parity error handling is disabled.
18026d84a31SYJwu2023         const DETECTED_PARITY_ERROR = 1 << 15;
18126d84a31SYJwu2023     }
18226d84a31SYJwu2023 }
18326d84a31SYJwu2023 
18426d84a31SYJwu2023 bitflags! {
18526d84a31SYJwu2023     /// The command register in PCI configuration space.
18678bf93f0SYJwu2023     pub struct Command: u16 {
18726d84a31SYJwu2023         /// The device can respond to I/O Space accesses.
18826d84a31SYJwu2023         const IO_SPACE = 1 << 0;
18926d84a31SYJwu2023         /// The device can respond to Memory Space accesses.
19026d84a31SYJwu2023         const MEMORY_SPACE = 1 << 1;
19126d84a31SYJwu2023         /// The device can behave as a bus master.
19226d84a31SYJwu2023         const BUS_MASTER = 1 << 2;
19326d84a31SYJwu2023         /// The device can monitor Special Cycle operations.
19426d84a31SYJwu2023         const SPECIAL_CYCLES = 1 << 3;
19526d84a31SYJwu2023         /// The device can generate the Memory Write and Invalidate command.
19626d84a31SYJwu2023         const MEMORY_WRITE_AND_INVALIDATE_ENABLE = 1 << 4;
19726d84a31SYJwu2023         /// The device will snoop palette register data.
19826d84a31SYJwu2023         const VGA_PALETTE_SNOOP = 1 << 5;
19926d84a31SYJwu2023         /// The device should take its normal action when a parity error is detected.
20026d84a31SYJwu2023         const PARITY_ERROR_RESPONSE = 1 << 6;
20126d84a31SYJwu2023         // Bit 7 is reserved.
20226d84a31SYJwu2023         /// The SERR# driver is enabled.
20326d84a31SYJwu2023         const SERR_ENABLE = 1 << 8;
20426d84a31SYJwu2023         /// The device is allowed to generate fast back-to-back transactions.
20526d84a31SYJwu2023         const FAST_BACK_TO_BACK_ENABLE = 1 << 9;
20626d84a31SYJwu2023         /// Assertion of the device's INTx# signal is disabled.
20726d84a31SYJwu2023         const INTERRUPT_DISABLE = 1 << 10;
20826d84a31SYJwu2023     }
20926d84a31SYJwu2023 }
21026d84a31SYJwu2023 
21178bf93f0SYJwu2023 /// The type of a PCI device function header.
21278bf93f0SYJwu2023 /// 标头类型/设备类型
21378bf93f0SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
21478bf93f0SYJwu2023 pub enum HeaderType {
21578bf93f0SYJwu2023     /// A normal PCI device.
21678bf93f0SYJwu2023     Standard,
21778bf93f0SYJwu2023     /// A PCI to PCI bridge.
21878bf93f0SYJwu2023     PciPciBridge,
21978bf93f0SYJwu2023     /// A PCI to CardBus bridge.
22078bf93f0SYJwu2023     PciCardbusBridge,
22178bf93f0SYJwu2023     /// Unrecognised header type.
22278bf93f0SYJwu2023     Unrecognised(u8),
22378bf93f0SYJwu2023 }
22478bf93f0SYJwu2023 /// u8到HeaderType的转换
22578bf93f0SYJwu2023 impl From<u8> for HeaderType {
22678bf93f0SYJwu2023     fn from(value: u8) -> Self {
22778bf93f0SYJwu2023         match value {
22878bf93f0SYJwu2023             0x00 => Self::Standard,
22978bf93f0SYJwu2023             0x01 => Self::PciPciBridge,
23078bf93f0SYJwu2023             0x02 => Self::PciCardbusBridge,
23178bf93f0SYJwu2023             _ => Self::Unrecognised(value),
23278bf93f0SYJwu2023         }
23378bf93f0SYJwu2023     }
23478bf93f0SYJwu2023 }
23578bf93f0SYJwu2023 /// Pci可能触发的各种错误
23678bf93f0SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
23778bf93f0SYJwu2023 pub enum PciError {
23878bf93f0SYJwu2023     /// The device reported an invalid BAR type.
23978bf93f0SYJwu2023     InvalidBarType,
24078bf93f0SYJwu2023     CreateMmioError,
24178bf93f0SYJwu2023     InvalidBusDeviceFunction,
24278bf93f0SYJwu2023     SegmentNotFound,
243*cc36cf4aSYJwu2023     McfgTableNotFound,
24478bf93f0SYJwu2023     GetWrongHeader,
24578bf93f0SYJwu2023     UnrecognisedHeaderType,
24678bf93f0SYJwu2023     PciDeviceStructureTransformError,
247*cc36cf4aSYJwu2023     PciIrqError(PciIrqError),
24878bf93f0SYJwu2023 }
24978bf93f0SYJwu2023 ///实现PciError的Display trait,使其可以直接输出
25078bf93f0SYJwu2023 impl Display for PciError {
25178bf93f0SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
25278bf93f0SYJwu2023         match self {
25378bf93f0SYJwu2023             Self::InvalidBarType => write!(f, "Invalid PCI BAR type."),
25478bf93f0SYJwu2023             Self::CreateMmioError => write!(f, "Error occurred while creating mmio."),
25578bf93f0SYJwu2023             Self::InvalidBusDeviceFunction => write!(f, "Found invalid BusDeviceFunction."),
25678bf93f0SYJwu2023             Self::SegmentNotFound => write!(f, "Target segment not found"),
257*cc36cf4aSYJwu2023             Self::McfgTableNotFound => write!(f, "ACPI MCFG Table not found"),
25878bf93f0SYJwu2023             Self::GetWrongHeader => write!(f, "GetWrongHeader with vendor id 0xffff"),
25978bf93f0SYJwu2023             Self::UnrecognisedHeaderType => write!(f, "Found device with unrecognised header type"),
26078bf93f0SYJwu2023             Self::PciDeviceStructureTransformError => {
26178bf93f0SYJwu2023                 write!(f, "Found None When transform Pci device structure")
26278bf93f0SYJwu2023             }
263*cc36cf4aSYJwu2023             Self::PciIrqError(err) => write!(f, "Error occurred while setting irq :{:?}.", err),
26478bf93f0SYJwu2023         }
26578bf93f0SYJwu2023     }
26678bf93f0SYJwu2023 }
26778bf93f0SYJwu2023 
26878bf93f0SYJwu2023 /// trait类型Pci_Device_Structure表示pci设备,动态绑定三种具体设备类型:Pci_Device_Structure_General_Device、Pci_Device_Structure_Pci_to_Pci_Bridge、Pci_Device_Structure_Pci_to_Cardbus_Bridge
26978bf93f0SYJwu2023 pub trait PciDeviceStructure: Send + Sync {
27078bf93f0SYJwu2023     /// @brief 获取设备类型
27178bf93f0SYJwu2023     /// @return HeaderType 设备类型
27278bf93f0SYJwu2023     fn header_type(&self) -> HeaderType;
27378bf93f0SYJwu2023     /// @brief 当其为standard设备时返回&Pci_Device_Structure_General_Device,其余情况返回None
274*cc36cf4aSYJwu2023     #[inline(always)]
27578bf93f0SYJwu2023     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
27678bf93f0SYJwu2023         None
27778bf93f0SYJwu2023     }
27878bf93f0SYJwu2023     /// @brief 当其为pci to pci bridge设备时返回&Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
279*cc36cf4aSYJwu2023     #[inline(always)]
28078bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
28178bf93f0SYJwu2023         None
28278bf93f0SYJwu2023     }
28378bf93f0SYJwu2023     /// @brief 当其为pci to cardbus bridge设备时返回&Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
284*cc36cf4aSYJwu2023     #[inline(always)]
28578bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
28678bf93f0SYJwu2023         None
28778bf93f0SYJwu2023     }
28878bf93f0SYJwu2023     /// @brief 获取Pci设备共有的common_header
28978bf93f0SYJwu2023     /// @return 返回其不可变引用
29078bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader;
29178bf93f0SYJwu2023     /// @brief 当其为standard设备时返回&mut Pci_Device_Structure_General_Device,其余情况返回None
292*cc36cf4aSYJwu2023     #[inline(always)]
29378bf93f0SYJwu2023     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
29478bf93f0SYJwu2023         None
29578bf93f0SYJwu2023     }
29678bf93f0SYJwu2023     /// @brief 当其为pci to pci bridge设备时返回&mut Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
297*cc36cf4aSYJwu2023     #[inline(always)]
29878bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
29978bf93f0SYJwu2023         None
30078bf93f0SYJwu2023     }
30178bf93f0SYJwu2023     /// @brief 当其为pci to cardbus bridge设备时返回&mut Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
302*cc36cf4aSYJwu2023     #[inline(always)]
30378bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device_mut(
30478bf93f0SYJwu2023         &mut self,
30578bf93f0SYJwu2023     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
30678bf93f0SYJwu2023         None
30778bf93f0SYJwu2023     }
30878bf93f0SYJwu2023     /// @brief 返回迭代器,遍历capabilities
30978bf93f0SYJwu2023     fn capabilities(&self) -> Option<CapabilityIterator> {
31078bf93f0SYJwu2023         None
31178bf93f0SYJwu2023     }
31278bf93f0SYJwu2023     /// @brief 获取Status、Command寄存器的值
31378bf93f0SYJwu2023     fn status_command(&self) -> (Status, Command) {
31478bf93f0SYJwu2023         let common_header = self.common_header();
31578bf93f0SYJwu2023         let status = Status::from_bits_truncate(common_header.status);
31678bf93f0SYJwu2023         let command = Command::from_bits_truncate(common_header.command);
31778bf93f0SYJwu2023         (status, command)
31878bf93f0SYJwu2023     }
31978bf93f0SYJwu2023     /// @brief 设置Command寄存器的值
32078bf93f0SYJwu2023     fn set_command(&mut self, command: Command) {
32178bf93f0SYJwu2023         let common_header = self.common_header_mut();
32278bf93f0SYJwu2023         let command = command.bits();
32378bf93f0SYJwu2023         common_header.command = command;
32478bf93f0SYJwu2023         PciArch::write_config(
32578bf93f0SYJwu2023             &common_header.bus_device_function,
32678bf93f0SYJwu2023             STATUS_COMMAND_OFFSET,
32778bf93f0SYJwu2023             command as u32,
32878bf93f0SYJwu2023         );
32978bf93f0SYJwu2023     }
33078bf93f0SYJwu2023     /// @brief 获取Pci设备共有的common_header
33178bf93f0SYJwu2023     /// @return 返回其可变引用
33278bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader;
333*cc36cf4aSYJwu2023 
33478bf93f0SYJwu2023     /// @brief 读取standard设备的bar寄存器,映射后将结果加入结构体的standard_device_bar变量
33578bf93f0SYJwu2023     /// @return 只有standard设备才返回成功或者错误,其余返回None
336*cc36cf4aSYJwu2023     #[inline(always)]
337*cc36cf4aSYJwu2023     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
33878bf93f0SYJwu2023         None
33978bf93f0SYJwu2023     }
340*cc36cf4aSYJwu2023     /// @brief 获取PCI设备的bar寄存器的引用
341*cc36cf4aSYJwu2023     /// @return
342*cc36cf4aSYJwu2023     #[inline(always)]
343*cc36cf4aSYJwu2023     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
34478bf93f0SYJwu2023         None
34578bf93f0SYJwu2023     }
346*cc36cf4aSYJwu2023     /// @brief 通过设置该pci设备的command
34778bf93f0SYJwu2023     fn enable_master(&mut self) {
34878bf93f0SYJwu2023         self.set_command(Command::IO_SPACE | Command::MEMORY_SPACE | Command::BUS_MASTER);
34978bf93f0SYJwu2023     }
350*cc36cf4aSYJwu2023     /// @brief 寻找设备的msix空间的offset
351*cc36cf4aSYJwu2023     fn msix_capability_offset(&self) -> Option<u8> {
352*cc36cf4aSYJwu2023         for capability in self.capabilities()? {
353*cc36cf4aSYJwu2023             if capability.id == PCI_CAP_ID_MSIX {
354*cc36cf4aSYJwu2023                 return Some(capability.offset);
355*cc36cf4aSYJwu2023             }
356*cc36cf4aSYJwu2023         }
357*cc36cf4aSYJwu2023         None
358*cc36cf4aSYJwu2023     }
359*cc36cf4aSYJwu2023     /// @brief 寻找设备的msi空间的offset
360*cc36cf4aSYJwu2023     fn msi_capability_offset(&self) -> Option<u8> {
361*cc36cf4aSYJwu2023         for capability in self.capabilities()? {
362*cc36cf4aSYJwu2023             if capability.id == PCI_CAP_ID_MSI {
363*cc36cf4aSYJwu2023                 return Some(capability.offset);
364*cc36cf4aSYJwu2023             }
365*cc36cf4aSYJwu2023         }
366*cc36cf4aSYJwu2023         None
367*cc36cf4aSYJwu2023     }
368*cc36cf4aSYJwu2023     /// @brief 返回结构体中的irq_type的可变引用
369*cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType>;
370*cc36cf4aSYJwu2023     /// @brief 返回结构体中的irq_vector的可变引用
371*cc36cf4aSYJwu2023     fn irq_vector_mut(&mut self) -> Option<&mut Vec<u16>>;
37278bf93f0SYJwu2023 }
37378bf93f0SYJwu2023 
37478bf93f0SYJwu2023 /// Pci_Device_Structure_Header PCI设备结构体共有的头部
37578bf93f0SYJwu2023 #[derive(Clone, Debug)]
37678bf93f0SYJwu2023 pub struct PciDeviceStructureHeader {
37778bf93f0SYJwu2023     // ==== busdevicefunction变量表示该结构体所处的位置
37878bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
37978bf93f0SYJwu2023     pub vendor_id: u16, // 供应商ID 0xffff是一个无效值,在读取访问不存在的设备的配置空间寄存器时返回
38078bf93f0SYJwu2023     pub device_id: u16, // 设备ID,标志特定设备
38178bf93f0SYJwu2023     pub command: u16, // 提供对设备生成和响应pci周期的能力的控制 向该寄存器写入0时,设备与pci总线断开除配置空间访问以外的所有连接
38278bf93f0SYJwu2023     pub status: u16,  // 用于记录pci总线相关时间的状态信息寄存器
38378bf93f0SYJwu2023     pub revision_id: u8, // 修订ID,指定特定设备的修订标志符
38478bf93f0SYJwu2023     pub prog_if: u8, // 编程接口字节,一个只读寄存器,指定设备具有的寄存器级别的编程接口(如果有的话)
38578bf93f0SYJwu2023     pub subclass: u8, // 子类。指定设备执行的特定功能的只读寄存器
38678bf93f0SYJwu2023     pub class_code: u8, // 类代码,一个只读寄存器,指定设备执行的功能类型
38778bf93f0SYJwu2023     pub cache_line_size: u8, // 缓存线大小:以 32 位为单位指定系统缓存线大小。设备可以限制它可以支持的缓存线大小的数量,如果不支持的值写入该字段,设备将表现得好像写入了 0 值
38878bf93f0SYJwu2023     pub latency_timer: u8,   // 延迟计时器:以 PCI 总线时钟为单位指定延迟计时器。
38978bf93f0SYJwu2023     pub header_type: u8, // 标头类型 a value of 0x0 specifies a general device, a value of 0x1 specifies a PCI-to-PCI bridge, and a value of 0x2 specifies a CardBus bridge. If bit 7 of this register is set, the device has multiple functions; otherwise, it is a single function device.
39078bf93f0SYJwu2023     pub bist: u8, // Represents that status and allows control of a devices BIST (built-in self test).
39178bf93f0SYJwu2023                   // Here is the layout of the BIST register:
39278bf93f0SYJwu2023                   // |     bit7     |    bit6    | Bits 5-4 |     Bits 3-0    |
39378bf93f0SYJwu2023                   // | BIST Capable | Start BIST | Reserved | Completion Code |
39478bf93f0SYJwu2023                   // for more details, please visit https://wiki.osdev.org/PCI
39578bf93f0SYJwu2023 }
39678bf93f0SYJwu2023 
39778bf93f0SYJwu2023 /// Pci_Device_Structure_General_Device PCI标准设备结构体
39878bf93f0SYJwu2023 #[derive(Clone, Debug)]
39978bf93f0SYJwu2023 pub struct PciDeviceStructureGeneralDevice {
40078bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
401*cc36cf4aSYJwu2023     // 中断结构体,包括legacy,msi,msix三种情况
402*cc36cf4aSYJwu2023     pub irq_type: IrqType,
403*cc36cf4aSYJwu2023     // 使用的中断号的vec集合
404*cc36cf4aSYJwu2023     pub irq_vector: Vec<u16>,
40578bf93f0SYJwu2023     pub standard_device_bar: PciStandardDeviceBar,
40678bf93f0SYJwu2023     pub cardbus_cis_pointer: u32, // 指向卡信息结构,供在 CardBus 和 PCI 之间共享芯片的设备使用。
40778bf93f0SYJwu2023     pub subsystem_vendor_id: u16,
40878bf93f0SYJwu2023     pub subsystem_id: u16,
40978bf93f0SYJwu2023     pub expansion_rom_base_address: u32,
41078bf93f0SYJwu2023     pub capabilities_pointer: u8,
41178bf93f0SYJwu2023     pub reserved0: u8,
41278bf93f0SYJwu2023     pub reserved1: u16,
41378bf93f0SYJwu2023     pub reserved2: u32,
41478bf93f0SYJwu2023     pub interrupt_line: u8, // 指定设备的中断引脚连接到系统中断控制器的哪个输入,并由任何使用中断引脚的设备实现。对于 x86 架构,此寄存器对应于 PIC IRQ 编号 0-15(而不是 I/O APIC IRQ 编号),并且值0xFF定义为无连接。
41578bf93f0SYJwu2023     pub interrupt_pin: u8, // 指定设备使用的中断引脚。其中值为0x1INTA#、0x2INTB#、0x3INTC#、0x4INTD#,0x0表示设备不使用中断引脚。
41678bf93f0SYJwu2023     pub min_grant: u8, // 一个只读寄存器,用于指定设备所需的突发周期长度(以 1/4 微秒为单位)(假设时钟速率为 33 MHz)
41778bf93f0SYJwu2023     pub max_latency: u8, // 一个只读寄存器,指定设备需要多长时间访问一次 PCI 总线(以 1/4 微秒为单位)。
41878bf93f0SYJwu2023 }
41978bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructureGeneralDevice {
420*cc36cf4aSYJwu2023     #[inline(always)]
42178bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
42278bf93f0SYJwu2023         HeaderType::Standard
42378bf93f0SYJwu2023     }
424*cc36cf4aSYJwu2023     #[inline(always)]
42578bf93f0SYJwu2023     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
42678bf93f0SYJwu2023         Some(self)
42778bf93f0SYJwu2023     }
428*cc36cf4aSYJwu2023     #[inline(always)]
42978bf93f0SYJwu2023     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
43078bf93f0SYJwu2023         Some(self)
43178bf93f0SYJwu2023     }
432*cc36cf4aSYJwu2023     #[inline(always)]
43378bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
43478bf93f0SYJwu2023         &self.common_header
43578bf93f0SYJwu2023     }
436*cc36cf4aSYJwu2023     #[inline(always)]
43778bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
43878bf93f0SYJwu2023         &mut self.common_header
43978bf93f0SYJwu2023     }
44078bf93f0SYJwu2023     fn capabilities(&self) -> Option<CapabilityIterator> {
44178bf93f0SYJwu2023         Some(CapabilityIterator {
44278bf93f0SYJwu2023             bus_device_function: self.common_header.bus_device_function,
44378bf93f0SYJwu2023             next_capability_offset: Some(self.capabilities_pointer),
44478bf93f0SYJwu2023         })
44578bf93f0SYJwu2023     }
446*cc36cf4aSYJwu2023     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
44778bf93f0SYJwu2023         let common_header = &self.common_header;
44878bf93f0SYJwu2023         match pci_bar_init(common_header.bus_device_function) {
44978bf93f0SYJwu2023             Ok(bar) => {
45078bf93f0SYJwu2023                 self.standard_device_bar = bar;
45178bf93f0SYJwu2023                 Some(Ok(0))
45278bf93f0SYJwu2023             }
45378bf93f0SYJwu2023             Err(e) => Some(Err(e)),
45478bf93f0SYJwu2023         }
45578bf93f0SYJwu2023     }
456*cc36cf4aSYJwu2023     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
457*cc36cf4aSYJwu2023         Some(&self.standard_device_bar)
45878bf93f0SYJwu2023     }
459*cc36cf4aSYJwu2023     #[inline(always)]
460*cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
461*cc36cf4aSYJwu2023         Some(&mut self.irq_type)
462*cc36cf4aSYJwu2023     }
463*cc36cf4aSYJwu2023     #[inline(always)]
464*cc36cf4aSYJwu2023     fn irq_vector_mut(&mut self) -> Option<&mut Vec<u16>> {
465*cc36cf4aSYJwu2023         Some(&mut self.irq_vector)
466*cc36cf4aSYJwu2023     }
467*cc36cf4aSYJwu2023 }
468*cc36cf4aSYJwu2023 
46978bf93f0SYJwu2023 /// Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci桥设备结构体
47078bf93f0SYJwu2023 #[derive(Clone, Debug)]
47178bf93f0SYJwu2023 pub struct PciDeviceStructurePciToPciBridge {
47278bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
473*cc36cf4aSYJwu2023     // 中断结构体,包括legacy,msi,msix三种情况
474*cc36cf4aSYJwu2023     pub irq_type: IrqType,
475*cc36cf4aSYJwu2023     // 使用的中断号的vec集合
476*cc36cf4aSYJwu2023     pub irq_vector: Vec<u16>,
47778bf93f0SYJwu2023     pub bar0: u32,
47878bf93f0SYJwu2023     pub bar1: u32,
47978bf93f0SYJwu2023     pub primary_bus_number: u8,
48078bf93f0SYJwu2023     pub secondary_bus_number: u8,
48178bf93f0SYJwu2023     pub subordinate_bus_number: u8,
48278bf93f0SYJwu2023     pub secondary_latency_timer: u8,
48378bf93f0SYJwu2023     pub io_base: u8,
48478bf93f0SYJwu2023     pub io_limit: u8,
48578bf93f0SYJwu2023     pub secondary_status: u16,
48678bf93f0SYJwu2023     pub memory_base: u16,
48778bf93f0SYJwu2023     pub memory_limit: u16,
48878bf93f0SYJwu2023     pub prefetchable_memory_base: u16,
48978bf93f0SYJwu2023     pub prefetchable_memory_limit: u16,
49078bf93f0SYJwu2023     pub prefetchable_base_upper_32_bits: u32,
49178bf93f0SYJwu2023     pub prefetchable_limit_upper_32_bits: u32,
49278bf93f0SYJwu2023     pub io_base_upper_16_bits: u16,
49378bf93f0SYJwu2023     pub io_limit_upper_16_bits: u16,
49478bf93f0SYJwu2023     pub capability_pointer: u8,
49578bf93f0SYJwu2023     pub reserved0: u8,
49678bf93f0SYJwu2023     pub reserved1: u16,
49778bf93f0SYJwu2023     pub expansion_rom_base_address: u32,
49878bf93f0SYJwu2023     pub interrupt_line: u8,
49978bf93f0SYJwu2023     pub interrupt_pin: u8,
50078bf93f0SYJwu2023     pub bridge_control: u16,
50178bf93f0SYJwu2023 }
50278bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructurePciToPciBridge {
503*cc36cf4aSYJwu2023     #[inline(always)]
50478bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
50578bf93f0SYJwu2023         HeaderType::PciPciBridge
50678bf93f0SYJwu2023     }
507*cc36cf4aSYJwu2023     #[inline(always)]
50878bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
50978bf93f0SYJwu2023         Some(self)
51078bf93f0SYJwu2023     }
511*cc36cf4aSYJwu2023     #[inline(always)]
51278bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
51378bf93f0SYJwu2023         Some(self)
51478bf93f0SYJwu2023     }
515*cc36cf4aSYJwu2023     #[inline(always)]
51678bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
51778bf93f0SYJwu2023         &self.common_header
51878bf93f0SYJwu2023     }
519*cc36cf4aSYJwu2023     #[inline(always)]
52078bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
52178bf93f0SYJwu2023         &mut self.common_header
52278bf93f0SYJwu2023     }
523*cc36cf4aSYJwu2023     #[inline(always)]
524*cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
525*cc36cf4aSYJwu2023         Some(&mut self.irq_type)
526*cc36cf4aSYJwu2023     }
527*cc36cf4aSYJwu2023     #[inline(always)]
528*cc36cf4aSYJwu2023     fn irq_vector_mut(&mut self) -> Option<&mut Vec<u16>> {
529*cc36cf4aSYJwu2023         Some(&mut self.irq_vector)
530*cc36cf4aSYJwu2023     }
53178bf93f0SYJwu2023 }
53278bf93f0SYJwu2023 /// Pci_Device_Structure_Pci_to_Cardbus_Bridge Pci_to_Cardbus桥设备结构体
53378bf93f0SYJwu2023 #[derive(Clone, Debug)]
53478bf93f0SYJwu2023 pub struct PciDeviceStructurePciToCardbusBridge {
53578bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
53678bf93f0SYJwu2023     pub cardbus_socket_ex_ca_base_address: u32,
53778bf93f0SYJwu2023     pub offset_of_capabilities_list: u8,
53878bf93f0SYJwu2023     pub reserved: u8,
53978bf93f0SYJwu2023     pub secondary_status: u16,
54078bf93f0SYJwu2023     pub pci_bus_number: u8,
54178bf93f0SYJwu2023     pub card_bus_bus_number: u8,
54278bf93f0SYJwu2023     pub subordinate_bus_number: u8,
54378bf93f0SYJwu2023     pub card_bus_latency_timer: u8,
54478bf93f0SYJwu2023     pub memory_base_address0: u32,
54578bf93f0SYJwu2023     pub memory_limit0: u32,
54678bf93f0SYJwu2023     pub memory_base_address1: u32,
54778bf93f0SYJwu2023     pub memory_limit1: u32,
54878bf93f0SYJwu2023     pub io_base_address0: u32,
54978bf93f0SYJwu2023     pub io_limit0: u32,
55078bf93f0SYJwu2023     pub io_base_address1: u32,
55178bf93f0SYJwu2023     pub io_limit1: u32,
55278bf93f0SYJwu2023     pub interrupt_line: u8,
55378bf93f0SYJwu2023     pub interrupt_pin: u8,
55478bf93f0SYJwu2023     pub bridge_control: u16,
55578bf93f0SYJwu2023     pub subsystem_device_id: u16,
55678bf93f0SYJwu2023     pub subsystem_vendor_id: u16,
55778bf93f0SYJwu2023     pub pc_card_legacy_mode_base_address_16_bit: u32,
55878bf93f0SYJwu2023 }
55978bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructurePciToCardbusBridge {
560*cc36cf4aSYJwu2023     #[inline(always)]
56178bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
56278bf93f0SYJwu2023         HeaderType::PciCardbusBridge
56378bf93f0SYJwu2023     }
564*cc36cf4aSYJwu2023     #[inline(always)]
56578bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
56678bf93f0SYJwu2023         Some(&self)
56778bf93f0SYJwu2023     }
568*cc36cf4aSYJwu2023     #[inline(always)]
56978bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device_mut(
57078bf93f0SYJwu2023         &mut self,
57178bf93f0SYJwu2023     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
57278bf93f0SYJwu2023         Some(self)
57378bf93f0SYJwu2023     }
574*cc36cf4aSYJwu2023     #[inline(always)]
57578bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
57678bf93f0SYJwu2023         &self.common_header
57778bf93f0SYJwu2023     }
578*cc36cf4aSYJwu2023     #[inline(always)]
57978bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
58078bf93f0SYJwu2023         &mut self.common_header
58178bf93f0SYJwu2023     }
582*cc36cf4aSYJwu2023     #[inline(always)]
583*cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
584*cc36cf4aSYJwu2023         None
585*cc36cf4aSYJwu2023     }
586*cc36cf4aSYJwu2023     #[inline(always)]
587*cc36cf4aSYJwu2023     fn irq_vector_mut(&mut self) -> Option<&mut Vec<u16>> {
588*cc36cf4aSYJwu2023         None
589*cc36cf4aSYJwu2023     }
59078bf93f0SYJwu2023 }
59178bf93f0SYJwu2023 
59278bf93f0SYJwu2023 /// 代表一个PCI segement greoup.
59378bf93f0SYJwu2023 #[derive(Copy, Clone, Debug, PartialEq)]
59478bf93f0SYJwu2023 pub struct PciRoot {
59578bf93f0SYJwu2023     pub physical_address_base: u64,                //物理地址,acpi获取
59678bf93f0SYJwu2023     pub mmio_base: Option<*mut u32>,               //映射后的虚拟地址,为方便访问数据这里转化成指针
59778bf93f0SYJwu2023     pub segement_group_number: SegmentGroupNumber, //segement greoup的id
59878bf93f0SYJwu2023     pub bus_begin: u8,                             //该分组中的最小bus
59978bf93f0SYJwu2023     pub bus_end: u8,                               //该分组中的最大bus
60078bf93f0SYJwu2023 }
60178bf93f0SYJwu2023 ///线程间共享需要,该结构体只需要在初始化时写入数据,无需读写锁保证线程安全
60278bf93f0SYJwu2023 unsafe impl Send for PciRoot {}
60378bf93f0SYJwu2023 unsafe impl Sync for PciRoot {}
60478bf93f0SYJwu2023 ///实现PciRoot的Display trait,自定义输出
60578bf93f0SYJwu2023 impl Display for PciRoot {
60678bf93f0SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
60778bf93f0SYJwu2023         write!(
60878bf93f0SYJwu2023                 f,
6095c1e552cSYJwu2023                 "PCI Root with segement:{}, bus begin at {}, bus end at {}, physical address at {:#x},mapped at {:#x}",
61078bf93f0SYJwu2023                 self.segement_group_number, self.bus_begin, self.bus_end, self.physical_address_base, self.mmio_base.unwrap() as usize
61178bf93f0SYJwu2023             )
61278bf93f0SYJwu2023     }
61378bf93f0SYJwu2023 }
61478bf93f0SYJwu2023 
61578bf93f0SYJwu2023 impl PciRoot {
61678bf93f0SYJwu2023     /// @brief 初始化结构体,获取ecam root所在物理地址后map到虚拟地址,再将该虚拟地址加入mmio_base变量
61778bf93f0SYJwu2023     /// @return 成功返回结果,错误返回错误类型
61878bf93f0SYJwu2023     pub fn new(segment_group_number: SegmentGroupNumber) -> Result<Self, PciError> {
61978bf93f0SYJwu2023         let mut pci_root = PciArch::ecam_root(segment_group_number)?;
62078bf93f0SYJwu2023         pci_root.map()?;
62178bf93f0SYJwu2023         Ok(pci_root)
62278bf93f0SYJwu2023     }
62378bf93f0SYJwu2023     /// @brief  完成物理地址到虚拟地址的映射,并将虚拟地址加入mmio_base变量
62478bf93f0SYJwu2023     /// @return 返回错误或Ok(0)
62578bf93f0SYJwu2023     fn map(&mut self) -> Result<u8, PciError> {
6265c1e552cSYJwu2023         //kdebug!("bus_begin={},bus_end={}", self.bus_begin,self.bus_end);
6275c1e552cSYJwu2023         let bus_number = (self.bus_end - self.bus_begin) as u32 + 1;
6285c1e552cSYJwu2023         let bus_number_double = (bus_number - 1) / 2 + 1; //一个bus占据1MB空间,计算全部bus占据空间相对于2MB空间的个数
62978bf93f0SYJwu2023         let mut virtaddress: u64 = 0;
63078bf93f0SYJwu2023         let vaddr_ptr = &mut virtaddress as *mut u64;
63178bf93f0SYJwu2023         let mut virtsize: u64 = 0;
63278bf93f0SYJwu2023         let virtsize_ptr = &mut virtsize as *mut u64;
6335c1e552cSYJwu2023         let size = bus_number_double * PAGE_2M_SIZE;
63478bf93f0SYJwu2023         unsafe {
63578bf93f0SYJwu2023             let initial_mm_ptr = &mut initial_mm as *mut mm_struct;
63678bf93f0SYJwu2023             if let Err(_) =
63778bf93f0SYJwu2023                 MMIO_POOL.create_mmio(size, (VM_IO | VM_DONTCOPY) as u64, vaddr_ptr, virtsize_ptr)
63878bf93f0SYJwu2023             {
63978bf93f0SYJwu2023                 kerror!("Create mmio failed when initing ecam");
64078bf93f0SYJwu2023                 return Err(PciError::CreateMmioError);
64178bf93f0SYJwu2023             };
64278bf93f0SYJwu2023             //kdebug!("virtaddress={:#x},virtsize={:#x}",virtaddress,virtsize);
64378bf93f0SYJwu2023             mm_map(
64478bf93f0SYJwu2023                 initial_mm_ptr,
64578bf93f0SYJwu2023                 virtaddress,
64678bf93f0SYJwu2023                 size as u64,
64778bf93f0SYJwu2023                 self.physical_address_base,
64878bf93f0SYJwu2023             );
64978bf93f0SYJwu2023         }
65078bf93f0SYJwu2023         self.mmio_base = Some(virtaddress as *mut u32);
65178bf93f0SYJwu2023         Ok(0)
65278bf93f0SYJwu2023     }
65378bf93f0SYJwu2023     /// @brief 获得要操作的寄存器相对于mmio_offset的偏移量
65478bf93f0SYJwu2023     /// @param bus_device_function 在同一个group中pci设备的唯一标识符
65578bf93f0SYJwu2023     /// @param register_offset 寄存器在设备中的offset
65678bf93f0SYJwu2023     /// @return u32 要操作的寄存器相对于mmio_offset的偏移量
65778bf93f0SYJwu2023     fn cam_offset(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
65878bf93f0SYJwu2023         assert!(bus_device_function.valid());
65978bf93f0SYJwu2023         let bdf = ((bus_device_function.bus - self.bus_begin) as u32) << 8
66078bf93f0SYJwu2023             | (bus_device_function.device as u32) << 3
66178bf93f0SYJwu2023             | bus_device_function.function as u32;
66278bf93f0SYJwu2023         let address = bdf << 12 | register_offset as u32;
66378bf93f0SYJwu2023         // Ensure that address is word-aligned.
66478bf93f0SYJwu2023         assert!(address & 0x3 == 0);
66578bf93f0SYJwu2023         address
66678bf93f0SYJwu2023     }
66778bf93f0SYJwu2023     /// @brief 通过bus_device_function和offset读取相应位置寄存器的值(32位)
66878bf93f0SYJwu2023     /// @param bus_device_function 在同一个group中pci设备的唯一标识符
66978bf93f0SYJwu2023     /// @param register_offset 寄存器在设备中的offset
67078bf93f0SYJwu2023     /// @return u32 寄存器读值结果
67113776c11Slogin     pub fn read_config(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
67278bf93f0SYJwu2023         let address = self.cam_offset(bus_device_function, register_offset);
67378bf93f0SYJwu2023         unsafe {
67478bf93f0SYJwu2023             // Right shift to convert from byte offset to word offset.
67578bf93f0SYJwu2023             (self.mmio_base.unwrap().add((address >> 2) as usize)).read_volatile()
67678bf93f0SYJwu2023         }
67778bf93f0SYJwu2023     }
67878bf93f0SYJwu2023 
67978bf93f0SYJwu2023     /// @brief 通过bus_device_function和offset写入相应位置寄存器值(32位)
68078bf93f0SYJwu2023     /// @param bus_device_function 在同一个group中pci设备的唯一标识符
68178bf93f0SYJwu2023     /// @param register_offset 寄存器在设备中的offset
68278bf93f0SYJwu2023     /// @param data 要写入的值
68378bf93f0SYJwu2023     pub fn write_config(
68478bf93f0SYJwu2023         &mut self,
68578bf93f0SYJwu2023         bus_device_function: BusDeviceFunction,
68678bf93f0SYJwu2023         register_offset: u16,
68778bf93f0SYJwu2023         data: u32,
68878bf93f0SYJwu2023     ) {
68978bf93f0SYJwu2023         let address = self.cam_offset(bus_device_function, register_offset);
69078bf93f0SYJwu2023         // Safe because both the `mmio_base` and the address offset are properly aligned, and the
69178bf93f0SYJwu2023         // resulting pointer is within the MMIO range of the CAM.
69278bf93f0SYJwu2023         unsafe {
69378bf93f0SYJwu2023             // Right shift to convert from byte offset to word offset.
69478bf93f0SYJwu2023             (self.mmio_base.unwrap().add((address >> 2) as usize)).write_volatile(data)
69578bf93f0SYJwu2023         }
69678bf93f0SYJwu2023     }
69778bf93f0SYJwu2023     /// @brief 返回迭代器,遍历pcie设备的external_capabilities
69878bf93f0SYJwu2023     pub fn external_capabilities(
69978bf93f0SYJwu2023         &self,
70078bf93f0SYJwu2023         bus_device_function: BusDeviceFunction,
70178bf93f0SYJwu2023     ) -> ExternalCapabilityIterator {
70278bf93f0SYJwu2023         ExternalCapabilityIterator {
70378bf93f0SYJwu2023             root: self,
70478bf93f0SYJwu2023             bus_device_function,
70578bf93f0SYJwu2023             next_capability_offset: Some(0x100),
70678bf93f0SYJwu2023         }
70778bf93f0SYJwu2023     }
70878bf93f0SYJwu2023 }
70926d84a31SYJwu2023 /// Gets the capabilities 'pointer' for the device function, if any.
71026d84a31SYJwu2023 /// @brief 获取第一个capability 的offset
71178bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
71226d84a31SYJwu2023 /// @return Option<u8> offset
71378bf93f0SYJwu2023 pub fn capabilities_offset(bus_device_function: BusDeviceFunction) -> Option<u8> {
71478bf93f0SYJwu2023     let result = PciArch::read_config(&bus_device_function, STATUS_COMMAND_OFFSET);
71578bf93f0SYJwu2023     let status: Status = Status::from_bits_truncate((result >> 16) as u16);
71626d84a31SYJwu2023     if status.contains(Status::CAPABILITIES_LIST) {
71778bf93f0SYJwu2023         let cap_pointer = PciArch::read_config(&bus_device_function, 0x34) as u8 & 0xFC;
71826d84a31SYJwu2023         Some(cap_pointer)
71926d84a31SYJwu2023     } else {
72026d84a31SYJwu2023         None
72126d84a31SYJwu2023     }
72226d84a31SYJwu2023 }
72378bf93f0SYJwu2023 
72478bf93f0SYJwu2023 /// @brief 读取pci设备头部
72578bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
72678bf93f0SYJwu2023 /// @param add_to_list 是否添加到链表
72778bf93f0SYJwu2023 /// @return 返回的header(trait 类型)
72878bf93f0SYJwu2023 fn pci_read_header(
72978bf93f0SYJwu2023     bus_device_function: BusDeviceFunction,
73078bf93f0SYJwu2023     add_to_list: bool,
73178bf93f0SYJwu2023 ) -> Result<Box<dyn PciDeviceStructure>, PciError> {
73278bf93f0SYJwu2023     // 先读取公共header
73378bf93f0SYJwu2023     let result = PciArch::read_config(&bus_device_function, 0x00);
73478bf93f0SYJwu2023     let vendor_id = result as u16;
73578bf93f0SYJwu2023     let device_id = (result >> 16) as u16;
73678bf93f0SYJwu2023 
73778bf93f0SYJwu2023     let result = PciArch::read_config(&bus_device_function, 0x04);
73878bf93f0SYJwu2023     let command = result as u16;
73978bf93f0SYJwu2023     let status = (result >> 16) as u16;
74078bf93f0SYJwu2023 
74178bf93f0SYJwu2023     let result = PciArch::read_config(&bus_device_function, 0x08);
74278bf93f0SYJwu2023     let revision_id = result as u8;
74378bf93f0SYJwu2023     let prog_if = (result >> 8) as u8;
74478bf93f0SYJwu2023     let subclass = (result >> 16) as u8;
74578bf93f0SYJwu2023     let class_code = (result >> 24) as u8;
74678bf93f0SYJwu2023 
74778bf93f0SYJwu2023     let result = PciArch::read_config(&bus_device_function, 0x0c);
74878bf93f0SYJwu2023     let cache_line_size = result as u8;
74978bf93f0SYJwu2023     let latency_timer = (result >> 8) as u8;
75078bf93f0SYJwu2023     let header_type = (result >> 16) as u8;
75178bf93f0SYJwu2023     let bist = (result >> 24) as u8;
75278bf93f0SYJwu2023     if vendor_id == 0xffff {
75378bf93f0SYJwu2023         return Err(PciError::GetWrongHeader);
75478bf93f0SYJwu2023     }
75578bf93f0SYJwu2023     let header = PciDeviceStructureHeader {
75678bf93f0SYJwu2023         bus_device_function,
75778bf93f0SYJwu2023         vendor_id,
75878bf93f0SYJwu2023         device_id,
75978bf93f0SYJwu2023         command,
76078bf93f0SYJwu2023         status,
76178bf93f0SYJwu2023         revision_id,
76278bf93f0SYJwu2023         prog_if,
76378bf93f0SYJwu2023         subclass,
76478bf93f0SYJwu2023         class_code,
76578bf93f0SYJwu2023         cache_line_size,
76678bf93f0SYJwu2023         latency_timer,
76778bf93f0SYJwu2023         header_type,
76878bf93f0SYJwu2023         bist,
76978bf93f0SYJwu2023     };
77078bf93f0SYJwu2023     match HeaderType::from(header_type & 0x7f) {
77178bf93f0SYJwu2023         HeaderType::Standard => {
77278bf93f0SYJwu2023             let general_device = pci_read_general_device_header(header, &bus_device_function);
77378bf93f0SYJwu2023             let box_general_device = Box::new(general_device);
77478bf93f0SYJwu2023             let box_general_device_clone = box_general_device.clone();
77578bf93f0SYJwu2023             if add_to_list {
77678bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_general_device);
77778bf93f0SYJwu2023             }
77878bf93f0SYJwu2023             Ok(box_general_device_clone)
77978bf93f0SYJwu2023         }
78078bf93f0SYJwu2023         HeaderType::PciPciBridge => {
78178bf93f0SYJwu2023             let pci_to_pci_bridge = pci_read_pci_to_pci_bridge_header(header, &bus_device_function);
78278bf93f0SYJwu2023             let box_pci_to_pci_bridge = Box::new(pci_to_pci_bridge);
78378bf93f0SYJwu2023             let box_pci_to_pci_bridge_clone = box_pci_to_pci_bridge.clone();
78478bf93f0SYJwu2023             if add_to_list {
78578bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_pci_to_pci_bridge);
78678bf93f0SYJwu2023             }
78778bf93f0SYJwu2023             Ok(box_pci_to_pci_bridge_clone)
78878bf93f0SYJwu2023         }
78978bf93f0SYJwu2023         HeaderType::PciCardbusBridge => {
79078bf93f0SYJwu2023             let pci_cardbus_bridge =
79178bf93f0SYJwu2023                 pci_read_pci_to_cardbus_bridge_header(header, &bus_device_function);
79278bf93f0SYJwu2023             let box_pci_cardbus_bridge = Box::new(pci_cardbus_bridge);
79378bf93f0SYJwu2023             let box_pci_cardbus_bridge_clone = box_pci_cardbus_bridge.clone();
79478bf93f0SYJwu2023             if add_to_list {
79578bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_pci_cardbus_bridge);
79678bf93f0SYJwu2023             }
79778bf93f0SYJwu2023             Ok(box_pci_cardbus_bridge_clone)
79878bf93f0SYJwu2023         }
79978bf93f0SYJwu2023         HeaderType::Unrecognised(_) => Err(PciError::UnrecognisedHeaderType),
80078bf93f0SYJwu2023     }
80178bf93f0SYJwu2023 }
80278bf93f0SYJwu2023 
80378bf93f0SYJwu2023 /// @brief 读取type为0x0的pci设备的header
80478bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
80578bf93f0SYJwu2023 /// @param common_header 共有头部
80678bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
80778bf93f0SYJwu2023 /// @return Pci_Device_Structure_General_Device 标准设备头部
80878bf93f0SYJwu2023 fn pci_read_general_device_header(
80978bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
81078bf93f0SYJwu2023     bus_device_function: &BusDeviceFunction,
81178bf93f0SYJwu2023 ) -> PciDeviceStructureGeneralDevice {
81278bf93f0SYJwu2023     let standard_device_bar = PciStandardDeviceBar::default();
81378bf93f0SYJwu2023     let cardbus_cis_pointer = PciArch::read_config(bus_device_function, 0x28);
81478bf93f0SYJwu2023 
81578bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x2c);
81678bf93f0SYJwu2023     let subsystem_vendor_id = result as u16;
81778bf93f0SYJwu2023     let subsystem_id = (result >> 16) as u16;
81878bf93f0SYJwu2023 
81978bf93f0SYJwu2023     let expansion_rom_base_address = PciArch::read_config(bus_device_function, 0x30);
82078bf93f0SYJwu2023 
82178bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x34);
82278bf93f0SYJwu2023     let capabilities_pointer = result as u8;
82378bf93f0SYJwu2023     let reserved0 = (result >> 8) as u8;
82478bf93f0SYJwu2023     let reserved1 = (result >> 16) as u16;
82578bf93f0SYJwu2023 
82678bf93f0SYJwu2023     let reserved2 = PciArch::read_config(bus_device_function, 0x38);
82778bf93f0SYJwu2023 
82878bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x3c);
82978bf93f0SYJwu2023     let interrupt_line = result as u8;
83078bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
83178bf93f0SYJwu2023     let min_grant = (result >> 16) as u8;
83278bf93f0SYJwu2023     let max_latency = (result >> 24) as u8;
83378bf93f0SYJwu2023     PciDeviceStructureGeneralDevice {
83478bf93f0SYJwu2023         common_header,
835*cc36cf4aSYJwu2023         irq_type: IrqType::Unused,
836*cc36cf4aSYJwu2023         irq_vector: Vec::new(),
83778bf93f0SYJwu2023         standard_device_bar,
83878bf93f0SYJwu2023         cardbus_cis_pointer,
83978bf93f0SYJwu2023         subsystem_vendor_id,
84078bf93f0SYJwu2023         subsystem_id,
84178bf93f0SYJwu2023         expansion_rom_base_address,
84278bf93f0SYJwu2023         capabilities_pointer,
84378bf93f0SYJwu2023         reserved0,
84478bf93f0SYJwu2023         reserved1,
84578bf93f0SYJwu2023         reserved2,
84678bf93f0SYJwu2023         interrupt_line,
84778bf93f0SYJwu2023         interrupt_pin,
84878bf93f0SYJwu2023         min_grant,
84978bf93f0SYJwu2023         max_latency,
85078bf93f0SYJwu2023     }
85178bf93f0SYJwu2023 }
85278bf93f0SYJwu2023 
85378bf93f0SYJwu2023 /// @brief 读取type为0x1的pci设备的header
85478bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
85578bf93f0SYJwu2023 /// @param common_header 共有头部
85678bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
85778bf93f0SYJwu2023 /// @return Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci 桥设备头部
85878bf93f0SYJwu2023 fn pci_read_pci_to_pci_bridge_header(
85978bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
86078bf93f0SYJwu2023     bus_device_function: &BusDeviceFunction,
86178bf93f0SYJwu2023 ) -> PciDeviceStructurePciToPciBridge {
86278bf93f0SYJwu2023     let bar0 = PciArch::read_config(bus_device_function, 0x10);
86378bf93f0SYJwu2023     let bar1 = PciArch::read_config(bus_device_function, 0x14);
86478bf93f0SYJwu2023 
86578bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x18);
86678bf93f0SYJwu2023 
86778bf93f0SYJwu2023     let primary_bus_number = result as u8;
86878bf93f0SYJwu2023     let secondary_bus_number = (result >> 8) as u8;
86978bf93f0SYJwu2023     let subordinate_bus_number = (result >> 16) as u8;
87078bf93f0SYJwu2023     let secondary_latency_timer = (result >> 24) as u8;
87178bf93f0SYJwu2023 
87278bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x1c);
87378bf93f0SYJwu2023     let io_base = result as u8;
87478bf93f0SYJwu2023     let io_limit = (result >> 8) as u8;
87578bf93f0SYJwu2023     let secondary_status = (result >> 16) as u16;
87678bf93f0SYJwu2023 
87778bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x20);
87878bf93f0SYJwu2023     let memory_base = result as u16;
87978bf93f0SYJwu2023     let memory_limit = (result >> 16) as u16;
88078bf93f0SYJwu2023 
88178bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x24);
88278bf93f0SYJwu2023     let prefetchable_memory_base = result as u16;
88378bf93f0SYJwu2023     let prefetchable_memory_limit = (result >> 16) as u16;
88478bf93f0SYJwu2023 
88578bf93f0SYJwu2023     let prefetchable_base_upper_32_bits = PciArch::read_config(bus_device_function, 0x28);
88678bf93f0SYJwu2023     let prefetchable_limit_upper_32_bits = PciArch::read_config(bus_device_function, 0x2c);
88778bf93f0SYJwu2023 
88878bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x30);
88978bf93f0SYJwu2023     let io_base_upper_16_bits = result as u16;
89078bf93f0SYJwu2023     let io_limit_upper_16_bits = (result >> 16) as u16;
89178bf93f0SYJwu2023 
89278bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x34);
89378bf93f0SYJwu2023     let capability_pointer = result as u8;
89478bf93f0SYJwu2023     let reserved0 = (result >> 8) as u8;
89578bf93f0SYJwu2023     let reserved1 = (result >> 16) as u16;
89678bf93f0SYJwu2023 
89778bf93f0SYJwu2023     let expansion_rom_base_address = PciArch::read_config(bus_device_function, 0x38);
89878bf93f0SYJwu2023 
89978bf93f0SYJwu2023     let result = PciArch::read_config(bus_device_function, 0x3c);
90078bf93f0SYJwu2023     let interrupt_line = result as u8;
90178bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
90278bf93f0SYJwu2023     let bridge_control = (result >> 16) as u16;
90378bf93f0SYJwu2023     PciDeviceStructurePciToPciBridge {
90478bf93f0SYJwu2023         common_header,
905*cc36cf4aSYJwu2023         irq_type: IrqType::Unused,
906*cc36cf4aSYJwu2023         irq_vector: Vec::new(),
90778bf93f0SYJwu2023         bar0,
90878bf93f0SYJwu2023         bar1,
90978bf93f0SYJwu2023         primary_bus_number,
91078bf93f0SYJwu2023         secondary_bus_number,
91178bf93f0SYJwu2023         subordinate_bus_number,
91278bf93f0SYJwu2023         secondary_latency_timer,
91378bf93f0SYJwu2023         io_base,
91478bf93f0SYJwu2023         io_limit,
91578bf93f0SYJwu2023         secondary_status,
91678bf93f0SYJwu2023         memory_base,
91778bf93f0SYJwu2023         memory_limit,
91878bf93f0SYJwu2023         prefetchable_memory_base,
91978bf93f0SYJwu2023         prefetchable_memory_limit,
92078bf93f0SYJwu2023         prefetchable_base_upper_32_bits,
92178bf93f0SYJwu2023         prefetchable_limit_upper_32_bits,
92278bf93f0SYJwu2023         io_base_upper_16_bits,
92378bf93f0SYJwu2023         io_limit_upper_16_bits,
92478bf93f0SYJwu2023         capability_pointer,
92578bf93f0SYJwu2023         reserved0,
92678bf93f0SYJwu2023         reserved1,
92778bf93f0SYJwu2023         expansion_rom_base_address,
92878bf93f0SYJwu2023         interrupt_line,
92978bf93f0SYJwu2023         interrupt_pin,
93078bf93f0SYJwu2023         bridge_control,
93178bf93f0SYJwu2023     }
93278bf93f0SYJwu2023 }
93378bf93f0SYJwu2023 
93478bf93f0SYJwu2023 /// @brief 读取type为0x2的pci设备的header
93578bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
93678bf93f0SYJwu2023 /// @param common_header 共有头部
93778bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
938*cc36cf4aSYJwu2023 /// @return   Pci_Device_Structure_Pci_to_Cardbus_Bridge  pci-to-cardbus 桥设备头部
93978bf93f0SYJwu2023 fn pci_read_pci_to_cardbus_bridge_header(
94078bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
94178bf93f0SYJwu2023     busdevicefunction: &BusDeviceFunction,
94278bf93f0SYJwu2023 ) -> PciDeviceStructurePciToCardbusBridge {
94378bf93f0SYJwu2023     let cardbus_socket_ex_ca_base_address = PciArch::read_config(busdevicefunction, 0x10);
94478bf93f0SYJwu2023 
94578bf93f0SYJwu2023     let result = PciArch::read_config(busdevicefunction, 0x14);
94678bf93f0SYJwu2023     let offset_of_capabilities_list = result as u8;
94778bf93f0SYJwu2023     let reserved = (result >> 8) as u8;
94878bf93f0SYJwu2023     let secondary_status = (result >> 16) as u16;
94978bf93f0SYJwu2023 
95078bf93f0SYJwu2023     let result = PciArch::read_config(busdevicefunction, 0x18);
95178bf93f0SYJwu2023     let pci_bus_number = result as u8;
95278bf93f0SYJwu2023     let card_bus_bus_number = (result >> 8) as u8;
95378bf93f0SYJwu2023     let subordinate_bus_number = (result >> 16) as u8;
95478bf93f0SYJwu2023     let card_bus_latency_timer = (result >> 24) as u8;
95578bf93f0SYJwu2023 
95678bf93f0SYJwu2023     let memory_base_address0 = PciArch::read_config(busdevicefunction, 0x1c);
95778bf93f0SYJwu2023     let memory_limit0 = PciArch::read_config(busdevicefunction, 0x20);
95878bf93f0SYJwu2023     let memory_base_address1 = PciArch::read_config(busdevicefunction, 0x24);
95978bf93f0SYJwu2023     let memory_limit1 = PciArch::read_config(busdevicefunction, 0x28);
96078bf93f0SYJwu2023 
96178bf93f0SYJwu2023     let io_base_address0 = PciArch::read_config(busdevicefunction, 0x2c);
96278bf93f0SYJwu2023     let io_limit0 = PciArch::read_config(busdevicefunction, 0x30);
96378bf93f0SYJwu2023     let io_base_address1 = PciArch::read_config(busdevicefunction, 0x34);
96478bf93f0SYJwu2023     let io_limit1 = PciArch::read_config(busdevicefunction, 0x38);
96578bf93f0SYJwu2023     let result = PciArch::read_config(busdevicefunction, 0x3c);
96678bf93f0SYJwu2023     let interrupt_line = result as u8;
96778bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
96878bf93f0SYJwu2023     let bridge_control = (result >> 16) as u16;
96978bf93f0SYJwu2023 
97078bf93f0SYJwu2023     let result = PciArch::read_config(busdevicefunction, 0x40);
97178bf93f0SYJwu2023     let subsystem_device_id = result as u16;
97278bf93f0SYJwu2023     let subsystem_vendor_id = (result >> 16) as u16;
97378bf93f0SYJwu2023 
97478bf93f0SYJwu2023     let pc_card_legacy_mode_base_address_16_bit = PciArch::read_config(busdevicefunction, 0x44);
97578bf93f0SYJwu2023     PciDeviceStructurePciToCardbusBridge {
97678bf93f0SYJwu2023         common_header,
97778bf93f0SYJwu2023         cardbus_socket_ex_ca_base_address,
97878bf93f0SYJwu2023         offset_of_capabilities_list,
97978bf93f0SYJwu2023         reserved,
98078bf93f0SYJwu2023         secondary_status,
98178bf93f0SYJwu2023         pci_bus_number,
98278bf93f0SYJwu2023         card_bus_bus_number,
98378bf93f0SYJwu2023         subordinate_bus_number,
98478bf93f0SYJwu2023         card_bus_latency_timer,
98578bf93f0SYJwu2023         memory_base_address0,
98678bf93f0SYJwu2023         memory_limit0,
98778bf93f0SYJwu2023         memory_base_address1,
98878bf93f0SYJwu2023         memory_limit1,
98978bf93f0SYJwu2023         io_base_address0,
99078bf93f0SYJwu2023         io_limit0,
99178bf93f0SYJwu2023         io_base_address1,
99278bf93f0SYJwu2023         io_limit1,
99378bf93f0SYJwu2023         interrupt_line,
99478bf93f0SYJwu2023         interrupt_pin,
99578bf93f0SYJwu2023         bridge_control,
99678bf93f0SYJwu2023         subsystem_device_id,
99778bf93f0SYJwu2023         subsystem_vendor_id,
99878bf93f0SYJwu2023         pc_card_legacy_mode_base_address_16_bit,
99978bf93f0SYJwu2023     }
100078bf93f0SYJwu2023 }
100178bf93f0SYJwu2023 
100278bf93f0SYJwu2023 /// @brief 检查所有bus上的设备并将其加入链表
100378bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
100478bf93f0SYJwu2023 fn pci_check_all_buses() -> Result<u8, PciError> {
100578bf93f0SYJwu2023     kinfo!("Checking all devices in PCI bus...");
100678bf93f0SYJwu2023     let busdevicefunction = BusDeviceFunction {
100778bf93f0SYJwu2023         bus: 0,
100878bf93f0SYJwu2023         device: 0,
100978bf93f0SYJwu2023         function: 0,
101078bf93f0SYJwu2023     };
101178bf93f0SYJwu2023     let header = pci_read_header(busdevicefunction, false)?;
101278bf93f0SYJwu2023     let common_header = header.common_header();
101378bf93f0SYJwu2023     pci_check_bus(0)?;
101478bf93f0SYJwu2023     if common_header.header_type & 0x80 != 0 {
101578bf93f0SYJwu2023         for function in 1..8 {
101678bf93f0SYJwu2023             pci_check_bus(function)?;
101778bf93f0SYJwu2023         }
101878bf93f0SYJwu2023     }
101978bf93f0SYJwu2023     Ok(0)
102078bf93f0SYJwu2023 }
102178bf93f0SYJwu2023 /// @brief 检查特定设备并将其加入链表
102278bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
102378bf93f0SYJwu2023 fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciError> {
102478bf93f0SYJwu2023     //kdebug!("PCI check function {}", busdevicefunction.function);
102578bf93f0SYJwu2023     let header = match pci_read_header(busdevicefunction, true) {
102678bf93f0SYJwu2023         Ok(header) => header,
102778bf93f0SYJwu2023         Err(PciError::GetWrongHeader) => {
102878bf93f0SYJwu2023             return Ok(255);
102978bf93f0SYJwu2023         }
103078bf93f0SYJwu2023         Err(e) => {
103178bf93f0SYJwu2023             return Err(e);
103278bf93f0SYJwu2023         }
103378bf93f0SYJwu2023     };
103478bf93f0SYJwu2023     let common_header = header.common_header();
103578bf93f0SYJwu2023     if (common_header.class_code == 0x06)
103678bf93f0SYJwu2023         && (common_header.subclass == 0x04 || common_header.subclass == 0x09)
103778bf93f0SYJwu2023     {
103878bf93f0SYJwu2023         let pci_to_pci_bridge = header
103978bf93f0SYJwu2023             .as_pci_to_pci_bridge_device()
104078bf93f0SYJwu2023             .ok_or(PciError::PciDeviceStructureTransformError)?;
104178bf93f0SYJwu2023         let secondary_bus = pci_to_pci_bridge.secondary_bus_number;
104278bf93f0SYJwu2023         pci_check_bus(secondary_bus)?;
104378bf93f0SYJwu2023     }
104478bf93f0SYJwu2023     Ok(0)
104578bf93f0SYJwu2023 }
104678bf93f0SYJwu2023 
104778bf93f0SYJwu2023 /// @brief 检查device上的设备并将其加入链表
104878bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
104978bf93f0SYJwu2023 fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
105078bf93f0SYJwu2023     //kdebug!("PCI check device {}", device);
105178bf93f0SYJwu2023     let busdevicefunction = BusDeviceFunction {
105278bf93f0SYJwu2023         bus,
105378bf93f0SYJwu2023         device,
105478bf93f0SYJwu2023         function: 0,
105578bf93f0SYJwu2023     };
105678bf93f0SYJwu2023     let header = match pci_read_header(busdevicefunction, false) {
105778bf93f0SYJwu2023         Ok(header) => header,
105878bf93f0SYJwu2023         Err(PciError::GetWrongHeader) => {
105978bf93f0SYJwu2023             //设备不存在,直接返回即可,不用终止遍历
106078bf93f0SYJwu2023             return Ok(255);
106178bf93f0SYJwu2023         }
106278bf93f0SYJwu2023         Err(e) => {
106378bf93f0SYJwu2023             return Err(e);
106478bf93f0SYJwu2023         }
106578bf93f0SYJwu2023     };
106678bf93f0SYJwu2023     pci_check_function(busdevicefunction)?;
106778bf93f0SYJwu2023     let common_header = header.common_header();
106878bf93f0SYJwu2023     if common_header.header_type & 0x80 != 0 {
106978bf93f0SYJwu2023         kdebug!(
107078bf93f0SYJwu2023             "Detected multi func device in bus{},device{}",
107178bf93f0SYJwu2023             busdevicefunction.bus,
107278bf93f0SYJwu2023             busdevicefunction.device
107378bf93f0SYJwu2023         );
107478bf93f0SYJwu2023         // 这是一个多function的设备,因此查询剩余的function
107578bf93f0SYJwu2023         for function in 1..8 {
107678bf93f0SYJwu2023             let busdevicefunction = BusDeviceFunction {
107778bf93f0SYJwu2023                 bus,
107878bf93f0SYJwu2023                 device,
107978bf93f0SYJwu2023                 function,
108078bf93f0SYJwu2023             };
108178bf93f0SYJwu2023             pci_check_function(busdevicefunction)?;
108278bf93f0SYJwu2023         }
108378bf93f0SYJwu2023     }
108478bf93f0SYJwu2023     Ok(0)
108578bf93f0SYJwu2023 }
108678bf93f0SYJwu2023 /// @brief 检查该bus上的设备并将其加入链表
108778bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
108878bf93f0SYJwu2023 fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
108978bf93f0SYJwu2023     //kdebug!("PCI check bus {}", bus);
109078bf93f0SYJwu2023     for device in 0..32 {
109178bf93f0SYJwu2023         pci_check_device(bus, device)?;
109278bf93f0SYJwu2023     }
109378bf93f0SYJwu2023     Ok(0)
109478bf93f0SYJwu2023 }
109578bf93f0SYJwu2023 /// @brief pci初始化函数(for c)
109678bf93f0SYJwu2023 #[no_mangle]
109778bf93f0SYJwu2023 pub extern "C" fn rs_pci_init() {
109878bf93f0SYJwu2023     pci_init();
10995c1e552cSYJwu2023     if PCI_ROOT_0.is_some() {
11005c1e552cSYJwu2023         kdebug!("{}", PCI_ROOT_0.unwrap());
11015c1e552cSYJwu2023         //以下为ecam的读取寄存器值测试,经测试可正常读取
11025c1e552cSYJwu2023         // let bus_device_function = BusDeviceFunction {
11035c1e552cSYJwu2023         //     bus: 0,
11045c1e552cSYJwu2023         //     device: 2,
11055c1e552cSYJwu2023         //     function: 0,
11065c1e552cSYJwu2023         // };
11075c1e552cSYJwu2023         // kdebug!(
11085c1e552cSYJwu2023         //     "Ecam read virtio-net device status={:#x}",
11095c1e552cSYJwu2023         //     (PCI_ROOT_0.unwrap().read_config(bus_device_function, 4)>>16) as u16
11105c1e552cSYJwu2023         // );
11115c1e552cSYJwu2023     }
111278bf93f0SYJwu2023 }
111378bf93f0SYJwu2023 /// @brief pci初始化函数
111478bf93f0SYJwu2023 pub fn pci_init() {
111578bf93f0SYJwu2023     kinfo!("Initializing PCI bus...");
111678bf93f0SYJwu2023     if let Err(e) = pci_check_all_buses() {
111778bf93f0SYJwu2023         kerror!("pci init failed when checking bus because of error: {}", e);
111878bf93f0SYJwu2023         return;
111978bf93f0SYJwu2023     }
112078bf93f0SYJwu2023     kinfo!(
112178bf93f0SYJwu2023         "Total pci device and function num = {}",
112278bf93f0SYJwu2023         PCI_DEVICE_LINKEDLIST.num()
112378bf93f0SYJwu2023     );
112478bf93f0SYJwu2023     let list = PCI_DEVICE_LINKEDLIST.read();
112578bf93f0SYJwu2023     for box_pci_device in list.iter() {
112678bf93f0SYJwu2023         let common_header = box_pci_device.common_header();
112778bf93f0SYJwu2023         match box_pci_device.header_type() {
112878bf93f0SYJwu2023             HeaderType::Standard if common_header.status & 0x10 != 0 => {
11295c1e552cSYJwu2023                 kinfo!("Found pci standard device with class code ={} subclass={} status={:#x} cap_pointer={:#x}  vendor={:#x}, device id={:#x},bdf={}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_standard_device().unwrap().capabilities_pointer,common_header.vendor_id, common_header.device_id,common_header.bus_device_function);
113078bf93f0SYJwu2023             }
113178bf93f0SYJwu2023             HeaderType::Standard => {
113278bf93f0SYJwu2023                 kinfo!(
113378bf93f0SYJwu2023                     "Found pci standard device with class code ={} subclass={} status={:#x} ",
113478bf93f0SYJwu2023                     common_header.class_code,
113578bf93f0SYJwu2023                     common_header.subclass,
113678bf93f0SYJwu2023                     common_header.status
113778bf93f0SYJwu2023                 );
113878bf93f0SYJwu2023             }
113978bf93f0SYJwu2023             HeaderType::PciPciBridge if common_header.status & 0x10 != 0 => {
114078bf93f0SYJwu2023                 kinfo!("Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} cap_pointer={:#x}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_standard_device().unwrap().capabilities_pointer);
114178bf93f0SYJwu2023             }
114278bf93f0SYJwu2023             HeaderType::PciPciBridge => {
114378bf93f0SYJwu2023                 kinfo!(
114478bf93f0SYJwu2023                     "Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} ",
114578bf93f0SYJwu2023                     common_header.class_code,
114678bf93f0SYJwu2023                     common_header.subclass,
114778bf93f0SYJwu2023                     common_header.status
114878bf93f0SYJwu2023                 );
114978bf93f0SYJwu2023             }
115078bf93f0SYJwu2023             HeaderType::PciCardbusBridge => {
115178bf93f0SYJwu2023                 kinfo!(
115278bf93f0SYJwu2023                     "Found pcicardbus bridge device with class code ={} subclass={} status={:#x} ",
115378bf93f0SYJwu2023                     common_header.class_code,
115478bf93f0SYJwu2023                     common_header.subclass,
115578bf93f0SYJwu2023                     common_header.status
115678bf93f0SYJwu2023                 );
115778bf93f0SYJwu2023             }
115878bf93f0SYJwu2023             HeaderType::Unrecognised(_) => {}
115978bf93f0SYJwu2023         }
116078bf93f0SYJwu2023     }
116178bf93f0SYJwu2023     kinfo!("PCI bus initialized.");
116278bf93f0SYJwu2023 }
116378bf93f0SYJwu2023 
116426d84a31SYJwu2023 /// An identifier for a PCI bus, device and function.
116526d84a31SYJwu2023 /// PCI设备的唯一标识
116626d84a31SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
116778bf93f0SYJwu2023 pub struct BusDeviceFunction {
116826d84a31SYJwu2023     /// The PCI bus number, between 0 and 255.
116926d84a31SYJwu2023     pub bus: u8,
117026d84a31SYJwu2023     /// The device number on the bus, between 0 and 31.
117126d84a31SYJwu2023     pub device: u8,
117226d84a31SYJwu2023     /// The function number of the device, between 0 and 7.
117326d84a31SYJwu2023     pub function: u8,
117426d84a31SYJwu2023 }
117578bf93f0SYJwu2023 impl BusDeviceFunction {
117626d84a31SYJwu2023     /// Returns whether the device and function numbers are valid, i.e. the device is between 0 and
117778bf93f0SYJwu2023     ///@brief 检测BusDeviceFunction实例是否有效
117826d84a31SYJwu2023     ///@param self
117926d84a31SYJwu2023     ///@return bool 是否有效
118073c607aaSYJwu2023     #[allow(dead_code)]
118126d84a31SYJwu2023     pub fn valid(&self) -> bool {
118226d84a31SYJwu2023         self.device < 32 && self.function < 8
118326d84a31SYJwu2023     }
118426d84a31SYJwu2023 }
118578bf93f0SYJwu2023 ///实现BusDeviceFunction的Display trait,使其可以直接输出
118678bf93f0SYJwu2023 impl Display for BusDeviceFunction {
118726d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
11885c1e552cSYJwu2023         write!(
11895c1e552cSYJwu2023             f,
11905c1e552cSYJwu2023             "bus {} device {} function{}",
11915c1e552cSYJwu2023             self.bus, self.device, self.function
11925c1e552cSYJwu2023         )
119326d84a31SYJwu2023     }
119426d84a31SYJwu2023 }
119526d84a31SYJwu2023 /// The location allowed for a memory BAR.
119626d84a31SYJwu2023 /// memory BAR的三种情况
119726d84a31SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
119826d84a31SYJwu2023 pub enum MemoryBarType {
119926d84a31SYJwu2023     /// The BAR has a 32-bit address and can be mapped anywhere in 32-bit address space.
120026d84a31SYJwu2023     Width32,
120126d84a31SYJwu2023     /// The BAR must be mapped below 1MiB.
120226d84a31SYJwu2023     Below1MiB,
120326d84a31SYJwu2023     /// The BAR has a 64-bit address and can be mapped anywhere in 64-bit address space.
120426d84a31SYJwu2023     Width64,
120526d84a31SYJwu2023 }
120626d84a31SYJwu2023 ///实现MemoryBarType与u8的类型转换
120726d84a31SYJwu2023 impl From<MemoryBarType> for u8 {
120826d84a31SYJwu2023     fn from(bar_type: MemoryBarType) -> Self {
120926d84a31SYJwu2023         match bar_type {
121026d84a31SYJwu2023             MemoryBarType::Width32 => 0,
121126d84a31SYJwu2023             MemoryBarType::Below1MiB => 1,
121226d84a31SYJwu2023             MemoryBarType::Width64 => 2,
121326d84a31SYJwu2023         }
121426d84a31SYJwu2023     }
121526d84a31SYJwu2023 }
121626d84a31SYJwu2023 ///实现MemoryBarType与u8的类型转换
121726d84a31SYJwu2023 impl TryFrom<u8> for MemoryBarType {
121826d84a31SYJwu2023     type Error = PciError;
121926d84a31SYJwu2023     fn try_from(value: u8) -> Result<Self, Self::Error> {
122026d84a31SYJwu2023         match value {
122126d84a31SYJwu2023             0 => Ok(Self::Width32),
122226d84a31SYJwu2023             1 => Ok(Self::Below1MiB),
122326d84a31SYJwu2023             2 => Ok(Self::Width64),
122426d84a31SYJwu2023             _ => Err(PciError::InvalidBarType),
122526d84a31SYJwu2023         }
122626d84a31SYJwu2023     }
122726d84a31SYJwu2023 }
122826d84a31SYJwu2023 
122926d84a31SYJwu2023 /// Information about a PCI Base Address Register.
123026d84a31SYJwu2023 /// BAR的三种类型 Memory/IO/Unused
123126d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
123226d84a31SYJwu2023 pub enum BarInfo {
123326d84a31SYJwu2023     /// The BAR is for a memory region.
123426d84a31SYJwu2023     Memory {
123526d84a31SYJwu2023         /// The size of the BAR address and where it can be located.
123626d84a31SYJwu2023         address_type: MemoryBarType,
123726d84a31SYJwu2023         /// If true, then reading from the region doesn't have side effects. The CPU may cache reads
123826d84a31SYJwu2023         /// and merge repeated stores.
123926d84a31SYJwu2023         prefetchable: bool,
124026d84a31SYJwu2023         /// The memory address, always 16-byte aligned.
124126d84a31SYJwu2023         address: u64,
124226d84a31SYJwu2023         /// The size of the BAR in bytes.
124326d84a31SYJwu2023         size: u32,
124426d84a31SYJwu2023         /// The virtaddress for a memory bar(mapped).
124526d84a31SYJwu2023         virtaddress: u64,
124626d84a31SYJwu2023     },
124726d84a31SYJwu2023     /// The BAR is for an I/O region.
124826d84a31SYJwu2023     IO {
124926d84a31SYJwu2023         /// The I/O address, always 4-byte aligned.
125026d84a31SYJwu2023         address: u32,
125126d84a31SYJwu2023         /// The size of the BAR in bytes.
125226d84a31SYJwu2023         size: u32,
125326d84a31SYJwu2023     },
125426d84a31SYJwu2023     Unused,
125526d84a31SYJwu2023 }
125626d84a31SYJwu2023 
125726d84a31SYJwu2023 impl BarInfo {
125826d84a31SYJwu2023     /// Returns the address and size of this BAR if it is a memory bar, or `None` if it is an IO
125926d84a31SYJwu2023     /// BAR.
126026d84a31SYJwu2023     ///@brief 得到某个bar的memory_address与size(前提是他的类型为Memory Bar)
126126d84a31SYJwu2023     ///@param self
126226d84a31SYJwu2023     ///@return Option<(u64, u32) 是Memory Bar返回内存地址与大小,不是则返回None
126326d84a31SYJwu2023     pub fn memory_address_size(&self) -> Option<(u64, u32)> {
126426d84a31SYJwu2023         if let Self::Memory { address, size, .. } = self {
126526d84a31SYJwu2023             Some((*address, *size))
126626d84a31SYJwu2023         } else {
126726d84a31SYJwu2023             None
126826d84a31SYJwu2023         }
126926d84a31SYJwu2023     }
127026d84a31SYJwu2023     ///@brief 得到某个bar的virtaddress(前提是他的类型为Memory Bar)
127126d84a31SYJwu2023     ///@param self
127226d84a31SYJwu2023     ///@return Option<(u64) 是Memory Bar返回映射的虚拟地址,不是则返回None
127326d84a31SYJwu2023     pub fn virtual_address(&self) -> Option<u64> {
127426d84a31SYJwu2023         if let Self::Memory { virtaddress, .. } = self {
127526d84a31SYJwu2023             Some(*virtaddress)
127626d84a31SYJwu2023         } else {
127726d84a31SYJwu2023             None
127826d84a31SYJwu2023         }
127926d84a31SYJwu2023     }
128026d84a31SYJwu2023 }
128178bf93f0SYJwu2023 ///实现BarInfo的Display trait,自定义输出
128226d84a31SYJwu2023 impl Display for BarInfo {
128326d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
128426d84a31SYJwu2023         match self {
128526d84a31SYJwu2023             Self::Memory {
128626d84a31SYJwu2023                 address_type,
128726d84a31SYJwu2023                 prefetchable,
128826d84a31SYJwu2023                 address,
128926d84a31SYJwu2023                 size,
129026d84a31SYJwu2023                 virtaddress,
129126d84a31SYJwu2023             } => write!(
129226d84a31SYJwu2023                 f,
129326d84a31SYJwu2023                 "Memory space at {:#010x}, size {}, type {:?}, prefetchable {},mapped at {:#x}",
129426d84a31SYJwu2023                 address, size, address_type, prefetchable, virtaddress
129526d84a31SYJwu2023             ),
129626d84a31SYJwu2023             Self::IO { address, size } => {
129726d84a31SYJwu2023                 write!(f, "I/O space at {:#010x}, size {}", address, size)
129826d84a31SYJwu2023             }
129926d84a31SYJwu2023             Self::Unused => {
130026d84a31SYJwu2023                 write!(f, "Unused bar")
130126d84a31SYJwu2023             }
130226d84a31SYJwu2023         }
130326d84a31SYJwu2023     }
130426d84a31SYJwu2023 }
1305*cc36cf4aSYJwu2023 //todo 增加对桥的bar的支持
1306*cc36cf4aSYJwu2023 pub trait PciDeviceBar {}
130778bf93f0SYJwu2023 ///一个普通PCI设备(非桥)有6个BAR寄存器,PciStandardDeviceBar存储其全部信息
130826d84a31SYJwu2023 #[derive(Clone, Debug, Eq, PartialEq)]
130978bf93f0SYJwu2023 pub struct PciStandardDeviceBar {
131026d84a31SYJwu2023     bar0: BarInfo,
131126d84a31SYJwu2023     bar1: BarInfo,
131226d84a31SYJwu2023     bar2: BarInfo,
131326d84a31SYJwu2023     bar3: BarInfo,
131426d84a31SYJwu2023     bar4: BarInfo,
131526d84a31SYJwu2023     bar5: BarInfo,
131626d84a31SYJwu2023 }
131726d84a31SYJwu2023 
131878bf93f0SYJwu2023 impl PciStandardDeviceBar {
131926d84a31SYJwu2023     ///@brief 得到某个bar的barinfo
132026d84a31SYJwu2023     ///@param self ,bar_index(0-5)
132126d84a31SYJwu2023     ///@return Result<&BarInfo, PciError> bar_index在0-5则返回对应的bar_info结构体,超出范围则返回错误
132226d84a31SYJwu2023     pub fn get_bar(&self, bar_index: u8) -> Result<&BarInfo, PciError> {
132326d84a31SYJwu2023         match bar_index {
132426d84a31SYJwu2023             0 => Ok(&self.bar0),
132526d84a31SYJwu2023             1 => Ok(&self.bar1),
132626d84a31SYJwu2023             2 => Ok(&self.bar2),
132726d84a31SYJwu2023             3 => Ok(&self.bar3),
132826d84a31SYJwu2023             4 => Ok(&self.bar4),
132978bf93f0SYJwu2023             5 => Ok(&self.bar5),
133026d84a31SYJwu2023             _ => Err(PciError::InvalidBarType),
133126d84a31SYJwu2023         }
133226d84a31SYJwu2023     }
133326d84a31SYJwu2023 }
133478bf93f0SYJwu2023 ///实现PciStandardDeviceBar的Display trait,使其可以直接输出
133578bf93f0SYJwu2023 impl Display for PciStandardDeviceBar {
133626d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
133726d84a31SYJwu2023         write!(
133826d84a31SYJwu2023             f,
133926d84a31SYJwu2023             "\r\nBar0:{}\r\n Bar1:{}\r\n Bar2:{}\r\n Bar3:{}\r\nBar4:{}\r\nBar5:{}",
134026d84a31SYJwu2023             self.bar0, self.bar1, self.bar2, self.bar3, self.bar4, self.bar5
134126d84a31SYJwu2023         )
134226d84a31SYJwu2023     }
134326d84a31SYJwu2023 }
134478bf93f0SYJwu2023 ///实现PciStandardDeviceBar的Default trait,使其可以简单初始化
134578bf93f0SYJwu2023 impl Default for PciStandardDeviceBar {
134626d84a31SYJwu2023     fn default() -> Self {
134778bf93f0SYJwu2023         PciStandardDeviceBar {
134826d84a31SYJwu2023             bar0: BarInfo::Unused,
134926d84a31SYJwu2023             bar1: BarInfo::Unused,
135026d84a31SYJwu2023             bar2: BarInfo::Unused,
135126d84a31SYJwu2023             bar3: BarInfo::Unused,
135226d84a31SYJwu2023             bar4: BarInfo::Unused,
135326d84a31SYJwu2023             bar5: BarInfo::Unused,
135426d84a31SYJwu2023         }
135526d84a31SYJwu2023     }
135626d84a31SYJwu2023 }
135726d84a31SYJwu2023 
135878bf93f0SYJwu2023 ///@brief 将某个pci设备的bar寄存器读取值后映射到虚拟地址
135978bf93f0SYJwu2023 ///@param self ,bus_device_function PCI设备的唯一标识符
136078bf93f0SYJwu2023 ///@return Result<PciStandardDeviceBar, PciError> 成功则返回对应的PciStandardDeviceBar结构体,失败则返回错误类型
136178bf93f0SYJwu2023 pub fn pci_bar_init(
136278bf93f0SYJwu2023     bus_device_function: BusDeviceFunction,
136378bf93f0SYJwu2023 ) -> Result<PciStandardDeviceBar, PciError> {
136478bf93f0SYJwu2023     let mut device_bar: PciStandardDeviceBar = PciStandardDeviceBar::default();
136526d84a31SYJwu2023     let mut bar_index_ignore: u8 = 255;
136626d84a31SYJwu2023     for bar_index in 0..6 {
136726d84a31SYJwu2023         if bar_index == bar_index_ignore {
136826d84a31SYJwu2023             continue;
136926d84a31SYJwu2023         }
137026d84a31SYJwu2023         let bar_info;
137126d84a31SYJwu2023         let mut virtaddress: u64 = 0;
137278bf93f0SYJwu2023         let bar_orig = PciArch::read_config(&bus_device_function, BAR0_OFFSET + 4 * bar_index);
137378bf93f0SYJwu2023         PciArch::write_config(
137478bf93f0SYJwu2023             &bus_device_function,
137526d84a31SYJwu2023             BAR0_OFFSET + 4 * bar_index,
137626d84a31SYJwu2023             0xffffffff,
137726d84a31SYJwu2023         );
137878bf93f0SYJwu2023         let size_mask = PciArch::read_config(&bus_device_function, BAR0_OFFSET + 4 * bar_index);
137926d84a31SYJwu2023         // A wrapping add is necessary to correctly handle the case of unused BARs, which read back
138026d84a31SYJwu2023         // as 0, and should be treated as size 0.
138126d84a31SYJwu2023         let size = (!(size_mask & 0xfffffff0)).wrapping_add(1);
138226d84a31SYJwu2023         //kdebug!("bar_orig:{:#x},size: {:#x}", bar_orig,size);
138326d84a31SYJwu2023         // Restore the original value.
138478bf93f0SYJwu2023         PciArch::write_config(&bus_device_function, BAR0_OFFSET + 4 * bar_index, bar_orig);
138526d84a31SYJwu2023         if size == 0 {
138626d84a31SYJwu2023             continue;
138726d84a31SYJwu2023         }
138826d84a31SYJwu2023         if bar_orig & 0x00000001 == 0x00000001 {
138926d84a31SYJwu2023             // I/O space
139026d84a31SYJwu2023             let address = bar_orig & 0xfffffffc;
139126d84a31SYJwu2023             bar_info = BarInfo::IO { address, size };
139226d84a31SYJwu2023         } else {
139326d84a31SYJwu2023             // Memory space
139426d84a31SYJwu2023             let mut address = u64::from(bar_orig & 0xfffffff0);
139526d84a31SYJwu2023             let prefetchable = bar_orig & 0x00000008 != 0;
139626d84a31SYJwu2023             let address_type = MemoryBarType::try_from(((bar_orig & 0x00000006) >> 1) as u8)?;
139726d84a31SYJwu2023             if address_type == MemoryBarType::Width64 {
139826d84a31SYJwu2023                 if bar_index >= 5 {
139926d84a31SYJwu2023                     return Err(PciError::InvalidBarType);
140026d84a31SYJwu2023                 }
140178bf93f0SYJwu2023                 let address_top =
140278bf93f0SYJwu2023                     PciArch::read_config(&bus_device_function, BAR0_OFFSET + 4 * (bar_index + 1));
140326d84a31SYJwu2023                 address |= u64::from(address_top) << 32;
140426d84a31SYJwu2023                 bar_index_ignore = bar_index + 1; //下个bar跳过,因为64位的memory bar覆盖了两个bar
140526d84a31SYJwu2023             }
14065c1e552cSYJwu2023             let pci_address = PciAddr::new(address as usize);
14075c1e552cSYJwu2023             address = PciArch::address_pci_to_physical(pci_address) as u64; //PCI总线域物理地址转换为存储器域物理地址
140826d84a31SYJwu2023             unsafe {
140926d84a31SYJwu2023                 let vaddr_ptr = &mut virtaddress as *mut u64;
141026d84a31SYJwu2023                 let mut virtsize: u64 = 0;
141126d84a31SYJwu2023                 let virtsize_ptr = &mut virtsize as *mut u64;
141226d84a31SYJwu2023                 let initial_mm_ptr = &mut initial_mm as *mut mm_struct;
141326d84a31SYJwu2023                 //kdebug!("size want={:#x}", size);
141426d84a31SYJwu2023                 if let Err(_) = MMIO_POOL.create_mmio(
141526d84a31SYJwu2023                     size,
141626d84a31SYJwu2023                     (VM_IO | VM_DONTCOPY) as u64,
141726d84a31SYJwu2023                     vaddr_ptr,
141826d84a31SYJwu2023                     virtsize_ptr,
141926d84a31SYJwu2023                 ) {
142026d84a31SYJwu2023                     kerror!("Create mmio failed when initing pci bar");
142126d84a31SYJwu2023                     return Err(PciError::CreateMmioError);
142226d84a31SYJwu2023                 };
142326d84a31SYJwu2023                 //kdebug!("virtaddress={:#x},virtsize={:#x}",virtaddress,virtsize);
142426d84a31SYJwu2023                 mm_map(initial_mm_ptr, virtaddress, size as u64, address);
142526d84a31SYJwu2023             }
142626d84a31SYJwu2023             bar_info = BarInfo::Memory {
142726d84a31SYJwu2023                 address_type,
142826d84a31SYJwu2023                 prefetchable,
142926d84a31SYJwu2023                 address,
143026d84a31SYJwu2023                 size,
143126d84a31SYJwu2023                 virtaddress,
143226d84a31SYJwu2023             };
143326d84a31SYJwu2023         }
143426d84a31SYJwu2023         match bar_index {
143526d84a31SYJwu2023             0 => {
143626d84a31SYJwu2023                 device_bar.bar0 = bar_info;
143726d84a31SYJwu2023             }
143826d84a31SYJwu2023             1 => {
143926d84a31SYJwu2023                 device_bar.bar1 = bar_info;
144026d84a31SYJwu2023             }
144126d84a31SYJwu2023             2 => {
144226d84a31SYJwu2023                 device_bar.bar2 = bar_info;
144326d84a31SYJwu2023             }
144426d84a31SYJwu2023             3 => {
144526d84a31SYJwu2023                 device_bar.bar3 = bar_info;
144626d84a31SYJwu2023             }
144726d84a31SYJwu2023             4 => {
144826d84a31SYJwu2023                 device_bar.bar4 = bar_info;
144926d84a31SYJwu2023             }
145026d84a31SYJwu2023             5 => {
145126d84a31SYJwu2023                 device_bar.bar5 = bar_info;
145226d84a31SYJwu2023             }
145326d84a31SYJwu2023             _ => {}
145426d84a31SYJwu2023         }
145526d84a31SYJwu2023     }
145626d84a31SYJwu2023     kdebug!("pci_device_bar:{}", device_bar);
145726d84a31SYJwu2023     return Ok(device_bar);
145826d84a31SYJwu2023 }
145926d84a31SYJwu2023 
146026d84a31SYJwu2023 /// Information about a PCI device capability.
146126d84a31SYJwu2023 /// PCI设备的capability的信息
146226d84a31SYJwu2023 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
146326d84a31SYJwu2023 pub struct CapabilityInfo {
146426d84a31SYJwu2023     /// The offset of the capability in the PCI configuration space of the device function.
146526d84a31SYJwu2023     pub offset: u8,
146626d84a31SYJwu2023     /// The ID of the capability.
146726d84a31SYJwu2023     pub id: u8,
146826d84a31SYJwu2023     /// The third and fourth bytes of the capability, to save reading them again.
146926d84a31SYJwu2023     pub private_header: u16,
147026d84a31SYJwu2023 }
147173c607aaSYJwu2023 
147226d84a31SYJwu2023 /// Iterator over capabilities for a device.
147326d84a31SYJwu2023 /// 创建迭代器以遍历PCI设备的capability
147426d84a31SYJwu2023 #[derive(Debug)]
147526d84a31SYJwu2023 pub struct CapabilityIterator {
147678bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
147726d84a31SYJwu2023     pub next_capability_offset: Option<u8>,
147826d84a31SYJwu2023 }
147926d84a31SYJwu2023 
148026d84a31SYJwu2023 impl Iterator for CapabilityIterator {
148126d84a31SYJwu2023     type Item = CapabilityInfo;
148226d84a31SYJwu2023     fn next(&mut self) -> Option<Self::Item> {
148326d84a31SYJwu2023         let offset = self.next_capability_offset?;
148426d84a31SYJwu2023 
148526d84a31SYJwu2023         // Read the first 4 bytes of the capability.
148678bf93f0SYJwu2023         let capability_header = PciArch::read_config(&self.bus_device_function, offset);
148726d84a31SYJwu2023         let id = capability_header as u8;
148826d84a31SYJwu2023         let next_offset = (capability_header >> 8) as u8;
148926d84a31SYJwu2023         let private_header = (capability_header >> 16) as u16;
149026d84a31SYJwu2023 
149126d84a31SYJwu2023         self.next_capability_offset = if next_offset == 0 {
149226d84a31SYJwu2023             None
149326d84a31SYJwu2023         } else if next_offset < 64 || next_offset & 0x3 != 0 {
149426d84a31SYJwu2023             kwarn!("Invalid next capability offset {:#04x}", next_offset);
149526d84a31SYJwu2023             None
149626d84a31SYJwu2023         } else {
149726d84a31SYJwu2023             Some(next_offset)
149826d84a31SYJwu2023         };
149926d84a31SYJwu2023 
150026d84a31SYJwu2023         Some(CapabilityInfo {
150126d84a31SYJwu2023             offset,
150226d84a31SYJwu2023             id,
150326d84a31SYJwu2023             private_header,
150426d84a31SYJwu2023         })
150526d84a31SYJwu2023     }
150626d84a31SYJwu2023 }
150773c607aaSYJwu2023 
150878bf93f0SYJwu2023 /// Information about a PCIe device capability.
150978bf93f0SYJwu2023 /// PCIe设备的external capability的信息
151078bf93f0SYJwu2023 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
151178bf93f0SYJwu2023 pub struct ExternalCapabilityInfo {
151278bf93f0SYJwu2023     /// The offset of the capability in the PCI configuration space of the device function.
151378bf93f0SYJwu2023     pub offset: u16,
151478bf93f0SYJwu2023     /// The ID of the capability.
151578bf93f0SYJwu2023     pub id: u16,
151678bf93f0SYJwu2023     /// The third and fourth bytes of the capability, to save reading them again.
151778bf93f0SYJwu2023     pub capability_version: u8,
151873c607aaSYJwu2023 }
151978bf93f0SYJwu2023 
152078bf93f0SYJwu2023 /// Iterator over capabilities for a device.
152178bf93f0SYJwu2023 /// 创建迭代器以遍历PCIe设备的external capability
152278bf93f0SYJwu2023 #[derive(Debug)]
152378bf93f0SYJwu2023 pub struct ExternalCapabilityIterator<'a> {
152478bf93f0SYJwu2023     pub root: &'a PciRoot,
152578bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
152678bf93f0SYJwu2023     pub next_capability_offset: Option<u16>,
152773c607aaSYJwu2023 }
152878bf93f0SYJwu2023 impl<'a> Iterator for ExternalCapabilityIterator<'a> {
152978bf93f0SYJwu2023     type Item = ExternalCapabilityInfo;
153078bf93f0SYJwu2023     fn next(&mut self) -> Option<Self::Item> {
153178bf93f0SYJwu2023         let offset = self.next_capability_offset?;
153278bf93f0SYJwu2023 
153378bf93f0SYJwu2023         // Read the first 4 bytes of the capability.
153478bf93f0SYJwu2023         let capability_header = self.root.read_config(self.bus_device_function, offset);
153578bf93f0SYJwu2023         let id = capability_header as u16;
153678bf93f0SYJwu2023         let next_offset = (capability_header >> 20) as u16;
153778bf93f0SYJwu2023         let capability_version = ((capability_header >> 16) & 0xf) as u8;
153878bf93f0SYJwu2023 
153978bf93f0SYJwu2023         self.next_capability_offset = if next_offset == 0 {
154078bf93f0SYJwu2023             None
154178bf93f0SYJwu2023         } else if next_offset < 0x100 || next_offset & 0x3 != 0 {
154278bf93f0SYJwu2023             kwarn!("Invalid next capability offset {:#04x}", next_offset);
154378bf93f0SYJwu2023             None
154478bf93f0SYJwu2023         } else {
154578bf93f0SYJwu2023             Some(next_offset)
154678bf93f0SYJwu2023         };
154778bf93f0SYJwu2023 
154878bf93f0SYJwu2023         Some(ExternalCapabilityInfo {
154978bf93f0SYJwu2023             offset,
155078bf93f0SYJwu2023             id,
155178bf93f0SYJwu2023             capability_version,
155278bf93f0SYJwu2023         })
155378bf93f0SYJwu2023     }
155473c607aaSYJwu2023 }
1555