memory_map.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. use crate::{Tag, TagTrait, TagType, TagTypeId};
  2. use core::convert::TryInto;
  3. use core::marker::PhantomData;
  4. use core::mem;
  5. #[cfg(feature = "builder")]
  6. use {crate::builder::boxed_dst_tag, crate::builder::traits::StructAsBytes, alloc::boxed::Box};
  7. const METADATA_SIZE: usize = mem::size_of::<TagTypeId>() + 3 * mem::size_of::<u32>();
  8. /// This tag provides an initial host memory map.
  9. ///
  10. /// The map provided is guaranteed to list all standard RAM that should be
  11. /// available for normal use. This type however includes the regions occupied
  12. /// by kernel, mbi, segments and modules. Kernel must take care not to
  13. /// overwrite these regions.
  14. ///
  15. /// This tag may not be provided by some boot loaders on EFI platforms if EFI
  16. /// boot services are enabled and available for the loaded image (The EFI boot
  17. /// services tag may exist in the Multiboot2 boot information structure).
  18. #[derive(Debug, ptr_meta::Pointee)]
  19. #[repr(C)]
  20. pub struct MemoryMapTag {
  21. typ: TagTypeId,
  22. size: u32,
  23. entry_size: u32,
  24. entry_version: u32,
  25. areas: [MemoryArea],
  26. }
  27. impl MemoryMapTag {
  28. #[cfg(feature = "builder")]
  29. pub fn new(areas: &[MemoryArea]) -> Box<Self> {
  30. let entry_size: u32 = mem::size_of::<MemoryArea>().try_into().unwrap();
  31. let entry_version: u32 = 0;
  32. let mut bytes = [entry_size.to_le_bytes(), entry_version.to_le_bytes()].concat();
  33. for area in areas {
  34. bytes.extend(area.struct_as_bytes());
  35. }
  36. boxed_dst_tag(TagType::Mmap, bytes.as_slice())
  37. }
  38. /// Return an iterator over all memory areas that have the type
  39. /// [`MemoryAreaType::Available`].
  40. pub fn available_memory_areas(&self) -> impl Iterator<Item = &MemoryArea> {
  41. self.memory_areas()
  42. .filter(|entry| matches!(entry.typ, MemoryAreaType::Available))
  43. }
  44. /// Return an iterator over all memory areas.
  45. pub fn memory_areas(&self) -> MemoryAreaIter {
  46. let self_ptr = self as *const MemoryMapTag;
  47. let start_area = (&self.areas[0]) as *const MemoryArea;
  48. MemoryAreaIter {
  49. current_area: start_area as u64,
  50. // NOTE: `last_area` is only a bound, it doesn't necessarily point exactly to the last element
  51. last_area: (self_ptr as *const () as u64 + (self.size - self.entry_size) as u64),
  52. entry_size: self.entry_size,
  53. phantom: PhantomData,
  54. }
  55. }
  56. }
  57. impl TagTrait for MemoryMapTag {
  58. fn dst_size(base_tag: &Tag) -> usize {
  59. assert!(base_tag.size as usize >= METADATA_SIZE);
  60. base_tag.size as usize - METADATA_SIZE
  61. }
  62. }
  63. #[cfg(feature = "builder")]
  64. impl StructAsBytes for MemoryMapTag {
  65. fn byte_size(&self) -> usize {
  66. self.size.try_into().unwrap()
  67. }
  68. }
  69. /// A memory area entry descriptor.
  70. #[derive(Debug, Clone)]
  71. #[repr(C)]
  72. pub struct MemoryArea {
  73. base_addr: u64,
  74. length: u64,
  75. typ: MemoryAreaType,
  76. _reserved: u32,
  77. }
  78. impl MemoryArea {
  79. /// Create a new MemoryArea.
  80. pub fn new(base_addr: u64, length: u64, typ: MemoryAreaType) -> Self {
  81. Self {
  82. base_addr,
  83. length,
  84. typ,
  85. _reserved: 0,
  86. }
  87. }
  88. /// The start address of the memory region.
  89. pub fn start_address(&self) -> u64 {
  90. self.base_addr
  91. }
  92. /// The end address of the memory region.
  93. pub fn end_address(&self) -> u64 {
  94. self.base_addr + self.length
  95. }
  96. /// The size, in bytes, of the memory region.
  97. pub fn size(&self) -> u64 {
  98. self.length
  99. }
  100. /// The type of the memory region.
  101. pub fn typ(&self) -> MemoryAreaType {
  102. self.typ
  103. }
  104. }
  105. #[cfg(feature = "builder")]
  106. impl StructAsBytes for MemoryArea {
  107. fn byte_size(&self) -> usize {
  108. mem::size_of::<Self>()
  109. }
  110. }
  111. /// An enum of possible reported region types.
  112. /// Inside the Multiboot2 spec this is kind of hidden
  113. /// inside the implementation of `struct multiboot_mmap_entry`.
  114. #[derive(Debug, PartialEq, Eq, Copy, Clone)]
  115. #[repr(u32)]
  116. pub enum MemoryAreaType {
  117. /// Available memory free to be used by the OS.
  118. Available = 1,
  119. /// A reserved area that must not be used.
  120. Reserved = 2,
  121. /// Usable memory holding ACPI information.
  122. AcpiAvailable = 3,
  123. /// Reserved memory which needs to be preserved on hibernation.
  124. /// Also called NVS in spec, which stands for "Non-Volatile Sleep/Storage",
  125. /// which is part of ACPI specification.
  126. ReservedHibernate = 4,
  127. /// Memory which is occupied by defective RAM modules.
  128. Defective = 5,
  129. }
  130. /// An iterator over all memory areas
  131. #[derive(Clone, Debug)]
  132. pub struct MemoryAreaIter<'a> {
  133. current_area: u64,
  134. last_area: u64,
  135. entry_size: u32,
  136. phantom: PhantomData<&'a MemoryArea>,
  137. }
  138. impl<'a> Iterator for MemoryAreaIter<'a> {
  139. type Item = &'a MemoryArea;
  140. fn next(&mut self) -> Option<&'a MemoryArea> {
  141. if self.current_area > self.last_area {
  142. None
  143. } else {
  144. let area = unsafe { &*(self.current_area as *const MemoryArea) };
  145. self.current_area += self.entry_size as u64;
  146. Some(area)
  147. }
  148. }
  149. }
  150. /// Basic memory info
  151. ///
  152. /// This tag includes "basic memory information".
  153. /// This means (legacy) lower and upper memory:
  154. /// In Real Mode (modeled after the 8086),
  155. /// only the first 1MB of memory is accessible.
  156. /// Typically, the region between 640KB and 1MB is not freely usable,
  157. /// because it is used for memory-mapped IO, for instance.
  158. /// The term “lower memory” refers to those first 640KB of memory that are
  159. /// freely usable for an application in Real Mode.
  160. /// “Upper memory” then refers to the next freely usable chunk of memory,
  161. /// starting at 1MB up to about 10MB, in practice.
  162. /// This is the memory an application running on a 286
  163. /// (which had a 24-bit address bus) could use, historically.
  164. /// Nowadays, much bigger chunks of continuous memory are available at higher
  165. /// addresses, but the Multiboot standard still references those two terms.
  166. #[derive(Debug)]
  167. #[repr(C, packed)]
  168. pub struct BasicMemoryInfoTag {
  169. typ: TagTypeId,
  170. size: u32,
  171. memory_lower: u32,
  172. memory_upper: u32,
  173. }
  174. impl BasicMemoryInfoTag {
  175. pub fn new(memory_lower: u32, memory_upper: u32) -> Self {
  176. Self {
  177. typ: TagType::BasicMeminfo.into(),
  178. size: mem::size_of::<BasicMemoryInfoTag>().try_into().unwrap(),
  179. memory_lower,
  180. memory_upper,
  181. }
  182. }
  183. pub fn memory_lower(&self) -> u32 {
  184. self.memory_lower
  185. }
  186. pub fn memory_upper(&self) -> u32 {
  187. self.memory_upper
  188. }
  189. }
  190. #[cfg(feature = "builder")]
  191. impl StructAsBytes for BasicMemoryInfoTag {
  192. fn byte_size(&self) -> usize {
  193. mem::size_of::<Self>()
  194. }
  195. }
  196. /// EFI memory map as per EFI specification.
  197. #[derive(Debug)]
  198. #[repr(C)]
  199. pub struct EFIMemoryMapTag {
  200. typ: TagTypeId,
  201. size: u32,
  202. desc_size: u32,
  203. desc_version: u32,
  204. first_desc: [EFIMemoryDesc; 0],
  205. }
  206. impl EFIMemoryMapTag {
  207. /// Return an iterator over ALL marked memory areas.
  208. ///
  209. /// This differs from `MemoryMapTag` as for UEFI, the OS needs some non-
  210. /// available memory areas for tables and such.
  211. pub fn memory_areas(&self) -> EFIMemoryAreaIter {
  212. let self_ptr = self as *const EFIMemoryMapTag;
  213. let start_area = self.first_desc.as_ptr();
  214. EFIMemoryAreaIter {
  215. current_area: start_area as u64,
  216. // NOTE: `last_area` is only a bound, it doesn't necessarily point exactly to the last element
  217. last_area: (self_ptr as u64
  218. + (self.size as u64 - core::mem::size_of::<EFIMemoryMapTag>() as u64)),
  219. entry_size: self.desc_size,
  220. phantom: PhantomData,
  221. }
  222. }
  223. }
  224. /// EFI Boot Memory Map Descriptor
  225. #[derive(Debug)]
  226. #[repr(C)]
  227. pub struct EFIMemoryDesc {
  228. typ: u32,
  229. _padding: u32,
  230. phys_addr: u64,
  231. virt_addr: u64,
  232. num_pages: u64,
  233. attr: u64,
  234. }
  235. /// An enum of possible reported region types.
  236. #[derive(Debug, PartialEq, Eq)]
  237. pub enum EFIMemoryAreaType {
  238. /// Unusable.
  239. EfiReservedMemoryType,
  240. /// Code area of a UEFI application.
  241. EfiLoaderCode,
  242. /// Data area of a UEFI application.
  243. EfiLoaderData,
  244. /// Code area of a UEFI Boot Service Driver.
  245. EfiBootServicesCode,
  246. /// Data area of a UEFI Boot Service Driver.
  247. EfiBootServicesData,
  248. /// Code area of a UEFI Runtime Driver.
  249. ///
  250. /// Must be preserved in working and ACPI S1-S3 states.
  251. EfiRuntimeServicesCode,
  252. /// Data area of a UEFI Runtime Driver.
  253. ///
  254. /// Must be preserved in working and ACPI S1-S3 states.
  255. EfiRuntimeServicesData,
  256. /// Available memory.
  257. EfiConventionalMemory,
  258. /// Memory with errors, treat as unusable.
  259. EfiUnusableMemory,
  260. /// Memory containing the ACPI tables.
  261. ///
  262. /// Must be preserved in working and ACPI S1-S3 states.
  263. EfiACPIReclaimMemory,
  264. /// Memory reserved by firmware.
  265. ///
  266. /// Must be preserved in working and ACPI S1-S3 states.
  267. EfiACPIMemoryNVS,
  268. /// Memory used by firmware for requesting memory mapping of IO.
  269. ///
  270. /// Should not be used by the OS. Use the ACPI tables for memory mapped IO
  271. /// information.
  272. EfiMemoryMappedIO,
  273. /// Memory used to translate memory cycles to IO cycles.
  274. ///
  275. /// Should not be used by the OS. Use the ACPI tables for memory mapped IO
  276. /// information.
  277. EfiMemoryMappedIOPortSpace,
  278. /// Memory used by the processor.
  279. ///
  280. /// Must be preserved in working and ACPI S1-S4 states. Processor defined
  281. /// otherwise.
  282. EfiPalCode,
  283. /// Available memory supporting byte-addressable non-volatility.
  284. EfiPersistentMemory,
  285. /// Unknown region type, treat as unusable.
  286. EfiUnknown,
  287. }
  288. impl EFIMemoryDesc {
  289. /// The physical address of the memory region.
  290. pub fn physical_address(&self) -> u64 {
  291. self.phys_addr
  292. }
  293. /// The virtual address of the memory region.
  294. pub fn virtual_address(&self) -> u64 {
  295. self.virt_addr
  296. }
  297. /// The size in bytes of the memory region.
  298. pub fn size(&self) -> u64 {
  299. // Spec says this is number of 4KiB pages.
  300. self.num_pages * 4096
  301. }
  302. /// The type of the memory region.
  303. pub fn typ(&self) -> EFIMemoryAreaType {
  304. match self.typ {
  305. 0 => EFIMemoryAreaType::EfiReservedMemoryType,
  306. 1 => EFIMemoryAreaType::EfiLoaderCode,
  307. 2 => EFIMemoryAreaType::EfiLoaderData,
  308. 3 => EFIMemoryAreaType::EfiBootServicesCode,
  309. 4 => EFIMemoryAreaType::EfiBootServicesData,
  310. 5 => EFIMemoryAreaType::EfiRuntimeServicesCode,
  311. 6 => EFIMemoryAreaType::EfiRuntimeServicesData,
  312. 7 => EFIMemoryAreaType::EfiConventionalMemory,
  313. 8 => EFIMemoryAreaType::EfiUnusableMemory,
  314. 9 => EFIMemoryAreaType::EfiACPIReclaimMemory,
  315. 10 => EFIMemoryAreaType::EfiACPIMemoryNVS,
  316. 11 => EFIMemoryAreaType::EfiMemoryMappedIO,
  317. 12 => EFIMemoryAreaType::EfiMemoryMappedIOPortSpace,
  318. 13 => EFIMemoryAreaType::EfiPalCode,
  319. 14 => EFIMemoryAreaType::EfiPersistentMemory,
  320. _ => EFIMemoryAreaType::EfiUnknown,
  321. }
  322. }
  323. }
  324. /// EFI ExitBootServices was not called
  325. #[derive(Debug)]
  326. #[repr(C)]
  327. pub struct EFIBootServicesNotExited {
  328. typ: u32,
  329. size: u32,
  330. }
  331. /// An iterator over ALL EFI memory areas.
  332. #[derive(Clone, Debug)]
  333. pub struct EFIMemoryAreaIter<'a> {
  334. current_area: u64,
  335. last_area: u64,
  336. entry_size: u32,
  337. phantom: PhantomData<&'a EFIMemoryDesc>,
  338. }
  339. impl<'a> Iterator for EFIMemoryAreaIter<'a> {
  340. type Item = &'a EFIMemoryDesc;
  341. fn next(&mut self) -> Option<&'a EFIMemoryDesc> {
  342. if self.current_area > self.last_area {
  343. None
  344. } else {
  345. let area = unsafe { &*(self.current_area as *const EFIMemoryDesc) };
  346. self.current_area += self.entry_size as u64;
  347. Some(area)
  348. }
  349. }
  350. }