From 79ba52b0df2da0b89b6cf67f026c7eebe92faec7 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:23:54 -0500 Subject: [PATCH] fix(installer): read a SATA or IDE disk's serial through its controller's ATA pass-through or vendor disk information with the AHCI driver's own reading, and log what a disk without one offers, where firmware without standard disk information left every such disk without a serial number in the picker --- crates/stela-boot/src/installer.rs | 10 +- crates/stela-boot/src/payload.rs | 245 ++++++++++++++++++-- crates/stela-driver-base/src/block.rs | 28 +++ crates/stela-driver-base/src/block/tests.rs | 32 +++ crates/stela-driver-storage/src/ahci.rs | 10 +- 5 files changed, 299 insertions(+), 26 deletions(-) diff --git a/crates/stela-boot/src/installer.rs b/crates/stela-boot/src/installer.rs index 7f1bfa5a37..022cafd977 100644 --- a/crates/stela-boot/src/installer.rs +++ b/crates/stela-boot/src/installer.rs @@ -26,7 +26,7 @@ use crate::{ choice::{self, Press, Wait}, console::{Framebuffer, font}, output, - payload::{Aligned, device_path, disk_model, disk_rotation, disk_serial}, + payload::{Aligned, device_path, disk_model, disk_rotation, disk_serial, serial_sources}, ui::{self, Canvas}, }; use alloc::string::ToString; @@ -551,6 +551,14 @@ fn disks() -> Vec { blocks: media.last_block() + 1, }; let serial = disk_serial(handle, &path); + // What a disk without a serial number offers, which says why. + if serial.is_none() { + output::arguments(format_args!( + "INSTALLER disk {} without a serial number: {}\n", + bus(&path), + serial_sources(handle, &path) + )); + } let rotation = disk_rotation(handle); let mut disk = Disk { media: media.media_id(), diff --git a/crates/stela-boot/src/payload.rs b/crates/stela-boot/src/payload.rs index c7d72496a3..42c0198810 100644 --- a/crates/stela-boot/src/payload.rs +++ b/crates/stela-boot/src/payload.rs @@ -30,6 +30,7 @@ use uefi::{ file::{Directory, File, FileAttribute, FileInfo, FileMode, RegularFile}, fs::SimpleFileSystem, }, + unsafe_protocol, }, }; use { @@ -435,24 +436,30 @@ const NVME_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(5); /// the model number, two characters per word with the first in the high /// byte. const ATA_IDENTIFY_BYTES: usize = 512; -const ATA_SERIAL: core::ops::Range = 20..40; -const ATA_MODEL: core::ops::Range = 54..94; +const ATA_SERIAL: core::ops::Range = 10..20; +const ATA_MODEL: core::ops::Range = 27..47; /// ATA IDENTIFY DEVICE word 217: the nominal media rotation rate. const ATA_ROTATION: usize = 217; /// NVMe Identify Controller bytes 24-63: the model number. const NVME_MODEL: core::ops::Range = 24..64; -fn trimmed(bytes: &[u8]) -> Option { - let text = core::str::from_utf8(bytes).ok()?.trim_matches([' ', '\0']); - (!text.is_empty()).then(|| text.into()) +/// A fixed-width identify field as Stela's own NVMe driver reads it +/// (`stela_drivers::block::ascii`), so both name the disk alike; `None` +/// when blank. +fn identify_text(bytes: &[u8]) -> Option { + let text = stela_drivers::block::ascii(bytes); + (!text.is_empty()).then_some(text) } /// A whole disk's serial number, from its NVMe controller, its ATA /// IDENTIFY data or its USB device's serial number string. Other buses, -/// such as virtio, report none. +/// such as virtio, report none. Each is read as Stela's own driver for that +/// bus reads it after the firmware has exited, which finds the disk by it. +/// SCSI disks' unit serial numbers (VPD page 0x80) are not read: no driver +/// of Stela's reads them, so a disk named by one could not be found again. pub(crate) fn disk_serial(handle: Handle, path: &str) -> Option { nvme_identify(path) - .and_then(|data| trimmed(data.get(NVME_SERIAL)?)) + .and_then(|data| identify_text(data.get(NVME_SERIAL)?)) .or_else(|| ata_text(handle, ATA_SERIAL)) .or_else(|| usb_string(path, |device| device.str_serial_number)) } @@ -461,7 +468,7 @@ pub(crate) fn disk_serial(handle: Handle, path: &str) -> Option { /// (the USB device's product string). pub(crate) fn disk_model(handle: Handle, path: &str) -> Option { nvme_identify(path) - .and_then(|data| trimmed(data.get(NVME_MODEL)?)) + .and_then(|data| identify_text(data.get(NVME_MODEL)?)) .or_else(|| ata_text(handle, ATA_MODEL)) .or_else(|| usb_string(path, |device| device.str_product)) } @@ -557,9 +564,18 @@ pub(crate) fn disk_rotation(handle: Handle) -> stela_drivers::block::Rotation { }) } -/// The disk's ATA IDENTIFY data, as much as the firmware's disk information -/// keeps for an AHCI or IDE disk. +/// The disk's ATA IDENTIFY data: as much as the firmware's disk information +/// keeps for an AHCI or IDE disk, or else what the disk answers an IDENTIFY +/// DEVICE through its controller's ATA pass-through, as some firmware's ATA +/// drivers install no disk information. fn ata_identify(handle: Handle) -> Option> { + disk_info_identify(handle).or_else(|| ata_pass_thru_identify(handle)) +} + +/// The firmware's disk information's IDENTIFY data, for an AHCI or IDE +/// disk, or a disk of an interface the UEFI specification does not name +/// whose data carries ATA's integrity word, as only ATA IDENTIFY data does. +fn disk_info_identify(handle: Handle) -> Option> { use uefi::proto::media::disk_info::{DiskInfo, DiskInfoInterface}; // SAFETY: the identify data is only read. let info = unsafe { @@ -573,25 +589,216 @@ fn ata_identify(handle: Handle) -> Option> { ) } .ok()?; + let interface = info.interface(); if !matches!( - info.interface(), - DiskInfoInterface::AHCI | DiskInfoInterface::IDE + interface, + DiskInfoInterface::AHCI | DiskInfoInterface::IDE | DiskInfoInterface::Unknown ) { return None; } let mut data = vec![0u8; ATA_IDENTIFY_BYTES]; let bytes = info.identify(&mut data).ok()?; data.truncate(bytes); - Some(data) + (interface != DiskInfoInterface::Unknown || stela_drivers::block::ata_identify_signed(&data)) + .then_some(data) } -/// The text in `range` of the disk's ATA IDENTIFY data. -fn ata_text(handle: Handle, range: core::ops::Range) -> Option { - let mut text = ata_identify(handle)?.get(range)?.to_vec(); - for pair in text.as_chunks_mut::<2>().0 { - pair.swap(0, 1); +/// What the firmware offers a disk none of [`disk_serial`]'s sources gave a +/// serial number for, for the log: whether its device path reads as text +/// (the NVMe and USB sources find their controller by it), its disk +/// information's interface, and which pass-through or USB protocol leads to +/// it. +pub(crate) fn serial_sources(handle: Handle, path: &str) -> String { + use uefi::proto::{media::disk_info::DiskInfo, nvme::pass_thru::NvmePassThru, usb::io::UsbIo}; + // SAFETY: only the interface is read. + let info = unsafe { + boot::open_protocol::( + OpenProtocolParams { + handle, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) } + .map_or_else( + |_| String::from("none"), + |info| format!("{:?}", info.interface()), + ); + // SAFETY: the disk's device path, only read while it is open. + let binary = unsafe { + boot::open_protocol::( + OpenProtocolParams { + handle, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + }; + let leads = |found: fn(&mut &DevicePath) -> bool| match &binary { + Ok(path) => { + let mut remaining: &DevicePath = path; + found(&mut remaining) + } + Err(_) => false, + }; + format!( + "path-text={} disk-info={info} ata-pass-thru={} nvme-pass-thru={} usb-io={}", + !path.is_empty(), + leads(|path| boot::locate_device_path::(path).is_ok()), + leads(|path| boot::locate_device_path::(path).is_ok()), + leads(|path| boot::locate_device_path::(path).is_ok()), + ) +} + +/// The text of the IDENTIFY words `words` of the disk's ATA IDENTIFY data. +fn ata_text(handle: Handle, words: core::ops::Range) -> Option { // As Stela's AHCI driver reads the field, so both name the disk alike. - let text = stela_drivers::block::ascii(&text); + let text = stela_drivers::block::ata_string(&ata_identify(handle)?, words); (!text.is_empty()).then_some(text) } + +/// `EFI_ATA_PASS_THRU_PROTOCOL` (UEFI 2.10 section 13.13); the slots the +/// identify does not use are opaque pointer-sized fields, never invoked. +#[repr(C)] +#[unsafe_protocol("1d3de7f0-0807-424f-aa69-11a54e19a46f")] +struct AtaPassThru { + mode: *const AtaPassThruMode, + pass_thru: unsafe extern "efiapi" fn( + *mut AtaPassThru, + u16, + u16, + *mut AtaPassThruPacket, + *mut core::ffi::c_void, + ) -> uefi::Status, + get_next_port_get_next_device_build_device_path: [usize; 3], + get_device: unsafe extern "efiapi" fn( + *mut AtaPassThru, + *const core::ffi::c_void, + *mut u16, + *mut u16, + ) -> uefi::Status, + reset_port_reset_device: [usize; 2], +} + +/// `EFI_ATA_PASS_THRU_MODE`. +#[repr(C)] +struct AtaPassThruMode { + _attributes: u32, + io_align: u32, +} + +/// `EFI_ATA_PASS_THRU_COMMAND_PACKET`; its status and command blocks are +/// the 24-byte `EFI_ATA_STATUS_BLOCK` and `EFI_ATA_COMMAND_BLOCK`. +#[repr(C)] +struct AtaPassThruPacket { + asb: *mut u8, + acb: *const u8, + timeout: u64, + in_data_buffer: *mut u8, + out_data_buffer: *const u8, + in_transfer_length: u32, + out_transfer_length: u32, + protocol: u8, + length: u8, +} + +const _: () = { + assert!(size_of::() == 64); + assert!(core::mem::offset_of!(AtaPassThru, get_device) == 40); + assert!(size_of::() == 56); +}; + +/// What the disk answers ATA IDENTIFY DEVICE through the ATA pass-through +/// of the controller its device path leads through, the port and port +/// multiplier port the controller names for the rest of that path +/// (`GetDevice`), as edk2's ATA bus driver asks it. +fn ata_pass_thru_identify(handle: Handle) -> Option> { + /// `EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN`. + const PIO_DATA_IN: u8 = 0x04; + /// `EFI_ATA_PASS_THRU_LENGTH_BYTES | EFI_ATA_PASS_THRU_LENGTH_SECTOR_COUNT`. + const LENGTH: u8 = 0x80 | 0x20; + /// `ATA_CMD_IDENTIFY_DRIVE`. + const IDENTIFY_DEVICE: u8 = 0xec; + /// Five seconds, in the 100 ns units the packet counts. + const TIMEOUT: u64 = 50_000_000; + /// `EFI_ATA_COMMAND_BLOCK` offsets of the command and device fields. + const ACB_COMMAND: usize = 2; + const ACB_DEVICE_HEAD: usize = 7; + // SAFETY: the disk's device path, only read while it is open. + let path = unsafe { + boot::open_protocol::( + OpenProtocolParams { + handle, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } + .ok()?; + let mut remaining: &DevicePath = &path; + let controller = boot::locate_device_path::(&mut remaining).ok()?; + // SAFETY: the controller's protocol, used only by this read. + let mut ata = unsafe { + boot::open_protocol::( + OpenProtocolParams { + handle: controller, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } + .ok()?; + let ata: *mut AtaPassThru = &mut *ata; + // SAFETY: the firmware's mode structure, when it gives one. The buffers + // below are page aligned. + let mode = unsafe { (*ata).mode.as_ref() }?; + if mode.io_align > 4096 { + return None; + } + let (mut port, mut multiplier) = (0u16, 0u16); + // SAFETY: the firmware's protocol; the node is the rest of the disk's + // path, which outlives the call. + let found = unsafe { + ((*ata).get_device)( + ata, + remaining.as_ffi_ptr().cast(), + &mut port, + &mut multiplier, + ) + }; + if found.is_error() { + return None; + } + // edk2's ATA bus driver: the device bits, and the second device of an + // IDE channel (port multiplier port 1) in bit 4. + let mut acb = Aligned::new(24); + acb.bytes()[ACB_COMMAND] = IDENTIFY_DEVICE; + acb.bytes()[ACB_DEVICE_HEAD] = 0xe0 | if multiplier == 1 { 0x10 } else { 0 }; + let mut asb = Aligned::new(24); + let mut data = Aligned::new(ATA_IDENTIFY_BYTES); + let mut packet = AtaPassThruPacket { + asb: asb.bytes().as_mut_ptr(), + acb: acb.bytes().as_ptr(), + timeout: TIMEOUT, + in_data_buffer: data.bytes().as_mut_ptr(), + out_data_buffer: core::ptr::null(), + in_transfer_length: ATA_IDENTIFY_BYTES as u32, + out_transfer_length: 0, + protocol: PIO_DATA_IN, + length: LENGTH, + }; + // SAFETY: a blocking IDENTIFY DEVICE, which only reads the disk's + // identity into `data`; every buffer is page aligned, as any IoAlign + // asks, and outlives the call. + let status = + unsafe { ((*ata).pass_thru)(ata, port, multiplier, &mut packet, core::ptr::null_mut()) }; + if status.is_error() { + return None; + } + let bytes = (packet.in_transfer_length as usize).min(ATA_IDENTIFY_BYTES); + Some(data.bytes()[..bytes].to_vec()) +} diff --git a/crates/stela-driver-base/src/block.rs b/crates/stela-driver-base/src/block.rs index 1980ce7265..9f951e8f87 100644 --- a/crates/stela-driver-base/src/block.rs +++ b/crates/stela-driver-base/src/block.rs @@ -1310,6 +1310,34 @@ impl BlockDevice for Box { } } +/// The text of the ATA IDENTIFY words `words` in `data`, two characters +/// per word with the first in the high byte, as [`ascii`] reads it; empty +/// where `data` ends first. Stela's AHCI driver and the firmware's disk +/// picker both read a disk's serial number with it: the picker records it, +/// and the driver must find the disk by it, byte for byte. +pub fn ata_string(data: &[u8], words: core::ops::Range) -> String { + let Some(field) = data.get(2 * words.start..2 * words.end) else { + return String::new(); + }; + let bytes: alloc::vec::Vec = field + .as_chunks::<2>() + .0 + .iter() + .flat_map(|&[first, second]| [second, first]) + .collect(); + ascii(&bytes) +} + +/// Whether `data` begins with 512 bytes of IDENTIFY data that carry ATA's +/// integrity word: word 255's low byte is the signature 0xa5 and its high +/// byte a checksum that brings the sum of all 512 bytes to zero (ACS-3 +/// 7.12.7.97), which other identify data, such as SCSI's, does not. +pub fn ata_identify_signed(data: &[u8]) -> bool { + data.get(..512).is_some_and(|page| { + page[510] == 0xa5 && page.iter().fold(0u8, |sum, byte| sum.wrapping_add(*byte)) == 0 + }) +} + /// ASCII from a fixed-width identify field, trimmed of padding. pub fn ascii(bytes: &[u8]) -> String { let text: String = bytes diff --git a/crates/stela-driver-base/src/block/tests.rs b/crates/stela-driver-base/src/block/tests.rs index e6118b1d3c..9d8231f6d4 100644 --- a/crates/stela-driver-base/src/block/tests.rs +++ b/crates/stela-driver-base/src/block/tests.rs @@ -1090,6 +1090,38 @@ fn identify_strings_lose_padding_and_terminators() { assert_eq!(ascii(b"a\x01b"), "a?b"); } +#[test] +fn ata_strings_swap_each_word_and_lose_padding() { + // Words 10-19 of an IDENTIFY page: "WD-WCC4E1234567" padded with spaces, + // each word's first character in its high byte. + let mut data = [0u8; 512]; + let serial = b" WD-WCC4E1234567"; + for (word, &[first, second]) in serial.as_chunks::<2>().0.iter().enumerate() { + data[2 * (10 + word)] = second; + data[2 * (10 + word) + 1] = first; + } + assert_eq!(ata_string(&data, 10..20), "WD-WCC4E1234567"); + // Past the end of a short page: no text, not a panic. + assert_eq!(ata_string(&data[..30], 10..20), ""); + assert_eq!(ata_string(&data, 0..0), ""); +} + +#[test] +fn only_identify_data_with_its_integrity_word_counts_as_signed() { + let mut data = [0u8; 512]; + data[20] = b'W'; + assert!(!ata_identify_signed(&data)); + data[510] = 0xa5; + let sum = data.iter().fold(0u8, |sum, byte| sum.wrapping_add(*byte)); + data[511] = 0u8.wrapping_sub(sum); + assert!(ata_identify_signed(&data)); + // A wrong checksum, or a short page, is not. + data[511] ^= 1; + assert!(!ata_identify_signed(&data)); + data[511] ^= 1; + assert!(!ata_identify_signed(&data[..511])); +} + #[test] fn only_a_write_zeroes_that_stores_zeros_counts_as_written() { let zeroes = |unmap| Command::WriteZeroes { diff --git a/crates/stela-driver-storage/src/ahci.rs b/crates/stela-driver-storage/src/ahci.rs index 4f4612ae7b..3a23911115 100644 --- a/crates/stela-driver-storage/src/ahci.rs +++ b/crates/stela-driver-storage/src/ahci.rs @@ -12,7 +12,7 @@ use crate::{ Clock, Deadline, Handoff, block::{ BlockDevice, BlockError, Command, DiscardLimits, Expired, Extent, Features, Finished, - Identity, Rotation, Sense, SenseCompletion, Transport, ascii, + Identity, Rotation, Sense, SenseCompletion, Transport, ata_string, }, bus::{ dma::{DmaAllocator, DmaBuffer}, @@ -976,11 +976,9 @@ fn sense_reporting(word: impl Fn(usize) -> u16) -> (bool, bool) { fn identify(data: &[u8]) -> Result { let word = |index: usize| u16::from_le_bytes([data[2 * index], data[2 * index + 1]]); - // ATA strings hold two characters per word, high byte first. - let string = |words: core::ops::Range| { - let bytes: Vec = words.flat_map(|index| word(index).to_be_bytes()).collect(); - ascii(&bytes) - }; + // As the firmware's disk picker reads them, which names the disk by its + // serial number for this driver to find. + let string = |words: core::ops::Range| ata_string(data, words); if word(IDENTIFY_COMMANDS_2) & COMMANDS_2_LBA48 == 0 { return Err(BlockError::Unsupported( "SATA disk without 48-bit addressing",