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