pci.rs 54 KB

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