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