xref: /DragonOS/kernel/src/driver/pci/pci.rs (revision 2709e017d0d216d61b2caed3c7286459de7794c7)
178bf93f0SYJwu2023 #![allow(dead_code)]
278bf93f0SYJwu2023 // 目前仅支持单主桥单Segment
378bf93f0SYJwu2023 
4cc36cf4aSYJwu2023 use super::pci_irq::{IrqType, PciIrqError};
57ae679ddSLoGin use crate::arch::{PciArch, TraitPciArch};
6e2841179SLoGin use crate::exception::IrqNumber;
72dd9f0c7SLoGin use crate::include::bindings::bindings::PAGE_2M_SIZE;
878bf93f0SYJwu2023 use crate::libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
92dd9f0c7SLoGin 
102dd9f0c7SLoGin use crate::mm::mmio_buddy::{mmio_pool, MMIOSpaceGuard};
112dd9f0c7SLoGin 
1240fe15e0SLoGin use crate::mm::{PhysAddr, VirtAddr};
1378bf93f0SYJwu2023 use crate::{kdebug, kerror, kinfo, kwarn};
142dd9f0c7SLoGin use alloc::sync::Arc;
1578bf93f0SYJwu2023 use alloc::vec::Vec;
1678bf93f0SYJwu2023 use alloc::{boxed::Box, collections::LinkedList};
1726d84a31SYJwu2023 use bitflags::bitflags;
1840fe15e0SLoGin 
1926d84a31SYJwu2023 use core::{
2026d84a31SYJwu2023     convert::TryFrom,
215c1e552cSYJwu2023     fmt::{self, Debug, Display, Formatter},
2226d84a31SYJwu2023 };
2378bf93f0SYJwu2023 // PCI_DEVICE_LINKEDLIST 添加了读写锁的全局链表,里面存储了检索到的PCI设备结构体
2478bf93f0SYJwu2023 // PCI_ROOT_0 Segment为0的全局PciRoot
2578bf93f0SYJwu2023 lazy_static! {
2678bf93f0SYJwu2023     pub static ref PCI_DEVICE_LINKEDLIST: PciDeviceLinkedList = PciDeviceLinkedList::new();
2778bf93f0SYJwu2023     pub static ref PCI_ROOT_0: Option<PciRoot> = {
28*2709e017SLoGin         match PciRoot::new(0, PciCam::Ecam) {
2978bf93f0SYJwu2023             Ok(root) => Some(root),
3078bf93f0SYJwu2023             Err(err) => {
3178bf93f0SYJwu2023                 kerror!("Pci_root init failed because of error: {}", err);
3278bf93f0SYJwu2023                 None
3378bf93f0SYJwu2023             }
3478bf93f0SYJwu2023         }
3578bf93f0SYJwu2023     };
3678bf93f0SYJwu2023 }
37*2709e017SLoGin 
38*2709e017SLoGin #[inline(always)]
39*2709e017SLoGin pub fn pci_root_0() -> &'static PciRoot {
40*2709e017SLoGin     PCI_ROOT_0.as_ref().unwrap()
41*2709e017SLoGin }
42*2709e017SLoGin 
435c1e552cSYJwu2023 /// PCI域地址
445c1e552cSYJwu2023 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
455c1e552cSYJwu2023 #[repr(transparent)]
465c1e552cSYJwu2023 pub struct PciAddr(usize);
475c1e552cSYJwu2023 
485c1e552cSYJwu2023 impl PciAddr {
495c1e552cSYJwu2023     #[inline(always)]
505c1e552cSYJwu2023     pub const fn new(address: usize) -> Self {
515c1e552cSYJwu2023         Self(address)
525c1e552cSYJwu2023     }
535c1e552cSYJwu2023 
545c1e552cSYJwu2023     /// @brief 获取PCI域地址的值
555c1e552cSYJwu2023     #[inline(always)]
565c1e552cSYJwu2023     pub fn data(&self) -> usize {
575c1e552cSYJwu2023         self.0
585c1e552cSYJwu2023     }
595c1e552cSYJwu2023 
605c1e552cSYJwu2023     /// @brief 将PCI域地址加上一个偏移量
615c1e552cSYJwu2023     #[inline(always)]
625c1e552cSYJwu2023     pub fn add(self, offset: usize) -> Self {
635c1e552cSYJwu2023         Self(self.0 + offset)
645c1e552cSYJwu2023     }
655c1e552cSYJwu2023 
665c1e552cSYJwu2023     /// @brief 判断PCI域地址是否按照指定要求对齐
675c1e552cSYJwu2023     #[inline(always)]
685c1e552cSYJwu2023     pub fn check_aligned(&self, align: usize) -> bool {
695c1e552cSYJwu2023         return self.0 & (align - 1) == 0;
705c1e552cSYJwu2023     }
715c1e552cSYJwu2023 }
725c1e552cSYJwu2023 impl Debug for PciAddr {
735c1e552cSYJwu2023     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
745c1e552cSYJwu2023         write!(f, "PciAddr({:#x})", self.0)
755c1e552cSYJwu2023     }
765c1e552cSYJwu2023 }
7778bf93f0SYJwu2023 
7878bf93f0SYJwu2023 /// 添加了读写锁的链表,存储PCI设备结构体
7978bf93f0SYJwu2023 pub struct PciDeviceLinkedList {
8078bf93f0SYJwu2023     list: RwLock<LinkedList<Box<dyn PciDeviceStructure>>>,
8178bf93f0SYJwu2023 }
8278bf93f0SYJwu2023 
8378bf93f0SYJwu2023 impl PciDeviceLinkedList {
8478bf93f0SYJwu2023     /// @brief 初始化结构体
8578bf93f0SYJwu2023     fn new() -> Self {
8678bf93f0SYJwu2023         PciDeviceLinkedList {
8778bf93f0SYJwu2023             list: RwLock::new(LinkedList::new()),
8878bf93f0SYJwu2023         }
8978bf93f0SYJwu2023     }
9078bf93f0SYJwu2023     /// @brief 获取可读的linkedlist(读锁守卫)
9178bf93f0SYJwu2023     /// @return RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>>  读锁守卫
9213776c11Slogin     pub fn read(&self) -> RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
9378bf93f0SYJwu2023         self.list.read()
9478bf93f0SYJwu2023     }
9578bf93f0SYJwu2023     /// @brief 获取可写的linkedlist(写锁守卫)
9678bf93f0SYJwu2023     /// @return RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>>  写锁守卫
9713776c11Slogin     pub fn write(&self) -> RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
9878bf93f0SYJwu2023         self.list.write()
9978bf93f0SYJwu2023     }
10078bf93f0SYJwu2023     /// @brief 获取链表中PCI结构体数目
10178bf93f0SYJwu2023     /// @return usize 链表中PCI结构体数目
10278bf93f0SYJwu2023     pub fn num(&self) -> usize {
10378bf93f0SYJwu2023         let list = self.list.read();
10478bf93f0SYJwu2023         list.len()
10578bf93f0SYJwu2023     }
10678bf93f0SYJwu2023     /// @brief 添加Pci设备结构体到链表中
10778bf93f0SYJwu2023     pub fn add(&self, device: Box<dyn PciDeviceStructure>) {
10878bf93f0SYJwu2023         let mut list = self.list.write();
10978bf93f0SYJwu2023         list.push_back(device);
11078bf93f0SYJwu2023     }
11178bf93f0SYJwu2023 }
11278bf93f0SYJwu2023 
11378bf93f0SYJwu2023 /// @brief 在链表中寻找满足条件的PCI设备结构体并返回其可变引用
11478bf93f0SYJwu2023 /// @param list 链表的写锁守卫
11578bf93f0SYJwu2023 /// @param class_code 寄存器值
11678bf93f0SYJwu2023 /// @param subclass 寄存器值,与class_code一起确定设备类型
11778bf93f0SYJwu2023 /// @return Vec<&'a mut Box<(dyn PciDeviceStructure)  包含链表中所有满足条件的PCI结构体的可变引用的容器
11878bf93f0SYJwu2023 pub fn get_pci_device_structure_mut<'a>(
11978bf93f0SYJwu2023     list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
12078bf93f0SYJwu2023     class_code: u8,
12178bf93f0SYJwu2023     subclass: u8,
12278bf93f0SYJwu2023 ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
12378bf93f0SYJwu2023     let mut result = Vec::new();
12478bf93f0SYJwu2023     for box_pci_device_structure in list.iter_mut() {
12578bf93f0SYJwu2023         let common_header = (*box_pci_device_structure).common_header();
12678bf93f0SYJwu2023         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
12778bf93f0SYJwu2023             result.push(box_pci_device_structure);
12878bf93f0SYJwu2023         }
12978bf93f0SYJwu2023     }
13078bf93f0SYJwu2023     result
13178bf93f0SYJwu2023 }
13278bf93f0SYJwu2023 /// @brief 在链表中寻找满足条件的PCI设备结构体并返回其不可变引用
13378bf93f0SYJwu2023 /// @param list 链表的读锁守卫
13478bf93f0SYJwu2023 /// @param class_code 寄存器值
13578bf93f0SYJwu2023 /// @param subclass 寄存器值,与class_code一起确定设备类型
13678bf93f0SYJwu2023 /// @return Vec<&'a Box<(dyn PciDeviceStructure)  包含链表中所有满足条件的PCI结构体的不可变引用的容器
137b5b571e0SLoGin #[allow(clippy::borrowed_box)]
13878bf93f0SYJwu2023 pub fn get_pci_device_structure<'a>(
13978bf93f0SYJwu2023     list: &'a mut RwLockReadGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
14078bf93f0SYJwu2023     class_code: u8,
14178bf93f0SYJwu2023     subclass: u8,
14278bf93f0SYJwu2023 ) -> Vec<&'a Box<(dyn PciDeviceStructure)>> {
14378bf93f0SYJwu2023     let mut result = Vec::new();
14478bf93f0SYJwu2023     for box_pci_device_structure in list.iter() {
14578bf93f0SYJwu2023         let common_header = (*box_pci_device_structure).common_header();
14678bf93f0SYJwu2023         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
14778bf93f0SYJwu2023             result.push(box_pci_device_structure);
14878bf93f0SYJwu2023         }
14978bf93f0SYJwu2023     }
15078bf93f0SYJwu2023     result
15178bf93f0SYJwu2023 }
15278bf93f0SYJwu2023 
15326d84a31SYJwu2023 //Bar0寄存器的offset
15426d84a31SYJwu2023 const BAR0_OFFSET: u8 = 0x10;
15526d84a31SYJwu2023 //Status、Command寄存器的offset
15626d84a31SYJwu2023 const STATUS_COMMAND_OFFSET: u8 = 0x04;
15726d84a31SYJwu2023 /// ID for vendor-specific PCI capabilities.(Virtio Capabilities)
15826d84a31SYJwu2023 pub const PCI_CAP_ID_VNDR: u8 = 0x09;
159cc36cf4aSYJwu2023 pub const PCI_CAP_ID_MSI: u8 = 0x05;
160cc36cf4aSYJwu2023 pub const PCI_CAP_ID_MSIX: u8 = 0x11;
16178bf93f0SYJwu2023 pub const PORT_PCI_CONFIG_ADDRESS: u16 = 0xcf8;
16278bf93f0SYJwu2023 pub const PORT_PCI_CONFIG_DATA: u16 = 0xcfc;
16378bf93f0SYJwu2023 // pci设备分组的id
16478bf93f0SYJwu2023 pub type SegmentGroupNumber = u16; //理论上最多支持65535个Segment_Group
16526d84a31SYJwu2023 
16626d84a31SYJwu2023 bitflags! {
16726d84a31SYJwu2023     /// The status register in PCI configuration space.
16826d84a31SYJwu2023     pub struct Status: u16 {
16926d84a31SYJwu2023         // Bits 0-2 are reserved.
17026d84a31SYJwu2023         /// The state of the device's INTx# signal.
17126d84a31SYJwu2023         const INTERRUPT_STATUS = 1 << 3;
17226d84a31SYJwu2023         /// The device has a linked list of capabilities.
17326d84a31SYJwu2023         const CAPABILITIES_LIST = 1 << 4;
17426d84a31SYJwu2023         /// The device is capabile of running at 66 MHz rather than 33 MHz.
17526d84a31SYJwu2023         const MHZ_66_CAPABLE = 1 << 5;
17626d84a31SYJwu2023         // Bit 6 is reserved.
17726d84a31SYJwu2023         /// The device can accept fast back-to-back transactions not from the same agent.
17826d84a31SYJwu2023         const FAST_BACK_TO_BACK_CAPABLE = 1 << 7;
17926d84a31SYJwu2023         /// The bus agent observed a parity error (if parity error handling is enabled).
18026d84a31SYJwu2023         const MASTER_DATA_PARITY_ERROR = 1 << 8;
18126d84a31SYJwu2023         // Bits 9-10 are DEVSEL timing.
18226d84a31SYJwu2023         /// A target device terminated a transaction with target-abort.
18326d84a31SYJwu2023         const SIGNALED_TARGET_ABORT = 1 << 11;
18426d84a31SYJwu2023         /// A master device transaction was terminated with target-abort.
18526d84a31SYJwu2023         const RECEIVED_TARGET_ABORT = 1 << 12;
18626d84a31SYJwu2023         /// A master device transaction was terminated with master-abort.
18726d84a31SYJwu2023         const RECEIVED_MASTER_ABORT = 1 << 13;
18826d84a31SYJwu2023         /// A device asserts SERR#.
18926d84a31SYJwu2023         const SIGNALED_SYSTEM_ERROR = 1 << 14;
19026d84a31SYJwu2023         /// The device detects a parity error, even if parity error handling is disabled.
19126d84a31SYJwu2023         const DETECTED_PARITY_ERROR = 1 << 15;
19226d84a31SYJwu2023     }
19326d84a31SYJwu2023 }
19426d84a31SYJwu2023 
19526d84a31SYJwu2023 bitflags! {
19626d84a31SYJwu2023     /// The command register in PCI configuration space.
19778bf93f0SYJwu2023     pub struct Command: u16 {
19826d84a31SYJwu2023         /// The device can respond to I/O Space accesses.
19926d84a31SYJwu2023         const IO_SPACE = 1 << 0;
20026d84a31SYJwu2023         /// The device can respond to Memory Space accesses.
20126d84a31SYJwu2023         const MEMORY_SPACE = 1 << 1;
20226d84a31SYJwu2023         /// The device can behave as a bus master.
20326d84a31SYJwu2023         const BUS_MASTER = 1 << 2;
20426d84a31SYJwu2023         /// The device can monitor Special Cycle operations.
20526d84a31SYJwu2023         const SPECIAL_CYCLES = 1 << 3;
20626d84a31SYJwu2023         /// The device can generate the Memory Write and Invalidate command.
20726d84a31SYJwu2023         const MEMORY_WRITE_AND_INVALIDATE_ENABLE = 1 << 4;
20826d84a31SYJwu2023         /// The device will snoop palette register data.
20926d84a31SYJwu2023         const VGA_PALETTE_SNOOP = 1 << 5;
21026d84a31SYJwu2023         /// The device should take its normal action when a parity error is detected.
21126d84a31SYJwu2023         const PARITY_ERROR_RESPONSE = 1 << 6;
21226d84a31SYJwu2023         // Bit 7 is reserved.
21326d84a31SYJwu2023         /// The SERR# driver is enabled.
21426d84a31SYJwu2023         const SERR_ENABLE = 1 << 8;
21526d84a31SYJwu2023         /// The device is allowed to generate fast back-to-back transactions.
21626d84a31SYJwu2023         const FAST_BACK_TO_BACK_ENABLE = 1 << 9;
21726d84a31SYJwu2023         /// Assertion of the device's INTx# signal is disabled.
21826d84a31SYJwu2023         const INTERRUPT_DISABLE = 1 << 10;
21926d84a31SYJwu2023     }
22026d84a31SYJwu2023 }
22126d84a31SYJwu2023 
22278bf93f0SYJwu2023 /// The type of a PCI device function header.
22378bf93f0SYJwu2023 /// 标头类型/设备类型
22478bf93f0SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
22578bf93f0SYJwu2023 pub enum HeaderType {
22678bf93f0SYJwu2023     /// A normal PCI device.
22778bf93f0SYJwu2023     Standard,
22878bf93f0SYJwu2023     /// A PCI to PCI bridge.
22978bf93f0SYJwu2023     PciPciBridge,
23078bf93f0SYJwu2023     /// A PCI to CardBus bridge.
23178bf93f0SYJwu2023     PciCardbusBridge,
23278bf93f0SYJwu2023     /// Unrecognised header type.
23378bf93f0SYJwu2023     Unrecognised(u8),
23478bf93f0SYJwu2023 }
23578bf93f0SYJwu2023 /// u8到HeaderType的转换
23678bf93f0SYJwu2023 impl From<u8> for HeaderType {
23778bf93f0SYJwu2023     fn from(value: u8) -> Self {
23878bf93f0SYJwu2023         match value {
23978bf93f0SYJwu2023             0x00 => Self::Standard,
24078bf93f0SYJwu2023             0x01 => Self::PciPciBridge,
24178bf93f0SYJwu2023             0x02 => Self::PciCardbusBridge,
24278bf93f0SYJwu2023             _ => Self::Unrecognised(value),
24378bf93f0SYJwu2023         }
24478bf93f0SYJwu2023     }
24578bf93f0SYJwu2023 }
24678bf93f0SYJwu2023 /// Pci可能触发的各种错误
24778bf93f0SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
24878bf93f0SYJwu2023 pub enum PciError {
24978bf93f0SYJwu2023     /// The device reported an invalid BAR type.
25078bf93f0SYJwu2023     InvalidBarType,
25178bf93f0SYJwu2023     CreateMmioError,
25278bf93f0SYJwu2023     InvalidBusDeviceFunction,
25378bf93f0SYJwu2023     SegmentNotFound,
254cc36cf4aSYJwu2023     McfgTableNotFound,
25578bf93f0SYJwu2023     GetWrongHeader,
25678bf93f0SYJwu2023     UnrecognisedHeaderType,
25778bf93f0SYJwu2023     PciDeviceStructureTransformError,
258cc36cf4aSYJwu2023     PciIrqError(PciIrqError),
25978bf93f0SYJwu2023 }
26078bf93f0SYJwu2023 ///实现PciError的Display trait,使其可以直接输出
26178bf93f0SYJwu2023 impl Display for PciError {
26278bf93f0SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
26378bf93f0SYJwu2023         match self {
26478bf93f0SYJwu2023             Self::InvalidBarType => write!(f, "Invalid PCI BAR type."),
26578bf93f0SYJwu2023             Self::CreateMmioError => write!(f, "Error occurred while creating mmio."),
26678bf93f0SYJwu2023             Self::InvalidBusDeviceFunction => write!(f, "Found invalid BusDeviceFunction."),
26778bf93f0SYJwu2023             Self::SegmentNotFound => write!(f, "Target segment not found"),
268cc36cf4aSYJwu2023             Self::McfgTableNotFound => write!(f, "ACPI MCFG Table not found"),
26978bf93f0SYJwu2023             Self::GetWrongHeader => write!(f, "GetWrongHeader with vendor id 0xffff"),
27078bf93f0SYJwu2023             Self::UnrecognisedHeaderType => write!(f, "Found device with unrecognised header type"),
27178bf93f0SYJwu2023             Self::PciDeviceStructureTransformError => {
27278bf93f0SYJwu2023                 write!(f, "Found None When transform Pci device structure")
27378bf93f0SYJwu2023             }
274cc36cf4aSYJwu2023             Self::PciIrqError(err) => write!(f, "Error occurred while setting irq :{:?}.", err),
27578bf93f0SYJwu2023         }
27678bf93f0SYJwu2023     }
27778bf93f0SYJwu2023 }
27878bf93f0SYJwu2023 
27978bf93f0SYJwu2023 /// trait类型Pci_Device_Structure表示pci设备,动态绑定三种具体设备类型:Pci_Device_Structure_General_Device、Pci_Device_Structure_Pci_to_Pci_Bridge、Pci_Device_Structure_Pci_to_Cardbus_Bridge
28078bf93f0SYJwu2023 pub trait PciDeviceStructure: Send + Sync {
28178bf93f0SYJwu2023     /// @brief 获取设备类型
28278bf93f0SYJwu2023     /// @return HeaderType 设备类型
28378bf93f0SYJwu2023     fn header_type(&self) -> HeaderType;
28478bf93f0SYJwu2023     /// @brief 当其为standard设备时返回&Pci_Device_Structure_General_Device,其余情况返回None
285cc36cf4aSYJwu2023     #[inline(always)]
28678bf93f0SYJwu2023     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
28778bf93f0SYJwu2023         None
28878bf93f0SYJwu2023     }
28978bf93f0SYJwu2023     /// @brief 当其为pci to pci bridge设备时返回&Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
290cc36cf4aSYJwu2023     #[inline(always)]
29178bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
29278bf93f0SYJwu2023         None
29378bf93f0SYJwu2023     }
29478bf93f0SYJwu2023     /// @brief 当其为pci to cardbus bridge设备时返回&Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
295cc36cf4aSYJwu2023     #[inline(always)]
29678bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
29778bf93f0SYJwu2023         None
29878bf93f0SYJwu2023     }
29978bf93f0SYJwu2023     /// @brief 获取Pci设备共有的common_header
30078bf93f0SYJwu2023     /// @return 返回其不可变引用
30178bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader;
30278bf93f0SYJwu2023     /// @brief 当其为standard设备时返回&mut Pci_Device_Structure_General_Device,其余情况返回None
303cc36cf4aSYJwu2023     #[inline(always)]
30478bf93f0SYJwu2023     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
30578bf93f0SYJwu2023         None
30678bf93f0SYJwu2023     }
30778bf93f0SYJwu2023     /// @brief 当其为pci to pci bridge设备时返回&mut Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
308cc36cf4aSYJwu2023     #[inline(always)]
30978bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
31078bf93f0SYJwu2023         None
31178bf93f0SYJwu2023     }
31278bf93f0SYJwu2023     /// @brief 当其为pci to cardbus bridge设备时返回&mut Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
313cc36cf4aSYJwu2023     #[inline(always)]
31478bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device_mut(
31578bf93f0SYJwu2023         &mut self,
31678bf93f0SYJwu2023     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
31778bf93f0SYJwu2023         None
31878bf93f0SYJwu2023     }
31978bf93f0SYJwu2023     /// @brief 返回迭代器,遍历capabilities
32078bf93f0SYJwu2023     fn capabilities(&self) -> Option<CapabilityIterator> {
32178bf93f0SYJwu2023         None
32278bf93f0SYJwu2023     }
32378bf93f0SYJwu2023     /// @brief 获取Status、Command寄存器的值
32478bf93f0SYJwu2023     fn status_command(&self) -> (Status, Command) {
32578bf93f0SYJwu2023         let common_header = self.common_header();
32678bf93f0SYJwu2023         let status = Status::from_bits_truncate(common_header.status);
32778bf93f0SYJwu2023         let command = Command::from_bits_truncate(common_header.command);
32878bf93f0SYJwu2023         (status, command)
32978bf93f0SYJwu2023     }
33078bf93f0SYJwu2023     /// @brief 设置Command寄存器的值
33178bf93f0SYJwu2023     fn set_command(&mut self, command: Command) {
33278bf93f0SYJwu2023         let common_header = self.common_header_mut();
33378bf93f0SYJwu2023         let command = command.bits();
33478bf93f0SYJwu2023         common_header.command = command;
335*2709e017SLoGin         pci_root_0().write_config(
336*2709e017SLoGin             common_header.bus_device_function,
337*2709e017SLoGin             STATUS_COMMAND_OFFSET.into(),
33878bf93f0SYJwu2023             command as u32,
33978bf93f0SYJwu2023         );
34078bf93f0SYJwu2023     }
34178bf93f0SYJwu2023     /// @brief 获取Pci设备共有的common_header
34278bf93f0SYJwu2023     /// @return 返回其可变引用
34378bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader;
344cc36cf4aSYJwu2023 
34578bf93f0SYJwu2023     /// @brief 读取standard设备的bar寄存器,映射后将结果加入结构体的standard_device_bar变量
34678bf93f0SYJwu2023     /// @return 只有standard设备才返回成功或者错误,其余返回None
347cc36cf4aSYJwu2023     #[inline(always)]
348cc36cf4aSYJwu2023     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
34978bf93f0SYJwu2023         None
35078bf93f0SYJwu2023     }
351cc36cf4aSYJwu2023     /// @brief 获取PCI设备的bar寄存器的引用
352cc36cf4aSYJwu2023     /// @return
353cc36cf4aSYJwu2023     #[inline(always)]
354cc36cf4aSYJwu2023     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
35578bf93f0SYJwu2023         None
35678bf93f0SYJwu2023     }
357cc36cf4aSYJwu2023     /// @brief 通过设置该pci设备的command
35878bf93f0SYJwu2023     fn enable_master(&mut self) {
35978bf93f0SYJwu2023         self.set_command(Command::IO_SPACE | Command::MEMORY_SPACE | Command::BUS_MASTER);
36078bf93f0SYJwu2023     }
361cc36cf4aSYJwu2023     /// @brief 寻找设备的msix空间的offset
362cc36cf4aSYJwu2023     fn msix_capability_offset(&self) -> Option<u8> {
363cc36cf4aSYJwu2023         for capability in self.capabilities()? {
364cc36cf4aSYJwu2023             if capability.id == PCI_CAP_ID_MSIX {
365cc36cf4aSYJwu2023                 return Some(capability.offset);
366cc36cf4aSYJwu2023             }
367cc36cf4aSYJwu2023         }
368cc36cf4aSYJwu2023         None
369cc36cf4aSYJwu2023     }
370cc36cf4aSYJwu2023     /// @brief 寻找设备的msi空间的offset
371cc36cf4aSYJwu2023     fn msi_capability_offset(&self) -> Option<u8> {
372cc36cf4aSYJwu2023         for capability in self.capabilities()? {
373cc36cf4aSYJwu2023             if capability.id == PCI_CAP_ID_MSI {
374cc36cf4aSYJwu2023                 return Some(capability.offset);
375cc36cf4aSYJwu2023             }
376cc36cf4aSYJwu2023         }
377cc36cf4aSYJwu2023         None
378cc36cf4aSYJwu2023     }
379cc36cf4aSYJwu2023     /// @brief 返回结构体中的irq_type的可变引用
380cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType>;
381cc36cf4aSYJwu2023     /// @brief 返回结构体中的irq_vector的可变引用
382e2841179SLoGin     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>>;
38378bf93f0SYJwu2023 }
38478bf93f0SYJwu2023 
38578bf93f0SYJwu2023 /// Pci_Device_Structure_Header PCI设备结构体共有的头部
38678bf93f0SYJwu2023 #[derive(Clone, Debug)]
38778bf93f0SYJwu2023 pub struct PciDeviceStructureHeader {
38878bf93f0SYJwu2023     // ==== busdevicefunction变量表示该结构体所处的位置
38978bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
39078bf93f0SYJwu2023     pub vendor_id: u16, // 供应商ID 0xffff是一个无效值,在读取访问不存在的设备的配置空间寄存器时返回
39178bf93f0SYJwu2023     pub device_id: u16, // 设备ID,标志特定设备
39278bf93f0SYJwu2023     pub command: u16, // 提供对设备生成和响应pci周期的能力的控制 向该寄存器写入0时,设备与pci总线断开除配置空间访问以外的所有连接
39378bf93f0SYJwu2023     pub status: u16,  // 用于记录pci总线相关时间的状态信息寄存器
39478bf93f0SYJwu2023     pub revision_id: u8, // 修订ID,指定特定设备的修订标志符
39578bf93f0SYJwu2023     pub prog_if: u8, // 编程接口字节,一个只读寄存器,指定设备具有的寄存器级别的编程接口(如果有的话)
39678bf93f0SYJwu2023     pub subclass: u8, // 子类。指定设备执行的特定功能的只读寄存器
39778bf93f0SYJwu2023     pub class_code: u8, // 类代码,一个只读寄存器,指定设备执行的功能类型
39878bf93f0SYJwu2023     pub cache_line_size: u8, // 缓存线大小:以 32 位为单位指定系统缓存线大小。设备可以限制它可以支持的缓存线大小的数量,如果不支持的值写入该字段,设备将表现得好像写入了 0 值
39978bf93f0SYJwu2023     pub latency_timer: u8,   // 延迟计时器:以 PCI 总线时钟为单位指定延迟计时器。
40078bf93f0SYJwu2023     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.
40178bf93f0SYJwu2023     pub bist: u8, // Represents that status and allows control of a devices BIST (built-in self test).
40278bf93f0SYJwu2023                   // Here is the layout of the BIST register:
40378bf93f0SYJwu2023                   // |     bit7     |    bit6    | Bits 5-4 |     Bits 3-0    |
40478bf93f0SYJwu2023                   // | BIST Capable | Start BIST | Reserved | Completion Code |
40578bf93f0SYJwu2023                   // for more details, please visit https://wiki.osdev.org/PCI
40678bf93f0SYJwu2023 }
40778bf93f0SYJwu2023 
40878bf93f0SYJwu2023 /// Pci_Device_Structure_General_Device PCI标准设备结构体
40978bf93f0SYJwu2023 #[derive(Clone, Debug)]
41078bf93f0SYJwu2023 pub struct PciDeviceStructureGeneralDevice {
41178bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
412cc36cf4aSYJwu2023     // 中断结构体,包括legacy,msi,msix三种情况
413cc36cf4aSYJwu2023     pub irq_type: IrqType,
414cc36cf4aSYJwu2023     // 使用的中断号的vec集合
415e2841179SLoGin     pub irq_vector: Vec<IrqNumber>,
41678bf93f0SYJwu2023     pub standard_device_bar: PciStandardDeviceBar,
41778bf93f0SYJwu2023     pub cardbus_cis_pointer: u32, // 指向卡信息结构,供在 CardBus 和 PCI 之间共享芯片的设备使用。
41878bf93f0SYJwu2023     pub subsystem_vendor_id: u16,
41978bf93f0SYJwu2023     pub subsystem_id: u16,
42078bf93f0SYJwu2023     pub expansion_rom_base_address: u32,
42178bf93f0SYJwu2023     pub capabilities_pointer: u8,
42278bf93f0SYJwu2023     pub reserved0: u8,
42378bf93f0SYJwu2023     pub reserved1: u16,
42478bf93f0SYJwu2023     pub reserved2: u32,
42578bf93f0SYJwu2023     pub interrupt_line: u8, // 指定设备的中断引脚连接到系统中断控制器的哪个输入,并由任何使用中断引脚的设备实现。对于 x86 架构,此寄存器对应于 PIC IRQ 编号 0-15(而不是 I/O APIC IRQ 编号),并且值0xFF定义为无连接。
42678bf93f0SYJwu2023     pub interrupt_pin: u8, // 指定设备使用的中断引脚。其中值为0x1INTA#、0x2INTB#、0x3INTC#、0x4INTD#,0x0表示设备不使用中断引脚。
42778bf93f0SYJwu2023     pub min_grant: u8, // 一个只读寄存器,用于指定设备所需的突发周期长度(以 1/4 微秒为单位)(假设时钟速率为 33 MHz)
42878bf93f0SYJwu2023     pub max_latency: u8, // 一个只读寄存器,指定设备需要多长时间访问一次 PCI 总线(以 1/4 微秒为单位)。
42978bf93f0SYJwu2023 }
43078bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructureGeneralDevice {
431cc36cf4aSYJwu2023     #[inline(always)]
43278bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
43378bf93f0SYJwu2023         HeaderType::Standard
43478bf93f0SYJwu2023     }
435cc36cf4aSYJwu2023     #[inline(always)]
43678bf93f0SYJwu2023     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
43778bf93f0SYJwu2023         Some(self)
43878bf93f0SYJwu2023     }
439cc36cf4aSYJwu2023     #[inline(always)]
44078bf93f0SYJwu2023     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
44178bf93f0SYJwu2023         Some(self)
44278bf93f0SYJwu2023     }
443cc36cf4aSYJwu2023     #[inline(always)]
44478bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
44578bf93f0SYJwu2023         &self.common_header
44678bf93f0SYJwu2023     }
447cc36cf4aSYJwu2023     #[inline(always)]
44878bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
44978bf93f0SYJwu2023         &mut self.common_header
45078bf93f0SYJwu2023     }
45178bf93f0SYJwu2023     fn capabilities(&self) -> Option<CapabilityIterator> {
45278bf93f0SYJwu2023         Some(CapabilityIterator {
45378bf93f0SYJwu2023             bus_device_function: self.common_header.bus_device_function,
45478bf93f0SYJwu2023             next_capability_offset: Some(self.capabilities_pointer),
45578bf93f0SYJwu2023         })
45678bf93f0SYJwu2023     }
457cc36cf4aSYJwu2023     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
45878bf93f0SYJwu2023         let common_header = &self.common_header;
45978bf93f0SYJwu2023         match pci_bar_init(common_header.bus_device_function) {
46078bf93f0SYJwu2023             Ok(bar) => {
46178bf93f0SYJwu2023                 self.standard_device_bar = bar;
46278bf93f0SYJwu2023                 Some(Ok(0))
46378bf93f0SYJwu2023             }
46478bf93f0SYJwu2023             Err(e) => Some(Err(e)),
46578bf93f0SYJwu2023         }
46678bf93f0SYJwu2023     }
467cc36cf4aSYJwu2023     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
468cc36cf4aSYJwu2023         Some(&self.standard_device_bar)
46978bf93f0SYJwu2023     }
470cc36cf4aSYJwu2023     #[inline(always)]
471cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
472cc36cf4aSYJwu2023         Some(&mut self.irq_type)
473cc36cf4aSYJwu2023     }
474cc36cf4aSYJwu2023     #[inline(always)]
475e2841179SLoGin     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
476cc36cf4aSYJwu2023         Some(&mut self.irq_vector)
477cc36cf4aSYJwu2023     }
478cc36cf4aSYJwu2023 }
479cc36cf4aSYJwu2023 
48078bf93f0SYJwu2023 /// Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci桥设备结构体
48178bf93f0SYJwu2023 #[derive(Clone, Debug)]
48278bf93f0SYJwu2023 pub struct PciDeviceStructurePciToPciBridge {
48378bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
484cc36cf4aSYJwu2023     // 中断结构体,包括legacy,msi,msix三种情况
485cc36cf4aSYJwu2023     pub irq_type: IrqType,
486cc36cf4aSYJwu2023     // 使用的中断号的vec集合
487e2841179SLoGin     pub irq_vector: Vec<IrqNumber>,
48878bf93f0SYJwu2023     pub bar0: u32,
48978bf93f0SYJwu2023     pub bar1: u32,
49078bf93f0SYJwu2023     pub primary_bus_number: u8,
49178bf93f0SYJwu2023     pub secondary_bus_number: u8,
49278bf93f0SYJwu2023     pub subordinate_bus_number: u8,
49378bf93f0SYJwu2023     pub secondary_latency_timer: u8,
49478bf93f0SYJwu2023     pub io_base: u8,
49578bf93f0SYJwu2023     pub io_limit: u8,
49678bf93f0SYJwu2023     pub secondary_status: u16,
49778bf93f0SYJwu2023     pub memory_base: u16,
49878bf93f0SYJwu2023     pub memory_limit: u16,
49978bf93f0SYJwu2023     pub prefetchable_memory_base: u16,
50078bf93f0SYJwu2023     pub prefetchable_memory_limit: u16,
50178bf93f0SYJwu2023     pub prefetchable_base_upper_32_bits: u32,
50278bf93f0SYJwu2023     pub prefetchable_limit_upper_32_bits: u32,
50378bf93f0SYJwu2023     pub io_base_upper_16_bits: u16,
50478bf93f0SYJwu2023     pub io_limit_upper_16_bits: u16,
50578bf93f0SYJwu2023     pub capability_pointer: u8,
50678bf93f0SYJwu2023     pub reserved0: u8,
50778bf93f0SYJwu2023     pub reserved1: u16,
50878bf93f0SYJwu2023     pub expansion_rom_base_address: u32,
50978bf93f0SYJwu2023     pub interrupt_line: u8,
51078bf93f0SYJwu2023     pub interrupt_pin: u8,
51178bf93f0SYJwu2023     pub bridge_control: u16,
51278bf93f0SYJwu2023 }
51378bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructurePciToPciBridge {
514cc36cf4aSYJwu2023     #[inline(always)]
51578bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
51678bf93f0SYJwu2023         HeaderType::PciPciBridge
51778bf93f0SYJwu2023     }
518cc36cf4aSYJwu2023     #[inline(always)]
51978bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
52078bf93f0SYJwu2023         Some(self)
52178bf93f0SYJwu2023     }
522cc36cf4aSYJwu2023     #[inline(always)]
52378bf93f0SYJwu2023     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
52478bf93f0SYJwu2023         Some(self)
52578bf93f0SYJwu2023     }
526cc36cf4aSYJwu2023     #[inline(always)]
52778bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
52878bf93f0SYJwu2023         &self.common_header
52978bf93f0SYJwu2023     }
530cc36cf4aSYJwu2023     #[inline(always)]
53178bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
53278bf93f0SYJwu2023         &mut self.common_header
53378bf93f0SYJwu2023     }
534cc36cf4aSYJwu2023     #[inline(always)]
535cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
536cc36cf4aSYJwu2023         Some(&mut self.irq_type)
537cc36cf4aSYJwu2023     }
538cc36cf4aSYJwu2023     #[inline(always)]
539e2841179SLoGin     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
540cc36cf4aSYJwu2023         Some(&mut self.irq_vector)
541cc36cf4aSYJwu2023     }
54278bf93f0SYJwu2023 }
54378bf93f0SYJwu2023 /// Pci_Device_Structure_Pci_to_Cardbus_Bridge Pci_to_Cardbus桥设备结构体
54478bf93f0SYJwu2023 #[derive(Clone, Debug)]
54578bf93f0SYJwu2023 pub struct PciDeviceStructurePciToCardbusBridge {
54678bf93f0SYJwu2023     pub common_header: PciDeviceStructureHeader,
54778bf93f0SYJwu2023     pub cardbus_socket_ex_ca_base_address: u32,
54878bf93f0SYJwu2023     pub offset_of_capabilities_list: u8,
54978bf93f0SYJwu2023     pub reserved: u8,
55078bf93f0SYJwu2023     pub secondary_status: u16,
55178bf93f0SYJwu2023     pub pci_bus_number: u8,
55278bf93f0SYJwu2023     pub card_bus_bus_number: u8,
55378bf93f0SYJwu2023     pub subordinate_bus_number: u8,
55478bf93f0SYJwu2023     pub card_bus_latency_timer: u8,
55578bf93f0SYJwu2023     pub memory_base_address0: u32,
55678bf93f0SYJwu2023     pub memory_limit0: u32,
55778bf93f0SYJwu2023     pub memory_base_address1: u32,
55878bf93f0SYJwu2023     pub memory_limit1: u32,
55978bf93f0SYJwu2023     pub io_base_address0: u32,
56078bf93f0SYJwu2023     pub io_limit0: u32,
56178bf93f0SYJwu2023     pub io_base_address1: u32,
56278bf93f0SYJwu2023     pub io_limit1: u32,
56378bf93f0SYJwu2023     pub interrupt_line: u8,
56478bf93f0SYJwu2023     pub interrupt_pin: u8,
56578bf93f0SYJwu2023     pub bridge_control: u16,
56678bf93f0SYJwu2023     pub subsystem_device_id: u16,
56778bf93f0SYJwu2023     pub subsystem_vendor_id: u16,
56878bf93f0SYJwu2023     pub pc_card_legacy_mode_base_address_16_bit: u32,
56978bf93f0SYJwu2023 }
57078bf93f0SYJwu2023 impl PciDeviceStructure for PciDeviceStructurePciToCardbusBridge {
571cc36cf4aSYJwu2023     #[inline(always)]
57278bf93f0SYJwu2023     fn header_type(&self) -> HeaderType {
57378bf93f0SYJwu2023         HeaderType::PciCardbusBridge
57478bf93f0SYJwu2023     }
575cc36cf4aSYJwu2023     #[inline(always)]
57678bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
577b5b571e0SLoGin         Some(self)
57878bf93f0SYJwu2023     }
579cc36cf4aSYJwu2023     #[inline(always)]
58078bf93f0SYJwu2023     fn as_pci_to_carbus_bridge_device_mut(
58178bf93f0SYJwu2023         &mut self,
58278bf93f0SYJwu2023     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
58378bf93f0SYJwu2023         Some(self)
58478bf93f0SYJwu2023     }
585cc36cf4aSYJwu2023     #[inline(always)]
58678bf93f0SYJwu2023     fn common_header(&self) -> &PciDeviceStructureHeader {
58778bf93f0SYJwu2023         &self.common_header
58878bf93f0SYJwu2023     }
589cc36cf4aSYJwu2023     #[inline(always)]
59078bf93f0SYJwu2023     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
59178bf93f0SYJwu2023         &mut self.common_header
59278bf93f0SYJwu2023     }
593cc36cf4aSYJwu2023     #[inline(always)]
594cc36cf4aSYJwu2023     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
595cc36cf4aSYJwu2023         None
596cc36cf4aSYJwu2023     }
597cc36cf4aSYJwu2023     #[inline(always)]
598e2841179SLoGin     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
599cc36cf4aSYJwu2023         None
600cc36cf4aSYJwu2023     }
60178bf93f0SYJwu2023 }
60278bf93f0SYJwu2023 
60378bf93f0SYJwu2023 /// 代表一个PCI segement greoup.
6042dd9f0c7SLoGin #[derive(Clone, Debug)]
60578bf93f0SYJwu2023 pub struct PciRoot {
6062dd9f0c7SLoGin     pub physical_address_base: PhysAddr,         //物理地址,acpi获取
6072dd9f0c7SLoGin     pub mmio_guard: Option<Arc<MMIOSpaceGuard>>, //映射后的虚拟地址,为方便访问数据这里转化成指针
60878bf93f0SYJwu2023     pub segement_group_number: SegmentGroupNumber, //segement greoup的id
60978bf93f0SYJwu2023     pub bus_begin: u8,                           //该分组中的最小bus
61078bf93f0SYJwu2023     pub bus_end: u8,                             //该分组中的最大bus
611*2709e017SLoGin     /// 配置空间访问机制
612*2709e017SLoGin     pub cam: PciCam,
61378bf93f0SYJwu2023 }
614*2709e017SLoGin 
615*2709e017SLoGin /// PCI配置空间访问机制
616*2709e017SLoGin ///
617*2709e017SLoGin /// 用于访问PCI设备的功能配置空间的一组机制。
618*2709e017SLoGin #[derive(Copy, Clone, Debug, Eq, PartialEq)]
619*2709e017SLoGin pub enum PciCam {
620*2709e017SLoGin     /// PCI内存映射配置访问机制
621*2709e017SLoGin     ///
622*2709e017SLoGin     /// 为每个设备功能提供256字节的配置空间访问。
623*2709e017SLoGin     MmioCam,
624*2709e017SLoGin     /// PCIe内存映射增强配置访问机制
625*2709e017SLoGin     ///
626*2709e017SLoGin     /// 为每个设备功能提供4千字节(4096字节)的配置空间访问。
627*2709e017SLoGin     Ecam,
628*2709e017SLoGin }
629*2709e017SLoGin 
630*2709e017SLoGin impl PciCam {
631*2709e017SLoGin     /// Returns the total size in bytes of the memory-mapped region.
632*2709e017SLoGin     pub const fn size(self) -> u32 {
633*2709e017SLoGin         match self {
634*2709e017SLoGin             Self::MmioCam => 0x1000000,
635*2709e017SLoGin             Self::Ecam => 0x10000000,
636*2709e017SLoGin         }
637*2709e017SLoGin     }
638*2709e017SLoGin }
639*2709e017SLoGin 
64078bf93f0SYJwu2023 ///线程间共享需要,该结构体只需要在初始化时写入数据,无需读写锁保证线程安全
64178bf93f0SYJwu2023 unsafe impl Send for PciRoot {}
64278bf93f0SYJwu2023 unsafe impl Sync for PciRoot {}
64378bf93f0SYJwu2023 ///实现PciRoot的Display trait,自定义输出
64478bf93f0SYJwu2023 impl Display for PciRoot {
64578bf93f0SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
64678bf93f0SYJwu2023         write!(
64778bf93f0SYJwu2023                 f,
6482dd9f0c7SLoGin                 "PCI Root with segement:{}, bus begin at {}, bus end at {}, physical address at {:?},mapped at {:?}",
6492dd9f0c7SLoGin                 self.segement_group_number, self.bus_begin, self.bus_end, self.physical_address_base, self.mmio_guard
65078bf93f0SYJwu2023             )
65178bf93f0SYJwu2023     }
65278bf93f0SYJwu2023 }
65378bf93f0SYJwu2023 
65478bf93f0SYJwu2023 impl PciRoot {
655*2709e017SLoGin     /// 此函数用于初始化一个PciRoot结构体实例,
656*2709e017SLoGin     /// 该结构体基于ECAM根的物理地址,将其映射到虚拟地址
657*2709e017SLoGin     ///
658*2709e017SLoGin     /// ## 参数
659*2709e017SLoGin     ///
660*2709e017SLoGin     /// - segment_group_number: ECAM根的段组号。
661*2709e017SLoGin     /// - cam: PCI配置空间访问机制
662*2709e017SLoGin     ///
663*2709e017SLoGin     /// ## 返回值
664*2709e017SLoGin     ///
665*2709e017SLoGin     /// - Ok(Self): 初始化成功,返回一个新的结构体实例。
666*2709e017SLoGin     /// - Err(PciError): 初始化过程中发生错误,返回错误信息。
667*2709e017SLoGin     ///
668*2709e017SLoGin     /// ## 副作用
669*2709e017SLoGin     ///
670*2709e017SLoGin     /// - 成功执行后,结构体的内部状态将被初始化为包含映射后的虚拟地址。
671*2709e017SLoGin     pub fn new(segment_group_number: SegmentGroupNumber, cam: PciCam) -> Result<Self, PciError> {
672*2709e017SLoGin         assert_eq!(cam, PciCam::Ecam);
67378bf93f0SYJwu2023         let mut pci_root = PciArch::ecam_root(segment_group_number)?;
67478bf93f0SYJwu2023         pci_root.map()?;
67578bf93f0SYJwu2023         Ok(pci_root)
67678bf93f0SYJwu2023     }
67778bf93f0SYJwu2023     /// @brief  完成物理地址到虚拟地址的映射,并将虚拟地址加入mmio_base变量
67878bf93f0SYJwu2023     /// @return 返回错误或Ok(0)
67978bf93f0SYJwu2023     fn map(&mut self) -> Result<u8, PciError> {
6805c1e552cSYJwu2023         //kdebug!("bus_begin={},bus_end={}", self.bus_begin,self.bus_end);
6815c1e552cSYJwu2023         let bus_number = (self.bus_end - self.bus_begin) as u32 + 1;
6825c1e552cSYJwu2023         let bus_number_double = (bus_number - 1) / 2 + 1; //一个bus占据1MB空间,计算全部bus占据空间相对于2MB空间的个数
68340fe15e0SLoGin 
6842dd9f0c7SLoGin         let size = (bus_number_double as usize) * (PAGE_2M_SIZE as usize);
6852dd9f0c7SLoGin         unsafe {
6862dd9f0c7SLoGin             let space_guard = mmio_pool()
687b5b571e0SLoGin                 .create_mmio(size)
6882dd9f0c7SLoGin                 .map_err(|_| PciError::CreateMmioError)?;
6892dd9f0c7SLoGin             let space_guard = Arc::new(space_guard);
6902dd9f0c7SLoGin             self.mmio_guard = Some(space_guard.clone());
6912dd9f0c7SLoGin 
6927ae679ddSLoGin             assert!(space_guard
6937ae679ddSLoGin                 .map_phys(self.physical_address_base, size)
6947ae679ddSLoGin                 .is_ok());
69578bf93f0SYJwu2023         }
6962dd9f0c7SLoGin         return Ok(0);
69778bf93f0SYJwu2023     }
698*2709e017SLoGin 
699*2709e017SLoGin     /// # cam_offset - 获得要操作的寄存器相对于mmio_offset的偏移量
700*2709e017SLoGin     ///
701*2709e017SLoGin     /// 此函数用于计算一个PCI设备中特定寄存器相对于该设备的MMIO基地址的偏移量。
702*2709e017SLoGin     ///
703*2709e017SLoGin     /// ## 参数
704*2709e017SLoGin     ///
705*2709e017SLoGin     /// - `bus_device_function`: BusDeviceFunction,用于标识在同一组中的PCI设备。
706*2709e017SLoGin     /// - `register_offset`: u16,寄存器在设备中的偏移量。
707*2709e017SLoGin     ///
708*2709e017SLoGin     /// ## 返回值
709*2709e017SLoGin     ///
710*2709e017SLoGin     /// - `u32`: 成功时,返回要操作的寄存器相对于mmio_offset的偏移量。
711*2709e017SLoGin     ///
712*2709e017SLoGin     /// ## Panic
713*2709e017SLoGin     ///
714*2709e017SLoGin     /// - 此函数在参数有效性方面进行了断言,如果传入的`bus_device_function`无效,将panic。
715*2709e017SLoGin     /// - 此函数计算出的地址需要是字对齐的(即地址与0x3对齐)。如果不是,将panic。
71678bf93f0SYJwu2023     fn cam_offset(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
71778bf93f0SYJwu2023         assert!(bus_device_function.valid());
71878bf93f0SYJwu2023         let bdf = ((bus_device_function.bus - self.bus_begin) as u32) << 8
71978bf93f0SYJwu2023             | (bus_device_function.device as u32) << 3
72078bf93f0SYJwu2023             | bus_device_function.function as u32;
721*2709e017SLoGin         let address =
722*2709e017SLoGin             bdf << match self.cam {
723*2709e017SLoGin                 PciCam::MmioCam => 8,
724*2709e017SLoGin                 PciCam::Ecam => 12,
725*2709e017SLoGin             } | register_offset as u32;
72678bf93f0SYJwu2023         // Ensure that address is word-aligned.
72778bf93f0SYJwu2023         assert!(address & 0x3 == 0);
72878bf93f0SYJwu2023         address
72978bf93f0SYJwu2023     }
73078bf93f0SYJwu2023     /// @brief 通过bus_device_function和offset读取相应位置寄存器的值(32位)
73178bf93f0SYJwu2023     /// @param bus_device_function 在同一个group中pci设备的唯一标识符
73278bf93f0SYJwu2023     /// @param register_offset 寄存器在设备中的offset
73378bf93f0SYJwu2023     /// @return u32 寄存器读值结果
73413776c11Slogin     pub fn read_config(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
73578bf93f0SYJwu2023         let address = self.cam_offset(bus_device_function, register_offset);
73678bf93f0SYJwu2023         unsafe {
73778bf93f0SYJwu2023             // Right shift to convert from byte offset to word offset.
7382dd9f0c7SLoGin             ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
7392dd9f0c7SLoGin                 .add((address >> 2) as usize))
7402dd9f0c7SLoGin             .read_volatile()
74178bf93f0SYJwu2023         }
74278bf93f0SYJwu2023     }
74378bf93f0SYJwu2023 
74478bf93f0SYJwu2023     /// @brief 通过bus_device_function和offset写入相应位置寄存器值(32位)
74578bf93f0SYJwu2023     /// @param bus_device_function 在同一个group中pci设备的唯一标识符
74678bf93f0SYJwu2023     /// @param register_offset 寄存器在设备中的offset
74778bf93f0SYJwu2023     /// @param data 要写入的值
74878bf93f0SYJwu2023     pub fn write_config(
749*2709e017SLoGin         &self,
75078bf93f0SYJwu2023         bus_device_function: BusDeviceFunction,
75178bf93f0SYJwu2023         register_offset: u16,
75278bf93f0SYJwu2023         data: u32,
75378bf93f0SYJwu2023     ) {
75478bf93f0SYJwu2023         let address = self.cam_offset(bus_device_function, register_offset);
75578bf93f0SYJwu2023         // Safe because both the `mmio_base` and the address offset are properly aligned, and the
75678bf93f0SYJwu2023         // resulting pointer is within the MMIO range of the CAM.
75778bf93f0SYJwu2023         unsafe {
75878bf93f0SYJwu2023             // Right shift to convert from byte offset to word offset.
7592dd9f0c7SLoGin             ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
7602dd9f0c7SLoGin                 .add((address >> 2) as usize))
7612dd9f0c7SLoGin             .write_volatile(data)
76278bf93f0SYJwu2023         }
76378bf93f0SYJwu2023     }
76478bf93f0SYJwu2023     /// @brief 返回迭代器,遍历pcie设备的external_capabilities
76578bf93f0SYJwu2023     pub fn external_capabilities(
76678bf93f0SYJwu2023         &self,
76778bf93f0SYJwu2023         bus_device_function: BusDeviceFunction,
76878bf93f0SYJwu2023     ) -> ExternalCapabilityIterator {
76978bf93f0SYJwu2023         ExternalCapabilityIterator {
77078bf93f0SYJwu2023             root: self,
77178bf93f0SYJwu2023             bus_device_function,
77278bf93f0SYJwu2023             next_capability_offset: Some(0x100),
77378bf93f0SYJwu2023         }
77478bf93f0SYJwu2023     }
77578bf93f0SYJwu2023 }
77626d84a31SYJwu2023 /// Gets the capabilities 'pointer' for the device function, if any.
77726d84a31SYJwu2023 /// @brief 获取第一个capability 的offset
77878bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
77926d84a31SYJwu2023 /// @return Option<u8> offset
78078bf93f0SYJwu2023 pub fn capabilities_offset(bus_device_function: BusDeviceFunction) -> Option<u8> {
781*2709e017SLoGin     let result = pci_root_0().read_config(bus_device_function, STATUS_COMMAND_OFFSET.into());
78278bf93f0SYJwu2023     let status: Status = Status::from_bits_truncate((result >> 16) as u16);
78326d84a31SYJwu2023     if status.contains(Status::CAPABILITIES_LIST) {
784*2709e017SLoGin         let cap_pointer = pci_root_0().read_config(bus_device_function, 0x34) as u8 & 0xFC;
78526d84a31SYJwu2023         Some(cap_pointer)
78626d84a31SYJwu2023     } else {
78726d84a31SYJwu2023         None
78826d84a31SYJwu2023     }
78926d84a31SYJwu2023 }
79078bf93f0SYJwu2023 
79178bf93f0SYJwu2023 /// @brief 读取pci设备头部
79278bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
79378bf93f0SYJwu2023 /// @param add_to_list 是否添加到链表
79478bf93f0SYJwu2023 /// @return 返回的header(trait 类型)
79578bf93f0SYJwu2023 fn pci_read_header(
79678bf93f0SYJwu2023     bus_device_function: BusDeviceFunction,
79778bf93f0SYJwu2023     add_to_list: bool,
79878bf93f0SYJwu2023 ) -> Result<Box<dyn PciDeviceStructure>, PciError> {
79978bf93f0SYJwu2023     // 先读取公共header
800*2709e017SLoGin     let result = pci_root_0().read_config(bus_device_function, 0x00);
80178bf93f0SYJwu2023     let vendor_id = result as u16;
80278bf93f0SYJwu2023     let device_id = (result >> 16) as u16;
80378bf93f0SYJwu2023 
804*2709e017SLoGin     let result = pci_root_0().read_config(bus_device_function, 0x04);
80578bf93f0SYJwu2023     let command = result as u16;
80678bf93f0SYJwu2023     let status = (result >> 16) as u16;
80778bf93f0SYJwu2023 
808*2709e017SLoGin     let result = pci_root_0().read_config(bus_device_function, 0x08);
80978bf93f0SYJwu2023     let revision_id = result as u8;
81078bf93f0SYJwu2023     let prog_if = (result >> 8) as u8;
81178bf93f0SYJwu2023     let subclass = (result >> 16) as u8;
81278bf93f0SYJwu2023     let class_code = (result >> 24) as u8;
81378bf93f0SYJwu2023 
814*2709e017SLoGin     let result = pci_root_0().read_config(bus_device_function, 0x0c);
81578bf93f0SYJwu2023     let cache_line_size = result as u8;
81678bf93f0SYJwu2023     let latency_timer = (result >> 8) as u8;
81778bf93f0SYJwu2023     let header_type = (result >> 16) as u8;
81878bf93f0SYJwu2023     let bist = (result >> 24) as u8;
81978bf93f0SYJwu2023     if vendor_id == 0xffff {
82078bf93f0SYJwu2023         return Err(PciError::GetWrongHeader);
82178bf93f0SYJwu2023     }
82278bf93f0SYJwu2023     let header = PciDeviceStructureHeader {
82378bf93f0SYJwu2023         bus_device_function,
82478bf93f0SYJwu2023         vendor_id,
82578bf93f0SYJwu2023         device_id,
82678bf93f0SYJwu2023         command,
82778bf93f0SYJwu2023         status,
82878bf93f0SYJwu2023         revision_id,
82978bf93f0SYJwu2023         prog_if,
83078bf93f0SYJwu2023         subclass,
83178bf93f0SYJwu2023         class_code,
83278bf93f0SYJwu2023         cache_line_size,
83378bf93f0SYJwu2023         latency_timer,
83478bf93f0SYJwu2023         header_type,
83578bf93f0SYJwu2023         bist,
83678bf93f0SYJwu2023     };
83778bf93f0SYJwu2023     match HeaderType::from(header_type & 0x7f) {
83878bf93f0SYJwu2023         HeaderType::Standard => {
83978bf93f0SYJwu2023             let general_device = pci_read_general_device_header(header, &bus_device_function);
84078bf93f0SYJwu2023             let box_general_device = Box::new(general_device);
84178bf93f0SYJwu2023             let box_general_device_clone = box_general_device.clone();
84278bf93f0SYJwu2023             if add_to_list {
84378bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_general_device);
84478bf93f0SYJwu2023             }
84578bf93f0SYJwu2023             Ok(box_general_device_clone)
84678bf93f0SYJwu2023         }
84778bf93f0SYJwu2023         HeaderType::PciPciBridge => {
84878bf93f0SYJwu2023             let pci_to_pci_bridge = pci_read_pci_to_pci_bridge_header(header, &bus_device_function);
84978bf93f0SYJwu2023             let box_pci_to_pci_bridge = Box::new(pci_to_pci_bridge);
85078bf93f0SYJwu2023             let box_pci_to_pci_bridge_clone = box_pci_to_pci_bridge.clone();
85178bf93f0SYJwu2023             if add_to_list {
85278bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_pci_to_pci_bridge);
85378bf93f0SYJwu2023             }
85478bf93f0SYJwu2023             Ok(box_pci_to_pci_bridge_clone)
85578bf93f0SYJwu2023         }
85678bf93f0SYJwu2023         HeaderType::PciCardbusBridge => {
85778bf93f0SYJwu2023             let pci_cardbus_bridge =
85878bf93f0SYJwu2023                 pci_read_pci_to_cardbus_bridge_header(header, &bus_device_function);
85978bf93f0SYJwu2023             let box_pci_cardbus_bridge = Box::new(pci_cardbus_bridge);
86078bf93f0SYJwu2023             let box_pci_cardbus_bridge_clone = box_pci_cardbus_bridge.clone();
86178bf93f0SYJwu2023             if add_to_list {
86278bf93f0SYJwu2023                 PCI_DEVICE_LINKEDLIST.add(box_pci_cardbus_bridge);
86378bf93f0SYJwu2023             }
86478bf93f0SYJwu2023             Ok(box_pci_cardbus_bridge_clone)
86578bf93f0SYJwu2023         }
86678bf93f0SYJwu2023         HeaderType::Unrecognised(_) => Err(PciError::UnrecognisedHeaderType),
86778bf93f0SYJwu2023     }
86878bf93f0SYJwu2023 }
86978bf93f0SYJwu2023 
87078bf93f0SYJwu2023 /// @brief 读取type为0x0的pci设备的header
87178bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
87278bf93f0SYJwu2023 /// @param common_header 共有头部
87378bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
87478bf93f0SYJwu2023 /// @return Pci_Device_Structure_General_Device 标准设备头部
87578bf93f0SYJwu2023 fn pci_read_general_device_header(
87678bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
87778bf93f0SYJwu2023     bus_device_function: &BusDeviceFunction,
87878bf93f0SYJwu2023 ) -> PciDeviceStructureGeneralDevice {
87978bf93f0SYJwu2023     let standard_device_bar = PciStandardDeviceBar::default();
880*2709e017SLoGin     let cardbus_cis_pointer = pci_root_0().read_config(*bus_device_function, 0x28);
88178bf93f0SYJwu2023 
882*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x2c);
88378bf93f0SYJwu2023     let subsystem_vendor_id = result as u16;
88478bf93f0SYJwu2023     let subsystem_id = (result >> 16) as u16;
88578bf93f0SYJwu2023 
886*2709e017SLoGin     let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x30);
88778bf93f0SYJwu2023 
888*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x34);
88978bf93f0SYJwu2023     let capabilities_pointer = result as u8;
89078bf93f0SYJwu2023     let reserved0 = (result >> 8) as u8;
89178bf93f0SYJwu2023     let reserved1 = (result >> 16) as u16;
89278bf93f0SYJwu2023 
893*2709e017SLoGin     let reserved2 = pci_root_0().read_config(*bus_device_function, 0x38);
89478bf93f0SYJwu2023 
895*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x3c);
89678bf93f0SYJwu2023     let interrupt_line = result as u8;
89778bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
89878bf93f0SYJwu2023     let min_grant = (result >> 16) as u8;
89978bf93f0SYJwu2023     let max_latency = (result >> 24) as u8;
90078bf93f0SYJwu2023     PciDeviceStructureGeneralDevice {
90178bf93f0SYJwu2023         common_header,
902cc36cf4aSYJwu2023         irq_type: IrqType::Unused,
903cc36cf4aSYJwu2023         irq_vector: Vec::new(),
90478bf93f0SYJwu2023         standard_device_bar,
90578bf93f0SYJwu2023         cardbus_cis_pointer,
90678bf93f0SYJwu2023         subsystem_vendor_id,
90778bf93f0SYJwu2023         subsystem_id,
90878bf93f0SYJwu2023         expansion_rom_base_address,
90978bf93f0SYJwu2023         capabilities_pointer,
91078bf93f0SYJwu2023         reserved0,
91178bf93f0SYJwu2023         reserved1,
91278bf93f0SYJwu2023         reserved2,
91378bf93f0SYJwu2023         interrupt_line,
91478bf93f0SYJwu2023         interrupt_pin,
91578bf93f0SYJwu2023         min_grant,
91678bf93f0SYJwu2023         max_latency,
91778bf93f0SYJwu2023     }
91878bf93f0SYJwu2023 }
91978bf93f0SYJwu2023 
92078bf93f0SYJwu2023 /// @brief 读取type为0x1的pci设备的header
92178bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
92278bf93f0SYJwu2023 /// @param common_header 共有头部
92378bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
92478bf93f0SYJwu2023 /// @return Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci 桥设备头部
92578bf93f0SYJwu2023 fn pci_read_pci_to_pci_bridge_header(
92678bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
92778bf93f0SYJwu2023     bus_device_function: &BusDeviceFunction,
92878bf93f0SYJwu2023 ) -> PciDeviceStructurePciToPciBridge {
929*2709e017SLoGin     let bar0 = pci_root_0().read_config(*bus_device_function, 0x10);
930*2709e017SLoGin     let bar1 = pci_root_0().read_config(*bus_device_function, 0x14);
93178bf93f0SYJwu2023 
932*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x18);
93378bf93f0SYJwu2023 
93478bf93f0SYJwu2023     let primary_bus_number = result as u8;
93578bf93f0SYJwu2023     let secondary_bus_number = (result >> 8) as u8;
93678bf93f0SYJwu2023     let subordinate_bus_number = (result >> 16) as u8;
93778bf93f0SYJwu2023     let secondary_latency_timer = (result >> 24) as u8;
93878bf93f0SYJwu2023 
939*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x1c);
94078bf93f0SYJwu2023     let io_base = result as u8;
94178bf93f0SYJwu2023     let io_limit = (result >> 8) as u8;
94278bf93f0SYJwu2023     let secondary_status = (result >> 16) as u16;
94378bf93f0SYJwu2023 
944*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x20);
94578bf93f0SYJwu2023     let memory_base = result as u16;
94678bf93f0SYJwu2023     let memory_limit = (result >> 16) as u16;
94778bf93f0SYJwu2023 
948*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x24);
94978bf93f0SYJwu2023     let prefetchable_memory_base = result as u16;
95078bf93f0SYJwu2023     let prefetchable_memory_limit = (result >> 16) as u16;
95178bf93f0SYJwu2023 
952*2709e017SLoGin     let prefetchable_base_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x28);
953*2709e017SLoGin     let prefetchable_limit_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x2c);
95478bf93f0SYJwu2023 
955*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x30);
95678bf93f0SYJwu2023     let io_base_upper_16_bits = result as u16;
95778bf93f0SYJwu2023     let io_limit_upper_16_bits = (result >> 16) as u16;
95878bf93f0SYJwu2023 
959*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x34);
96078bf93f0SYJwu2023     let capability_pointer = result as u8;
96178bf93f0SYJwu2023     let reserved0 = (result >> 8) as u8;
96278bf93f0SYJwu2023     let reserved1 = (result >> 16) as u16;
96378bf93f0SYJwu2023 
964*2709e017SLoGin     let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x38);
96578bf93f0SYJwu2023 
966*2709e017SLoGin     let result = pci_root_0().read_config(*bus_device_function, 0x3c);
96778bf93f0SYJwu2023     let interrupt_line = result as u8;
96878bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
96978bf93f0SYJwu2023     let bridge_control = (result >> 16) as u16;
97078bf93f0SYJwu2023     PciDeviceStructurePciToPciBridge {
97178bf93f0SYJwu2023         common_header,
972cc36cf4aSYJwu2023         irq_type: IrqType::Unused,
973cc36cf4aSYJwu2023         irq_vector: Vec::new(),
97478bf93f0SYJwu2023         bar0,
97578bf93f0SYJwu2023         bar1,
97678bf93f0SYJwu2023         primary_bus_number,
97778bf93f0SYJwu2023         secondary_bus_number,
97878bf93f0SYJwu2023         subordinate_bus_number,
97978bf93f0SYJwu2023         secondary_latency_timer,
98078bf93f0SYJwu2023         io_base,
98178bf93f0SYJwu2023         io_limit,
98278bf93f0SYJwu2023         secondary_status,
98378bf93f0SYJwu2023         memory_base,
98478bf93f0SYJwu2023         memory_limit,
98578bf93f0SYJwu2023         prefetchable_memory_base,
98678bf93f0SYJwu2023         prefetchable_memory_limit,
98778bf93f0SYJwu2023         prefetchable_base_upper_32_bits,
98878bf93f0SYJwu2023         prefetchable_limit_upper_32_bits,
98978bf93f0SYJwu2023         io_base_upper_16_bits,
99078bf93f0SYJwu2023         io_limit_upper_16_bits,
99178bf93f0SYJwu2023         capability_pointer,
99278bf93f0SYJwu2023         reserved0,
99378bf93f0SYJwu2023         reserved1,
99478bf93f0SYJwu2023         expansion_rom_base_address,
99578bf93f0SYJwu2023         interrupt_line,
99678bf93f0SYJwu2023         interrupt_pin,
99778bf93f0SYJwu2023         bridge_control,
99878bf93f0SYJwu2023     }
99978bf93f0SYJwu2023 }
100078bf93f0SYJwu2023 
100178bf93f0SYJwu2023 /// @brief 读取type为0x2的pci设备的header
100278bf93f0SYJwu2023 /// 本函数只应被 pci_read_header()调用
100378bf93f0SYJwu2023 /// @param common_header 共有头部
100478bf93f0SYJwu2023 /// @param bus_device_function PCI设备的唯一标识
1005cc36cf4aSYJwu2023 /// @return   Pci_Device_Structure_Pci_to_Cardbus_Bridge  pci-to-cardbus 桥设备头部
100678bf93f0SYJwu2023 fn pci_read_pci_to_cardbus_bridge_header(
100778bf93f0SYJwu2023     common_header: PciDeviceStructureHeader,
100878bf93f0SYJwu2023     busdevicefunction: &BusDeviceFunction,
100978bf93f0SYJwu2023 ) -> PciDeviceStructurePciToCardbusBridge {
1010*2709e017SLoGin     let cardbus_socket_ex_ca_base_address = pci_root_0().read_config(*busdevicefunction, 0x10);
101178bf93f0SYJwu2023 
1012*2709e017SLoGin     let result = pci_root_0().read_config(*busdevicefunction, 0x14);
101378bf93f0SYJwu2023     let offset_of_capabilities_list = result as u8;
101478bf93f0SYJwu2023     let reserved = (result >> 8) as u8;
101578bf93f0SYJwu2023     let secondary_status = (result >> 16) as u16;
101678bf93f0SYJwu2023 
1017*2709e017SLoGin     let result = pci_root_0().read_config(*busdevicefunction, 0x18);
101878bf93f0SYJwu2023     let pci_bus_number = result as u8;
101978bf93f0SYJwu2023     let card_bus_bus_number = (result >> 8) as u8;
102078bf93f0SYJwu2023     let subordinate_bus_number = (result >> 16) as u8;
102178bf93f0SYJwu2023     let card_bus_latency_timer = (result >> 24) as u8;
102278bf93f0SYJwu2023 
1023*2709e017SLoGin     let memory_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x1c);
1024*2709e017SLoGin     let memory_limit0 = pci_root_0().read_config(*busdevicefunction, 0x20);
1025*2709e017SLoGin     let memory_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x24);
1026*2709e017SLoGin     let memory_limit1 = pci_root_0().read_config(*busdevicefunction, 0x28);
102778bf93f0SYJwu2023 
1028*2709e017SLoGin     let io_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x2c);
1029*2709e017SLoGin     let io_limit0 = pci_root_0().read_config(*busdevicefunction, 0x30);
1030*2709e017SLoGin     let io_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x34);
1031*2709e017SLoGin     let io_limit1 = pci_root_0().read_config(*busdevicefunction, 0x38);
1032*2709e017SLoGin     let result = pci_root_0().read_config(*busdevicefunction, 0x3c);
103378bf93f0SYJwu2023     let interrupt_line = result as u8;
103478bf93f0SYJwu2023     let interrupt_pin = (result >> 8) as u8;
103578bf93f0SYJwu2023     let bridge_control = (result >> 16) as u16;
103678bf93f0SYJwu2023 
1037*2709e017SLoGin     let result = pci_root_0().read_config(*busdevicefunction, 0x40);
103878bf93f0SYJwu2023     let subsystem_device_id = result as u16;
103978bf93f0SYJwu2023     let subsystem_vendor_id = (result >> 16) as u16;
104078bf93f0SYJwu2023 
1041*2709e017SLoGin     let pc_card_legacy_mode_base_address_16_bit =
1042*2709e017SLoGin         pci_root_0().read_config(*busdevicefunction, 0x44);
104378bf93f0SYJwu2023     PciDeviceStructurePciToCardbusBridge {
104478bf93f0SYJwu2023         common_header,
104578bf93f0SYJwu2023         cardbus_socket_ex_ca_base_address,
104678bf93f0SYJwu2023         offset_of_capabilities_list,
104778bf93f0SYJwu2023         reserved,
104878bf93f0SYJwu2023         secondary_status,
104978bf93f0SYJwu2023         pci_bus_number,
105078bf93f0SYJwu2023         card_bus_bus_number,
105178bf93f0SYJwu2023         subordinate_bus_number,
105278bf93f0SYJwu2023         card_bus_latency_timer,
105378bf93f0SYJwu2023         memory_base_address0,
105478bf93f0SYJwu2023         memory_limit0,
105578bf93f0SYJwu2023         memory_base_address1,
105678bf93f0SYJwu2023         memory_limit1,
105778bf93f0SYJwu2023         io_base_address0,
105878bf93f0SYJwu2023         io_limit0,
105978bf93f0SYJwu2023         io_base_address1,
106078bf93f0SYJwu2023         io_limit1,
106178bf93f0SYJwu2023         interrupt_line,
106278bf93f0SYJwu2023         interrupt_pin,
106378bf93f0SYJwu2023         bridge_control,
106478bf93f0SYJwu2023         subsystem_device_id,
106578bf93f0SYJwu2023         subsystem_vendor_id,
106678bf93f0SYJwu2023         pc_card_legacy_mode_base_address_16_bit,
106778bf93f0SYJwu2023     }
106878bf93f0SYJwu2023 }
106978bf93f0SYJwu2023 
107078bf93f0SYJwu2023 /// @brief 检查所有bus上的设备并将其加入链表
107178bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
107278bf93f0SYJwu2023 fn pci_check_all_buses() -> Result<u8, PciError> {
107378bf93f0SYJwu2023     kinfo!("Checking all devices in PCI bus...");
107478bf93f0SYJwu2023     let busdevicefunction = BusDeviceFunction {
107578bf93f0SYJwu2023         bus: 0,
107678bf93f0SYJwu2023         device: 0,
107778bf93f0SYJwu2023         function: 0,
107878bf93f0SYJwu2023     };
107978bf93f0SYJwu2023     let header = pci_read_header(busdevicefunction, false)?;
108078bf93f0SYJwu2023     let common_header = header.common_header();
108178bf93f0SYJwu2023     pci_check_bus(0)?;
108278bf93f0SYJwu2023     if common_header.header_type & 0x80 != 0 {
108378bf93f0SYJwu2023         for function in 1..8 {
108478bf93f0SYJwu2023             pci_check_bus(function)?;
108578bf93f0SYJwu2023         }
108678bf93f0SYJwu2023     }
108778bf93f0SYJwu2023     Ok(0)
108878bf93f0SYJwu2023 }
108978bf93f0SYJwu2023 /// @brief 检查特定设备并将其加入链表
109078bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
109178bf93f0SYJwu2023 fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciError> {
109278bf93f0SYJwu2023     //kdebug!("PCI check function {}", busdevicefunction.function);
109378bf93f0SYJwu2023     let header = match pci_read_header(busdevicefunction, true) {
109478bf93f0SYJwu2023         Ok(header) => header,
109578bf93f0SYJwu2023         Err(PciError::GetWrongHeader) => {
109678bf93f0SYJwu2023             return Ok(255);
109778bf93f0SYJwu2023         }
109878bf93f0SYJwu2023         Err(e) => {
109978bf93f0SYJwu2023             return Err(e);
110078bf93f0SYJwu2023         }
110178bf93f0SYJwu2023     };
110278bf93f0SYJwu2023     let common_header = header.common_header();
110378bf93f0SYJwu2023     if (common_header.class_code == 0x06)
110478bf93f0SYJwu2023         && (common_header.subclass == 0x04 || common_header.subclass == 0x09)
110578bf93f0SYJwu2023     {
110678bf93f0SYJwu2023         let pci_to_pci_bridge = header
110778bf93f0SYJwu2023             .as_pci_to_pci_bridge_device()
110878bf93f0SYJwu2023             .ok_or(PciError::PciDeviceStructureTransformError)?;
110978bf93f0SYJwu2023         let secondary_bus = pci_to_pci_bridge.secondary_bus_number;
111078bf93f0SYJwu2023         pci_check_bus(secondary_bus)?;
111178bf93f0SYJwu2023     }
111278bf93f0SYJwu2023     Ok(0)
111378bf93f0SYJwu2023 }
111478bf93f0SYJwu2023 
111578bf93f0SYJwu2023 /// @brief 检查device上的设备并将其加入链表
111678bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
111778bf93f0SYJwu2023 fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
111878bf93f0SYJwu2023     //kdebug!("PCI check device {}", device);
111978bf93f0SYJwu2023     let busdevicefunction = BusDeviceFunction {
112078bf93f0SYJwu2023         bus,
112178bf93f0SYJwu2023         device,
112278bf93f0SYJwu2023         function: 0,
112378bf93f0SYJwu2023     };
112478bf93f0SYJwu2023     let header = match pci_read_header(busdevicefunction, false) {
112578bf93f0SYJwu2023         Ok(header) => header,
112678bf93f0SYJwu2023         Err(PciError::GetWrongHeader) => {
112778bf93f0SYJwu2023             //设备不存在,直接返回即可,不用终止遍历
112878bf93f0SYJwu2023             return Ok(255);
112978bf93f0SYJwu2023         }
113078bf93f0SYJwu2023         Err(e) => {
113178bf93f0SYJwu2023             return Err(e);
113278bf93f0SYJwu2023         }
113378bf93f0SYJwu2023     };
113478bf93f0SYJwu2023     pci_check_function(busdevicefunction)?;
113578bf93f0SYJwu2023     let common_header = header.common_header();
113678bf93f0SYJwu2023     if common_header.header_type & 0x80 != 0 {
113778bf93f0SYJwu2023         kdebug!(
113878bf93f0SYJwu2023             "Detected multi func device in bus{},device{}",
113978bf93f0SYJwu2023             busdevicefunction.bus,
114078bf93f0SYJwu2023             busdevicefunction.device
114178bf93f0SYJwu2023         );
114278bf93f0SYJwu2023         // 这是一个多function的设备,因此查询剩余的function
114378bf93f0SYJwu2023         for function in 1..8 {
114478bf93f0SYJwu2023             let busdevicefunction = BusDeviceFunction {
114578bf93f0SYJwu2023                 bus,
114678bf93f0SYJwu2023                 device,
114778bf93f0SYJwu2023                 function,
114878bf93f0SYJwu2023             };
114978bf93f0SYJwu2023             pci_check_function(busdevicefunction)?;
115078bf93f0SYJwu2023         }
115178bf93f0SYJwu2023     }
115278bf93f0SYJwu2023     Ok(0)
115378bf93f0SYJwu2023 }
115478bf93f0SYJwu2023 /// @brief 检查该bus上的设备并将其加入链表
115578bf93f0SYJwu2023 /// @return 成功返回ok(),失败返回失败原因
115678bf93f0SYJwu2023 fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
115778bf93f0SYJwu2023     //kdebug!("PCI check bus {}", bus);
115878bf93f0SYJwu2023     for device in 0..32 {
115978bf93f0SYJwu2023         pci_check_device(bus, device)?;
116078bf93f0SYJwu2023     }
116178bf93f0SYJwu2023     Ok(0)
116278bf93f0SYJwu2023 }
11635b59005fSLoGin 
11645b59005fSLoGin /// pci初始化函数
11655b59005fSLoGin #[inline(never)]
116678bf93f0SYJwu2023 pub fn pci_init() {
116778bf93f0SYJwu2023     kinfo!("Initializing PCI bus...");
116878bf93f0SYJwu2023     if let Err(e) = pci_check_all_buses() {
116978bf93f0SYJwu2023         kerror!("pci init failed when checking bus because of error: {}", e);
117078bf93f0SYJwu2023         return;
117178bf93f0SYJwu2023     }
117278bf93f0SYJwu2023     kinfo!(
117378bf93f0SYJwu2023         "Total pci device and function num = {}",
117478bf93f0SYJwu2023         PCI_DEVICE_LINKEDLIST.num()
117578bf93f0SYJwu2023     );
117678bf93f0SYJwu2023     let list = PCI_DEVICE_LINKEDLIST.read();
117778bf93f0SYJwu2023     for box_pci_device in list.iter() {
117878bf93f0SYJwu2023         let common_header = box_pci_device.common_header();
117978bf93f0SYJwu2023         match box_pci_device.header_type() {
118078bf93f0SYJwu2023             HeaderType::Standard if common_header.status & 0x10 != 0 => {
11815c1e552cSYJwu2023                 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);
118278bf93f0SYJwu2023             }
118378bf93f0SYJwu2023             HeaderType::Standard => {
118478bf93f0SYJwu2023                 kinfo!(
118578bf93f0SYJwu2023                     "Found pci standard device with class code ={} subclass={} status={:#x} ",
118678bf93f0SYJwu2023                     common_header.class_code,
118778bf93f0SYJwu2023                     common_header.subclass,
118878bf93f0SYJwu2023                     common_header.status
118978bf93f0SYJwu2023                 );
119078bf93f0SYJwu2023             }
119178bf93f0SYJwu2023             HeaderType::PciPciBridge if common_header.status & 0x10 != 0 => {
119278bf93f0SYJwu2023                 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);
119378bf93f0SYJwu2023             }
119478bf93f0SYJwu2023             HeaderType::PciPciBridge => {
119578bf93f0SYJwu2023                 kinfo!(
119678bf93f0SYJwu2023                     "Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} ",
119778bf93f0SYJwu2023                     common_header.class_code,
119878bf93f0SYJwu2023                     common_header.subclass,
119978bf93f0SYJwu2023                     common_header.status
120078bf93f0SYJwu2023                 );
120178bf93f0SYJwu2023             }
120278bf93f0SYJwu2023             HeaderType::PciCardbusBridge => {
120378bf93f0SYJwu2023                 kinfo!(
120478bf93f0SYJwu2023                     "Found pcicardbus bridge device with class code ={} subclass={} status={:#x} ",
120578bf93f0SYJwu2023                     common_header.class_code,
120678bf93f0SYJwu2023                     common_header.subclass,
120778bf93f0SYJwu2023                     common_header.status
120878bf93f0SYJwu2023                 );
120978bf93f0SYJwu2023             }
121078bf93f0SYJwu2023             HeaderType::Unrecognised(_) => {}
121178bf93f0SYJwu2023         }
121278bf93f0SYJwu2023     }
121378bf93f0SYJwu2023     kinfo!("PCI bus initialized.");
121478bf93f0SYJwu2023 }
121578bf93f0SYJwu2023 
121626d84a31SYJwu2023 /// An identifier for a PCI bus, device and function.
121726d84a31SYJwu2023 /// PCI设备的唯一标识
121826d84a31SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
121978bf93f0SYJwu2023 pub struct BusDeviceFunction {
122026d84a31SYJwu2023     /// The PCI bus number, between 0 and 255.
122126d84a31SYJwu2023     pub bus: u8,
122226d84a31SYJwu2023     /// The device number on the bus, between 0 and 31.
122326d84a31SYJwu2023     pub device: u8,
122426d84a31SYJwu2023     /// The function number of the device, between 0 and 7.
122526d84a31SYJwu2023     pub function: u8,
122626d84a31SYJwu2023 }
122778bf93f0SYJwu2023 impl BusDeviceFunction {
122826d84a31SYJwu2023     /// Returns whether the device and function numbers are valid, i.e. the device is between 0 and
122978bf93f0SYJwu2023     ///@brief 检测BusDeviceFunction实例是否有效
123026d84a31SYJwu2023     ///@param self
123126d84a31SYJwu2023     ///@return bool 是否有效
123273c607aaSYJwu2023     #[allow(dead_code)]
123326d84a31SYJwu2023     pub fn valid(&self) -> bool {
123426d84a31SYJwu2023         self.device < 32 && self.function < 8
123526d84a31SYJwu2023     }
123626d84a31SYJwu2023 }
123778bf93f0SYJwu2023 ///实现BusDeviceFunction的Display trait,使其可以直接输出
123878bf93f0SYJwu2023 impl Display for BusDeviceFunction {
123926d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
12405c1e552cSYJwu2023         write!(
12415c1e552cSYJwu2023             f,
12425c1e552cSYJwu2023             "bus {} device {} function{}",
12435c1e552cSYJwu2023             self.bus, self.device, self.function
12445c1e552cSYJwu2023         )
124526d84a31SYJwu2023     }
124626d84a31SYJwu2023 }
124726d84a31SYJwu2023 /// The location allowed for a memory BAR.
124826d84a31SYJwu2023 /// memory BAR的三种情况
124926d84a31SYJwu2023 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
125026d84a31SYJwu2023 pub enum MemoryBarType {
125126d84a31SYJwu2023     /// The BAR has a 32-bit address and can be mapped anywhere in 32-bit address space.
125226d84a31SYJwu2023     Width32,
125326d84a31SYJwu2023     /// The BAR must be mapped below 1MiB.
125426d84a31SYJwu2023     Below1MiB,
125526d84a31SYJwu2023     /// The BAR has a 64-bit address and can be mapped anywhere in 64-bit address space.
125626d84a31SYJwu2023     Width64,
125726d84a31SYJwu2023 }
125826d84a31SYJwu2023 ///实现MemoryBarType与u8的类型转换
125926d84a31SYJwu2023 impl From<MemoryBarType> for u8 {
126026d84a31SYJwu2023     fn from(bar_type: MemoryBarType) -> Self {
126126d84a31SYJwu2023         match bar_type {
126226d84a31SYJwu2023             MemoryBarType::Width32 => 0,
126326d84a31SYJwu2023             MemoryBarType::Below1MiB => 1,
126426d84a31SYJwu2023             MemoryBarType::Width64 => 2,
126526d84a31SYJwu2023         }
126626d84a31SYJwu2023     }
126726d84a31SYJwu2023 }
126826d84a31SYJwu2023 ///实现MemoryBarType与u8的类型转换
126926d84a31SYJwu2023 impl TryFrom<u8> for MemoryBarType {
127026d84a31SYJwu2023     type Error = PciError;
127126d84a31SYJwu2023     fn try_from(value: u8) -> Result<Self, Self::Error> {
127226d84a31SYJwu2023         match value {
127326d84a31SYJwu2023             0 => Ok(Self::Width32),
127426d84a31SYJwu2023             1 => Ok(Self::Below1MiB),
127526d84a31SYJwu2023             2 => Ok(Self::Width64),
127626d84a31SYJwu2023             _ => Err(PciError::InvalidBarType),
127726d84a31SYJwu2023         }
127826d84a31SYJwu2023     }
127926d84a31SYJwu2023 }
128026d84a31SYJwu2023 
128126d84a31SYJwu2023 /// Information about a PCI Base Address Register.
128226d84a31SYJwu2023 /// BAR的三种类型 Memory/IO/Unused
12832dd9f0c7SLoGin #[derive(Clone, Debug)]
128426d84a31SYJwu2023 pub enum BarInfo {
128526d84a31SYJwu2023     /// The BAR is for a memory region.
128626d84a31SYJwu2023     Memory {
128726d84a31SYJwu2023         /// The size of the BAR address and where it can be located.
128826d84a31SYJwu2023         address_type: MemoryBarType,
128926d84a31SYJwu2023         /// If true, then reading from the region doesn't have side effects. The CPU may cache reads
129026d84a31SYJwu2023         /// and merge repeated stores.
129126d84a31SYJwu2023         prefetchable: bool,
129226d84a31SYJwu2023         /// The memory address, always 16-byte aligned.
129326d84a31SYJwu2023         address: u64,
129426d84a31SYJwu2023         /// The size of the BAR in bytes.
129526d84a31SYJwu2023         size: u32,
129626d84a31SYJwu2023         /// The virtaddress for a memory bar(mapped).
12972dd9f0c7SLoGin         mmio_guard: Arc<MMIOSpaceGuard>,
129826d84a31SYJwu2023     },
129926d84a31SYJwu2023     /// The BAR is for an I/O region.
130026d84a31SYJwu2023     IO {
130126d84a31SYJwu2023         /// The I/O address, always 4-byte aligned.
130226d84a31SYJwu2023         address: u32,
130326d84a31SYJwu2023         /// The size of the BAR in bytes.
130426d84a31SYJwu2023         size: u32,
130526d84a31SYJwu2023     },
130626d84a31SYJwu2023     Unused,
130726d84a31SYJwu2023 }
130826d84a31SYJwu2023 
130926d84a31SYJwu2023 impl BarInfo {
131026d84a31SYJwu2023     /// Returns the address and size of this BAR if it is a memory bar, or `None` if it is an IO
131126d84a31SYJwu2023     /// BAR.
131226d84a31SYJwu2023     ///@brief 得到某个bar的memory_address与size(前提是他的类型为Memory Bar)
131326d84a31SYJwu2023     ///@param self
131426d84a31SYJwu2023     ///@return Option<(u64, u32) 是Memory Bar返回内存地址与大小,不是则返回None
131526d84a31SYJwu2023     pub fn memory_address_size(&self) -> Option<(u64, u32)> {
131626d84a31SYJwu2023         if let Self::Memory { address, size, .. } = self {
131726d84a31SYJwu2023             Some((*address, *size))
131826d84a31SYJwu2023         } else {
131926d84a31SYJwu2023             None
132026d84a31SYJwu2023         }
132126d84a31SYJwu2023     }
132226d84a31SYJwu2023     ///@brief 得到某个bar的virtaddress(前提是他的类型为Memory Bar)
132326d84a31SYJwu2023     ///@param self
132426d84a31SYJwu2023     ///@return Option<(u64) 是Memory Bar返回映射的虚拟地址,不是则返回None
13252dd9f0c7SLoGin     pub fn virtual_address(&self) -> Option<VirtAddr> {
13262dd9f0c7SLoGin         if let Self::Memory { mmio_guard, .. } = self {
13272dd9f0c7SLoGin             Some(mmio_guard.vaddr())
132826d84a31SYJwu2023         } else {
132926d84a31SYJwu2023             None
133026d84a31SYJwu2023         }
133126d84a31SYJwu2023     }
133226d84a31SYJwu2023 }
133378bf93f0SYJwu2023 ///实现BarInfo的Display trait,自定义输出
133426d84a31SYJwu2023 impl Display for BarInfo {
133526d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
133626d84a31SYJwu2023         match self {
133726d84a31SYJwu2023             Self::Memory {
133826d84a31SYJwu2023                 address_type,
133926d84a31SYJwu2023                 prefetchable,
134026d84a31SYJwu2023                 address,
134126d84a31SYJwu2023                 size,
13422dd9f0c7SLoGin                 mmio_guard,
134326d84a31SYJwu2023             } => write!(
134426d84a31SYJwu2023                 f,
13452dd9f0c7SLoGin                 "Memory space at {:#010x}, size {}, type {:?}, prefetchable {}, mmio_guard: {:?}",
13462dd9f0c7SLoGin                 address, size, address_type, prefetchable, mmio_guard
134726d84a31SYJwu2023             ),
134826d84a31SYJwu2023             Self::IO { address, size } => {
134926d84a31SYJwu2023                 write!(f, "I/O space at {:#010x}, size {}", address, size)
135026d84a31SYJwu2023             }
135126d84a31SYJwu2023             Self::Unused => {
135226d84a31SYJwu2023                 write!(f, "Unused bar")
135326d84a31SYJwu2023             }
135426d84a31SYJwu2023         }
135526d84a31SYJwu2023     }
135626d84a31SYJwu2023 }
1357cc36cf4aSYJwu2023 // todo 增加对桥的bar的支持
1358cc36cf4aSYJwu2023 pub trait PciDeviceBar {}
135940fe15e0SLoGin 
136078bf93f0SYJwu2023 ///一个普通PCI设备(非桥)有6个BAR寄存器,PciStandardDeviceBar存储其全部信息
13612dd9f0c7SLoGin #[derive(Clone, Debug)]
136278bf93f0SYJwu2023 pub struct PciStandardDeviceBar {
136326d84a31SYJwu2023     bar0: BarInfo,
136426d84a31SYJwu2023     bar1: BarInfo,
136526d84a31SYJwu2023     bar2: BarInfo,
136626d84a31SYJwu2023     bar3: BarInfo,
136726d84a31SYJwu2023     bar4: BarInfo,
136826d84a31SYJwu2023     bar5: BarInfo,
136926d84a31SYJwu2023 }
137026d84a31SYJwu2023 
137178bf93f0SYJwu2023 impl PciStandardDeviceBar {
137226d84a31SYJwu2023     ///@brief 得到某个bar的barinfo
137326d84a31SYJwu2023     ///@param self ,bar_index(0-5)
137426d84a31SYJwu2023     ///@return Result<&BarInfo, PciError> bar_index在0-5则返回对应的bar_info结构体,超出范围则返回错误
137526d84a31SYJwu2023     pub fn get_bar(&self, bar_index: u8) -> Result<&BarInfo, PciError> {
137626d84a31SYJwu2023         match bar_index {
137726d84a31SYJwu2023             0 => Ok(&self.bar0),
137826d84a31SYJwu2023             1 => Ok(&self.bar1),
137926d84a31SYJwu2023             2 => Ok(&self.bar2),
138026d84a31SYJwu2023             3 => Ok(&self.bar3),
138126d84a31SYJwu2023             4 => Ok(&self.bar4),
138278bf93f0SYJwu2023             5 => Ok(&self.bar5),
138326d84a31SYJwu2023             _ => Err(PciError::InvalidBarType),
138426d84a31SYJwu2023         }
138526d84a31SYJwu2023     }
138626d84a31SYJwu2023 }
138778bf93f0SYJwu2023 ///实现PciStandardDeviceBar的Display trait,使其可以直接输出
138878bf93f0SYJwu2023 impl Display for PciStandardDeviceBar {
138926d84a31SYJwu2023     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
139026d84a31SYJwu2023         write!(
139126d84a31SYJwu2023             f,
139226d84a31SYJwu2023             "\r\nBar0:{}\r\nBar1:{}\r\nBar2:{}\r\nBar3:{}\r\nBar4:{}\r\nBar5:{}",
139326d84a31SYJwu2023             self.bar0, self.bar1, self.bar2, self.bar3, self.bar4, self.bar5
139426d84a31SYJwu2023         )
139526d84a31SYJwu2023     }
139626d84a31SYJwu2023 }
139778bf93f0SYJwu2023 ///实现PciStandardDeviceBar的Default trait,使其可以简单初始化
139878bf93f0SYJwu2023 impl Default for PciStandardDeviceBar {
139926d84a31SYJwu2023     fn default() -> Self {
140078bf93f0SYJwu2023         PciStandardDeviceBar {
140126d84a31SYJwu2023             bar0: BarInfo::Unused,
140226d84a31SYJwu2023             bar1: BarInfo::Unused,
140326d84a31SYJwu2023             bar2: BarInfo::Unused,
140426d84a31SYJwu2023             bar3: BarInfo::Unused,
140526d84a31SYJwu2023             bar4: BarInfo::Unused,
140626d84a31SYJwu2023             bar5: BarInfo::Unused,
140726d84a31SYJwu2023         }
140826d84a31SYJwu2023     }
140926d84a31SYJwu2023 }
141026d84a31SYJwu2023 
141178bf93f0SYJwu2023 ///@brief 将某个pci设备的bar寄存器读取值后映射到虚拟地址
141278bf93f0SYJwu2023 ///@param self ,bus_device_function PCI设备的唯一标识符
141378bf93f0SYJwu2023 ///@return Result<PciStandardDeviceBar, PciError> 成功则返回对应的PciStandardDeviceBar结构体,失败则返回错误类型
141478bf93f0SYJwu2023 pub fn pci_bar_init(
141578bf93f0SYJwu2023     bus_device_function: BusDeviceFunction,
141678bf93f0SYJwu2023 ) -> Result<PciStandardDeviceBar, PciError> {
141778bf93f0SYJwu2023     let mut device_bar: PciStandardDeviceBar = PciStandardDeviceBar::default();
141826d84a31SYJwu2023     let mut bar_index_ignore: u8 = 255;
141926d84a31SYJwu2023     for bar_index in 0..6 {
142026d84a31SYJwu2023         if bar_index == bar_index_ignore {
142126d84a31SYJwu2023             continue;
142226d84a31SYJwu2023         }
142326d84a31SYJwu2023         let bar_info;
1424*2709e017SLoGin         let bar_orig =
1425*2709e017SLoGin             pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
1426*2709e017SLoGin         pci_root_0().write_config(
1427*2709e017SLoGin             bus_device_function,
1428*2709e017SLoGin             (BAR0_OFFSET + 4 * bar_index).into(),
142926d84a31SYJwu2023             0xffffffff,
143026d84a31SYJwu2023         );
1431*2709e017SLoGin         let size_mask =
1432*2709e017SLoGin             pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
143326d84a31SYJwu2023         // A wrapping add is necessary to correctly handle the case of unused BARs, which read back
143426d84a31SYJwu2023         // as 0, and should be treated as size 0.
143526d84a31SYJwu2023         let size = (!(size_mask & 0xfffffff0)).wrapping_add(1);
143626d84a31SYJwu2023         //kdebug!("bar_orig:{:#x},size: {:#x}", bar_orig,size);
143726d84a31SYJwu2023         // Restore the original value.
1438*2709e017SLoGin         pci_root_0().write_config(
1439*2709e017SLoGin             bus_device_function,
1440*2709e017SLoGin             (BAR0_OFFSET + 4 * bar_index).into(),
1441*2709e017SLoGin             bar_orig,
1442*2709e017SLoGin         );
144326d84a31SYJwu2023         if size == 0 {
144426d84a31SYJwu2023             continue;
144526d84a31SYJwu2023         }
144626d84a31SYJwu2023         if bar_orig & 0x00000001 == 0x00000001 {
144726d84a31SYJwu2023             // I/O space
144826d84a31SYJwu2023             let address = bar_orig & 0xfffffffc;
144926d84a31SYJwu2023             bar_info = BarInfo::IO { address, size };
145026d84a31SYJwu2023         } else {
145126d84a31SYJwu2023             // Memory space
145226d84a31SYJwu2023             let mut address = u64::from(bar_orig & 0xfffffff0);
145326d84a31SYJwu2023             let prefetchable = bar_orig & 0x00000008 != 0;
145426d84a31SYJwu2023             let address_type = MemoryBarType::try_from(((bar_orig & 0x00000006) >> 1) as u8)?;
145526d84a31SYJwu2023             if address_type == MemoryBarType::Width64 {
145626d84a31SYJwu2023                 if bar_index >= 5 {
145726d84a31SYJwu2023                     return Err(PciError::InvalidBarType);
145826d84a31SYJwu2023                 }
1459*2709e017SLoGin                 let address_top = pci_root_0().read_config(
1460*2709e017SLoGin                     bus_device_function,
1461*2709e017SLoGin                     (BAR0_OFFSET + 4 * (bar_index + 1)).into(),
1462*2709e017SLoGin                 );
146326d84a31SYJwu2023                 address |= u64::from(address_top) << 32;
146426d84a31SYJwu2023                 bar_index_ignore = bar_index + 1; //下个bar跳过,因为64位的memory bar覆盖了两个bar
146526d84a31SYJwu2023             }
14665c1e552cSYJwu2023             let pci_address = PciAddr::new(address as usize);
14672dd9f0c7SLoGin             let paddr = PciArch::address_pci_to_physical(pci_address); //PCI总线域物理地址转换为存储器域物理地址
14682dd9f0c7SLoGin 
14692dd9f0c7SLoGin             let space_guard: Arc<MMIOSpaceGuard>;
147026d84a31SYJwu2023             unsafe {
147140fe15e0SLoGin                 let size_want = size as usize;
14722dd9f0c7SLoGin                 let tmp = mmio_pool()
14732dd9f0c7SLoGin                     .create_mmio(size_want)
14742dd9f0c7SLoGin                     .map_err(|_| PciError::CreateMmioError)?;
14752dd9f0c7SLoGin                 space_guard = Arc::new(tmp);
1476afc95d5cSYJwu2023                 //kdebug!("Pci bar init: mmio space: {space_guard:?}, paddr={paddr:?}, size_want={size_want}");
14772dd9f0c7SLoGin                 assert!(
14787ae679ddSLoGin                     space_guard.map_phys(paddr, size_want).is_ok(),
14792dd9f0c7SLoGin                     "pci_bar_init: map_phys failed"
14802dd9f0c7SLoGin                 );
148126d84a31SYJwu2023             }
148226d84a31SYJwu2023             bar_info = BarInfo::Memory {
148326d84a31SYJwu2023                 address_type,
148426d84a31SYJwu2023                 prefetchable,
148526d84a31SYJwu2023                 address,
148626d84a31SYJwu2023                 size,
14872dd9f0c7SLoGin                 mmio_guard: space_guard,
148826d84a31SYJwu2023             };
148926d84a31SYJwu2023         }
149026d84a31SYJwu2023         match bar_index {
149126d84a31SYJwu2023             0 => {
149226d84a31SYJwu2023                 device_bar.bar0 = bar_info;
149326d84a31SYJwu2023             }
149426d84a31SYJwu2023             1 => {
149526d84a31SYJwu2023                 device_bar.bar1 = bar_info;
149626d84a31SYJwu2023             }
149726d84a31SYJwu2023             2 => {
149826d84a31SYJwu2023                 device_bar.bar2 = bar_info;
149926d84a31SYJwu2023             }
150026d84a31SYJwu2023             3 => {
150126d84a31SYJwu2023                 device_bar.bar3 = bar_info;
150226d84a31SYJwu2023             }
150326d84a31SYJwu2023             4 => {
150426d84a31SYJwu2023                 device_bar.bar4 = bar_info;
150526d84a31SYJwu2023             }
150626d84a31SYJwu2023             5 => {
150726d84a31SYJwu2023                 device_bar.bar5 = bar_info;
150826d84a31SYJwu2023             }
150926d84a31SYJwu2023             _ => {}
151026d84a31SYJwu2023         }
151126d84a31SYJwu2023     }
1512afc95d5cSYJwu2023     //kdebug!("pci_device_bar:{}", device_bar);
151326d84a31SYJwu2023     return Ok(device_bar);
151426d84a31SYJwu2023 }
151526d84a31SYJwu2023 
151626d84a31SYJwu2023 /// Information about a PCI device capability.
151726d84a31SYJwu2023 /// PCI设备的capability的信息
151826d84a31SYJwu2023 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
151926d84a31SYJwu2023 pub struct CapabilityInfo {
152026d84a31SYJwu2023     /// The offset of the capability in the PCI configuration space of the device function.
152126d84a31SYJwu2023     pub offset: u8,
152226d84a31SYJwu2023     /// The ID of the capability.
152326d84a31SYJwu2023     pub id: u8,
152426d84a31SYJwu2023     /// The third and fourth bytes of the capability, to save reading them again.
152526d84a31SYJwu2023     pub private_header: u16,
152626d84a31SYJwu2023 }
152773c607aaSYJwu2023 
152826d84a31SYJwu2023 /// Iterator over capabilities for a device.
152926d84a31SYJwu2023 /// 创建迭代器以遍历PCI设备的capability
153026d84a31SYJwu2023 #[derive(Debug)]
153126d84a31SYJwu2023 pub struct CapabilityIterator {
153278bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
153326d84a31SYJwu2023     pub next_capability_offset: Option<u8>,
153426d84a31SYJwu2023 }
153526d84a31SYJwu2023 
153626d84a31SYJwu2023 impl Iterator for CapabilityIterator {
153726d84a31SYJwu2023     type Item = CapabilityInfo;
153826d84a31SYJwu2023     fn next(&mut self) -> Option<Self::Item> {
153926d84a31SYJwu2023         let offset = self.next_capability_offset?;
154026d84a31SYJwu2023 
154126d84a31SYJwu2023         // Read the first 4 bytes of the capability.
1542*2709e017SLoGin         let capability_header = pci_root_0().read_config(self.bus_device_function, offset.into());
154326d84a31SYJwu2023         let id = capability_header as u8;
154426d84a31SYJwu2023         let next_offset = (capability_header >> 8) as u8;
154526d84a31SYJwu2023         let private_header = (capability_header >> 16) as u16;
154626d84a31SYJwu2023 
154726d84a31SYJwu2023         self.next_capability_offset = if next_offset == 0 {
154826d84a31SYJwu2023             None
154926d84a31SYJwu2023         } else if next_offset < 64 || next_offset & 0x3 != 0 {
155026d84a31SYJwu2023             kwarn!("Invalid next capability offset {:#04x}", next_offset);
155126d84a31SYJwu2023             None
155226d84a31SYJwu2023         } else {
155326d84a31SYJwu2023             Some(next_offset)
155426d84a31SYJwu2023         };
155526d84a31SYJwu2023 
155626d84a31SYJwu2023         Some(CapabilityInfo {
155726d84a31SYJwu2023             offset,
155826d84a31SYJwu2023             id,
155926d84a31SYJwu2023             private_header,
156026d84a31SYJwu2023         })
156126d84a31SYJwu2023     }
156226d84a31SYJwu2023 }
156373c607aaSYJwu2023 
156478bf93f0SYJwu2023 /// Information about a PCIe device capability.
156578bf93f0SYJwu2023 /// PCIe设备的external capability的信息
156678bf93f0SYJwu2023 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
156778bf93f0SYJwu2023 pub struct ExternalCapabilityInfo {
156878bf93f0SYJwu2023     /// The offset of the capability in the PCI configuration space of the device function.
156978bf93f0SYJwu2023     pub offset: u16,
157078bf93f0SYJwu2023     /// The ID of the capability.
157178bf93f0SYJwu2023     pub id: u16,
157278bf93f0SYJwu2023     /// The third and fourth bytes of the capability, to save reading them again.
157378bf93f0SYJwu2023     pub capability_version: u8,
157473c607aaSYJwu2023 }
157578bf93f0SYJwu2023 
157678bf93f0SYJwu2023 /// Iterator over capabilities for a device.
157778bf93f0SYJwu2023 /// 创建迭代器以遍历PCIe设备的external capability
157878bf93f0SYJwu2023 #[derive(Debug)]
157978bf93f0SYJwu2023 pub struct ExternalCapabilityIterator<'a> {
158078bf93f0SYJwu2023     pub root: &'a PciRoot,
158178bf93f0SYJwu2023     pub bus_device_function: BusDeviceFunction,
158278bf93f0SYJwu2023     pub next_capability_offset: Option<u16>,
158373c607aaSYJwu2023 }
158478bf93f0SYJwu2023 impl<'a> Iterator for ExternalCapabilityIterator<'a> {
158578bf93f0SYJwu2023     type Item = ExternalCapabilityInfo;
158678bf93f0SYJwu2023     fn next(&mut self) -> Option<Self::Item> {
158778bf93f0SYJwu2023         let offset = self.next_capability_offset?;
158878bf93f0SYJwu2023 
158978bf93f0SYJwu2023         // Read the first 4 bytes of the capability.
159078bf93f0SYJwu2023         let capability_header = self.root.read_config(self.bus_device_function, offset);
159178bf93f0SYJwu2023         let id = capability_header as u16;
159278bf93f0SYJwu2023         let next_offset = (capability_header >> 20) as u16;
159378bf93f0SYJwu2023         let capability_version = ((capability_header >> 16) & 0xf) as u8;
159478bf93f0SYJwu2023 
159578bf93f0SYJwu2023         self.next_capability_offset = if next_offset == 0 {
159678bf93f0SYJwu2023             None
159778bf93f0SYJwu2023         } else if next_offset < 0x100 || next_offset & 0x3 != 0 {
159878bf93f0SYJwu2023             kwarn!("Invalid next capability offset {:#04x}", next_offset);
159978bf93f0SYJwu2023             None
160078bf93f0SYJwu2023         } else {
160178bf93f0SYJwu2023             Some(next_offset)
160278bf93f0SYJwu2023         };
160378bf93f0SYJwu2023 
160478bf93f0SYJwu2023         Some(ExternalCapabilityInfo {
160578bf93f0SYJwu2023             offset,
160678bf93f0SYJwu2023             id,
160778bf93f0SYJwu2023             capability_version,
160878bf93f0SYJwu2023         })
160978bf93f0SYJwu2023     }
161073c607aaSYJwu2023 }
1611