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/proto/scsi/mod.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 / proto / scsi / mod.rs` 372 lines ยท 14559 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! SCSI Bus specific protocols. 4 5 use crate::mem::{AlignedBuffer, AlignmentError}; 6 use core::alloc::LayoutError; 7 use core::marker::PhantomData; 8 use core::time::Duration; 9 use core::{ptr, slice}; 10 use uefi_raw::protocol::scsi::{ 11 ScsiIoDataDirection, ScsiIoHostAdapterStatus, ScsiIoScsiRequestPacket, ScsiIoTargetStatus, 12 }; 13 14 #[cfg(doc)] 15 use crate::Status; 16 17 pub mod pass_thru; 18 19 /// Represents the data direction for a SCSI request. 20 /// 21 /// Used to specify whether the request involves reading, writing, or bidirectional data transfer. 22 pub type ScsiRequestDirection = ScsiIoDataDirection; 23 24 /// Represents a SCSI request packet. 25 /// 26 /// This structure encapsulates the necessary data for sending a command to a SCSI device. 27 #[derive(Debug)] 28 pub struct ScsiRequest<'a> { 29 packet: ScsiIoScsiRequestPacket, 30 io_align: u32, 31 /// Capacity of the buffer the firmware was given. The firmware reports 32 /// how much it transferred in the packet, but a bogus value must not 33 /// produce an out-of-bounds slice. 34 in_data_capacity: usize, 35 sense_data_capacity: usize, 36 in_data_buffer: Option, 37 out_data_buffer: Option, 38 sense_data_buffer: Option, 39 cdb_buffer: Option, 40 _phantom: PhantomData<&'a u8>, 41 } 42 43 /// A builder for constructing [`ScsiRequest`] instances. 44 /// 45 /// Provides a safe and ergonomic interface for configuring SCSI request packets, including timeout, 46 /// data buffers, and command descriptor blocks. 47 #[derive(Debug)] 48 pub struct ScsiRequestBuilder<'a> { 49 req: ScsiRequest<'a>, 50 } 51 impl ScsiRequestBuilder<'_> { 52 /// Creates a new instance with the specified data direction and alignment. 53 /// 54 /// # Arguments 55 /// - `direction`: Specifies the direction of data transfer (READ, WRITE, or BIDIRECTIONAL). 56 /// - `io_align`: Specifies the required alignment for data buffers. (SCSI Controller specific!) 57 #[must_use] 58 pub fn new(direction: ScsiRequestDirection, io_align: u32) -> Self { 59 Self { 60 req: ScsiRequest { 61 in_data_capacity: 0, 62 sense_data_capacity: 0, 63 in_data_buffer: None, 64 out_data_buffer: None, 65 sense_data_buffer: None, 66 cdb_buffer: None, 67 packet: ScsiIoScsiRequestPacket { 68 timeout: 0, 69 in_data_buffer: ptr::null_mut(), 70 out_data_buffer: ptr::null_mut(), 71 sense_data: ptr::null_mut(), 72 cdb: ptr::null_mut(), 73 in_transfer_length: 0, 74 out_transfer_length: 0, 75 cdb_length: 0, 76 data_direction: direction, 77 host_adapter_status: ScsiIoHostAdapterStatus::default(), 78 target_status: ScsiIoTargetStatus::default(), 79 sense_data_length: 0, 80 }, 81 io_align, 82 _phantom: Default::default(), 83 }, 84 } 85 } 86 87 /// Starts a new builder preconfigured for READ operations. 88 /// 89 /// Some examples of SCSI read commands are: 90 /// - INQUIRY 91 /// - READ 92 /// - MODE_SENSE 93 /// 94 /// # Arguments 95 /// - `io_align`: Specifies the required alignment for data buffers. 96 #[must_use] 97 pub fn read(io_align: u32) -> Self { 98 Self::new(ScsiIoDataDirection::READ, io_align) 99 } 100 101 /// Starts a new builder preconfigured for WRITE operations. 102 /// 103 /// Some examples of SCSI write commands are: 104 /// - WRITE 105 /// - MODE_SELECT 106 /// 107 /// # Arguments 108 /// - `io_align`: Specifies the required alignment for data buffers. 109 #[must_use] 110 pub fn write(io_align: u32) -> Self { 111 Self::new(ScsiIoDataDirection::WRITE, io_align) 112 } 113 114 /// Starts a new builder preconfigured for BIDIRECTIONAL operations. 115 /// 116 /// Some examples of SCSI bidirectional commands are: 117 /// - SEND DIAGNOSTIC 118 /// 119 /// # Arguments 120 /// - `io_align`: Specifies the required alignment for data buffers. 121 #[must_use] 122 pub fn bidirectional(io_align: u32) -> Self { 123 Self::new(ScsiIoDataDirection::BIDIRECTIONAL, io_align) 124 } 125 } 126 127 impl<'a> ScsiRequestBuilder<'a> { 128 /// Sets a timeout for the SCSI request. 129 /// 130 /// # Arguments 131 /// - `timeout`: A [`Duration`] representing the maximum time allowed for the request. 132 /// The value is converted to 100-nanosecond units. 133 /// 134 /// # Description 135 /// By default (without calling this method, or by calling with [`Duration::ZERO`]), 136 /// SCSI requests have no timeout. 137 /// Setting a timeout here will cause SCSI commands to potentially fail with [`Status::TIMEOUT`]. 138 #[must_use] 139 pub const fn with_timeout(mut self, timeout: Duration) -> Self { 140 self.req.packet.timeout = (timeout.as_nanos() / 100) as u64; 141 self 142 } 143 144 // # IN BUFFER 145 // ######################################################################################## 146 147 /// Uses a user-supplied buffer for reading data from the device. 148 /// 149 /// # Arguments 150 /// - `bfr`: A mutable reference to an [`AlignedBuffer`] that will be used to store data read from the device. 151 /// 152 /// # Returns 153 /// `Result` indicating success or an alignment issue with the provided buffer. 154 /// 155 /// # Description 156 /// This method checks the alignment of the buffer against the protocol's requirements and assigns it to 157 /// the `in_data_buffer` of the underlying `ScsiRequest`. 158 pub fn use_read_buffer(mut self, bfr: &'a mut AlignedBuffer) -> Result { 159 // check alignment of externally supplied buffer 160 bfr.check_alignment(self.req.io_align as usize)?; 161 self.req.in_data_buffer = None; 162 self.req.in_data_capacity = bfr.size(); 163 self.req.packet.in_data_buffer = bfr.ptr_mut().cast(); 164 self.req.packet.in_transfer_length = bfr.size() as u32; 165 Ok(self) 166 } 167 168 /// Adds a newly allocated read buffer to the built SCSI request. 169 /// 170 /// # Arguments 171 /// - `len`: The size of the buffer (in bytes) to allocate for receiving data. 172 /// 173 /// # Returns 174 /// `Result` indicating success or a memory allocation error. 175 pub fn with_read_buffer(mut self, len: usize) -> Result { 176 let mut bfr = AlignedBuffer::from_size_align(len, self.req.io_align as usize)?; 177 self.req.in_data_capacity = bfr.size(); 178 self.req.packet.in_data_buffer = bfr.ptr_mut().cast(); 179 self.req.packet.in_transfer_length = bfr.size() as u32; 180 self.req.in_data_buffer = Some(bfr); 181 Ok(self) 182 } 183 184 // # SENSE BUFFER 185 // ######################################################################################## 186 187 /// Adds a newly allocated sense buffer to the built SCSI request. 188 /// 189 /// # Arguments 190 /// - `len`: The size of the buffer (in bytes) to allocate for receiving sense data. 191 /// 192 /// # Returns 193 /// `Result` indicating success or a memory allocation error. 194 pub fn with_sense_buffer(mut self, len: u8) -> Result { 195 let mut bfr = AlignedBuffer::from_size_align(len as usize, self.req.io_align as usize)?; 196 self.req.sense_data_capacity = bfr.size(); 197 self.req.packet.sense_data = bfr.ptr_mut().cast(); 198 self.req.packet.sense_data_length = len; 199 self.req.sense_data_buffer = Some(bfr); 200 Ok(self) 201 } 202 203 // # WRITE BUFFER 204 // ######################################################################################## 205 206 /// Uses a user-supplied buffer for writing data to the device. 207 /// 208 /// # Arguments 209 /// - `bfr`: A mutable reference to an [`AlignedBuffer`] containing the data to be written to the device. 210 /// 211 /// # Returns 212 /// `Result` indicating success or an alignment issue with the provided buffer. 213 /// 214 /// # Description 215 /// This method checks the alignment of the buffer against the protocol's requirements and assigns it to 216 /// the `out_data_buffer` of the underlying `ScsiRequest`. 217 pub fn use_write_buffer(mut self, bfr: &'a mut AlignedBuffer) -> Result { 218 // check alignment of externally supplied buffer 219 bfr.check_alignment(self.req.io_align as usize)?; 220 self.req.out_data_buffer = None; 221 self.req.packet.out_data_buffer = bfr.ptr_mut().cast(); 222 self.req.packet.out_transfer_length = bfr.size() as u32; 223 Ok(self) 224 } 225 226 /// Adds a newly allocated write buffer to the built SCSI request that is filled from the 227 /// given data buffer. (Done for memory alignment and lifetime purposes) 228 /// 229 /// # Arguments 230 /// - `data`: A slice of bytes representing the data to be written. 231 /// 232 /// # Returns 233 /// `Result` indicating success or a memory allocation error. 234 pub fn with_write_data(mut self, data: &[u8]) -> Result { 235 let mut bfr = AlignedBuffer::from_size_align(data.len(), self.req.io_align as usize)?; 236 bfr.copy_from_slice(data); 237 self.req.packet.out_data_buffer = bfr.ptr_mut().cast(); 238 self.req.packet.out_transfer_length = bfr.size() as u32; 239 self.req.out_data_buffer = Some(bfr); 240 Ok(self) 241 } 242 243 // # COMMAND BUFFER 244 // ######################################################################################## 245 246 /// Uses a user-supplied Command Data Block (CDB) buffer. 247 /// 248 /// # Arguments 249 /// - `data`: A mutable reference to an [`AlignedBuffer`] containing the CDB to be sent to the device. 250 /// 251 /// # Returns 252 /// `Result` indicating success or an alignment issue with the provided buffer. 253 /// 254 /// # Notes 255 /// The maximum length of a CDB is 255 bytes. 256 pub fn use_command_buffer( 257 mut self, 258 data: &'a mut AlignedBuffer, 259 ) -> Result { 260 assert!(data.size() <= 255); 261 // check alignment of externally supplied buffer 262 data.check_alignment(self.req.io_align as usize)?; 263 self.req.cdb_buffer = None; 264 self.req.packet.cdb = data.ptr_mut().cast(); 265 self.req.packet.cdb_length = data.size() as u8; 266 Ok(self) 267 } 268 269 /// Adds a newly allocated Command Data Block (CDB) buffer to the built SCSI request that is filled from the 270 /// given data buffer. (Done for memory alignment and lifetime purposes) 271 /// 272 /// # Arguments 273 /// - `data`: A slice of bytes representing the command to be sent. 274 /// 275 /// # Returns 276 /// `Result` indicating success or a memory allocation error. 277 /// 278 /// # Notes 279 /// The maximum length of a CDB is 255 bytes. 280 pub fn with_command_data(mut self, data: &[u8]) -> Result { 281 assert!(data.len() <= 255); 282 let mut bfr = AlignedBuffer::from_size_align(data.len(), self.req.io_align as usize)?; 283 bfr.copy_from_slice(data); 284 self.req.packet.cdb = bfr.ptr_mut().cast(); 285 self.req.packet.cdb_length = bfr.size() as u8; 286 self.req.cdb_buffer = Some(bfr); 287 Ok(self) 288 } 289 290 /// Build the final `ScsiRequest`. 291 /// 292 /// # Returns 293 /// A fully-configured [`ScsiRequest`] ready for execution. 294 #[must_use] 295 pub fn build(self) -> ScsiRequest<'a> { 296 self.req 297 } 298 } 299 300 /// Represents the response of a SCSI request. 301 /// 302 /// This struct encapsulates the results of a SCSI operation, including data buffers 303 /// for read and sense data, as well as status codes returned by the host adapter and target device. 304 #[derive(Debug)] 305 #[repr(transparent)] 306 pub struct ScsiResponse<'a>(ScsiRequest<'a>); 307 impl ScsiResponse<'_> { 308 /// Retrieves the buffer containing data read from the device (if any). 309 /// 310 /// # Returns 311 /// `Option<&[u8]>`: A slice of the data read from the device, or `None` if no read buffer was assigned. 312 /// 313 /// # Safety 314 /// - If the buffer pointer is `NULL`, the method returns `None` and avoids dereferencing it. 315 #[must_use] 316 pub const fn read_buffer(&self) -> Option<&[u8]> { 317 if self.0.packet.in_data_buffer.is_null() { 318 return None; 319 } 320 // The firmware reports the transferred length; clamp it so that a 321 // bogus value cannot produce an out-of-bounds slice. 322 let reported = self.0.packet.in_transfer_length as usize; 323 let cap = self.0.in_data_capacity; 324 let len = if reported < cap { reported } else { cap }; 325 // SAFETY: The buffer holds at least `len` initialized bytes. 326 unsafe { 327 Some(slice::from_raw_parts( 328 self.0.packet.in_data_buffer.cast(), 329 len, 330 )) 331 } 332 } 333 334 /// Retrieves the buffer containing sense data returned by the device (if any). 335 /// 336 /// # Returns 337 /// `Option<&[u8]>`: A slice of the sense data, or `None` if no sense data buffer was assigned. 338 /// 339 /// # Safety 340 /// - If the buffer pointer is `NULL`, the method returns `None` and avoids dereferencing it. 341 #[must_use] 342 pub const fn sense_data(&self) -> Option<&[u8]> { 343 if self.0.packet.sense_data.is_null() { 344 return None; 345 } 346 // The firmware reports how much sense data it wrote; clamp it so 347 // that a bogus value cannot produce an out-of-bounds slice. 348 let reported = self.0.packet.sense_data_length as usize; 349 let cap = self.0.sense_data_capacity; 350 let len = if reported < cap { reported } else { cap }; 351 // SAFETY: The buffer holds at least `len` initialized bytes. 352 unsafe { Some(slice::from_raw_parts(self.0.packet.sense_data.cast(), len)) } 353 } 354 355 /// Retrieves the status of the host adapter after executing the SCSI request. 356 /// 357 /// # Returns 358 /// [`ScsiIoHostAdapterStatus`]: The status code indicating the result of the operation from the host adapter. 359 #[must_use] 360 pub const fn host_adapter_status(&self) -> ScsiIoHostAdapterStatus { 361 self.0.packet.host_adapter_status 362 } 363 364 /// Retrieves the status of the target device after executing the SCSI request. 365 /// 366 /// # Returns 367 /// [`ScsiIoTargetStatus`]: The status code returned by the target device. 368 #[must_use] 369 pub const fn target_status(&self) -> ScsiIoTargetStatus { 370 self.0.packet.target_status 371 } 372 }