lib.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. //! This crate provides types for representing the RSDP (the Root System Descriptor Table; the first ACPI table)
  2. //! and methods for searching for it on BIOS systems. Importantly, this crate (unlike `acpi`, which re-exports the
  3. //! contents of this crate) does not need `alloc`, and so can be used in environments that can't allocate. This is
  4. //! specifically meant to be used from bootloaders for finding the RSDP, so it can be passed to the payload. If you
  5. //! don't have this requirement, and want to do more than just find the RSDP, you can use `acpi` instead of this
  6. //! crate.
  7. //!
  8. //! To use this crate, you will need to provide an implementation of `AcpiHandler`. This is the same handler type
  9. //! used in the `acpi` crate.
  10. #![no_std]
  11. #![deny(unsafe_op_in_unsafe_fn)]
  12. #[cfg(test)]
  13. extern crate std;
  14. pub mod handler;
  15. use core::{mem, ops::Range, slice, str};
  16. use handler::{AcpiHandler, PhysicalMapping};
  17. use log::warn;
  18. #[derive(Clone, Copy, PartialEq, Eq, Debug)]
  19. pub enum RsdpError {
  20. NoValidRsdp,
  21. IncorrectSignature,
  22. InvalidOemId,
  23. InvalidChecksum,
  24. }
  25. /// The first structure found in ACPI. It just tells us where the RSDT is.
  26. ///
  27. /// On BIOS systems, it is either found in the first 1KB of the Extended Bios Data Area, or between
  28. /// 0x000E0000 and 0x000FFFFF. The signature is always on a 16 byte boundary. On (U)EFI, it may not
  29. /// be located in these locations, and so an address should be found in the EFI configuration table
  30. /// instead.
  31. ///
  32. /// The recommended way of locating the RSDP is to let the bootloader do it - Multiboot2 can pass a
  33. /// tag with the physical address of it. If this is not possible, a manual scan can be done.
  34. ///
  35. /// If `revision > 0`, (the hardware ACPI version is Version 2.0 or greater), the RSDP contains
  36. /// some new fields. For ACPI Version 1.0, these fields are not valid and should not be accessed.
  37. /// For ACPI Version 2.0+, `xsdt_address` should be used (truncated to `u32` on x86) instead of
  38. /// `rsdt_address`.
  39. #[derive(Clone, Copy, Debug)]
  40. #[repr(C, packed)]
  41. pub struct Rsdp {
  42. signature: [u8; 8],
  43. checksum: u8,
  44. oem_id: [u8; 6],
  45. revision: u8,
  46. rsdt_address: u32,
  47. /*
  48. * These fields are only valid for ACPI Version 2.0 and greater
  49. */
  50. length: u32,
  51. xsdt_address: u64,
  52. ext_checksum: u8,
  53. reserved: [u8; 3],
  54. }
  55. impl Rsdp {
  56. /// This searches for a RSDP on BIOS systems.
  57. ///
  58. /// ### Safety
  59. /// This function probes memory in three locations:
  60. /// - It reads a word from `40:0e` to locate the EBDA.
  61. /// - The first 1KiB of the EBDA (Extended BIOS Data Area).
  62. /// - The BIOS memory area at `0xe0000..=0xfffff`.
  63. ///
  64. /// This should be fine on all BIOS systems. However, UEFI platforms are free to put the RSDP wherever they
  65. /// please, so this won't always find the RSDP. Further, prodding these memory locations may have unintended
  66. /// side-effects. On UEFI systems, the RSDP should be found in the Configuration Table, using two GUIDs:
  67. /// - ACPI v1.0 structures use `eb9d2d30-2d88-11d3-9a16-0090273fc14d`.
  68. /// - ACPI v2.0 or later structures use `8868e871-e4f1-11d3-bc22-0080c73c8881`.
  69. /// You should search the entire table for the v2.0 GUID before searching for the v1.0 one.
  70. pub unsafe fn search_for_on_bios<H>(handler: H) -> Result<PhysicalMapping<H, Rsdp>, RsdpError>
  71. where
  72. H: AcpiHandler,
  73. {
  74. let rsdp_address = {
  75. let mut rsdp_address = None;
  76. let areas = find_search_areas(handler.clone());
  77. 'areas: for area in areas.iter() {
  78. let mapping = unsafe { handler.map_physical_region::<u8>(area.start, area.end - area.start) };
  79. for address in area.clone().step_by(16) {
  80. let ptr_in_mapping =
  81. unsafe { mapping.virtual_start().as_ptr().offset((address - area.start) as isize) };
  82. let signature = unsafe { *(ptr_in_mapping as *const [u8; 8]) };
  83. if signature == *RSDP_SIGNATURE {
  84. match unsafe { *(ptr_in_mapping as *const Rsdp) }.validate() {
  85. Ok(()) => {
  86. rsdp_address = Some(address);
  87. break 'areas;
  88. }
  89. Err(err) => warn!("Invalid RSDP found at {:#x}: {:?}", address, err),
  90. }
  91. }
  92. }
  93. }
  94. rsdp_address
  95. };
  96. match rsdp_address {
  97. Some(address) => {
  98. let rsdp_mapping = unsafe { handler.map_physical_region::<Rsdp>(address, mem::size_of::<Rsdp>()) };
  99. Ok(rsdp_mapping)
  100. }
  101. None => Err(RsdpError::NoValidRsdp),
  102. }
  103. }
  104. /// Checks that:
  105. /// 1) The signature is correct
  106. /// 2) The checksum is correct
  107. /// 3) For Version 2.0+, that the extension checksum is correct
  108. pub fn validate(&self) -> Result<(), RsdpError> {
  109. const RSDP_V1_LENGTH: usize = 20;
  110. // Check the signature
  111. if &self.signature != RSDP_SIGNATURE {
  112. return Err(RsdpError::IncorrectSignature);
  113. }
  114. // Check the OEM id is valid UTF8 (allows use of unwrap)
  115. if str::from_utf8(&self.oem_id).is_err() {
  116. return Err(RsdpError::InvalidOemId);
  117. }
  118. /*
  119. * `self.length` doesn't exist on ACPI version 1.0, so we mustn't rely on it. Instead,
  120. * check for version 1.0 and use a hard-coded length instead.
  121. */
  122. let length = if self.revision > 0 {
  123. // For Version 2.0+, include the number of bytes specified by `length`
  124. self.length as usize
  125. } else {
  126. RSDP_V1_LENGTH
  127. };
  128. let bytes = unsafe { slice::from_raw_parts(self as *const Rsdp as *const u8, length) };
  129. let sum = bytes.iter().fold(0u8, |sum, &byte| sum.wrapping_add(byte));
  130. if sum != 0 {
  131. return Err(RsdpError::InvalidChecksum);
  132. }
  133. Ok(())
  134. }
  135. pub fn oem_id(&self) -> &str {
  136. str::from_utf8(&self.oem_id).unwrap()
  137. }
  138. pub fn revision(&self) -> u8 {
  139. self.revision
  140. }
  141. pub fn rsdt_address(&self) -> u32 {
  142. self.rsdt_address
  143. }
  144. pub fn xsdt_address(&self) -> u64 {
  145. assert!(self.revision > 0, "Tried to read extended RSDP field with ACPI Version 1.0");
  146. self.xsdt_address
  147. }
  148. }
  149. /// Find the areas we should search for the RSDP in.
  150. pub fn find_search_areas<H>(handler: H) -> [Range<usize>; 2]
  151. where
  152. H: AcpiHandler,
  153. {
  154. /*
  155. * Read the base address of the EBDA from its location in the BDA (BIOS Data Area). Not all BIOSs fill this out
  156. * unfortunately, so we might not get a sensible result. We shift it left 4, as it's a segment address.
  157. */
  158. let ebda_start_mapping =
  159. unsafe { handler.map_physical_region::<u16>(EBDA_START_SEGMENT_PTR, mem::size_of::<u16>()) };
  160. let ebda_start = (*ebda_start_mapping as usize) << 4;
  161. [
  162. /*
  163. * The main BIOS area below 1MiB. In practice, from my [Restioson's] testing, the RSDP is more often here
  164. * than the EBDA. We also don't want to search the entire possibele EBDA range, if we've failed to find it
  165. * from the BDA.
  166. */
  167. RSDP_BIOS_AREA_START..(RSDP_BIOS_AREA_END + 1),
  168. // Check if base segment ptr is in valid range for EBDA base
  169. if (EBDA_EARLIEST_START..EBDA_END).contains(&ebda_start) {
  170. // First KiB of EBDA
  171. ebda_start..ebda_start + 1024
  172. } else {
  173. // We don't know where the EBDA starts, so just search the largest possible EBDA
  174. EBDA_EARLIEST_START..(EBDA_END + 1)
  175. },
  176. ]
  177. }
  178. /// This (usually!) contains the base address of the EBDA (Extended Bios Data Area), shifted right by 4
  179. const EBDA_START_SEGMENT_PTR: usize = 0x40e;
  180. /// The earliest (lowest) memory address an EBDA (Extended Bios Data Area) can start
  181. const EBDA_EARLIEST_START: usize = 0x80000;
  182. /// The end of the EBDA (Extended Bios Data Area)
  183. const EBDA_END: usize = 0x9ffff;
  184. /// The start of the main BIOS area below 1mb in which to search for the RSDP (Root System Description Pointer)
  185. const RSDP_BIOS_AREA_START: usize = 0xe0000;
  186. /// The end of the main BIOS area below 1mb in which to search for the RSDP (Root System Description Pointer)
  187. const RSDP_BIOS_AREA_END: usize = 0xfffff;
  188. /// The RSDP (Root System Description Pointer)'s signature, "RSD PTR " (note trailing space)
  189. const RSDP_SIGNATURE: &'static [u8; 8] = b"RSD PTR ";