2
0

lib.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //! A library for parsing ACPI tables. This crate can be used by bootloaders and kernels for architectures that
  2. //! support ACPI. This crate is not feature-complete, but can parse lots of the more common tables. Parsing the
  3. //! ACPI tables is required for correctly setting up the APICs, HPET, and provides useful information about power
  4. //! management and many other platform capabilities.
  5. //!
  6. //! This crate is designed to find and parse the static tables ACPI provides. It should be used in conjunction with
  7. //! the `aml` crate, which is the (much less complete) AML parser used to parse the DSDT and SSDTs. These crates
  8. //! are separate because some kernels may want to detect the static tables, but delay AML parsing to a later stage.
  9. //!
  10. //! This crate requires `alloc` to make heap allocations. If you are trying to find the RSDP in an environment that
  11. //! does not have a heap (e.g. a bootloader), you can use the `rsdp` crate. The types from that crate are
  12. //! compatible with `acpi`.
  13. //!
  14. //! ### Usage
  15. //! To use the library, you will need to provide an implementation of the `AcpiHandler` trait, which allows the
  16. //! library to make requests such as mapping a particular region of physical memory into the virtual address space.
  17. //!
  18. //! You then need to construct an instance of `AcpiTables`, which can be done in a few ways depending on how much
  19. //! information you have:
  20. //! * Use `AcpiTables::from_rsdp` if you have the physical address of the RSDP
  21. //! * Use `AcpiTables::from_rsdt` if you have the physical address of the RSDT/XSDT
  22. //! * Use `AcpiTables::search_for_rsdp_bios` if you don't have the address of either, but **you know you are
  23. //! running on BIOS, not UEFI**
  24. //! * Use `AcpiTables::from_tables_direct` if you are using the library in an unusual setting, such as in usermode,
  25. //! and have a custom method to enumerate and access the tables.
  26. //!
  27. //! `AcpiTables` stores the addresses of all of the tables detected on a platform. The SDTs are parsed by this
  28. //! library, or can be accessed directly with `from_sdt`, while the `DSDT` and any `SSDTs` should be parsed with
  29. //! `aml`.
  30. //!
  31. //! To gather information out of the static tables, a few of the types you should take a look at are:
  32. //! - [`PlatformInfo`](crate::platform::PlatformInfo) parses the FADT and MADT to create a nice view of the
  33. //! processor topology and interrupt controllers on `x86_64`, and the interrupt controllers on other platforms.
  34. //! `AcpiTables::platform_info` is a convenience method for constructing a `PlatformInfo`.
  35. //! - [`HpetInfo`](crate::hpet::HpetInfo) parses the HPET table and tells you how to configure the High
  36. //! Precision Event Timer.
  37. //! - [`PciConfigRegions`](crate::mcfg::PciConfigRegions) parses the MCFG and tells you how PCIe configuration
  38. //! space is mapped into physical memory.
  39. /*
  40. * Contributing notes (you may find these useful if you're new to contributing to the library):
  41. * - Accessing packed fields without UB: Lots of the structures defined by ACPI are defined with `repr(packed)`
  42. * to prevent padding being introduced, which would make the structure's layout incorrect. In Rust, this
  43. * creates a problem as references to these fields could be unaligned, which is undefined behaviour. For the
  44. * majority of these fields, this problem can be easily avoided by telling the compiler to make a copy of the
  45. * field's contents: this is the perhaps unfamiliar pattern of e.g. `!{ entry.flags }.get_bit(0)` we use
  46. * around the codebase.
  47. */
  48. #![no_std]
  49. #![deny(unsafe_op_in_unsafe_fn)]
  50. #![cfg_attr(feature = "allocator_api", feature(allocator_api, ptr_as_uninit))]
  51. #[cfg_attr(test, macro_use)]
  52. #[cfg(test)]
  53. extern crate std;
  54. pub mod address;
  55. pub mod bgrt;
  56. pub mod fadt;
  57. pub mod hpet;
  58. pub mod madt;
  59. pub mod mcfg;
  60. pub mod sdt;
  61. #[cfg(feature = "allocator_api")]
  62. mod managed_slice;
  63. #[cfg(feature = "allocator_api")]
  64. pub use managed_slice::*;
  65. #[cfg(feature = "allocator_api")]
  66. pub use crate::platform::{interrupt::InterruptModel, PlatformInfo};
  67. #[cfg(feature = "allocator_api")]
  68. pub mod platform;
  69. pub use crate::{fadt::PowerProfile, hpet::HpetInfo, madt::MadtError, mcfg::PciConfigRegions};
  70. pub use rsdp::{
  71. handler::{AcpiHandler, PhysicalMapping},
  72. RsdpError,
  73. };
  74. use crate::sdt::{SdtHeader, Signature};
  75. use core::mem;
  76. use rsdp::Rsdp;
  77. /// Result type used by error-returning functions.
  78. pub type AcpiResult<T> = core::result::Result<T, AcpiError>;
  79. /// All types representing ACPI tables should implement this trait.
  80. ///
  81. /// ### Safety
  82. ///
  83. /// The table's memory is naively interpreted, so you must be careful in providing a type that
  84. /// correctly represents the table's structure. Regardless of the provided type's size, the region mapped will
  85. /// be the size specified in the SDT's header. Providing a table impl that is larger than this, *may* lead to
  86. /// page-faults, aliasing references, or derefencing uninitialized memory (the latter two being UB).
  87. /// This isn't forbidden, however, because some tables rely on the impl being larger than a provided SDT in some
  88. /// versions of ACPI (the [`ExtendedField`](crate::sdt::ExtendedField) type will be useful if you need to do
  89. /// this. See our [`Fadt`](crate::fadt::Fadt) type for an example of this).
  90. pub unsafe trait AcpiTable {
  91. const SIGNATURE: Signature;
  92. fn header(&self) -> &sdt::SdtHeader;
  93. fn validate(&self) -> AcpiResult<()> {
  94. self.header().validate(Self::SIGNATURE)
  95. }
  96. }
  97. /// Error type used by functions that return an `AcpiResult<T>`.
  98. #[derive(Debug)]
  99. pub enum AcpiError {
  100. Rsdp(RsdpError),
  101. SdtInvalidSignature(Signature),
  102. SdtInvalidOemId(Signature),
  103. SdtInvalidTableId(Signature),
  104. SdtInvalidChecksum(Signature),
  105. TableMissing(Signature),
  106. InvalidFacsAddress,
  107. InvalidDsdtAddress,
  108. InvalidMadt(MadtError),
  109. InvalidGenericAddress,
  110. AllocError,
  111. }
  112. /// Type capable of enumerating the existing ACPI tables on the system.
  113. ///
  114. ///
  115. /// ### Implementation Note
  116. ///
  117. /// When using the `allocator_api` feature, [`PlatformInfo::new()`] provides a much cleaner
  118. /// API for enumerating ACPI structures once an `AcpiTables` has been constructed.
  119. #[derive(Debug)]
  120. pub struct AcpiTables<H: AcpiHandler> {
  121. mapping: PhysicalMapping<H, SdtHeader>,
  122. revision: u8,
  123. handler: H,
  124. }
  125. impl<H> AcpiTables<H>
  126. where
  127. H: AcpiHandler,
  128. {
  129. /// Create an `AcpiTables` if you have the physical address of the RSDP.
  130. ///
  131. /// ### Safety: Caller must ensure the provided address is valid to read as an RSDP.
  132. pub unsafe fn from_rsdp(handler: H, address: usize) -> AcpiResult<Self> {
  133. let rsdp_mapping = unsafe { handler.map_physical_region::<Rsdp>(address, mem::size_of::<Rsdp>()) };
  134. rsdp_mapping.validate().map_err(AcpiError::Rsdp)?;
  135. // Safety: `RSDP` has been validated.
  136. unsafe { Self::from_validated_rsdp(handler, rsdp_mapping) }
  137. }
  138. /// Search for the RSDP on a BIOS platform. This accesses BIOS-specific memory locations and will probably not
  139. /// work on UEFI platforms. See [Rsdp::search_for_rsdp_bios](rsdp_search::Rsdp::search_for_rsdp_bios) for
  140. /// details.
  141. pub unsafe fn search_for_rsdp_bios(handler: H) -> AcpiResult<Self> {
  142. let rsdp_mapping = unsafe { Rsdp::search_for_on_bios(handler.clone()) }.map_err(AcpiError::Rsdp)?;
  143. // Safety: RSDP has been validated from `Rsdp::search_for_on_bios`
  144. unsafe { Self::from_validated_rsdp(handler, rsdp_mapping) }
  145. }
  146. /// Create an `AcpiTables` if you have a `PhysicalMapping` of the RSDP that you know is correct. This is called
  147. /// from `from_rsdp` after validation, but can also be used if you've searched for the RSDP manually on a BIOS
  148. /// system.
  149. ///
  150. /// ### Safety: Caller must ensure that the provided mapping is a fully validated RSDP.
  151. pub unsafe fn from_validated_rsdp(handler: H, rsdp_mapping: PhysicalMapping<H, Rsdp>) -> AcpiResult<Self> {
  152. macro_rules! read_root_table {
  153. ($signature_name:ident, $address_getter:ident) => {{
  154. #[repr(transparent)]
  155. struct RootTable {
  156. header: SdtHeader,
  157. }
  158. unsafe impl AcpiTable for RootTable {
  159. const SIGNATURE: Signature = Signature::$signature_name;
  160. fn header(&self) -> &SdtHeader {
  161. &self.header
  162. }
  163. }
  164. // Unmap RSDP as soon as possible
  165. let table_phys_start = rsdp_mapping.$address_getter() as usize;
  166. drop(rsdp_mapping);
  167. // Map and validate root table
  168. // SAFETY: Addresses from a validated `RSDP` are also guaranteed to be valid.
  169. let table_mapping = unsafe { read_table::<_, RootTable>(handler.clone(), table_phys_start) }?;
  170. // Convert `table_mapping` to header mapping for storage
  171. // Avoid requesting table unmap twice (from both original and converted `table_mapping`s)
  172. let table_mapping = mem::ManuallyDrop::new(table_mapping);
  173. // SAFETY: `SdtHeader` is equivalent to `Sdt` memory-wise
  174. let table_mapping = unsafe {
  175. PhysicalMapping::new(
  176. table_mapping.physical_start(),
  177. table_mapping.virtual_start().cast::<SdtHeader>(),
  178. table_mapping.region_length(),
  179. table_mapping.mapped_length(),
  180. handler.clone(),
  181. )
  182. };
  183. table_mapping
  184. }};
  185. }
  186. let revision = rsdp_mapping.revision();
  187. let root_table_mapping = if revision == 0 {
  188. /*
  189. * We're running on ACPI Version 1.0. We should use the 32-bit RSDT address.
  190. */
  191. read_root_table!(RSDT, rsdt_address)
  192. } else {
  193. /*
  194. * We're running on ACPI Version 2.0+. We should use the 64-bit XSDT address, truncated
  195. * to 32 bits on x86.
  196. */
  197. read_root_table!(XSDT, xsdt_address)
  198. };
  199. Ok(Self { mapping: root_table_mapping, revision, handler })
  200. }
  201. /// The ACPI revision of the tables enumerated by this structure.
  202. #[inline]
  203. pub const fn revision(&self) -> u8 {
  204. self.revision
  205. }
  206. /// Constructs a [`TablesPhysPtrsIter`] over this table.
  207. fn tables_phys_ptrs(&self) -> TablesPhysPtrsIter<'_> {
  208. // SAFETY: The virtual address of the array of pointers follows the virtual address of the table in memory.
  209. let ptrs_virt_start = unsafe { self.mapping.virtual_start().as_ptr().add(1).cast::<u8>() };
  210. let ptrs_bytes_len = self.mapping.region_length() - mem::size_of::<SdtHeader>();
  211. // SAFETY: `ptrs_virt_start` points to an array of `ptrs_bytes_len` bytes that lives as long as `self`.
  212. let ptrs_bytes = unsafe { core::slice::from_raw_parts(ptrs_virt_start, ptrs_bytes_len) };
  213. let ptr_size = if self.revision == 0 {
  214. 4 // RSDT entry size
  215. } else {
  216. 8 // XSDT entry size
  217. };
  218. ptrs_bytes.chunks(ptr_size).map(|ptr_bytes_src| {
  219. // Construct a native pointer using as many bytes as required from `ptr_bytes_src` (note that ACPI is
  220. // little-endian)
  221. let mut ptr_bytes_dst = [0; mem::size_of::<usize>()];
  222. let common_ptr_size = usize::min(mem::size_of::<usize>(), ptr_bytes_src.len());
  223. ptr_bytes_dst[..common_ptr_size].copy_from_slice(&ptr_bytes_src[..common_ptr_size]);
  224. usize::from_le_bytes(ptr_bytes_dst) as *const SdtHeader
  225. })
  226. }
  227. /// Searches through the ACPI table headers and attempts to locate the table with a matching `T::SIGNATURE`.
  228. pub fn find_table<T: AcpiTable>(&self) -> AcpiResult<PhysicalMapping<H, T>> {
  229. self.tables_phys_ptrs()
  230. .find_map(|table_phys_ptr| {
  231. // SAFETY: Table guarantees its contained addresses to be valid.
  232. match unsafe { read_table(self.handler.clone(), table_phys_ptr as usize) } {
  233. Ok(table_mapping) => Some(table_mapping),
  234. Err(AcpiError::SdtInvalidSignature(_)) => None,
  235. Err(e) => {
  236. log::warn!(
  237. "Found invalid {} table at physical address {:p}: {:?}",
  238. T::SIGNATURE,
  239. table_phys_ptr,
  240. e
  241. );
  242. None
  243. }
  244. }
  245. })
  246. .ok_or(AcpiError::TableMissing(T::SIGNATURE))
  247. }
  248. /// Finds and returns the DSDT AML table, if it exists.
  249. pub fn dsdt(&self) -> AcpiResult<AmlTable> {
  250. self.find_table::<fadt::Fadt>().and_then(|fadt| {
  251. struct Dsdt;
  252. // Safety: Implementation properly represents a valid DSDT.
  253. unsafe impl AcpiTable for Dsdt {
  254. const SIGNATURE: Signature = Signature::DSDT;
  255. fn header(&self) -> &sdt::SdtHeader {
  256. // Safety: DSDT will always be valid for an SdtHeader at its `self` pointer.
  257. unsafe { &*(self as *const Self as *const sdt::SdtHeader) }
  258. }
  259. }
  260. let dsdt_address = fadt.dsdt_address()?;
  261. let dsdt = unsafe { read_table::<H, Dsdt>(self.handler.clone(), dsdt_address)? };
  262. Ok(AmlTable::new(dsdt_address, dsdt.header().length))
  263. })
  264. }
  265. /// Iterates through all of the SSDT tables.
  266. pub fn ssdts(&self) -> SsdtIterator<H> {
  267. SsdtIterator { tables_phys_ptrs: self.tables_phys_ptrs(), handler: self.handler.clone() }
  268. }
  269. /// Convenience method for contructing a [`PlatformInfo`](crate::platform::PlatformInfo). This is one of the
  270. /// first things you should usually do with an `AcpiTables`, and allows to collect helpful information about
  271. /// the platform from the ACPI tables.
  272. #[cfg(feature = "allocator_api")]
  273. pub fn platform_info_in<'a, A>(&'a self, allocator: &'a A) -> AcpiResult<PlatformInfo<A>>
  274. where
  275. A: core::alloc::Allocator,
  276. {
  277. PlatformInfo::new_in(self, allocator)
  278. }
  279. }
  280. #[derive(Debug)]
  281. pub struct Sdt {
  282. /// Physical address of the start of the SDT, including the header.
  283. pub physical_address: usize,
  284. /// Length of the table in bytes.
  285. pub length: u32,
  286. /// Whether this SDT has been validated. This is set to `true` the first time it is mapped and validated.
  287. pub validated: bool,
  288. }
  289. /// An iterator over the physical table addresses in an RSDT or XSDT.
  290. type TablesPhysPtrsIter<'t> = core::iter::Map<core::slice::Chunks<'t, u8>, fn(&[u8]) -> *const SdtHeader>;
  291. #[derive(Debug)]
  292. pub struct AmlTable {
  293. /// Physical address of the start of the AML stream (excluding the table header).
  294. pub address: usize,
  295. /// Length (in bytes) of the AML stream.
  296. pub length: u32,
  297. }
  298. impl AmlTable {
  299. /// Create an `AmlTable` from the address and length of the table **including the SDT header**.
  300. pub(crate) fn new(address: usize, length: u32) -> AmlTable {
  301. AmlTable {
  302. address: address + mem::size_of::<SdtHeader>(),
  303. length: length - mem::size_of::<SdtHeader>() as u32,
  304. }
  305. }
  306. }
  307. /// ### Safety: Caller must ensure the provided address is valid for being read as an `SdtHeader`.
  308. unsafe fn read_table<H: AcpiHandler, T: AcpiTable>(
  309. handler: H,
  310. address: usize,
  311. ) -> AcpiResult<PhysicalMapping<H, T>> {
  312. // Attempt to peek at the SDT header to correctly enumerate the entire table.
  313. // SAFETY: `address` needs to be valid for the size of `SdtHeader`, or the ACPI tables are malformed (not a
  314. // software issue).
  315. let header_mapping = unsafe { handler.map_physical_region::<SdtHeader>(address, mem::size_of::<SdtHeader>()) };
  316. SdtHeader::validate_lazy(header_mapping, handler)
  317. }
  318. /// Iterator that steps through all of the tables, and returns only the SSDTs as `AmlTable`s.
  319. pub struct SsdtIterator<'t, H>
  320. where
  321. H: AcpiHandler,
  322. {
  323. tables_phys_ptrs: TablesPhysPtrsIter<'t>,
  324. handler: H,
  325. }
  326. impl<'t, H> Iterator for SsdtIterator<'t, H>
  327. where
  328. H: AcpiHandler,
  329. {
  330. type Item = AmlTable;
  331. fn next(&mut self) -> Option<Self::Item> {
  332. #[repr(transparent)]
  333. struct Ssdt {
  334. header: SdtHeader,
  335. }
  336. // SAFETY: Implementation properly represents a valid SSDT.
  337. unsafe impl AcpiTable for Ssdt {
  338. const SIGNATURE: Signature = Signature::SSDT;
  339. fn header(&self) -> &SdtHeader {
  340. &self.header
  341. }
  342. }
  343. // Borrow single field for closure to avoid immutable reference to `self` that inhibits `find_map`
  344. let handler = &self.handler;
  345. // Consume iterator until next valid SSDT and return the latter
  346. self.tables_phys_ptrs.find_map(|table_phys_ptr| {
  347. // SAFETY: Table guarantees its contained addresses to be valid.
  348. match unsafe { read_table::<_, Ssdt>(handler.clone(), table_phys_ptr as usize) } {
  349. Ok(ssdt_mapping) => Some(AmlTable::new(ssdt_mapping.physical_start(), ssdt_mapping.header.length)),
  350. Err(AcpiError::SdtInvalidSignature(_)) => None,
  351. Err(e) => {
  352. log::warn!("Found invalid SSDT at physical address {:p}: {:?}", table_phys_ptr, e);
  353. None
  354. }
  355. }
  356. })
  357. }
  358. }