pci.rs 57 KB

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