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