interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / mem / memory_map / mod.rs

389 lines · 12955 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Bundles all relevant types and helpers to work with the UEFI memory map.
4//!
5//! To work with the memory map, you should use one of the structs
6//! [`MemoryMapOwned`], [`MemoryMapRef`], or [`MemoryMapRefMut`] - depending on
7//! your use-case. The traits [`MemoryMap`] and [`MemoryMapMut`] mainly exist
8//! to guarantee a streamlined API across these types. We recommend to work with
9//! the specific implementation.
10//!
11//! # Obtaining a UEFI Memory Map
12//!
13//! Use [`boot::exit_boot_services`] or [`boot::memory_map`] to obtain a
14//! properly initialized [`MemoryMapOwned`].
15//!
16//! # Parsing a Memory Slice as a UEFI Memory Map
17//!
18//! To parse memory supplied by a bootloader such as GRUB or Limine as a UEFI
19//! memory map, use [`MemoryMapRef`] or [`MemoryMapRefMut`].
20//!
21//! # Relevant Exports
22//!
23//! - the traits [`MemoryMap`] and [`MemoryMapMut`],
24//! - the trait implementations [`MemoryMapOwned`], [`MemoryMapRef`], and
25//! [`MemoryMapRefMut`],
26//! - the iterator [`MemoryMapIter`]
27//! - various associated helper types, such as [`MemoryMapKey`] and
28//! [`MemoryMapMeta`],
29//! - re-exports [`MemoryDescriptor`], [`MemoryType`], and [`MemoryAttribute`].
30//!
31//! [`boot::exit_boot_services`]: crate::boot::exit_boot_services
32//! [`boot::memory_map`]: crate::boot::memory_map
33
34mod api;
35mod impl_;
36mod iter;
37
38pub use api::*;
39pub use impl_::*;
40pub use iter::*;
41pub use uefi_raw::table::boot::{MemoryAttribute, MemoryDescriptor, MemoryType};
42
43use crate::data_types::Align;
44
45impl Align for MemoryDescriptor {
46 fn alignment() -> usize {
47 align_of::<Self>()
48 }
49}
50
51/// A unique identifier of a UEFI memory map, used to tell the firmware that one
52/// has the latest valid memory map when exiting boot services.
53///
54/// If the memory map changes, due to any allocation or deallocation, this value
55/// is no longer valid, and exiting boot services will fail.
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
57#[repr(C)]
58pub struct MemoryMapKey(pub(crate) usize);
59
60/// A structure containing the meta attributes associated with a call to
61/// `GetMemoryMap` of UEFI.
62///
63/// Note that all values refer to the time this was
64/// called. All following invocations (hidden, subtle, and asynchronous ones)
65/// will likely invalidate this.
66#[derive(Copy, Clone, Debug)]
67pub struct MemoryMapMeta {
68 /// The actual size of the map.
69 pub map_size: usize,
70 /// The reported memory descriptor size. Note that this is the reference
71 /// and never `size_of::<MemoryDescriptor>()`!
72 pub desc_size: usize,
73 /// A unique memory key bound to a specific memory map version/state.
74 pub map_key: MemoryMapKey,
75 /// The version of the descriptor struct.
76 pub desc_version: u32,
77}
78
79impl MemoryMapMeta {
80 /// Returns the amount of entries in the map.
81 #[must_use]
82 pub fn entry_count(&self) -> usize {
83 assert_eq!(self.map_size % self.desc_size, 0);
84 self.map_size / self.desc_size
85 }
86
87 /// Runs some sanity assertions.
88 pub fn assert_sanity_checks(&self) {
89 assert!(self.desc_size > 0);
90 // Although very unlikely, this might fail if the memory descriptor is
91 // extended by a future UEFI revision by a significant amount, we
92 // update the struct, but an old UEFI implementation reports a small
93 // size.
94 assert!(self.desc_size >= size_of::<MemoryDescriptor>());
95 assert!(self.map_size > 0);
96
97 // Ensure the mmap size is (somehow) sane.
98 const ONE_GB: usize = 1024 * 1024 * 1024;
99 assert!(self.map_size <= ONE_GB);
100 }
101}
102
103/// Comprehensive unit test of the memory map functionality with the simplified
104/// data. Here, `desc_size` equals `size_of::<MemoryDescriptor`.
105#[cfg(test)]
106mod tests_mmap_artificial {
107 use super::*;
108
109 fn buffer_to_map(buffer: &mut [MemoryDescriptor]) -> MemoryMapRefMut<'_> {
110 let mmap_len = size_of_val(buffer);
111 let mmap = {
112 // SAFETY: The pointer is valid for the requested slice length.
113 unsafe { core::slice::from_raw_parts_mut(buffer.as_mut_ptr().cast::<u8>(), mmap_len) }
114 };
115
116 MemoryMapRefMut::new(
117 mmap,
118 MemoryMapMeta {
119 map_size: mmap_len,
120 desc_size: size_of::<MemoryDescriptor>(),
121 map_key: Default::default(),
122 desc_version: MemoryDescriptor::VERSION,
123 },
124 )
125 .unwrap()
126 }
127
128 #[test]
129 fn mem_map_sorting() {
130 // Doesn't matter what type it is.
131 const TY: MemoryType = MemoryType::RESERVED;
132
133 const BASE: MemoryDescriptor = MemoryDescriptor {
134 ty: TY,
135 padding: 0,
136 phys_start: 0,
137 virt_start: 0,
138 page_count: 0,
139 att: MemoryAttribute::empty(),
140 };
141
142 let mut buffer = [
143 MemoryDescriptor {
144 phys_start: 2000,
145 ..BASE
146 },
147 MemoryDescriptor {
148 phys_start: 3000,
149 ..BASE
150 },
151 BASE,
152 MemoryDescriptor {
153 phys_start: 1000,
154 ..BASE
155 },
156 ];
157
158 let mut mem_map = buffer_to_map(&mut buffer);
159
160 mem_map.sort();
161
162 if !is_sorted(&mem_map.entries()) {
163 panic!("mem_map is not sorted: {:?}", mem_map);
164 }
165 }
166
167 #[test]
168 fn mem_map_get() {
169 // Doesn't matter what type it is.
170 const TY: MemoryType = MemoryType::RESERVED;
171
172 const BASE: MemoryDescriptor = MemoryDescriptor {
173 padding: 0,
174 ty: TY,
175 phys_start: 0,
176 virt_start: 0,
177 page_count: 0,
178 att: MemoryAttribute::empty(),
179 };
180
181 const BUFFER: [MemoryDescriptor; 4] = [
182 MemoryDescriptor {
183 phys_start: 2000,
184 ..BASE
185 },
186 MemoryDescriptor {
187 phys_start: 3000,
188 ..BASE
189 },
190 BASE,
191 MemoryDescriptor {
192 phys_start: 1000,
193 ..BASE
194 },
195 ];
196
197 let mut buffer = BUFFER;
198
199 let mut mem_map = buffer_to_map(&mut buffer);
200
201 for index in 0..3 {
202 assert_eq!(mem_map.get(index), BUFFER.get(index));
203
204 // Test Index impl
205 assert_eq!(Some(&mem_map[index]), BUFFER.get(index));
206 }
207
208 let mut_desc = mem_map.get_mut(2).unwrap();
209
210 mut_desc.phys_start = 300;
211
212 let desc = mem_map.get(2).unwrap();
213
214 assert_ne!(*desc, BUFFER[2]);
215 }
216
217 fn is_sorted(iter: &MemoryMapIter) -> bool {
218 let mut iter = iter.clone();
219 let mut curr_start;
220
221 if let Some(val) = iter.next() {
222 curr_start = val.phys_start;
223 } else {
224 return true;
225 }
226
227 for desc in iter {
228 if desc.phys_start <= curr_start {
229 return false;
230 }
231 curr_start = desc.phys_start
232 }
233 true
234 }
235}
236
237/// Comprehensive unit test of the memory map functionality with the data from a
238/// real UEFI memory map. The important property that we test here is that
239/// the reported `desc_size` doesn't equal `size_of::<MemoryDescriptor`.
240#[cfg(test)]
241mod tests_mmap_real {
242 use super::*;
243 use alloc::vec::Vec;
244 use core::slice;
245 use size_of;
246
247 const MMAP_META: MemoryMapMeta = MemoryMapMeta {
248 map_size: MMAP_RAW.len() * size_of::<u64>(),
249 desc_size: 48,
250 map_key: MemoryMapKey(0),
251 desc_version: 1,
252 };
253 /// Sample with 10 entries of a real UEFI memory map extracted from our
254 /// UEFI test runner.
255 const MMAP_RAW: [u64; 60] = [
256 3, 0, 0, 1, 15, 0, 7, 4096, 0, 134, 15, 0, 4, 552960, 0, 1, 15, 0, 7, 557056, 0, 24, 15, 0,
257 7, 1048576, 0, 1792, 15, 0, 10, 8388608, 0, 8, 15, 0, 7, 8421376, 0, 3, 15, 0, 10, 8433664,
258 0, 1, 15, 0, 7, 8437760, 0, 4, 15, 0, 10, 8454144, 0, 240, 15, 0,
259 ];
260
261 #[test]
262 fn basic_functionality() {
263 let mut buf = MMAP_RAW;
264 let buf =
265 // SAFETY: The pointer is valid for the requested slice length.
266 unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr().cast::<u8>(), MMAP_META.map_size) };
267 let mut mmap = MemoryMapRefMut::new(buf, MMAP_META).unwrap();
268
269 assert!(mmap.is_sorted());
270 mmap.sort();
271 assert!(mmap.is_sorted());
272
273 let entries = mmap.entries().copied().collect::<Vec<_>>();
274
275 let expected = [
276 MemoryDescriptor {
277 ty: MemoryType::BOOT_SERVICES_CODE,
278 padding: 0,
279 phys_start: 0x0,
280 virt_start: 0x0,
281 page_count: 0x1,
282 att: MemoryAttribute::UNCACHEABLE
283 | MemoryAttribute::WRITE_COMBINE
284 | MemoryAttribute::WRITE_THROUGH
285 | MemoryAttribute::WRITE_BACK,
286 },
287 MemoryDescriptor {
288 ty: MemoryType::CONVENTIONAL,
289 padding: 0,
290 phys_start: 0x1000,
291 virt_start: 0x0,
292 page_count: 0x86,
293 att: MemoryAttribute::UNCACHEABLE
294 | MemoryAttribute::WRITE_COMBINE
295 | MemoryAttribute::WRITE_THROUGH
296 | MemoryAttribute::WRITE_BACK,
297 },
298 MemoryDescriptor {
299 ty: MemoryType::BOOT_SERVICES_DATA,
300 padding: 0,
301 phys_start: 0x87000,
302 virt_start: 0x0,
303 page_count: 0x1,
304 att: MemoryAttribute::UNCACHEABLE
305 | MemoryAttribute::WRITE_COMBINE
306 | MemoryAttribute::WRITE_THROUGH
307 | MemoryAttribute::WRITE_BACK,
308 },
309 MemoryDescriptor {
310 ty: MemoryType::CONVENTIONAL,
311 padding: 0,
312 phys_start: 0x88000,
313 virt_start: 0x0,
314 page_count: 0x18,
315 att: MemoryAttribute::UNCACHEABLE
316 | MemoryAttribute::WRITE_COMBINE
317 | MemoryAttribute::WRITE_THROUGH
318 | MemoryAttribute::WRITE_BACK,
319 },
320 MemoryDescriptor {
321 ty: MemoryType::CONVENTIONAL,
322 padding: 0,
323 phys_start: 0x100000,
324 virt_start: 0x0,
325 page_count: 0x700,
326 att: MemoryAttribute::UNCACHEABLE
327 | MemoryAttribute::WRITE_COMBINE
328 | MemoryAttribute::WRITE_THROUGH
329 | MemoryAttribute::WRITE_BACK,
330 },
331 MemoryDescriptor {
332 ty: MemoryType::ACPI_NON_VOLATILE,
333 padding: 0,
334 phys_start: 0x800000,
335 virt_start: 0x0,
336 page_count: 0x8,
337 att: MemoryAttribute::UNCACHEABLE
338 | MemoryAttribute::WRITE_COMBINE
339 | MemoryAttribute::WRITE_THROUGH
340 | MemoryAttribute::WRITE_BACK,
341 },
342 MemoryDescriptor {
343 ty: MemoryType::CONVENTIONAL,
344 padding: 0,
345 phys_start: 0x808000,
346 virt_start: 0x0,
347 page_count: 0x3,
348 att: MemoryAttribute::UNCACHEABLE
349 | MemoryAttribute::WRITE_COMBINE
350 | MemoryAttribute::WRITE_THROUGH
351 | MemoryAttribute::WRITE_BACK,
352 },
353 MemoryDescriptor {
354 ty: MemoryType::ACPI_NON_VOLATILE,
355 padding: 0,
356 phys_start: 0x80b000,
357 virt_start: 0x0,
358 page_count: 0x1,
359 att: MemoryAttribute::UNCACHEABLE
360 | MemoryAttribute::WRITE_COMBINE
361 | MemoryAttribute::WRITE_THROUGH
362 | MemoryAttribute::WRITE_BACK,
363 },
364 MemoryDescriptor {
365 ty: MemoryType::CONVENTIONAL,
366 padding: 0,
367 phys_start: 0x80c000,
368 virt_start: 0x0,
369 page_count: 0x4,
370 att: MemoryAttribute::UNCACHEABLE
371 | MemoryAttribute::WRITE_COMBINE
372 | MemoryAttribute::WRITE_THROUGH
373 | MemoryAttribute::WRITE_BACK,
374 },
375 MemoryDescriptor {
376 ty: MemoryType::ACPI_NON_VOLATILE,
377 padding: 0,
378 phys_start: 0x810000,
379 virt_start: 0x0,
380 page_count: 0xf0,
381 att: MemoryAttribute::UNCACHEABLE
382 | MemoryAttribute::WRITE_COMBINE
383 | MemoryAttribute::WRITE_THROUGH
384 | MemoryAttribute::WRITE_BACK,
385 },
386 ];
387 assert_eq!(entries.as_slice(), &expected);
388 }
389}