aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / proto / nvme / pass_thru.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | //! NVM Express Pass Thru Protocol. |
| 4 | |
| 5 | use super::{NvmeRequest, NvmeResponse}; |
| 6 | use crate::StatusExt; |
| 7 | use crate::mem::{AlignedBuffer, PoolAllocation}; |
| 8 | use crate::proto::device_path::PoolDevicePathNode; |
| 9 | use core::alloc::LayoutError; |
| 10 | use core::cell::UnsafeCell; |
| 11 | use core::ptr::{self, NonNull}; |
| 12 | use uefi_macros::unsafe_protocol; |
| 13 | use uefi_raw::Status; |
| 14 | use uefi_raw::protocol::device_path::DevicePathProtocol; |
| 15 | use uefi_raw::protocol::nvme::{ |
| 16 | NvmExpressCompletion, NvmExpressPassThruMode, NvmExpressPassThruProtocol, |
| 17 | }; |
| 18 | |
| 19 | /// Nvme Pass Thru Protocol Mode structure. |
| 20 | /// |
| 21 | /// This contains information regarding the specific capabilities and requirements |
| 22 | /// of the NVMe controller, such as buffer alignment constraints. |
| 23 | pub type NvmePassThruMode = NvmExpressPassThruMode; |
| 24 | |
| 25 | /// Identifier for an NVMe namespace. |
| 26 | /// |
| 27 | /// Namespace IDs are used to target specific namespaces on an NVMe device for commands. |
| 28 | pub type NvmeNamespaceId = u32; |
| 29 | |
| 30 | /// NVMe Pass Thru Protocol. |
| 31 | /// |
| 32 | /// One protocol instance corresponds to one NVMe controller |
| 33 | /// (which, most of the time, corresponds to one SSD). |
| 34 | /// |
| 35 | /// This API offers a safe and convenient, yet still low-level interface to NVMe devices. |
| 36 | /// It is designed as a foundational layer, leaving higher-level abstractions responsible for implementing |
| 37 | /// richer storage semantics, device-specific commands, and advanced use cases. |
| 38 | /// |
| 39 | /// # UEFI Specification |
| 40 | /// The `EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL` provides essential functionality for interacting |
| 41 | /// with NVMe controllers and namespaces. It allows sending NVMe commands to either the |
| 42 | /// controller itself or specific namespaces within the controller. |
| 43 | #[derive(Debug)] |
| 44 | #[repr(transparent)] |
| 45 | #[unsafe_protocol(NvmExpressPassThruProtocol::GUID)] |
| 46 | pub struct NvmePassThru(UnsafeCell<NvmExpressPassThruProtocol>); |
| 47 | |
| 48 | impl NvmePassThru { |
| 49 | /// Retrieves the mode of the NVMe Pass Thru protocol. |
| 50 | /// |
| 51 | /// # Returns |
| 52 | /// An instance of [`NvmePassThruMode`] describing the NVMe controller's capabilities. |
| 53 | #[must_use] |
| 54 | pub fn mode(&self) -> NvmePassThruMode { |
| 55 | // SAFETY: The memory is valid. |
| 56 | let mut mode = unsafe { (*(*self.0.get()).mode).clone() }; |
| 57 | mode.io_align = mode.io_align.max(1); // 0 and 1 is the same, says UEFI spec |
| 58 | mode |
| 59 | } |
| 60 | |
| 61 | /// Retrieves the alignment requirements for I/O buffers. |
| 62 | /// |
| 63 | /// # Returns |
| 64 | /// An alignment value (in bytes) that all I/O buffers must adhere to for successful operation. |
| 65 | #[must_use] |
| 66 | pub fn io_align(&self) -> u32 { |
| 67 | self.mode().io_align |
| 68 | } |
| 69 | |
| 70 | /// Allocates an I/O buffer with the necessary alignment for this NVMe Controller. |
| 71 | /// |
| 72 | /// You can alternatively do this yourself using the [`AlignedBuffer`] helper directly. |
| 73 | /// The `nvme` api will validate that your buffers have the correct alignment and error |
| 74 | /// if they don't. |
| 75 | /// |
| 76 | /// # Arguments |
| 77 | /// - `len`: The size (in bytes) of the buffer to allocate. |
| 78 | /// |
| 79 | /// # Returns |
| 80 | /// [`AlignedBuffer`] containing the allocated memory. |
| 81 | /// |
| 82 | /// # Errors |
| 83 | /// This method can fail due to alignment or memory allocation issues. |
| 84 | pub fn alloc_io_buffer(&self, len: usize) -> Result<AlignedBuffer, LayoutError> { |
| 85 | AlignedBuffer::from_size_align(len, self.io_align() as usize) |
| 86 | } |
| 87 | |
| 88 | /// Iterate over all valid namespaces on this NVMe controller. |
| 89 | /// |
| 90 | /// This ignores the 0-namespaces, which corresponds to the controller itself. |
| 91 | /// The iterator yields [`NvmeNamespace`] instances representing individual namespaces. |
| 92 | /// |
| 93 | /// # Returns |
| 94 | /// A [`NvmeNamespaceIterator`] for iterating through the namespaces. |
| 95 | #[must_use] |
| 96 | pub const fn iter_namespaces(&self) -> NvmeNamespaceIterator<'_> { |
| 97 | NvmeNamespaceIterator { |
| 98 | proto: &self.0, |
| 99 | prev: 0xFFFFFFFF, |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Get the controller namespace (id = 0). |
| 104 | /// This can be used to send ADMIN commands. |
| 105 | /// |
| 106 | /// # Returns |
| 107 | /// A [`NvmeNamespace`] addressing the controller (nsid = 0). |
| 108 | #[must_use] |
| 109 | pub const fn controller(&self) -> NvmeNamespace<'_> { |
| 110 | NvmeNamespace { |
| 111 | proto: &self.0, |
| 112 | namespace_id: 0, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Get the broadcast namespace (id = 0xffffffff). |
| 117 | /// |
| 118 | /// # Returns |
| 119 | /// A [`NvmeNamespace`] with nsid = 0xffffffff. |
| 120 | #[must_use] |
| 121 | pub const fn broadcast(&self) -> NvmeNamespace<'_> { |
| 122 | NvmeNamespace { |
| 123 | proto: &self.0, |
| 124 | namespace_id: 0xffffffff, |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Represents one namespace on an NVMe controller. |
| 130 | /// |
| 131 | /// A namespace is a shard of storage that the controller can be partitioned into. |
| 132 | /// Typically, consumer devices only have a single namespace where all the data resides (id 1). |
| 133 | #[derive(Debug)] |
| 134 | pub struct NvmeNamespace<'a> { |
| 135 | proto: &'a UnsafeCell<NvmExpressPassThruProtocol>, |
| 136 | namespace_id: NvmeNamespaceId, |
| 137 | } |
| 138 | |
| 139 | impl NvmeNamespace<'_> { |
| 140 | /// Retrieves the namespace identifier (NSID) associated with this NVMe namespace. |
| 141 | #[must_use] |
| 142 | pub const fn namespace_id(&self) -> NvmeNamespaceId { |
| 143 | self.namespace_id |
| 144 | } |
| 145 | |
| 146 | /// Get the final device path node for this namespace. |
| 147 | /// |
| 148 | /// For a full [`crate::proto::device_path::DevicePath`] pointing to this namespace on the |
| 149 | /// corresponding NVMe controller. |
| 150 | pub fn path_node(&self) -> crate::Result<PoolDevicePathNode> { |
| 151 | // SAFETY: The memory is valid. |
| 152 | unsafe { |
| 153 | let mut path_ptr: *mut DevicePathProtocol = ptr::null_mut(); |
| 154 | ((*self.proto.get()).build_device_path)( |
| 155 | self.proto.get(), |
| 156 | self.namespace_id, |
| 157 | &mut path_ptr, |
| 158 | ) |
| 159 | .to_result()?; |
| 160 | NonNull::new(path_ptr) |
| 161 | .map(|p| PoolDevicePathNode(PoolAllocation::new(p.cast()))) |
| 162 | .ok_or_else(|| Status::OUT_OF_RESOURCES.into()) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Sends an NVM Express command to this namespace (Namespace ID ≥ 1). |
| 167 | /// |
| 168 | /// # Arguments |
| 169 | /// - `req`: The [`NvmeRequest`] containing the command and associated data to send to the namespace. |
| 170 | /// |
| 171 | /// # Returns |
| 172 | /// - [`NvmeResponse`] containing the results of the operation, such as data and status. |
| 173 | /// |
| 174 | /// # Errors |
| 175 | /// - [`Status::BAD_BUFFER_SIZE`] The NVM Express Command Packet was not executed. The number |
| 176 | /// of bytes that could be transferred is returned in `TransferLength`. |
| 177 | /// - [`Status::NOT_READY`] The NVM Express Command Packet could not be sent because the controller |
| 178 | /// is not ready. The caller may retry later. |
| 179 | /// - [`Status::DEVICE_ERROR`] A device error occurred while attempting to send the NVM Express |
| 180 | /// Command Packet. Additional status information is available in `NvmeCompletion`. |
| 181 | /// - [`Status::INVALID_PARAMETER`] The Namespace ID or the contents of the Command Packet are invalid. |
| 182 | /// The NVM Express Command Packet was not sent, and no additional status information is available. |
| 183 | /// - [`Status::UNSUPPORTED`] The command described by the NVM Express Command Packet is not supported |
| 184 | /// by the NVM Express controller. The Command Packet was not sent, and no additional status |
| 185 | /// information is available. |
| 186 | /// - [`Status::TIMEOUT`] A timeout occurred while executing the NVM Express Command Packet. |
| 187 | /// Additional status information is available in `NvmeCompletion`. |
| 188 | pub fn execute_command<'req>( |
| 189 | &mut self, |
| 190 | mut req: NvmeRequest<'req>, |
| 191 | ) -> crate::Result<NvmeResponse<'req>> { |
| 192 | let mut completion = NvmExpressCompletion::default(); |
| 193 | // prepare cmd packet |
| 194 | req.cmd.nsid = self.namespace_id; |
| 195 | req.packet.nvme_cmd = &req.cmd; |
| 196 | req.packet.nvme_completion = &mut completion; |
| 197 | // SAFETY: The memory is valid. |
| 198 | unsafe { |
| 199 | ((*self.proto.get()).pass_thru)( |
| 200 | self.proto.get(), |
| 201 | self.namespace_id, |
| 202 | &mut req.packet, |
| 203 | ptr::null_mut(), |
| 204 | ) |
| 205 | .to_result_with_val(|| NvmeResponse { req, completion }) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /// An iterator over the namespaces of an NVMe controller. |
| 211 | /// |
| 212 | /// The iterator yields [`NvmeNamespace`] instances, each representing one namespace |
| 213 | /// on the NVMe controller. |
| 214 | #[derive(Debug)] |
| 215 | pub struct NvmeNamespaceIterator<'a> { |
| 216 | proto: &'a UnsafeCell<NvmExpressPassThruProtocol>, |
| 217 | prev: NvmeNamespaceId, |
| 218 | } |
| 219 | |
| 220 | impl<'a> Iterator for NvmeNamespaceIterator<'a> { |
| 221 | type Item = NvmeNamespace<'a>; |
| 222 | |
| 223 | fn next(&mut self) -> Option<Self::Item> { |
| 224 | let result = |
| 225 | // SAFETY: The memory is valid. |
| 226 | unsafe { ((*self.proto.get()).get_next_namespace)(self.proto.get(), &mut self.prev) }; |
| 227 | match result { |
| 228 | Status::SUCCESS => Some(NvmeNamespace { |
| 229 | proto: self.proto, |
| 230 | namespace_id: self.prev, |
| 231 | }), |
| 232 | Status::NOT_FOUND => None, |
| 233 | _ => panic!("Must not happen according to spec!"), |
| 234 | } |
| 235 | } |
| 236 | } |