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 / proto / nvme / mod.rs

311 lines · 12976 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! NVM Express Protocols.
4
5use crate::mem::{AlignedBuffer, AlignmentError};
6use core::alloc::LayoutError;
7use core::marker::PhantomData;
8use core::time::Duration;
9use core::{ptr, slice};
10use uefi_raw::protocol::nvme::{
11 NvmExpressCommand, NvmExpressCommandCdwValidity, NvmExpressCompletion,
12 NvmExpressPassThruCommandPacket, NvmExpressQueueType,
13};
14
15pub mod pass_thru;
16
17/// Represents the completion status of an NVMe command.
18///
19/// This structure contains various fields related to the status and results
20/// of an executed command, including fields for error codes, specific command IDs,
21/// and general state of the NVMe device.
22pub type NvmeCompletion = NvmExpressCompletion;
23
24/// Type of queues an NVMe command can be placed into
25/// (Which queue a command should be placed into depends on the command)
26pub type NvmeQueueType = NvmExpressQueueType;
27
28/// Represents a request for executing an NVMe command.
29///
30/// This structure encapsulates the command to be sent to the NVMe device, along with
31/// optional data transfer and metadata buffers. It ensures proper alignment and safety
32/// during interactions with the NVMe protocol.
33///
34/// # Lifetime
35/// `'buffers`: Makes sure the io-buffers bound to the built request
36/// stay alive until the response was interpreted.
37#[derive(Debug)]
38pub struct NvmeRequest<'buffers> {
39 io_align: u32,
40 cmd: NvmExpressCommand,
41 packet: NvmExpressPassThruCommandPacket,
42 /// Capacity of the buffer the firmware was given. The firmware reports
43 /// how much it transferred in the packet, but a bogus value must not
44 /// produce an out-of-bounds slice.
45 transfer_capacity: usize,
46 meta_data_capacity: usize,
47 transfer_buffer: Option<AlignedBuffer>,
48 meta_data_buffer: Option<AlignedBuffer>,
49 _phantom: PhantomData<&'buffers u8>,
50}
51
52// NVMe commands consist of a bunch of CDWs (command data words) and a flags bitmask, where
53// one bit per cdw is set when it should be read. Our request builder has one setter method
54// with_cdwX() for every cdw, which also automatically sets the corresponding flag-bit.
55// This macro generates one such setter method.
56macro_rules! define_nvme_command_builder_with_cdw {
57 ($fnname:ident: $fieldname:ident => $flagmask:expr) => {
58 /// Set the $fieldname parameter on the constructed nvme command.
59 /// This also automatically flags the parameter as valid in the command's `flags` field.
60 ///
61 /// # About NVMe commands
62 /// NVMe commands are constructed of a bunch of numbered CDWs (command data words) and a `flags` field.
63 /// The `flags“ field tells the NVMe controller which CDWs was set and whether it should respect
64 /// the corresponding CDWs value.
65 /// CDWs have no fixed interpretation - the interpretation depends on the command to execute.
66 /// Which CDWs have to be supplied (and enabled in the `flags` field) depends on the command that
67 /// should be sent to and executed by the controller.
68 /// See: <https://nvmexpress.org/specifications/>
69 #[must_use]
70 pub const fn $fnname(mut self, $fieldname: u32) -> Self {
71 self.req.cmd.$fieldname = $fieldname;
72 self.req.cmd.flags |= $flagmask.bits();
73 self
74 }
75 };
76}
77
78/// Builder for constructing an NVMe request.
79///
80/// This structure provides convenient methods for configuring NVMe commands,
81/// including parameters like command-specific data words (CDWs)
82/// and optional buffers for transfer and metadata operations.
83///
84/// It ensures safe and ergonomic setup of NVMe requests.
85///
86/// # Lifetime
87/// `'buffers`: Makes sure the io-buffers bound to the built request
88/// stay alive until the response was interpreted.
89#[derive(Debug)]
90pub struct NvmeRequestBuilder<'buffers> {
91 req: NvmeRequest<'buffers>,
92}
93impl<'buffers> NvmeRequestBuilder<'buffers> {
94 /// Creates a new builder for configuring an NVMe request.
95 ///
96 /// # Arguments
97 /// - `io_align`: Memory alignment requirements for buffers.
98 /// - `opcode`: The opcode for the NVMe command.
99 /// - `queue_type`: Specifies the type of queue the command should be placed into.
100 ///
101 /// # Returns
102 /// An instance of [`NvmeRequestBuilder`] for further configuration.
103 #[must_use]
104 pub fn new(io_align: u32, opcode: u8, queue_type: NvmeQueueType) -> Self {
105 Self {
106 req: NvmeRequest {
107 io_align,
108 cmd: NvmExpressCommand {
109 cdw0: opcode as u32,
110 ..Default::default()
111 },
112 packet: NvmExpressPassThruCommandPacket {
113 command_timeout: 0,
114 transfer_buffer: ptr::null_mut(),
115 transfer_length: 0,
116 meta_data_buffer: ptr::null_mut(),
117 meta_data_length: 0,
118 queue_type,
119 nvme_cmd: ptr::null(), // filled during execution
120 nvme_completion: ptr::null_mut(), // filled during execution
121 },
122 transfer_capacity: 0,
123 meta_data_capacity: 0,
124 transfer_buffer: None,
125 meta_data_buffer: None,
126 _phantom: PhantomData,
127 },
128 }
129 }
130
131 /// Configure the given timeout for this request.
132 #[must_use]
133 pub const fn with_timeout(mut self, timeout: Duration) -> Self {
134 self.req.packet.command_timeout = (timeout.as_nanos() / 100) as u64;
135 self
136 }
137
138 // define the with_cdwX() builder methods
139 define_nvme_command_builder_with_cdw!(with_cdw2: cdw2 => NvmExpressCommandCdwValidity::CDW_2);
140 define_nvme_command_builder_with_cdw!(with_cdw3: cdw3 => NvmExpressCommandCdwValidity::CDW_3);
141 define_nvme_command_builder_with_cdw!(with_cdw10: cdw10 => NvmExpressCommandCdwValidity::CDW_10);
142 define_nvme_command_builder_with_cdw!(with_cdw11: cdw11 => NvmExpressCommandCdwValidity::CDW_11);
143 define_nvme_command_builder_with_cdw!(with_cdw12: cdw12 => NvmExpressCommandCdwValidity::CDW_12);
144 define_nvme_command_builder_with_cdw!(with_cdw13: cdw13 => NvmExpressCommandCdwValidity::CDW_13);
145 define_nvme_command_builder_with_cdw!(with_cdw14: cdw14 => NvmExpressCommandCdwValidity::CDW_14);
146 define_nvme_command_builder_with_cdw!(with_cdw15: cdw15 => NvmExpressCommandCdwValidity::CDW_15);
147
148 // # TRANSFER BUFFER
149 // ########################################################################################
150
151 /// Uses a user-supplied buffer for reading data from the device.
152 ///
153 /// # Arguments
154 /// - `bfr`: A mutable reference to an [`AlignedBuffer`] that will be used to store data read from the device.
155 ///
156 /// # Returns
157 /// `Result<Self, AlignmentError>` indicating success or an alignment issue with the provided buffer.
158 ///
159 /// # Description
160 /// This method checks the alignment of the buffer against the protocol's requirements and assigns it to
161 /// the `transfer_buffer` of the underlying [`NvmeRequest`].
162 pub fn use_transfer_buffer(
163 mut self,
164 bfr: &'buffers mut AlignedBuffer,
165 ) -> Result<Self, AlignmentError> {
166 // check alignment of externally supplied buffer
167 bfr.check_alignment(self.req.io_align as usize)?;
168 self.req.transfer_buffer = None;
169 self.req.transfer_capacity = bfr.size();
170 self.req.packet.transfer_buffer = bfr.ptr_mut().cast();
171 self.req.packet.transfer_length = bfr.size() as u32;
172 Ok(self)
173 }
174
175 /// Adds a newly allocated transfer buffer to the built NVMe request.
176 ///
177 /// # Arguments
178 /// - `len`: The size of the buffer (in bytes) to allocate for receiving data.
179 ///
180 /// # Returns
181 /// `Result<Self, LayoutError>` indicating success or a memory allocation error.
182 pub fn with_transfer_buffer(mut self, len: usize) -> Result<Self, LayoutError> {
183 let mut bfr = AlignedBuffer::from_size_align(len, self.req.io_align as usize)?;
184 self.req.transfer_capacity = bfr.size();
185 self.req.packet.transfer_buffer = bfr.ptr_mut().cast();
186 self.req.packet.transfer_length = bfr.size() as u32;
187 self.req.transfer_buffer = Some(bfr);
188 Ok(self)
189 }
190
191 // # METADATA BUFFER
192 // ########################################################################################
193
194 /// Uses a user-supplied metadata buffer.
195 ///
196 /// # Arguments
197 /// - `bfr`: A mutable reference to an [`AlignedBuffer`] that will be used to store metadata.
198 ///
199 /// # Returns
200 /// `Result<Self, AlignmentError>` indicating success or an alignment issue with the provided buffer.
201 ///
202 /// # Description
203 /// This method checks the alignment of the buffer against the protocol's requirements and assigns it to
204 /// the `meta_data_buffer` of the underlying [`NvmeRequest`].
205 pub fn use_metadata_buffer(
206 mut self,
207 bfr: &'buffers mut AlignedBuffer,
208 ) -> Result<Self, AlignmentError> {
209 // check alignment of externally supplied buffer
210 bfr.check_alignment(self.req.io_align as usize)?;
211 self.req.meta_data_buffer = None;
212 self.req.meta_data_capacity = bfr.size();
213 self.req.packet.meta_data_buffer = bfr.ptr_mut().cast();
214 self.req.packet.meta_data_length = bfr.size() as u32;
215 Ok(self)
216 }
217
218 /// Adds a newly allocated metadata buffer to the built NVMe request.
219 ///
220 /// # Arguments
221 /// - `len`: The size of the buffer (in bytes) to allocate for storing metadata.
222 ///
223 /// # Returns
224 /// `Result<Self, LayoutError>` indicating success or a memory allocation error.
225 pub fn with_metadata_buffer(mut self, len: usize) -> Result<Self, LayoutError> {
226 let mut bfr = AlignedBuffer::from_size_align(len, self.req.io_align as usize)?;
227 self.req.meta_data_capacity = bfr.size();
228 self.req.packet.meta_data_buffer = bfr.ptr_mut().cast();
229 self.req.packet.meta_data_length = bfr.size() as u32;
230 self.req.meta_data_buffer = Some(bfr);
231 Ok(self)
232 }
233
234 /// Build the final [`NvmeRequest`].
235 ///
236 /// # Returns
237 /// A fully-configured [`NvmeRequest`] ready for execution.
238 #[must_use]
239 pub fn build(self) -> NvmeRequest<'buffers> {
240 self.req
241 }
242}
243
244/// Represents the response from executing an NVMe command.
245///
246/// This structure encapsulates the original request, as well as the command's completion status.
247///
248/// # Lifetime
249/// `'buffers`: Makes sure the io-buffers bound to the built request
250/// stay alive until the response was interpreted.
251#[derive(Debug)]
252pub struct NvmeResponse<'buffers> {
253 req: NvmeRequest<'buffers>,
254 completion: NvmeCompletion,
255}
256impl NvmeResponse<'_> {
257 /// Returns the buffer containing transferred data from the device (if any).
258 ///
259 /// # Returns
260 /// `Option<&[u8]>`: A slice of the transfer buffer, or `None` if the request was started without.
261 #[must_use]
262 pub const fn transfer_buffer(&self) -> Option<&[u8]> {
263 if self.req.packet.transfer_buffer.is_null() {
264 return None;
265 }
266 // The firmware reports the transferred length; clamp it so that a
267 // bogus value cannot produce an out-of-bounds slice.
268 let reported = self.req.packet.transfer_length as usize;
269 let cap = self.req.transfer_capacity;
270 let len = if reported < cap { reported } else { cap };
271 // SAFETY: The buffer holds at least `len` initialized bytes.
272 unsafe {
273 Some(slice::from_raw_parts(
274 self.req.packet.transfer_buffer.cast(),
275 len,
276 ))
277 }
278 }
279
280 /// Returns the buffer containing metadata data from the device (if any).
281 ///
282 /// # Returns
283 /// `Option<&[u8]>`: A slice of the metadata buffer, or `None` if the request was started without.
284 #[must_use]
285 pub const fn metadata_buffer(&self) -> Option<&[u8]> {
286 if self.req.packet.meta_data_buffer.is_null() {
287 return None;
288 }
289 // The firmware reports the transferred length; clamp it so that a
290 // bogus value cannot produce an out-of-bounds slice.
291 let reported = self.req.packet.meta_data_length as usize;
292 let cap = self.req.meta_data_capacity;
293 let len = if reported < cap { reported } else { cap };
294 // SAFETY: The buffer holds at least `len` initialized bytes.
295 unsafe {
296 Some(slice::from_raw_parts(
297 self.req.packet.meta_data_buffer.cast(),
298 len,
299 ))
300 }
301 }
302
303 /// Provides access to the completion structure of the NVMe command.
304 ///
305 /// # Returns
306 /// A reference to the [`NvmeCompletion`] structure containing the status and results of the command.
307 #[must_use]
308 pub const fn completion(&self) -> &NvmeCompletion {
309 &self.completion
310 }
311}