pci.rs 55 KB

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