Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/driver.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / driver.rs` 297 lines ยท 12194 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! High-level support for writing UEFI drivers. 4 //! 5 //! # Driver How-To 6 //! 7 //! Start by defining a new Cargo binary target, which will be a (mostly) 8 //! regular `uefi-rs` application. 9 //! 10 //! The binary image must be explicitly designated as a UEFI driver by setting 11 //! the PE32+ subsystem to `EFI_BOOT_SERVICE_DRIVER` (see UEFI spec, section 12 //! 2.1). This can be done by adding the following line to `build.rs`: 13 //! 14 //! ```ignore 15 //! println!("cargo::rustc-link-arg=/SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER"); 16 //! ``` 17 //! 18 //! Setting the subsystem like this instructs the firmware to leave the driver's 19 //! code and data segments loaded in memory after its entrypoint returns. This 20 //! is necessary to ensure any objects such as protocol interfaces installed by 21 //! the driver remain functional after the driver is finished loading. 22 //! 23 //! In the driver's entrypoint, create and install one or more implementations 24 //! of the [`Driver`] trait using the [`install`] function. Later, the firmware 25 //! will invoke the `Driver` methods to identify supported controllers and begin 26 //! managing them. 27 //! 28 //! One method to load the driver is to use the UEFI shell's `load` command. 29 //! This will load the driver image, invoke its entrypoint, *and* subsequently 30 //! perform a [`ConnectController`][cnct-ctrl] sequence to bind the driver to 31 //! any compatible controller handles present on the system. Following a 32 //! successful `load`, any other application run from the UEFI shell should be 33 //! able to open and use the protocols installed by the driver. 34 //! 35 //! [cnct-ctrl]: crate::boot::connect_controller 36 //! 37 //! # Device and Bus Drivers 38 //! 39 //! The UEFI driver model distinguishes between "device" and "bus" drivers. 40 //! Device drivers manage a single device controller, while bus drivers manage a 41 //! bus which may have multiple child controllers. Both types of drivers use the 42 //! same underlying protocols and firmware infrastructure, but with different 43 //! expected behaviors and semantics. 44 //! 45 //! The helpers provided in this module are currently tailored towards (and 46 //! validated for use with) device drivers. Additional functionality may be 47 //! added in the future to better support bus drivers. 48 //! 49 //! # References 50 //! 51 //! * [UEFI Specification](https://uefi.org/specifications) 52 //! * [EDKII Driver Writer's Guide](https://tianocore-docs.github.io/edk2-UefiDriverWritersGuide/draft/) 53 //! * [/SUBSYSTEM (MSVC Linker)](https://learn.microsoft.com/en-us/cpp/build/reference/subsystem-specify-subsystem) 54 55 use core::mem; 56 57 use alloc::boxed::Box; 58 59 use log::{debug, error, trace, warn}; 60 61 use uefi_raw::protocol::device_path::DevicePathProtocol; 62 use uefi_raw::protocol::driver::DriverBindingProtocol; 63 64 use crate::mem::memory_map::MemoryType; 65 use crate::proto::device_path::DevicePath; 66 use crate::proto::loaded_image::LoadedImage; 67 use crate::{Handle, Result, ResultExt, Status, boot}; 68 69 /// Trait defining the behavior of a UEFI driver 70 /// 71 /// The methods of this trait correspond to the functions of the UEFI Driver 72 /// Binding Protocol. For complete technical information about the expected 73 /// behavior, refer to section 11.1 of the UEFI specification. 74 /// 75 /// In each of this trait's methods, the `agent` parameter is the handle of the 76 /// driver itself (which may not always be the same as the handle of it 77 /// containing image). This may be used when calling other UEFI services such as 78 /// `OpenProtocol`. 79 pub trait Driver { 80 /// Determines whether this driver supports device specified by 81 /// `controller`. 82 fn supported( 83 &mut self, 84 agent: Handle, 85 controller: Handle, 86 remaining: Option<&DevicePath>, 87 ) -> Result; 88 89 /// Activates this driver for the device specified by `controller`. 90 fn start( 91 &mut self, 92 agent: Handle, 93 controller: Handle, 94 remaining: Option<&DevicePath>, 95 ) -> Result; 96 97 /// Deactivates this driver for the device specified by `controller`. 98 fn stop(&mut self, agent: Handle, controller: Handle) -> Result; 99 } 100 101 /// Protocol interface structure for [`DriverBindingProtocol`]. 102 struct DriverBindingInterface { 103 protocol: DriverBindingProtocol, 104 driver: T, 105 } 106 107 impl DriverBindingInterface { 108 /// Recovers a reference to the interface structure from a pointer to its 109 /// protocol function table. 110 /// 111 /// # Safety 112 /// 113 /// `ptr` must be a valid pointer to a [`DriverBindingProtocol`] instance 114 /// embedded within a `DriverBindingInterface` structure. 115 /// 116 /// The lifetime `'a` specified by the caller must not outlive the actual 117 /// lifetime of the installed protocol interface. 118 /// 119 /// The caller must also ensure that it has exclusive access to the 120 /// interface for the lifetime `'a`. 121 unsafe fn from_proto_ptr_mut<'a>(ptr: *mut DriverBindingProtocol) -> &'a mut Self { 122 // Compute base offset from protocol pointer 123 let ptr = ptr 124 .cast::() 125 .wrapping_sub(mem::offset_of!(Self, protocol)) 126 .cast::(); 127 128 // SAFETY: The caller guarantees that `ptr` points to the `protocol` 129 // field of a live `DriverBindingInterface` and that the returned 130 // reference has exclusive access for its lifetime. 131 unsafe { &mut *ptr } 132 } 133 } 134 135 unsafe extern "efiapi" fn driver_supported( 136 this: *const DriverBindingProtocol, 137 controller: uefi_raw::Handle, 138 remaining: *const DevicePathProtocol, 139 ) -> Status { 140 // N.B. No trace logging since this is a very noisy function 141 142 if this.is_null() || controller.is_null() { 143 return Status::INVALID_PARAMETER; 144 } 145 146 // SAFETY: UEFI calls this function with the driver binding protocol 147 // pointer installed by `install`, whose allocation is intentionally leaked. 148 let this = unsafe { DriverBindingInterface::::from_proto_ptr_mut(this.cast_mut()) }; 149 // SAFETY: `driver_binding_handle` was initialized from a valid `Handle` 150 // when the protocol was installed. 151 let agent = unsafe { Handle::from_ptr(this.protocol.driver_binding_handle).unwrap() }; 152 // SAFETY: `controller` was checked for null above and is a UEFI handle 153 // supplied by the firmware for this callback. 154 let controller = unsafe { Handle::from_ptr(controller).unwrap() }; 155 let remaining = if remaining.is_null() { 156 None 157 } else { 158 // SAFETY: A non-null remaining device path is supplied by the firmware 159 // for this callback and remains valid for the duration of the call. 160 Some(unsafe { DevicePath::from_ffi_ptr(remaining.cast()) }) 161 }; 162 163 this.driver.supported(agent, controller, remaining).status() 164 } 165 166 unsafe extern "efiapi" fn driver_start( 167 this: *const DriverBindingProtocol, 168 controller: uefi_raw::Handle, 169 remaining: *const DevicePathProtocol, 170 ) -> Status { 171 trace!("this: {this:p}, controller: {controller:p}, remaining: {remaining:p}"); 172 173 if this.is_null() || controller.is_null() { 174 return Status::INVALID_PARAMETER; 175 } 176 177 // SAFETY: UEFI calls this function with the driver binding protocol 178 // pointer installed by `install`, whose allocation is intentionally leaked. 179 let this = unsafe { DriverBindingInterface::::from_proto_ptr_mut(this.cast_mut()) }; 180 // SAFETY: `driver_binding_handle` was initialized from a valid `Handle` 181 // when the protocol was installed. 182 let agent = unsafe { Handle::from_ptr(this.protocol.driver_binding_handle).unwrap() }; 183 // SAFETY: `controller` was checked for null above and is a UEFI handle 184 // supplied by the firmware for this callback. 185 let controller = unsafe { Handle::from_ptr(controller).unwrap() }; 186 let remaining = if remaining.is_null() { 187 None 188 } else { 189 // SAFETY: A non-null remaining device path is supplied by the firmware 190 // for this callback and remains valid for the duration of the call. 191 Some(unsafe { DevicePath::from_ffi_ptr(remaining.cast()) }) 192 }; 193 194 this.driver.start(agent, controller, remaining).status() 195 } 196 197 unsafe extern "efiapi" fn driver_stop( 198 this: *const DriverBindingProtocol, 199 controller: uefi_raw::Handle, 200 number_of_children: usize, 201 child_handle_buffer: *const uefi_raw::Handle, 202 ) -> Status { 203 trace!( 204 "this: {this:p}, controller: {controller:p}, number_of_children: {number_of_children}, child_handle_buffer: {child_handle_buffer:p}" 205 ); 206 207 if this.is_null() || controller.is_null() { 208 return Status::INVALID_PARAMETER; 209 } 210 211 // SAFETY: UEFI calls this function with the driver binding protocol 212 // pointer installed by `install`, whose allocation is intentionally leaked. 213 let this = unsafe { DriverBindingInterface::::from_proto_ptr_mut(this.cast_mut()) }; 214 // SAFETY: `driver_binding_handle` was initialized from a valid `Handle` 215 // when the protocol was installed. 216 let agent = unsafe { Handle::from_ptr(this.protocol.driver_binding_handle).unwrap() }; 217 // SAFETY: `controller` was checked for null above and is a UEFI handle 218 // supplied by the firmware for this callback. 219 let controller = unsafe { Handle::from_ptr(controller).unwrap() }; 220 221 if number_of_children == 0 { 222 this.driver.stop(agent, controller).status() 223 } else { 224 warn!("stop with children not currently supported"); 225 Status::UNSUPPORTED 226 } 227 } 228 229 /// Installs `driver` onto the specified `handle` (or the current image handle 230 /// if `None`). 231 /// 232 /// The current image must have been loaded as an EFI boot service driver image. 233 /// This function verifies that condition using the current image's 234 /// [`LoadedImage`] protocol before installing the driver binding protocol. This 235 /// is required because the installed protocol contains function pointers into 236 /// the current image, and those pointers must remain valid after the image's 237 /// entrypoint returns. 238 /// 239 /// # Errors 240 /// 241 /// This function returns errors from [`boot::open_protocol_exclusive`] and 242 /// [`boot::install_protocol_interface`]. It returns [`Status::UNSUPPORTED`] if 243 /// the current image was not loaded as an EFI boot service driver image. 244 pub fn install(driver: T, handle: Option) -> Result { 245 trace!("handle: {handle:?}"); 246 247 let image_handle = boot::image_handle(); 248 let target_handle = handle.unwrap_or(image_handle); 249 250 { 251 let loaded_image = boot::open_protocol_exclusive::(image_handle)?; 252 if loaded_image.code_type() != MemoryType::BOOT_SERVICES_CODE 253 || loaded_image.data_type() != MemoryType::BOOT_SERVICES_DATA 254 { 255 error!("current image was not loaded as an EFI boot service driver"); 256 return Err(Status::UNSUPPORTED.into()); 257 } 258 } 259 260 let mut ctx = Box::new(DriverBindingInterface { 261 protocol: DriverBindingProtocol { 262 supported: driver_supported::, 263 start: driver_start::, 264 stop: driver_stop::, 265 version: 1, 266 image_handle: image_handle.as_ptr(), 267 driver_binding_handle: target_handle.as_ptr(), 268 }, 269 driver, 270 }); 271 272 let proto_ptr = &raw mut ctx.protocol; 273 trace!("proto_ptr: {proto_ptr:p}"); 274 275 debug!("installing driver binding protocol"); 276 277 // SAFETY: `DriverBindingProtocol::GUID` matches the interface being 278 // installed, the loaded-image check above verifies that this image's code 279 // and data remain valid after its entrypoint returns, and `proto_ptr` points 280 // into `ctx`, which is leaked below so the installed protocol interface 281 // remains valid as long as the image remains loaded. 282 unsafe { 283 boot::install_protocol_interface( 284 Some(target_handle), 285 &DriverBindingProtocol::GUID, 286 proto_ptr.cast(), 287 )?; 288 } 289 290 // A pointer to the protocol interface is now installed onto the target 291 // handle and may be dereferenced at a later time by any user of the 292 // protocol. We intentionally leak the allocation here to ensure the memory 293 // is not cleaned up or repurposed while the interface remains installed. 294 Box::leak(ctx); 295 296 Ok(()) 297 }