xref: /DragonOS/kernel/src/driver/pci/pci.rs (revision 236e88d5ef24aae4c5f6ad424404f7cbd57e42b3)
1 #![allow(dead_code)]
2 // 目前仅支持单主桥单Segment
3 
4 use super::device::pci_device_manager;
5 use super::pci_irq::{IrqType, PciIrqError};
6 use super::raw_device::PciGeneralDevice;
7 use super::root::{pci_root_0, PciRoot};
8 
9 use crate::arch::{PciArch, TraitPciArch};
10 use crate::driver::pci::subsys::pci_bus_subsys_init;
11 use crate::exception::IrqNumber;
12 use crate::libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
13 
14 use crate::mm::mmio_buddy::{mmio_pool, MMIOSpaceGuard};
15 
16 use crate::mm::VirtAddr;
17 use crate::{kdebug, kerror, kinfo, kwarn};
18 use alloc::string::String;
19 use alloc::sync::Arc;
20 use alloc::vec::Vec;
21 use alloc::{boxed::Box, collections::LinkedList};
22 use bitflags::bitflags;
23 
24 use core::{
25     convert::TryFrom,
26     fmt::{self, Debug, Display, Formatter},
27 };
28 // PCI_DEVICE_LINKEDLIST 添加了读写锁的全局链表,里面存储了检索到的PCI设备结构体
29 lazy_static! {
30     pub static ref PCI_DEVICE_LINKEDLIST: PciDeviceLinkedList = PciDeviceLinkedList::new();
31 }
32 
33 /// PCI域地址
34 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
35 #[repr(transparent)]
36 pub struct PciAddr(usize);
37 
38 impl PciAddr {
39     #[inline(always)]
40     pub const fn new(address: usize) -> Self {
41         Self(address)
42     }
43 
44     /// @brief 获取PCI域地址的值
45     #[inline(always)]
46     pub fn data(&self) -> usize {
47         self.0
48     }
49 
50     /// @brief 将PCI域地址加上一个偏移量
51     #[inline(always)]
52     pub fn add(self, offset: usize) -> Self {
53         Self(self.0 + offset)
54     }
55 
56     /// @brief 判断PCI域地址是否按照指定要求对齐
57     #[inline(always)]
58     pub fn check_aligned(&self, align: usize) -> bool {
59         return self.0 & (align - 1) == 0;
60     }
61 }
62 impl Debug for PciAddr {
63     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
64         write!(f, "PciAddr({:#x})", self.0)
65     }
66 }
67 
68 /// 添加了读写锁的链表,存储PCI设备结构体
69 pub struct PciDeviceLinkedList {
70     list: RwLock<LinkedList<Box<dyn PciDeviceStructure>>>,
71 }
72 
73 impl PciDeviceLinkedList {
74     /// @brief 初始化结构体
75     fn new() -> Self {
76         PciDeviceLinkedList {
77             list: RwLock::new(LinkedList::new()),
78         }
79     }
80     /// @brief 获取可读的linkedlist(读锁守卫)
81     /// @return RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>>  读锁守卫
82     pub fn read(&self) -> RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
83         self.list.read()
84     }
85     /// @brief 获取可写的linkedlist(写锁守卫)
86     /// @return RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>>  写锁守卫
87     pub fn write(&self) -> RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
88         self.list.write()
89     }
90     /// @brief 获取链表中PCI结构体数目
91     /// @return usize 链表中PCI结构体数目
92     pub fn num(&self) -> usize {
93         let list = self.list.read();
94         list.len()
95     }
96     /// @brief 添加Pci设备结构体到链表中
97     pub fn add(&self, device: Box<dyn PciDeviceStructure>) {
98         let mut list = self.list.write();
99         list.push_back(device);
100     }
101 }
102 
103 /// # 获取具有特定供应商ID的PCI设备结构的引用
104 ///
105 /// 这个函数通过供应商ID搜索PCI设备结构列表,并返回匹配该ID的所有设备结构的引用。
106 ///
107 /// ## 参数
108 ///
109 /// - list: 一个可变的PCI设备结构链表,类型为`&'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>`。
110 /// - vendor_id: 要查找的PCI供应商ID,类型为`u16`。
111 ///
112 /// ## 返回值
113 ///
114 /// - 返回匹配的供应商ID的PCI设备结构的引用。
115 pub fn get_pci_device_structures_mut_by_vendor_id<'a>(
116     list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
117     vendor_id: u16,
118 ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
119     let mut result = Vec::new();
120     for box_pci_device_structure in list.iter_mut() {
121         let common_header = (*box_pci_device_structure).common_header();
122         if common_header.vendor_id == vendor_id {
123             result.push(box_pci_device_structure);
124         }
125     }
126     result
127 }
128 
129 /// # get_pci_device_structure_mut - 在链表中寻找满足条件的PCI设备结构体并返回其可变引用
130 ///
131 /// 该函数遍历给定的PCI设备链表,寻找其common_header中class_code和subclass字段与给定值匹配的设备结构体。
132 /// 对于每一个匹配的设备结构体,函数返回一个可变引用。
133 ///
134 /// ## 参数
135 ///
136 /// - list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>> — 链表的写锁守卫,用于访问和遍历PCI设备链表。
137 /// - class_code: u8 — PCI设备class code寄存器值,用于分类设备的功能。
138 /// - subclass: u8 — PCI设备subclass寄存器值,与class_code一起确定设备的子类型。
139 ///
140 /// ## 返回值
141 /// - 包含链表中所有满足条件的PCI结构体的可变引用的容器。
142 pub fn get_pci_device_structure_mut<'a>(
143     list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
144     class_code: u8,
145     subclass: u8,
146 ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
147     let mut result = Vec::new();
148     for box_pci_device_structure in list.iter_mut() {
149         let common_header = (*box_pci_device_structure).common_header();
150         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
151             result.push(box_pci_device_structure);
152         }
153     }
154     result
155 }
156 
157 /// # get_pci_device_structure - 在链表中寻找满足条件的PCI设备结构体并返回其不可变引用
158 ///
159 /// 该函数遍历给定的PCI设备链表,寻找其common_header中class_code和subclass字段与给定值匹配的设备结构体。
160 /// 对于每一个匹配的设备结构体,函数返回一个可变引用。
161 ///
162 /// ## 参数
163 ///
164 /// - list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>> — 链表的写锁守卫,用于访问和遍历PCI设备链表。
165 /// - class_code: u8 — PCI设备class code寄存器值,用于分类设备的功能。
166 /// - subclass: u8 — PCI设备subclass寄存器值,与class_code一起确定设备的子类型。
167 ///
168 /// ## 返回值
169 /// - 包含链表中所有满足条件的PCI结构体的不可变引用的容器。
170 #[allow(clippy::borrowed_box)]
171 pub fn get_pci_device_structure<'a>(
172     list: &'a mut RwLockReadGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
173     class_code: u8,
174     subclass: u8,
175 ) -> Vec<&'a Box<(dyn PciDeviceStructure)>> {
176     let mut result = Vec::new();
177     for box_pci_device_structure in list.iter() {
178         let common_header = (*box_pci_device_structure).common_header();
179         if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
180             result.push(box_pci_device_structure);
181         }
182     }
183     result
184 }
185 
186 //Bar0寄存器的offset
187 const BAR0_OFFSET: u8 = 0x10;
188 //Status、Command寄存器的offset
189 const STATUS_COMMAND_OFFSET: u8 = 0x04;
190 /// ID for vendor-specific PCI capabilities.(Virtio Capabilities)
191 pub const PCI_CAP_ID_VNDR: u8 = 0x09;
192 pub const PCI_CAP_ID_MSI: u8 = 0x05;
193 pub const PCI_CAP_ID_MSIX: u8 = 0x11;
194 pub const PORT_PCI_CONFIG_ADDRESS: u16 = 0xcf8;
195 pub const PORT_PCI_CONFIG_DATA: u16 = 0xcfc;
196 // pci设备分组的id
197 pub type SegmentGroupNumber = u16; //理论上最多支持65535个Segment_Group
198 
199 bitflags! {
200     /// The status register in PCI configuration space.
201     pub struct Status: u16 {
202         // Bits 0-2 are reserved.
203         /// The state of the device's INTx# signal.
204         const INTERRUPT_STATUS = 1 << 3;
205         /// The device has a linked list of capabilities.
206         const CAPABILITIES_LIST = 1 << 4;
207         /// The device is capabile of running at 66 MHz rather than 33 MHz.
208         const MHZ_66_CAPABLE = 1 << 5;
209         // Bit 6 is reserved.
210         /// The device can accept fast back-to-back transactions not from the same agent.
211         const FAST_BACK_TO_BACK_CAPABLE = 1 << 7;
212         /// The bus agent observed a parity error (if parity error handling is enabled).
213         const MASTER_DATA_PARITY_ERROR = 1 << 8;
214         // Bits 9-10 are DEVSEL timing.
215         /// A target device terminated a transaction with target-abort.
216         const SIGNALED_TARGET_ABORT = 1 << 11;
217         /// A master device transaction was terminated with target-abort.
218         const RECEIVED_TARGET_ABORT = 1 << 12;
219         /// A master device transaction was terminated with master-abort.
220         const RECEIVED_MASTER_ABORT = 1 << 13;
221         /// A device asserts SERR#.
222         const SIGNALED_SYSTEM_ERROR = 1 << 14;
223         /// The device detects a parity error, even if parity error handling is disabled.
224         const DETECTED_PARITY_ERROR = 1 << 15;
225     }
226 }
227 
228 bitflags! {
229     /// The command register in PCI configuration space.
230     pub struct Command: u16 {
231         /// The device can respond to I/O Space accesses.
232         const IO_SPACE = 1 << 0;
233         /// The device can respond to Memory Space accesses.
234         const MEMORY_SPACE = 1 << 1;
235         /// The device can behave as a bus master.
236         const BUS_MASTER = 1 << 2;
237         /// The device can monitor Special Cycle operations.
238         const SPECIAL_CYCLES = 1 << 3;
239         /// The device can generate the Memory Write and Invalidate command.
240         const MEMORY_WRITE_AND_INVALIDATE_ENABLE = 1 << 4;
241         /// The device will snoop palette register data.
242         const VGA_PALETTE_SNOOP = 1 << 5;
243         /// The device should take its normal action when a parity error is detected.
244         const PARITY_ERROR_RESPONSE = 1 << 6;
245         // Bit 7 is reserved.
246         /// The SERR# driver is enabled.
247         const SERR_ENABLE = 1 << 8;
248         /// The device is allowed to generate fast back-to-back transactions.
249         const FAST_BACK_TO_BACK_ENABLE = 1 << 9;
250         /// Assertion of the device's INTx# signal is disabled.
251         const INTERRUPT_DISABLE = 1 << 10;
252     }
253 }
254 
255 /// The type of a PCI device function header.
256 /// 标头类型/设备类型
257 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
258 pub enum HeaderType {
259     /// A normal PCI device.
260     Standard,
261     /// A PCI to PCI bridge.
262     PciPciBridge,
263     /// A PCI to CardBus bridge.
264     PciCardbusBridge,
265     /// Unrecognised header type.
266     Unrecognised(u8),
267 }
268 /// u8到HeaderType的转换
269 impl From<u8> for HeaderType {
270     fn from(value: u8) -> Self {
271         match value {
272             0x00 => Self::Standard,
273             0x01 => Self::PciPciBridge,
274             0x02 => Self::PciCardbusBridge,
275             _ => Self::Unrecognised(value),
276         }
277     }
278 }
279 /// Pci可能触发的各种错误
280 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
281 pub enum PciError {
282     /// The device reported an invalid BAR type.
283     InvalidBarType,
284     CreateMmioError,
285     InvalidBusDeviceFunction,
286     SegmentNotFound,
287     McfgTableNotFound,
288     GetWrongHeader,
289     UnrecognisedHeaderType,
290     PciDeviceStructureTransformError,
291     PciIrqError(PciIrqError),
292 }
293 ///实现PciError的Display trait,使其可以直接输出
294 impl Display for PciError {
295     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
296         match self {
297             Self::InvalidBarType => write!(f, "Invalid PCI BAR type."),
298             Self::CreateMmioError => write!(f, "Error occurred while creating mmio."),
299             Self::InvalidBusDeviceFunction => write!(f, "Found invalid BusDeviceFunction."),
300             Self::SegmentNotFound => write!(f, "Target segment not found"),
301             Self::McfgTableNotFound => write!(f, "ACPI MCFG Table not found"),
302             Self::GetWrongHeader => write!(f, "GetWrongHeader with vendor id 0xffff"),
303             Self::UnrecognisedHeaderType => write!(f, "Found device with unrecognised header type"),
304             Self::PciDeviceStructureTransformError => {
305                 write!(f, "Found None When transform Pci device structure")
306             }
307             Self::PciIrqError(err) => write!(f, "Error occurred while setting irq :{:?}.", err),
308         }
309     }
310 }
311 
312 /// trait类型Pci_Device_Structure表示pci设备,动态绑定三种具体设备类型:Pci_Device_Structure_General_Device、Pci_Device_Structure_Pci_to_Pci_Bridge、Pci_Device_Structure_Pci_to_Cardbus_Bridge
313 pub trait PciDeviceStructure: Send + Sync {
314     /// @brief 获取设备类型
315     /// @return HeaderType 设备类型
316     fn header_type(&self) -> HeaderType;
317     /// @brief 当其为standard设备时返回&Pci_Device_Structure_General_Device,其余情况返回None
318     #[inline(always)]
319     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
320         None
321     }
322     /// @brief 当其为pci to pci bridge设备时返回&Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
323     #[inline(always)]
324     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
325         None
326     }
327     /// @brief 当其为pci to cardbus bridge设备时返回&Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
328     #[inline(always)]
329     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
330         None
331     }
332     /// @brief 获取Pci设备共有的common_header
333     /// @return 返回其不可变引用
334     fn common_header(&self) -> &PciDeviceStructureHeader;
335     /// @brief 当其为standard设备时返回&mut Pci_Device_Structure_General_Device,其余情况返回None
336     #[inline(always)]
337     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
338         None
339     }
340     /// @brief 当其为pci to pci bridge设备时返回&mut Pci_Device_Structure_Pci_to_Pci_Bridge,其余情况返回None
341     #[inline(always)]
342     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
343         None
344     }
345     /// @brief 当其为pci to cardbus bridge设备时返回&mut Pci_Device_Structure_Pci_to_Cardbus_Bridge,其余情况返回None
346     #[inline(always)]
347     fn as_pci_to_carbus_bridge_device_mut(
348         &mut self,
349     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
350         None
351     }
352     /// @brief 返回迭代器,遍历capabilities
353     fn capabilities(&self) -> Option<CapabilityIterator> {
354         None
355     }
356     /// @brief 获取Status、Command寄存器的值
357     fn status_command(&self) -> (Status, Command) {
358         let common_header = self.common_header();
359         let status = Status::from_bits_truncate(common_header.status);
360         let command = Command::from_bits_truncate(common_header.command);
361         (status, command)
362     }
363     /// @brief 设置Command寄存器的值
364     fn set_command(&mut self, command: Command) {
365         let common_header = self.common_header_mut();
366         let command = command.bits();
367         common_header.command = command;
368         pci_root_0().write_config(
369             common_header.bus_device_function,
370             STATUS_COMMAND_OFFSET.into(),
371             command as u32,
372         );
373     }
374     /// @brief 获取Pci设备共有的common_header
375     /// @return 返回其可变引用
376     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader;
377 
378     /// @brief 读取standard设备的bar寄存器,映射后将结果加入结构体的standard_device_bar变量
379     /// @return 只有standard设备才返回成功或者错误,其余返回None
380     #[inline(always)]
381     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
382         None
383     }
384     /// @brief 获取PCI设备的bar寄存器的引用
385     /// @return
386     #[inline(always)]
387     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
388         None
389     }
390     /// @brief 通过设置该pci设备的command
391     fn enable_master(&mut self) {
392         self.set_command(Command::IO_SPACE | Command::MEMORY_SPACE | Command::BUS_MASTER);
393     }
394     /// @brief 寻找设备的msix空间的offset
395     fn msix_capability_offset(&self) -> Option<u8> {
396         for capability in self.capabilities()? {
397             if capability.id == PCI_CAP_ID_MSIX {
398                 return Some(capability.offset);
399             }
400         }
401         None
402     }
403     /// @brief 寻找设备的msi空间的offset
404     fn msi_capability_offset(&self) -> Option<u8> {
405         for capability in self.capabilities()? {
406             if capability.id == PCI_CAP_ID_MSI {
407                 return Some(capability.offset);
408             }
409         }
410         None
411     }
412     /// @brief 返回结构体中的irq_type的可变引用
413     fn irq_type_mut(&mut self) -> Option<&mut IrqType>;
414     /// @brief 返回结构体中的irq_vector的可变引用
415     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>>;
416 }
417 
418 /// Pci_Device_Structure_Header PCI设备结构体共有的头部
419 #[derive(Clone, Debug)]
420 pub struct PciDeviceStructureHeader {
421     // ==== busdevicefunction变量表示该结构体所处的位置
422     pub bus_device_function: BusDeviceFunction,
423     pub vendor_id: u16, // 供应商ID 0xffff是一个无效值,在读取访问不存在的设备的配置空间寄存器时返回
424     pub device_id: u16, // 设备ID,标志特定设备
425     pub command: u16, // 提供对设备生成和响应pci周期的能力的控制 向该寄存器写入0时,设备与pci总线断开除配置空间访问以外的所有连接
426     pub status: u16,  // 用于记录pci总线相关时间的状态信息寄存器
427     pub revision_id: u8, // 修订ID,指定特定设备的修订标志符
428     pub prog_if: u8, // 编程接口字节,一个只读寄存器,指定设备具有的寄存器级别的编程接口(如果有的话)
429     pub subclass: u8, // 子类。指定设备执行的特定功能的只读寄存器
430     pub class_code: u8, // 类代码,一个只读寄存器,指定设备执行的功能类型
431     pub cache_line_size: u8, // 缓存线大小:以 32 位为单位指定系统缓存线大小。设备可以限制它可以支持的缓存线大小的数量,如果不支持的值写入该字段,设备将表现得好像写入了 0 值
432     pub latency_timer: u8,   // 延迟计时器:以 PCI 总线时钟为单位指定延迟计时器。
433     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.
434     pub bist: u8, // Represents that status and allows control of a devices BIST (built-in self test).
435                   // Here is the layout of the BIST register:
436                   // |     bit7     |    bit6    | Bits 5-4 |     Bits 3-0    |
437                   // | BIST Capable | Start BIST | Reserved | Completion Code |
438                   // for more details, please visit https://wiki.osdev.org/PCI
439 }
440 
441 /// Pci_Device_Structure_General_Device PCI标准设备结构体
442 #[derive(Clone, Debug)]
443 pub struct PciDeviceStructureGeneralDevice {
444     pub common_header: PciDeviceStructureHeader,
445     // 中断结构体,包括legacy,msi,msix三种情况
446     pub irq_type: IrqType,
447     // 使用的中断号的vec集合
448     pub irq_vector: Vec<IrqNumber>,
449     pub standard_device_bar: PciStandardDeviceBar,
450     pub cardbus_cis_pointer: u32, // 指向卡信息结构,供在 CardBus 和 PCI 之间共享芯片的设备使用。
451     pub subsystem_vendor_id: u16,
452     pub subsystem_id: u16,
453     pub expansion_rom_base_address: u32,
454     pub capabilities_pointer: u8,
455     pub reserved0: u8,
456     pub reserved1: u16,
457     pub reserved2: u32,
458     pub interrupt_line: u8, // 指定设备的中断引脚连接到系统中断控制器的哪个输入,并由任何使用中断引脚的设备实现。对于 x86 架构,此寄存器对应于 PIC IRQ 编号 0-15(而不是 I/O APIC IRQ 编号),并且值0xFF定义为无连接。
459     pub interrupt_pin: u8, // 指定设备使用的中断引脚。其中值为0x1INTA#、0x2INTB#、0x3INTC#、0x4INTD#,0x0表示设备不使用中断引脚。
460     pub min_grant: u8, // 一个只读寄存器,用于指定设备所需的突发周期长度(以 1/4 微秒为单位)(假设时钟速率为 33 MHz)
461     pub max_latency: u8, // 一个只读寄存器,指定设备需要多长时间访问一次 PCI 总线(以 1/4 微秒为单位)。
462 }
463 impl PciDeviceStructure for PciDeviceStructureGeneralDevice {
464     #[inline(always)]
465     fn header_type(&self) -> HeaderType {
466         HeaderType::Standard
467     }
468     #[inline(always)]
469     fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
470         Some(self)
471     }
472     #[inline(always)]
473     fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
474         Some(self)
475     }
476     #[inline(always)]
477     fn common_header(&self) -> &PciDeviceStructureHeader {
478         &self.common_header
479     }
480     #[inline(always)]
481     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
482         &mut self.common_header
483     }
484     fn capabilities(&self) -> Option<CapabilityIterator> {
485         Some(CapabilityIterator {
486             bus_device_function: self.common_header.bus_device_function,
487             next_capability_offset: Some(self.capabilities_pointer),
488         })
489     }
490     fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
491         let common_header = &self.common_header;
492         match pci_bar_init(common_header.bus_device_function) {
493             Ok(bar) => {
494                 self.standard_device_bar = bar;
495                 Some(Ok(0))
496             }
497             Err(e) => Some(Err(e)),
498         }
499     }
500     fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
501         Some(&self.standard_device_bar)
502     }
503     #[inline(always)]
504     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
505         Some(&mut self.irq_type)
506     }
507     #[inline(always)]
508     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
509         Some(&mut self.irq_vector)
510     }
511 }
512 
513 /// Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci桥设备结构体
514 #[derive(Clone, Debug)]
515 pub struct PciDeviceStructurePciToPciBridge {
516     pub common_header: PciDeviceStructureHeader,
517     // 中断结构体,包括legacy,msi,msix三种情况
518     pub irq_type: IrqType,
519     // 使用的中断号的vec集合
520     pub irq_vector: Vec<IrqNumber>,
521     pub bar0: u32,
522     pub bar1: u32,
523     pub primary_bus_number: u8,
524     pub secondary_bus_number: u8,
525     pub subordinate_bus_number: u8,
526     pub secondary_latency_timer: u8,
527     pub io_base: u8,
528     pub io_limit: u8,
529     pub secondary_status: u16,
530     pub memory_base: u16,
531     pub memory_limit: u16,
532     pub prefetchable_memory_base: u16,
533     pub prefetchable_memory_limit: u16,
534     pub prefetchable_base_upper_32_bits: u32,
535     pub prefetchable_limit_upper_32_bits: u32,
536     pub io_base_upper_16_bits: u16,
537     pub io_limit_upper_16_bits: u16,
538     pub capability_pointer: u8,
539     pub reserved0: u8,
540     pub reserved1: u16,
541     pub expansion_rom_base_address: u32,
542     pub interrupt_line: u8,
543     pub interrupt_pin: u8,
544     pub bridge_control: u16,
545 }
546 impl PciDeviceStructure for PciDeviceStructurePciToPciBridge {
547     #[inline(always)]
548     fn header_type(&self) -> HeaderType {
549         HeaderType::PciPciBridge
550     }
551     #[inline(always)]
552     fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
553         Some(self)
554     }
555     #[inline(always)]
556     fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
557         Some(self)
558     }
559     #[inline(always)]
560     fn common_header(&self) -> &PciDeviceStructureHeader {
561         &self.common_header
562     }
563     #[inline(always)]
564     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
565         &mut self.common_header
566     }
567     #[inline(always)]
568     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
569         Some(&mut self.irq_type)
570     }
571     #[inline(always)]
572     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
573         Some(&mut self.irq_vector)
574     }
575 }
576 /// Pci_Device_Structure_Pci_to_Cardbus_Bridge Pci_to_Cardbus桥设备结构体
577 #[derive(Clone, Debug)]
578 pub struct PciDeviceStructurePciToCardbusBridge {
579     pub common_header: PciDeviceStructureHeader,
580     pub cardbus_socket_ex_ca_base_address: u32,
581     pub offset_of_capabilities_list: u8,
582     pub reserved: u8,
583     pub secondary_status: u16,
584     pub pci_bus_number: u8,
585     pub card_bus_bus_number: u8,
586     pub subordinate_bus_number: u8,
587     pub card_bus_latency_timer: u8,
588     pub memory_base_address0: u32,
589     pub memory_limit0: u32,
590     pub memory_base_address1: u32,
591     pub memory_limit1: u32,
592     pub io_base_address0: u32,
593     pub io_limit0: u32,
594     pub io_base_address1: u32,
595     pub io_limit1: u32,
596     pub interrupt_line: u8,
597     pub interrupt_pin: u8,
598     pub bridge_control: u16,
599     pub subsystem_device_id: u16,
600     pub subsystem_vendor_id: u16,
601     pub pc_card_legacy_mode_base_address_16_bit: u32,
602 }
603 impl PciDeviceStructure for PciDeviceStructurePciToCardbusBridge {
604     #[inline(always)]
605     fn header_type(&self) -> HeaderType {
606         HeaderType::PciCardbusBridge
607     }
608     #[inline(always)]
609     fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
610         Some(self)
611     }
612     #[inline(always)]
613     fn as_pci_to_carbus_bridge_device_mut(
614         &mut self,
615     ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
616         Some(self)
617     }
618     #[inline(always)]
619     fn common_header(&self) -> &PciDeviceStructureHeader {
620         &self.common_header
621     }
622     #[inline(always)]
623     fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
624         &mut self.common_header
625     }
626     #[inline(always)]
627     fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
628         None
629     }
630     #[inline(always)]
631     fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
632         None
633     }
634 }
635 
636 /// PCI配置空间访问机制
637 ///
638 /// 用于访问PCI设备的功能配置空间的一组机制。
639 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
640 pub enum PciCam {
641     /// PCI内存映射配置访问机制
642     ///
643     /// 为每个设备功能提供256字节的配置空间访问。
644     MmioCam,
645     /// PCIe内存映射增强配置访问机制
646     ///
647     /// 为每个设备功能提供4千字节(4096字节)的配置空间访问。
648     Ecam,
649 }
650 
651 impl PciCam {
652     /// Returns the total size in bytes of the memory-mapped region.
653     pub const fn size(self) -> u32 {
654         match self {
655             Self::MmioCam => 0x1000000,
656             Self::Ecam => 0x10000000,
657         }
658     }
659 }
660 
661 /// Gets the capabilities 'pointer' for the device function, if any.
662 /// @brief 获取第一个capability 的offset
663 /// @param bus_device_function PCI设备的唯一标识
664 /// @return Option<u8> offset
665 pub fn capabilities_offset(bus_device_function: BusDeviceFunction) -> Option<u8> {
666     let result = pci_root_0().read_config(bus_device_function, STATUS_COMMAND_OFFSET.into());
667     let status: Status = Status::from_bits_truncate((result >> 16) as u16);
668     if status.contains(Status::CAPABILITIES_LIST) {
669         let cap_pointer = pci_root_0().read_config(bus_device_function, 0x34) as u8 & 0xFC;
670         Some(cap_pointer)
671     } else {
672         None
673     }
674 }
675 
676 /// @brief 读取pci设备头部
677 /// @param bus_device_function PCI设备的唯一标识
678 /// @param add_to_list 是否添加到链表
679 /// @return 返回的header(trait 类型)
680 fn pci_read_header(
681     bus_device_function: BusDeviceFunction,
682     add_to_list: bool,
683 ) -> Result<Box<dyn PciDeviceStructure>, PciError> {
684     // 先读取公共header
685     let result = pci_root_0().read_config(bus_device_function, 0x00);
686     let vendor_id = result as u16;
687     let device_id = (result >> 16) as u16;
688 
689     let result = pci_root_0().read_config(bus_device_function, 0x04);
690     let command = result as u16;
691     let status = (result >> 16) as u16;
692 
693     let result = pci_root_0().read_config(bus_device_function, 0x08);
694     let revision_id = result as u8;
695     let prog_if = (result >> 8) as u8;
696     let subclass = (result >> 16) as u8;
697     let class_code = (result >> 24) as u8;
698 
699     let result = pci_root_0().read_config(bus_device_function, 0x0c);
700     let cache_line_size = result as u8;
701     let latency_timer = (result >> 8) as u8;
702     let header_type = (result >> 16) as u8;
703     let bist = (result >> 24) as u8;
704     if vendor_id == 0xffff {
705         return Err(PciError::GetWrongHeader);
706     }
707     let header = PciDeviceStructureHeader {
708         bus_device_function,
709         vendor_id,
710         device_id,
711         command,
712         status,
713         revision_id,
714         prog_if,
715         subclass,
716         class_code,
717         cache_line_size,
718         latency_timer,
719         header_type,
720         bist,
721     };
722     match HeaderType::from(header_type & 0x7f) {
723         HeaderType::Standard => {
724             let general_device: PciDeviceStructureGeneralDevice =
725                 pci_read_general_device_header(header, &bus_device_function);
726             let box_general_device = Box::new(general_device.clone());
727             let box_general_device_clone = box_general_device.clone();
728             if add_to_list {
729                 PCI_DEVICE_LINKEDLIST.add(box_general_device);
730                 //这里实际上不应该使用clone,因为raw是用于sysfs的结构,但是实际上pci设备是在PCI_DEVICE_LINKEDLIST链表上的,
731                 //这就导致sysfs呈现的对pci设备的操控接口实际上操控的是pci设备描述符是一个副本
732                 //但是无奈这里没有使用Arc
733                 //todo:修改pci设备描述符在静态链表中存在的方式,并修改这里的clone操作
734                 let raw = PciGeneralDevice::from(&general_device);
735                 let _ = pci_device_manager().device_add(Arc::new(raw));
736             }
737             Ok(box_general_device_clone)
738         }
739         HeaderType::PciPciBridge => {
740             let pci_to_pci_bridge = pci_read_pci_to_pci_bridge_header(header, &bus_device_function);
741             let box_pci_to_pci_bridge = Box::new(pci_to_pci_bridge);
742             let box_pci_to_pci_bridge_clone = box_pci_to_pci_bridge.clone();
743             if add_to_list {
744                 PCI_DEVICE_LINKEDLIST.add(box_pci_to_pci_bridge);
745             }
746             Ok(box_pci_to_pci_bridge_clone)
747         }
748         HeaderType::PciCardbusBridge => {
749             let pci_cardbus_bridge =
750                 pci_read_pci_to_cardbus_bridge_header(header, &bus_device_function);
751             let box_pci_cardbus_bridge = Box::new(pci_cardbus_bridge);
752             let box_pci_cardbus_bridge_clone = box_pci_cardbus_bridge.clone();
753             if add_to_list {
754                 PCI_DEVICE_LINKEDLIST.add(box_pci_cardbus_bridge);
755             }
756             Ok(box_pci_cardbus_bridge_clone)
757         }
758         HeaderType::Unrecognised(_) => Err(PciError::UnrecognisedHeaderType),
759     }
760 }
761 
762 /// @brief 读取type为0x0的pci设备的header
763 /// 本函数只应被 pci_read_header()调用
764 /// @param common_header 共有头部
765 /// @param bus_device_function PCI设备的唯一标识
766 /// @return Pci_Device_Structure_General_Device 标准设备头部
767 fn pci_read_general_device_header(
768     common_header: PciDeviceStructureHeader,
769     bus_device_function: &BusDeviceFunction,
770 ) -> PciDeviceStructureGeneralDevice {
771     let standard_device_bar = PciStandardDeviceBar::default();
772     let cardbus_cis_pointer = pci_root_0().read_config(*bus_device_function, 0x28);
773 
774     let result = pci_root_0().read_config(*bus_device_function, 0x2c);
775     let subsystem_vendor_id = result as u16;
776     let subsystem_id = (result >> 16) as u16;
777 
778     let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x30);
779 
780     let result = pci_root_0().read_config(*bus_device_function, 0x34);
781     let capabilities_pointer = result as u8;
782     let reserved0 = (result >> 8) as u8;
783     let reserved1 = (result >> 16) as u16;
784 
785     let reserved2 = pci_root_0().read_config(*bus_device_function, 0x38);
786 
787     let result = pci_root_0().read_config(*bus_device_function, 0x3c);
788     let interrupt_line = result as u8;
789     let interrupt_pin = (result >> 8) as u8;
790     let min_grant = (result >> 16) as u8;
791     let max_latency = (result >> 24) as u8;
792     PciDeviceStructureGeneralDevice {
793         common_header,
794         irq_type: IrqType::Unused,
795         irq_vector: Vec::new(),
796         standard_device_bar,
797         cardbus_cis_pointer,
798         subsystem_vendor_id,
799         subsystem_id,
800         expansion_rom_base_address,
801         capabilities_pointer,
802         reserved0,
803         reserved1,
804         reserved2,
805         interrupt_line,
806         interrupt_pin,
807         min_grant,
808         max_latency,
809     }
810 }
811 
812 /// @brief 读取type为0x1的pci设备的header
813 /// 本函数只应被 pci_read_header()调用
814 /// @param common_header 共有头部
815 /// @param bus_device_function PCI设备的唯一标识
816 /// @return Pci_Device_Structure_Pci_to_Pci_Bridge pci-to-pci 桥设备头部
817 fn pci_read_pci_to_pci_bridge_header(
818     common_header: PciDeviceStructureHeader,
819     bus_device_function: &BusDeviceFunction,
820 ) -> PciDeviceStructurePciToPciBridge {
821     let bar0 = pci_root_0().read_config(*bus_device_function, 0x10);
822     let bar1 = pci_root_0().read_config(*bus_device_function, 0x14);
823 
824     let result = pci_root_0().read_config(*bus_device_function, 0x18);
825 
826     let primary_bus_number = result as u8;
827     let secondary_bus_number = (result >> 8) as u8;
828     let subordinate_bus_number = (result >> 16) as u8;
829     let secondary_latency_timer = (result >> 24) as u8;
830 
831     let result = pci_root_0().read_config(*bus_device_function, 0x1c);
832     let io_base = result as u8;
833     let io_limit = (result >> 8) as u8;
834     let secondary_status = (result >> 16) as u16;
835 
836     let result = pci_root_0().read_config(*bus_device_function, 0x20);
837     let memory_base = result as u16;
838     let memory_limit = (result >> 16) as u16;
839 
840     let result = pci_root_0().read_config(*bus_device_function, 0x24);
841     let prefetchable_memory_base = result as u16;
842     let prefetchable_memory_limit = (result >> 16) as u16;
843 
844     let prefetchable_base_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x28);
845     let prefetchable_limit_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x2c);
846 
847     let result = pci_root_0().read_config(*bus_device_function, 0x30);
848     let io_base_upper_16_bits = result as u16;
849     let io_limit_upper_16_bits = (result >> 16) as u16;
850 
851     let result = pci_root_0().read_config(*bus_device_function, 0x34);
852     let capability_pointer = result as u8;
853     let reserved0 = (result >> 8) as u8;
854     let reserved1 = (result >> 16) as u16;
855 
856     let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x38);
857 
858     let result = pci_root_0().read_config(*bus_device_function, 0x3c);
859     let interrupt_line = result as u8;
860     let interrupt_pin = (result >> 8) as u8;
861     let bridge_control = (result >> 16) as u16;
862     PciDeviceStructurePciToPciBridge {
863         common_header,
864         irq_type: IrqType::Unused,
865         irq_vector: Vec::new(),
866         bar0,
867         bar1,
868         primary_bus_number,
869         secondary_bus_number,
870         subordinate_bus_number,
871         secondary_latency_timer,
872         io_base,
873         io_limit,
874         secondary_status,
875         memory_base,
876         memory_limit,
877         prefetchable_memory_base,
878         prefetchable_memory_limit,
879         prefetchable_base_upper_32_bits,
880         prefetchable_limit_upper_32_bits,
881         io_base_upper_16_bits,
882         io_limit_upper_16_bits,
883         capability_pointer,
884         reserved0,
885         reserved1,
886         expansion_rom_base_address,
887         interrupt_line,
888         interrupt_pin,
889         bridge_control,
890     }
891 }
892 
893 /// @brief 读取type为0x2的pci设备的header
894 /// 本函数只应被 pci_read_header()调用
895 /// @param common_header 共有头部
896 /// @param bus_device_function PCI设备的唯一标识
897 /// @return   Pci_Device_Structure_Pci_to_Cardbus_Bridge  pci-to-cardbus 桥设备头部
898 fn pci_read_pci_to_cardbus_bridge_header(
899     common_header: PciDeviceStructureHeader,
900     busdevicefunction: &BusDeviceFunction,
901 ) -> PciDeviceStructurePciToCardbusBridge {
902     let cardbus_socket_ex_ca_base_address = pci_root_0().read_config(*busdevicefunction, 0x10);
903 
904     let result = pci_root_0().read_config(*busdevicefunction, 0x14);
905     let offset_of_capabilities_list = result as u8;
906     let reserved = (result >> 8) as u8;
907     let secondary_status = (result >> 16) as u16;
908 
909     let result = pci_root_0().read_config(*busdevicefunction, 0x18);
910     let pci_bus_number = result as u8;
911     let card_bus_bus_number = (result >> 8) as u8;
912     let subordinate_bus_number = (result >> 16) as u8;
913     let card_bus_latency_timer = (result >> 24) as u8;
914 
915     let memory_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x1c);
916     let memory_limit0 = pci_root_0().read_config(*busdevicefunction, 0x20);
917     let memory_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x24);
918     let memory_limit1 = pci_root_0().read_config(*busdevicefunction, 0x28);
919 
920     let io_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x2c);
921     let io_limit0 = pci_root_0().read_config(*busdevicefunction, 0x30);
922     let io_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x34);
923     let io_limit1 = pci_root_0().read_config(*busdevicefunction, 0x38);
924     let result = pci_root_0().read_config(*busdevicefunction, 0x3c);
925     let interrupt_line = result as u8;
926     let interrupt_pin = (result >> 8) as u8;
927     let bridge_control = (result >> 16) as u16;
928 
929     let result = pci_root_0().read_config(*busdevicefunction, 0x40);
930     let subsystem_device_id = result as u16;
931     let subsystem_vendor_id = (result >> 16) as u16;
932 
933     let pc_card_legacy_mode_base_address_16_bit =
934         pci_root_0().read_config(*busdevicefunction, 0x44);
935     PciDeviceStructurePciToCardbusBridge {
936         common_header,
937         cardbus_socket_ex_ca_base_address,
938         offset_of_capabilities_list,
939         reserved,
940         secondary_status,
941         pci_bus_number,
942         card_bus_bus_number,
943         subordinate_bus_number,
944         card_bus_latency_timer,
945         memory_base_address0,
946         memory_limit0,
947         memory_base_address1,
948         memory_limit1,
949         io_base_address0,
950         io_limit0,
951         io_base_address1,
952         io_limit1,
953         interrupt_line,
954         interrupt_pin,
955         bridge_control,
956         subsystem_device_id,
957         subsystem_vendor_id,
958         pc_card_legacy_mode_base_address_16_bit,
959     }
960 }
961 
962 /// @brief 检查所有bus上的设备并将其加入链表
963 /// @return 成功返回ok(),失败返回失败原因
964 fn pci_check_all_buses() -> Result<u8, PciError> {
965     kinfo!("Checking all devices in PCI bus...");
966     let busdevicefunction = BusDeviceFunction {
967         bus: 0,
968         device: 0,
969         function: 0,
970     };
971     let header = pci_read_header(busdevicefunction, false)?;
972     let common_header = header.common_header();
973     pci_check_bus(0)?;
974     if common_header.header_type & 0x80 != 0 {
975         for function in 1..8 {
976             pci_check_bus(function)?;
977         }
978     }
979     Ok(0)
980 }
981 /// @brief 检查特定设备并将其加入链表
982 /// @return 成功返回ok(),失败返回失败原因
983 fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciError> {
984     //kdebug!("PCI check function {}", busdevicefunction.function);
985     let header = match pci_read_header(busdevicefunction, true) {
986         Ok(header) => header,
987         Err(PciError::GetWrongHeader) => {
988             return Ok(255);
989         }
990         Err(e) => {
991             return Err(e);
992         }
993     };
994     let common_header = header.common_header();
995     if (common_header.class_code == 0x06)
996         && (common_header.subclass == 0x04 || common_header.subclass == 0x09)
997     {
998         let pci_to_pci_bridge = header
999             .as_pci_to_pci_bridge_device()
1000             .ok_or(PciError::PciDeviceStructureTransformError)?;
1001         let secondary_bus = pci_to_pci_bridge.secondary_bus_number;
1002         pci_check_bus(secondary_bus)?;
1003     }
1004     Ok(0)
1005 }
1006 
1007 /// @brief 检查device上的设备并将其加入链表
1008 /// @return 成功返回ok(),失败返回失败原因
1009 fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
1010     //kdebug!("PCI check device {}", device);
1011     let busdevicefunction = BusDeviceFunction {
1012         bus,
1013         device,
1014         function: 0,
1015     };
1016     let header = match pci_read_header(busdevicefunction, false) {
1017         Ok(header) => header,
1018         Err(PciError::GetWrongHeader) => {
1019             //设备不存在,直接返回即可,不用终止遍历
1020             return Ok(255);
1021         }
1022         Err(e) => {
1023             return Err(e);
1024         }
1025     };
1026     pci_check_function(busdevicefunction)?;
1027     let common_header = header.common_header();
1028     if common_header.header_type & 0x80 != 0 {
1029         kdebug!(
1030             "Detected multi func device in bus{},device{}",
1031             busdevicefunction.bus,
1032             busdevicefunction.device
1033         );
1034         // 这是一个多function的设备,因此查询剩余的function
1035         for function in 1..8 {
1036             let busdevicefunction = BusDeviceFunction {
1037                 bus,
1038                 device,
1039                 function,
1040             };
1041             pci_check_function(busdevicefunction)?;
1042         }
1043     }
1044     Ok(0)
1045 }
1046 /// @brief 检查该bus上的设备并将其加入链表
1047 /// @return 成功返回ok(),失败返回失败原因
1048 fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
1049     //kdebug!("PCI check bus {}", bus);
1050     for device in 0..32 {
1051         pci_check_device(bus, device)?;
1052     }
1053     Ok(0)
1054 }
1055 
1056 /// pci初始化函数
1057 #[inline(never)]
1058 pub fn pci_init() {
1059     kinfo!("Initializing PCI bus...");
1060     pci_bus_subsys_init().expect("Failed to init pci bus subsystem");
1061     if let Err(e) = pci_check_all_buses() {
1062         kerror!("pci init failed when checking bus because of error: {}", e);
1063         return;
1064     }
1065     kinfo!(
1066         "Total pci device and function num = {}",
1067         PCI_DEVICE_LINKEDLIST.num()
1068     );
1069     let list = PCI_DEVICE_LINKEDLIST.read();
1070     for box_pci_device in list.iter() {
1071         let common_header = box_pci_device.common_header();
1072         match box_pci_device.header_type() {
1073             HeaderType::Standard if common_header.status & 0x10 != 0 => {
1074                 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);
1075             }
1076             HeaderType::Standard => {
1077                 kinfo!(
1078                     "Found pci standard device with class code ={} subclass={} status={:#x} ",
1079                     common_header.class_code,
1080                     common_header.subclass,
1081                     common_header.status
1082                 );
1083             }
1084             HeaderType::PciPciBridge if common_header.status & 0x10 != 0 => {
1085                 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_pci_to_pci_bridge_device().unwrap().capability_pointer);
1086             }
1087             HeaderType::PciPciBridge => {
1088                 kinfo!(
1089                     "Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} ",
1090                     common_header.class_code,
1091                     common_header.subclass,
1092                     common_header.status
1093                 );
1094             }
1095             HeaderType::PciCardbusBridge => {
1096                 kinfo!(
1097                     "Found pcicardbus bridge device with class code ={} subclass={} status={:#x} ",
1098                     common_header.class_code,
1099                     common_header.subclass,
1100                     common_header.status
1101                 );
1102             }
1103             HeaderType::Unrecognised(_) => {}
1104         }
1105     }
1106 
1107     kinfo!("PCI bus initialized.");
1108 }
1109 
1110 /// An identifier for a PCI bus, device and function.
1111 /// PCI设备的唯一标识
1112 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1113 pub struct BusDeviceFunction {
1114     /// The PCI bus number, between 0 and 255.
1115     pub bus: u8,
1116     /// The device number on the bus, between 0 and 31.
1117     pub device: u8,
1118     /// The function number of the device, between 0 and 7.
1119     pub function: u8,
1120 }
1121 impl BusDeviceFunction {
1122     /// Returns whether the device and function numbers are valid, i.e. the device is between 0 and
1123     ///@brief 检测BusDeviceFunction实例是否有效
1124     ///@param self
1125     ///@return bool 是否有效
1126     #[allow(dead_code)]
1127     pub fn valid(&self) -> bool {
1128         self.device < 32 && self.function < 8
1129     }
1130 }
1131 
1132 impl From<BusDeviceFunction> for String {
1133     /// # 函数的功能
1134     /// 这里提供一个由BusDeviceFunction到dddd:bb:vv.f字符串的转换函数,主要用于转换成设备的名称(pci设备的名称一般是诸如0000:00:00.1这种)
1135     fn from(value: BusDeviceFunction) -> Self {
1136         //需要注意,这里的0000应该是所谓的“域号”(Domain ID),但是尚不知道是如何获得的,故硬编码在这里
1137         //todo:实现域号的获取
1138         format!(
1139             "0000:{:02x}:{:02x}.{}",
1140             value.bus, value.device, value.function
1141         )
1142     }
1143 }
1144 ///实现BusDeviceFunction的Display trait,使其可以直接输出
1145 impl Display for BusDeviceFunction {
1146     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1147         write!(
1148             f,
1149             "bus {} device {} function{}",
1150             self.bus, self.device, self.function
1151         )
1152     }
1153 }
1154 /// The location allowed for a memory BAR.
1155 /// memory BAR的三种情况
1156 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1157 pub enum MemoryBarType {
1158     /// The BAR has a 32-bit address and can be mapped anywhere in 32-bit address space.
1159     Width32,
1160     /// The BAR must be mapped below 1MiB.
1161     Below1MiB,
1162     /// The BAR has a 64-bit address and can be mapped anywhere in 64-bit address space.
1163     Width64,
1164 }
1165 ///实现MemoryBarType与u8的类型转换
1166 impl From<MemoryBarType> for u8 {
1167     fn from(bar_type: MemoryBarType) -> Self {
1168         match bar_type {
1169             MemoryBarType::Width32 => 0,
1170             MemoryBarType::Below1MiB => 1,
1171             MemoryBarType::Width64 => 2,
1172         }
1173     }
1174 }
1175 ///实现MemoryBarType与u8的类型转换
1176 impl TryFrom<u8> for MemoryBarType {
1177     type Error = PciError;
1178     fn try_from(value: u8) -> Result<Self, Self::Error> {
1179         match value {
1180             0 => Ok(Self::Width32),
1181             1 => Ok(Self::Below1MiB),
1182             2 => Ok(Self::Width64),
1183             _ => Err(PciError::InvalidBarType),
1184         }
1185     }
1186 }
1187 
1188 /// Information about a PCI Base Address Register.
1189 /// BAR的三种类型 Memory/IO/Unused
1190 #[derive(Clone, Debug)]
1191 pub enum BarInfo {
1192     /// The BAR is for a memory region.
1193     Memory {
1194         /// The size of the BAR address and where it can be located.
1195         address_type: MemoryBarType,
1196         /// If true, then reading from the region doesn't have side effects. The CPU may cache reads
1197         /// and merge repeated stores.
1198         prefetchable: bool,
1199         /// The memory address, always 16-byte aligned.
1200         address: u64,
1201         /// The size of the BAR in bytes.
1202         size: u32,
1203         /// The virtaddress for a memory bar(mapped).
1204         mmio_guard: Arc<MMIOSpaceGuard>,
1205     },
1206     /// The BAR is for an I/O region.
1207     IO {
1208         /// The I/O address, always 4-byte aligned.
1209         address: u32,
1210         /// The size of the BAR in bytes.
1211         size: u32,
1212     },
1213     Unused,
1214 }
1215 
1216 impl BarInfo {
1217     /// Returns the address and size of this BAR if it is a memory bar, or `None` if it is an IO
1218     /// BAR.
1219     ///@brief 得到某个bar的memory_address与size(前提是他的类型为Memory Bar)
1220     ///@param self
1221     ///@return Option<(u64, u32) 是Memory Bar返回内存地址与大小,不是则返回None
1222     pub fn memory_address_size(&self) -> Option<(u64, u32)> {
1223         if let Self::Memory { address, size, .. } = self {
1224             Some((*address, *size))
1225         } else {
1226             None
1227         }
1228     }
1229     ///@brief 得到某个bar的virtaddress(前提是他的类型为Memory Bar)
1230     ///@param self
1231     ///@return Option<(u64) 是Memory Bar返回映射的虚拟地址,不是则返回None
1232     pub fn virtual_address(&self) -> Option<VirtAddr> {
1233         if let Self::Memory { mmio_guard, .. } = self {
1234             Some(mmio_guard.vaddr())
1235         } else {
1236             None
1237         }
1238     }
1239 }
1240 ///实现BarInfo的Display trait,自定义输出
1241 impl Display for BarInfo {
1242     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1243         match self {
1244             Self::Memory {
1245                 address_type,
1246                 prefetchable,
1247                 address,
1248                 size,
1249                 mmio_guard,
1250             } => write!(
1251                 f,
1252                 "Memory space at {:#010x}, size {}, type {:?}, prefetchable {}, mmio_guard: {:?}",
1253                 address, size, address_type, prefetchable, mmio_guard
1254             ),
1255             Self::IO { address, size } => {
1256                 write!(f, "I/O space at {:#010x}, size {}", address, size)
1257             }
1258             Self::Unused => {
1259                 write!(f, "Unused bar")
1260             }
1261         }
1262     }
1263 }
1264 // todo 增加对桥的bar的支持
1265 pub trait PciDeviceBar {}
1266 
1267 ///一个普通PCI设备(非桥)有6个BAR寄存器,PciStandardDeviceBar存储其全部信息
1268 #[derive(Clone, Debug)]
1269 pub struct PciStandardDeviceBar {
1270     bar0: BarInfo,
1271     bar1: BarInfo,
1272     bar2: BarInfo,
1273     bar3: BarInfo,
1274     bar4: BarInfo,
1275     bar5: BarInfo,
1276 }
1277 
1278 impl PciStandardDeviceBar {
1279     ///@brief 得到某个bar的barinfo
1280     ///@param self ,bar_index(0-5)
1281     ///@return Result<&BarInfo, PciError> bar_index在0-5则返回对应的bar_info结构体,超出范围则返回错误
1282     pub fn get_bar(&self, bar_index: u8) -> Result<&BarInfo, PciError> {
1283         match bar_index {
1284             0 => Ok(&self.bar0),
1285             1 => Ok(&self.bar1),
1286             2 => Ok(&self.bar2),
1287             3 => Ok(&self.bar3),
1288             4 => Ok(&self.bar4),
1289             5 => Ok(&self.bar5),
1290             _ => Err(PciError::InvalidBarType),
1291         }
1292     }
1293 }
1294 ///实现PciStandardDeviceBar的Display trait,使其可以直接输出
1295 impl Display for PciStandardDeviceBar {
1296     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1297         write!(
1298             f,
1299             "\r\nBar0:{}\r\nBar1:{}\r\nBar2:{}\r\nBar3:{}\r\nBar4:{}\r\nBar5:{}",
1300             self.bar0, self.bar1, self.bar2, self.bar3, self.bar4, self.bar5
1301         )
1302     }
1303 }
1304 ///实现PciStandardDeviceBar的Default trait,使其可以简单初始化
1305 impl Default for PciStandardDeviceBar {
1306     fn default() -> Self {
1307         PciStandardDeviceBar {
1308             bar0: BarInfo::Unused,
1309             bar1: BarInfo::Unused,
1310             bar2: BarInfo::Unused,
1311             bar3: BarInfo::Unused,
1312             bar4: BarInfo::Unused,
1313             bar5: BarInfo::Unused,
1314         }
1315     }
1316 }
1317 
1318 ///@brief 将某个pci设备的bar寄存器读取值后映射到虚拟地址
1319 ///@param self ,bus_device_function PCI设备的唯一标识符
1320 ///@return Result<PciStandardDeviceBar, PciError> 成功则返回对应的PciStandardDeviceBar结构体,失败则返回错误类型
1321 pub fn pci_bar_init(
1322     bus_device_function: BusDeviceFunction,
1323 ) -> Result<PciStandardDeviceBar, PciError> {
1324     let mut device_bar: PciStandardDeviceBar = PciStandardDeviceBar::default();
1325     let mut bar_index_ignore: u8 = 255;
1326     for bar_index in 0..6 {
1327         if bar_index == bar_index_ignore {
1328             continue;
1329         }
1330         let bar_info;
1331         let bar_orig =
1332             pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
1333         pci_root_0().write_config(
1334             bus_device_function,
1335             (BAR0_OFFSET + 4 * bar_index).into(),
1336             0xffffffff,
1337         );
1338         let size_mask =
1339             pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
1340         // A wrapping add is necessary to correctly handle the case of unused BARs, which read back
1341         // as 0, and should be treated as size 0.
1342         let size = (!(size_mask & 0xfffffff0)).wrapping_add(1);
1343         //kdebug!("bar_orig:{:#x},size: {:#x}", bar_orig,size);
1344         // Restore the original value.
1345         pci_root_0().write_config(
1346             bus_device_function,
1347             (BAR0_OFFSET + 4 * bar_index).into(),
1348             bar_orig,
1349         );
1350         if size == 0 {
1351             continue;
1352         }
1353         if bar_orig & 0x00000001 == 0x00000001 {
1354             // I/O space
1355             let address = bar_orig & 0xfffffffc;
1356             bar_info = BarInfo::IO { address, size };
1357         } else {
1358             // Memory space
1359             let mut address = u64::from(bar_orig & 0xfffffff0);
1360             let prefetchable = bar_orig & 0x00000008 != 0;
1361             let address_type = MemoryBarType::try_from(((bar_orig & 0x00000006) >> 1) as u8)?;
1362             if address_type == MemoryBarType::Width64 {
1363                 if bar_index >= 5 {
1364                     return Err(PciError::InvalidBarType);
1365                 }
1366                 let address_top = pci_root_0().read_config(
1367                     bus_device_function,
1368                     (BAR0_OFFSET + 4 * (bar_index + 1)).into(),
1369                 );
1370                 address |= u64::from(address_top) << 32;
1371                 bar_index_ignore = bar_index + 1; //下个bar跳过,因为64位的memory bar覆盖了两个bar
1372             }
1373             let pci_address = PciAddr::new(address as usize);
1374             let paddr = PciArch::address_pci_to_physical(pci_address); //PCI总线域物理地址转换为存储器域物理地址
1375 
1376             let space_guard: Arc<MMIOSpaceGuard>;
1377             unsafe {
1378                 let size_want = size as usize;
1379                 let tmp = mmio_pool()
1380                     .create_mmio(size_want)
1381                     .map_err(|_| PciError::CreateMmioError)?;
1382                 space_guard = Arc::new(tmp);
1383                 //kdebug!("Pci bar init: mmio space: {space_guard:?}, paddr={paddr:?}, size_want={size_want}");
1384                 assert!(
1385                     space_guard.map_phys(paddr, size_want).is_ok(),
1386                     "pci_bar_init: map_phys failed"
1387                 );
1388             }
1389             bar_info = BarInfo::Memory {
1390                 address_type,
1391                 prefetchable,
1392                 address,
1393                 size,
1394                 mmio_guard: space_guard,
1395             };
1396         }
1397         match bar_index {
1398             0 => {
1399                 device_bar.bar0 = bar_info;
1400             }
1401             1 => {
1402                 device_bar.bar1 = bar_info;
1403             }
1404             2 => {
1405                 device_bar.bar2 = bar_info;
1406             }
1407             3 => {
1408                 device_bar.bar3 = bar_info;
1409             }
1410             4 => {
1411                 device_bar.bar4 = bar_info;
1412             }
1413             5 => {
1414                 device_bar.bar5 = bar_info;
1415             }
1416             _ => {}
1417         }
1418     }
1419     //kdebug!("pci_device_bar:{}", device_bar);
1420     return Ok(device_bar);
1421 }
1422 
1423 /// Information about a PCI device capability.
1424 /// PCI设备的capability的信息
1425 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
1426 pub struct CapabilityInfo {
1427     /// The offset of the capability in the PCI configuration space of the device function.
1428     pub offset: u8,
1429     /// The ID of the capability.
1430     pub id: u8,
1431     /// The third and fourth bytes of the capability, to save reading them again.
1432     pub private_header: u16,
1433 }
1434 
1435 /// Iterator over capabilities for a device.
1436 /// 创建迭代器以遍历PCI设备的capability
1437 #[derive(Debug)]
1438 pub struct CapabilityIterator {
1439     pub bus_device_function: BusDeviceFunction,
1440     pub next_capability_offset: Option<u8>,
1441 }
1442 
1443 impl Iterator for CapabilityIterator {
1444     type Item = CapabilityInfo;
1445     fn next(&mut self) -> Option<Self::Item> {
1446         let offset = self.next_capability_offset?;
1447 
1448         // Read the first 4 bytes of the capability.
1449         let capability_header = pci_root_0().read_config(self.bus_device_function, offset.into());
1450         let id = capability_header as u8;
1451         let next_offset = (capability_header >> 8) as u8;
1452         let private_header = (capability_header >> 16) as u16;
1453 
1454         self.next_capability_offset = if next_offset == 0 {
1455             None
1456         } else if next_offset < 64 || next_offset & 0x3 != 0 {
1457             kwarn!("Invalid next capability offset {:#04x}", next_offset);
1458             None
1459         } else {
1460             Some(next_offset)
1461         };
1462 
1463         Some(CapabilityInfo {
1464             offset,
1465             id,
1466             private_header,
1467         })
1468     }
1469 }
1470 
1471 /// Information about a PCIe device capability.
1472 /// PCIe设备的external capability的信息
1473 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
1474 pub struct ExternalCapabilityInfo {
1475     /// The offset of the capability in the PCI configuration space of the device function.
1476     pub offset: u16,
1477     /// The ID of the capability.
1478     pub id: u16,
1479     /// The third and fourth bytes of the capability, to save reading them again.
1480     pub capability_version: u8,
1481 }
1482 
1483 /// Iterator over capabilities for a device.
1484 /// 创建迭代器以遍历PCIe设备的external capability
1485 #[derive(Debug)]
1486 pub struct ExternalCapabilityIterator<'a> {
1487     pub root: &'a PciRoot,
1488     pub bus_device_function: BusDeviceFunction,
1489     pub next_capability_offset: Option<u16>,
1490 }
1491 impl<'a> Iterator for ExternalCapabilityIterator<'a> {
1492     type Item = ExternalCapabilityInfo;
1493     fn next(&mut self) -> Option<Self::Item> {
1494         let offset = self.next_capability_offset?;
1495 
1496         // Read the first 4 bytes of the capability.
1497         let capability_header = self.root.read_config(self.bus_device_function, offset);
1498         let id = capability_header as u16;
1499         let next_offset = (capability_header >> 20) as u16;
1500         let capability_version = ((capability_header >> 16) & 0xf) as u8;
1501 
1502         self.next_capability_offset = if next_offset == 0 {
1503             None
1504         } else if next_offset < 0x100 || next_offset & 0x3 != 0 {
1505             kwarn!("Invalid next capability offset {:#04x}", next_offset);
1506             None
1507         } else {
1508             Some(next_offset)
1509         };
1510 
1511         Some(ExternalCapabilityInfo {
1512             offset,
1513             id,
1514             capability_version,
1515         })
1516     }
1517 }
1518