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-raw / src / table / boot.rs

562 lines · 21446 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! UEFI services available during boot.
4
5use crate::protocol::device_path::DevicePathProtocol;
6use crate::table::Header;
7use crate::{
8 Boolean, Char16, Event, Guid, Handle, PhysicalAddress, Status, VirtualAddress, newtype_enum,
9};
10use bitflags::bitflags;
11use core::ffi::c_void;
12use core::mem::offset_of;
13use core::ops::RangeInclusive;
14
15newtype_enum! {
16 /// The type of allocation to perform.
17 pub enum AllocateType: u32 => {
18 /// Allocate any available range of pages that satisfies the request.
19 ///
20 /// On input, the address pointed to by the memory parameter is ignored.
21 ANY_PAGES = 0,
22 /// Allocate any available range of pages whose uppermost address is
23 /// less than or equal to the address pointed to by the memory passed
24 /// parameter.
25 MAX_ADDRESS = 1,
26 /// Allocate pages at the address pointed to by the memory parameter.
27 ADDRESS = 2,
28 /// .
29 MAX_ALLOCATE_TYPE = 3,
30 }
31}
32
33/// Table of pointers to all the boot services.
34#[derive(Debug)]
35#[repr(C)]
36#[expect(missing_docs)]
37pub struct BootServices {
38 pub header: Header,
39
40 // Task Priority services
41 pub raise_tpl: unsafe extern "efiapi" fn(new_tpl: Tpl) -> Tpl,
42 pub restore_tpl: unsafe extern "efiapi" fn(old_tpl: Tpl),
43
44 // Memory allocation functions
45 pub allocate_pages: unsafe extern "efiapi" fn(
46 alloc_ty: AllocateType,
47 mem_ty: MemoryType,
48 count: usize,
49 addr: *mut PhysicalAddress,
50 ) -> Status,
51 pub free_pages: unsafe extern "efiapi" fn(addr: PhysicalAddress, pages: usize) -> Status,
52 pub get_memory_map: unsafe extern "efiapi" fn(
53 size: *mut usize,
54 map: *mut MemoryDescriptor,
55 key: *mut usize,
56 desc_size: *mut usize,
57 desc_version: *mut u32,
58 ) -> Status,
59 pub allocate_pool: unsafe extern "efiapi" fn(
60 pool_type: MemoryType,
61 size: usize,
62 buffer: *mut *mut u8,
63 ) -> Status,
64 pub free_pool: unsafe extern "efiapi" fn(buffer: *mut u8) -> Status,
65
66 // Event & timer functions
67 pub create_event: unsafe extern "efiapi" fn(
68 ty: EventType,
69 notify_tpl: Tpl,
70 notify_func: Option<EventNotifyFn>,
71 notify_ctx: *mut c_void,
72 out_event: *mut Event,
73 ) -> Status,
74 pub set_timer:
75 unsafe extern "efiapi" fn(event: Event, ty: TimerDelay, trigger_time: u64) -> Status,
76 pub wait_for_event: unsafe extern "efiapi" fn(
77 number_of_events: usize,
78 events: *const Event,
79 out_index: *mut usize,
80 ) -> Status,
81 pub signal_event: unsafe extern "efiapi" fn(event: Event) -> Status,
82 pub close_event: unsafe extern "efiapi" fn(event: Event) -> Status,
83 pub check_event: unsafe extern "efiapi" fn(event: Event) -> Status,
84
85 // Protocol handlers
86 pub install_protocol_interface: unsafe extern "efiapi" fn(
87 handle: *mut Handle,
88 guid: *const Guid,
89 interface_type: InterfaceType,
90 interface: *const c_void,
91 ) -> Status,
92 pub reinstall_protocol_interface: unsafe extern "efiapi" fn(
93 handle: Handle,
94 protocol: *const Guid,
95 old_interface: *const c_void,
96 new_interface: *const c_void,
97 ) -> Status,
98 pub uninstall_protocol_interface: unsafe extern "efiapi" fn(
99 handle: Handle,
100 protocol: *const Guid,
101 interface: *const c_void,
102 ) -> Status,
103 pub handle_protocol: unsafe extern "efiapi" fn(
104 handle: Handle,
105 proto: *const Guid,
106 out_proto: *mut *mut c_void,
107 ) -> Status,
108 pub reserved: *mut c_void,
109 pub register_protocol_notify: unsafe extern "efiapi" fn(
110 protocol: *const Guid,
111 event: Event,
112 registration: *mut *mut c_void,
113 ) -> Status,
114 pub locate_handle: unsafe extern "efiapi" fn(
115 search_ty: i32,
116 proto: *const Guid,
117 key: *const c_void,
118 buf_sz: *mut usize,
119 buf: *mut Handle,
120 ) -> Status,
121 pub locate_device_path: unsafe extern "efiapi" fn(
122 proto: *const Guid,
123 device_path: *mut *const DevicePathProtocol,
124 out_handle: *mut Handle,
125 ) -> Status,
126 pub install_configuration_table:
127 unsafe extern "efiapi" fn(guid_entry: *const Guid, table_ptr: *const c_void) -> Status,
128
129 // Image services
130 pub load_image: unsafe extern "efiapi" fn(
131 boot_policy: Boolean,
132 parent_image_handle: Handle,
133 device_path: *const DevicePathProtocol,
134 source_buffer: *const u8,
135 source_size: usize,
136 image_handle: *mut Handle,
137 ) -> Status,
138 pub start_image: unsafe extern "efiapi" fn(
139 image_handle: Handle,
140 exit_data_size: *mut usize,
141 exit_data: *mut *mut Char16,
142 ) -> Status,
143 pub exit: unsafe extern "efiapi" fn(
144 image_handle: Handle,
145 exit_status: Status,
146 exit_data_size: usize,
147 exit_data: *mut Char16,
148 ) -> Status,
149 pub unload_image: unsafe extern "efiapi" fn(image_handle: Handle) -> Status,
150 pub exit_boot_services:
151 unsafe extern "efiapi" fn(image_handle: Handle, map_key: usize) -> Status,
152
153 // Misc services
154 pub get_next_monotonic_count: unsafe extern "efiapi" fn(count: *mut u64) -> Status,
155 pub stall: unsafe extern "efiapi" fn(microseconds: usize) -> Status,
156 pub set_watchdog_timer: unsafe extern "efiapi" fn(
157 timeout: usize,
158 watchdog_code: u64,
159 data_size: usize,
160 watchdog_data: *const u16,
161 ) -> Status,
162
163 // Driver support services
164 pub connect_controller: unsafe extern "efiapi" fn(
165 controller: Handle,
166 driver_image: *const Handle,
167 remaining_device_path: *const DevicePathProtocol,
168 recursive: Boolean,
169 ) -> Status,
170 pub disconnect_controller: unsafe extern "efiapi" fn(
171 controller: Handle,
172 driver_image: Handle,
173 child: Handle,
174 ) -> Status,
175
176 // Protocol open / close services
177 pub open_protocol: unsafe extern "efiapi" fn(
178 handle: Handle,
179 protocol: *const Guid,
180 interface: *mut *mut c_void,
181 agent_handle: Handle,
182 controller_handle: Handle,
183 attributes: u32,
184 ) -> Status,
185 pub close_protocol: unsafe extern "efiapi" fn(
186 handle: Handle,
187 protocol: *const Guid,
188 agent_handle: Handle,
189 controller_handle: Handle,
190 ) -> Status,
191 pub open_protocol_information: unsafe extern "efiapi" fn(
192 handle: Handle,
193 protocol: *const Guid,
194 entry_buffer: *mut *mut OpenProtocolInformationEntry,
195 entry_count: *mut usize,
196 ) -> Status,
197
198 // Library services
199 pub protocols_per_handle: unsafe extern "efiapi" fn(
200 handle: Handle,
201 protocol_buffer: *mut *mut *const Guid,
202 protocol_buffer_count: *mut usize,
203 ) -> Status,
204 pub locate_handle_buffer: unsafe extern "efiapi" fn(
205 search_ty: i32,
206 proto: *const Guid,
207 key: *const c_void,
208 no_handles: *mut usize,
209 buf: *mut *mut Handle,
210 ) -> Status,
211 pub locate_protocol: unsafe extern "efiapi" fn(
212 proto: *const Guid,
213 registration: *const c_void,
214 out_proto: *mut *mut c_void,
215 ) -> Status,
216
217 /// Warning: this function pointer is declared as `extern "C"` rather than
218 /// `extern "efiapi". That means it will work correctly when called from a
219 /// UEFI target (`*-unknown-uefi`), but will not work when called from a
220 /// target with a different calling convention such as
221 /// `x86_64-unknown-linux-gnu`.
222 ///
223 /// Support for C-variadics with `efiapi` requires the unstable
224 /// [`extended_varargs_abi_support`](https://github.com/rust-lang/rust/issues/100189)
225 /// feature.
226 pub install_multiple_protocol_interfaces:
227 unsafe extern "C" fn(handle: *mut Handle, ...) -> Status,
228
229 /// Warning: this function pointer is declared as `extern "C"` rather than
230 /// `extern "efiapi". That means it will work correctly when called from a
231 /// UEFI target (`*-unknown-uefi`), but will not work when called from a
232 /// target with a different calling convention such as
233 /// `x86_64-unknown-linux-gnu`.
234 ///
235 /// Support for C-variadics with `efiapi` requires the unstable
236 /// [`extended_varargs_abi_support`](https://github.com/rust-lang/rust/issues/100189)
237 /// feature.
238 pub uninstall_multiple_protocol_interfaces: unsafe extern "C" fn(handle: Handle, ...) -> Status,
239
240 // CRC services
241 pub calculate_crc32:
242 unsafe extern "efiapi" fn(data: *const c_void, data_size: usize, crc32: *mut u32) -> Status,
243
244 // Misc services
245 pub copy_mem: unsafe extern "efiapi" fn(dest: *mut u8, src: *const u8, len: usize),
246 pub set_mem: unsafe extern "efiapi" fn(buffer: *mut u8, len: usize, value: u8),
247
248 // New event functions (UEFI 2.0 or newer)
249 pub create_event_ex: unsafe extern "efiapi" fn(
250 ty: EventType,
251 notify_tpl: Tpl,
252 notify_fn: Option<EventNotifyFn>,
253 notify_ctx: *const c_void,
254 event_group: *const Guid,
255 out_event: *mut Event,
256 ) -> Status,
257}
258
259bitflags! {
260 /// Flags describing the type of a UEFI event and its attributes.
261 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
262 #[repr(transparent)]
263 pub struct EventType: u32 {
264 /// The event is a timer event and may be passed to `BootServices::set_timer()`
265 /// Note that timers only function during boot services time.
266 const TIMER = 0x8000_0000;
267
268 /// The event is allocated from runtime memory.
269 /// This must be done if the event is to be signaled after ExitBootServices.
270 const RUNTIME = 0x4000_0000;
271
272 /// Calling wait_for_event or check_event will enqueue the notification
273 /// function if the event is not already in the signaled state.
274 /// Mutually exclusive with `NOTIFY_SIGNAL`.
275 const NOTIFY_WAIT = 0x0000_0100;
276
277 /// The notification function will be enqueued when the event is signaled
278 /// Mutually exclusive with `NOTIFY_WAIT`.
279 const NOTIFY_SIGNAL = 0x0000_0200;
280
281 /// The event will be signaled at ExitBootServices time.
282 /// This event type should not be combined with any other.
283 /// Its notification function must follow some special rules:
284 /// - Cannot use memory allocation services, directly or indirectly
285 /// - Cannot depend on timer events, since those will be deactivated
286 const SIGNAL_EXIT_BOOT_SERVICES = 0x0000_0201;
287
288 /// The event will be notified when SetVirtualAddressMap is performed.
289 /// This event type should not be combined with any other.
290 const SIGNAL_VIRTUAL_ADDRESS_CHANGE = 0x6000_0202;
291 }
292}
293
294newtype_enum! {
295/// Interface type of a protocol interface.
296pub enum InterfaceType: u32 => {
297 /// Native interface
298 NATIVE_INTERFACE = 0,
299}}
300
301/// Raw event notification function.
302///
303/// The firmware passes the context of `CreateEvent()`/`CreateEventEx()`
304/// through unchanged. It is the caller's own memory, which the notification
305/// function may write through, hence `*mut`. Note that `CreateEventEx()`
306/// declares the very same pointer `IN CONST VOID *NotifyContext`.
307pub type EventNotifyFn = unsafe extern "efiapi" fn(event: Event, context: *mut c_void);
308
309bitflags! {
310 /// Flags describing the capabilities of a memory range.
311 #[repr(transparent)]
312 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
313 pub struct MemoryAttribute: u64 {
314 /// Supports marking as uncacheable.
315 const UNCACHEABLE = 0x1;
316 /// Supports write-combining.
317 const WRITE_COMBINE = 0x2;
318 /// Supports write-through.
319 const WRITE_THROUGH = 0x4;
320 /// Support write-back.
321 const WRITE_BACK = 0x8;
322 /// Supports marking as uncacheable, exported and
323 /// supports the "fetch and add" semaphore mechanism.
324 const UNCACHABLE_EXPORTED = 0x10;
325 /// Supports write-protection.
326 const WRITE_PROTECT = 0x1000;
327 /// Supports read-protection.
328 const READ_PROTECT = 0x2000;
329 /// Supports disabling code execution.
330 const EXECUTE_PROTECT = 0x4000;
331 /// Persistent memory.
332 const NON_VOLATILE = 0x8000;
333 /// This memory region is more reliable than other memory.
334 const MORE_RELIABLE = 0x10000;
335 /// This memory range can be set as read-only.
336 const READ_ONLY = 0x20000;
337 /// This memory is earmarked for specific purposes such as for specific
338 /// device drivers or applications. This serves as a hint to the OS to
339 /// avoid this memory for core OS data or code that cannot be relocated.
340 const SPECIAL_PURPOSE = 0x4_0000;
341 /// This memory region is capable of being protected with the CPU's memory
342 /// cryptography capabilities.
343 const CPU_CRYPTO = 0x8_0000;
344 /// This memory region is capable of being hot-plugged (added or
345 /// removed at runtime). The OS should only use it for allocations
346 /// that can be relocated or freed, so that the region can be taken
347 /// offline.
348 const HOT_PLUGGABLE = 0x10_0000;
349 /// This memory must be mapped by the OS when a runtime service is called.
350 const RUNTIME = 0x8000_0000_0000_0000;
351 /// This memory region is described with additional ISA-specific memory
352 /// attributes as specified in `MemoryAttribute::ISA_MASK`.
353 const ISA_VALID = 0x4000_0000_0000_0000;
354 /// These bits are reserved for describing optional ISA-specific cache-
355 /// ability attributes that are not covered by the standard UEFI Memory
356 /// Attribute cacheability bits such as `UNCACHEABLE`, `WRITE_COMBINE`,
357 /// `WRITE_THROUGH`, `WRITE_BACK`, and `UNCACHEABLE_EXPORTED`.
358 ///
359 /// See Section 2.3 "Calling Conventions" in the UEFI Specification
360 /// for further information on each ISA that takes advantage of this.
361 const ISA_MASK = 0x0FFF_F000_0000_0000;
362 }
363}
364
365/// A structure describing a region of memory. This type corresponds to [version]
366/// of this struct in the UEFI spec and is always bound to a corresponding
367/// UEFI memory map.
368///
369/// # UEFI pitfalls
370/// As of May 2024:
371/// The memory descriptor struct might be extended in the future by a new UEFI
372/// spec revision, which will be reflected in another `version` of that
373/// descriptor. The version is reported when using `get_memory_map` of
374/// [`BootServices`].
375///
376/// Also note that you **must never** work with `size_of::<MemoryDescriptor>`
377/// but always with `desc_size`, which is reported when using `get_memory_map`
378/// as well [[0]]. For example, although the actual size is of version 1
379/// descriptors is `40`, the reported `desc_size` is `48`.
380///
381/// [version]: MemoryDescriptor::VERSION
382/// [0]: https://github.com/tianocore/edk2/blob/7142e648416ff5d3eac6c6d607874805f5de0ca8/MdeModulePkg/Core/PiSmmCore/Page.c#L1059
383#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
384#[repr(C, align(8))]
385pub struct MemoryDescriptor {
386 /// Type of memory occupying this range.
387 pub ty: MemoryType,
388 /// Implicit padding that should be set to 0.
389 ///
390 /// This field is required for a correct layout on non-UEFI targets to
391 /// properly parse a memory map.
392 pub padding: u32,
393 // Implicit 32-bit padding.
394 /// Starting physical address.
395 pub phys_start: PhysicalAddress,
396 /// Starting virtual address.
397 pub virt_start: VirtualAddress,
398 /// Number of 4 KiB pages contained in this range.
399 pub page_count: u64,
400 /// The capability attributes of this memory range.
401 pub att: MemoryAttribute,
402}
403
404// Ensure ABI guarantees for MemoryDescriptor.
405const _: () = {
406 assert!(size_of::<MemoryDescriptor>() == 40);
407 assert!(align_of::<MemoryDescriptor>() == 8);
408
409 assert!(offset_of!(MemoryDescriptor, ty) == 0);
410 assert!(offset_of!(MemoryDescriptor, phys_start) == 8);
411 assert!(offset_of!(MemoryDescriptor, virt_start) == 16);
412 assert!(offset_of!(MemoryDescriptor, page_count) == 24);
413 assert!(offset_of!(MemoryDescriptor, att) == 32);
414};
415
416impl MemoryDescriptor {
417 /// Memory descriptor version number.
418 pub const VERSION: u32 = 1;
419}
420
421impl Default for MemoryDescriptor {
422 fn default() -> Self {
423 Self {
424 ty: MemoryType::RESERVED,
425 padding: 0,
426 phys_start: 0,
427 virt_start: 0,
428 page_count: 0,
429 att: MemoryAttribute::empty(),
430 }
431 }
432}
433
434newtype_enum! {
435/// The type of a memory range.
436///
437/// UEFI allows firmwares and operating systems to introduce new memory types
438/// in the `0x7000_0000..=0xFFFF_FFFF` range. Therefore, we don't know the full set
439/// of memory types at compile time, and it is _not_ safe to model this C enum
440/// as a Rust enum.
441pub enum MemoryType: u32 => {
442 /// Not usable.
443 RESERVED = 0,
444 /// The code portions of a loaded UEFI application.
445 LOADER_CODE = 1,
446 /// The data portions of a loaded UEFI applications,
447 /// as well as any memory allocated by it.
448 LOADER_DATA = 2,
449 /// Code of the boot drivers.
450 ///
451 /// Can be reused after OS is loaded.
452 BOOT_SERVICES_CODE = 3,
453 /// Memory used to store boot drivers' data.
454 ///
455 /// Can be reused after OS is loaded.
456 BOOT_SERVICES_DATA = 4,
457 /// Runtime drivers' code.
458 RUNTIME_SERVICES_CODE = 5,
459 /// Runtime services' code.
460 RUNTIME_SERVICES_DATA = 6,
461 /// Free usable memory.
462 CONVENTIONAL = 7,
463 /// Memory in which errors have been detected.
464 UNUSABLE = 8,
465 /// Memory that holds ACPI tables.
466 /// Can be reclaimed after they are parsed.
467 ACPI_RECLAIM = 9,
468 /// Firmware-reserved addresses.
469 ACPI_NON_VOLATILE = 10,
470 /// A region used for memory-mapped I/O.
471 MMIO = 11,
472 /// Address space used for memory-mapped port I/O.
473 MMIO_PORT_SPACE = 12,
474 /// Address space which is part of the processor.
475 PAL_CODE = 13,
476 /// Memory region which is usable and is also non-volatile.
477 PERSISTENT_MEMORY = 14,
478 /// Memory that must be accepted by the boot target before it can be used.
479 UNACCEPTED = 15,
480 /// End of the defined memory types. Higher values are possible though, see
481 /// [`MemoryType::RESERVED_FOR_OEM`] and [`MemoryType::RESERVED_FOR_OS_LOADER`].
482 MAX = 16,
483}}
484
485impl MemoryType {
486 /// Range reserved for OEM use.
487 pub const RESERVED_FOR_OEM: RangeInclusive<u32> = 0x7000_0000..=0x7fff_ffff;
488
489 /// Range reserved for OS loaders.
490 pub const RESERVED_FOR_OS_LOADER: RangeInclusive<u32> = 0x8000_0000..=0xffff_ffff;
491
492 /// Construct a custom `MemoryType`. Values in the range `0x8000_0000..=0xffff_ffff` are free for use if you are
493 /// an OS loader.
494 ///
495 /// **Warning**: Some EFI firmware versions (e.g., OVMF r11337) may crash or [behave incorrectly](https://wiki.osdev.org/UEFI#My_bootloader_hangs_if_I_use_user_defined_EFI_MEMORY_TYPE_values) when using a custom `MemoryType`.
496 #[must_use]
497 pub const fn custom(value: u32) -> Self {
498 assert!(value >= 0x80000000);
499 Self(value)
500 }
501}
502
503#[derive(Debug)]
504#[repr(C)]
505#[expect(missing_docs)]
506pub struct OpenProtocolInformationEntry {
507 pub agent_handle: Handle,
508 pub controller_handle: Handle,
509 pub attributes: u32,
510 pub open_count: u32,
511}
512
513newtype_enum! {
514/// Task priority level.
515///
516/// Although the UEFI specification repeatedly states that only the variants
517/// specified below should be used in application-provided input, as the other
518/// are reserved for internal firmware use, it might still happen that the
519/// firmware accidentally discloses one of these internal TPLs to us.
520///
521/// Since feeding an unexpected variant to a Rust enum is UB, this means that
522/// this C enum must be interfaced via the newtype pattern.
523pub enum Tpl: usize => {
524 /// Normal task execution level.
525 APPLICATION = 4,
526 /// Async interrupt-style callbacks run at this TPL.
527 CALLBACK = 8,
528 /// Notifications are masked at this level.
529 ///
530 /// This is used in critical sections of code.
531 NOTIFY = 16,
532 /// Highest priority level.
533 ///
534 /// Even processor interrupts are disable at this level.
535 HIGH_LEVEL = 31,
536}}
537
538/// Size in bytes of a UEFI page.
539///
540/// Note that this is not necessarily the processor's page size. The UEFI page
541/// size is always 4 KiB.
542pub const PAGE_SIZE: usize = 4096;
543
544newtype_enum! {
545 /// The type of time that is specified.
546 pub enum TimerDelay: i32 => {
547 /// The event's timer setting is to be cancelled and no timer trigger
548 /// is to be set.
549 ///
550 /// TriggerTime is ignored when canceling a timer.
551 CANCEL = 0,
552 /// The event is to be signaled periodically at TriggerTime intervals
553 /// from the current time.
554 ///
555 /// This is the only timer trigger type for which the event timer does
556 /// not need to be reset for each notification. All other timer trigger
557 /// types are "one shot".
558 PERIODIC = 1,
559 /// The event is to be signaled in the configured amount of 100ns units.
560 RELATIVE = 2,
561 }
562}