Skip to content
Open
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5464,6 +5464,7 @@ dependencies = [
"pci_core",
"pci_resources",
"scsi_buffers",
"sha2",
"slab",
"task_control",
"thiserror 2.0.16",
Expand Down
1 change: 1 addition & 0 deletions vm/devices/storage/nvme/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ async-trait.workspace = true
futures.workspace = true
futures-concurrency.workspace = true
parking_lot.workspace = true
sha2.workspace = true
slab.workspace = true
thiserror.workspace = true
tracing.workspace = true
Expand Down
195 changes: 184 additions & 11 deletions vm/devices/storage/nvme/src/namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,24 @@ pub struct Namespace {
mem: GuestMemory,
block_shift: u32,
pr: bool,
/// Stable backing-store identity, when the disk supplies one.
///
/// A missing or all-zero disk ID is not replaced with a controller/NSID
/// derived value: those identify an attachment slot, not the backing
/// namespace, and can be reused for a different disk.
nguid: Option<[u8; 16]>,
}

impl Namespace {
pub fn new(mem: GuestMemory, nsid: u32, disk: Disk) -> Self {
let nguid = disk.disk_id().filter(|id| *id != [0; 16]);
Self {
block_shift: disk.sector_size().trailing_zeros(),
pr: disk.pr().is_some(),
mem,
disk,
nsid,
nguid,
}
}

Expand Down Expand Up @@ -63,25 +71,28 @@ impl Namespace {
nlbaf: 0,
flbas: nvm::Flbas::new().with_low_index(0),
rescap,
// Populate the inline field only when the backing store supplies
// a suitable identity. EUI64 remains zero.
nguid: self.nguid.unwrap_or_default(),
nsattr: nvm::Nsattr::new().with_write_protected(self.disk.is_read_only()),
..FromZeros::new_zeroed()
};
id.lbaf[0] = nvm::Lbaf::new().with_lbads(self.block_shift as u8);
}

pub fn namespace_id_descriptor(&self, buf: &mut [u8]) {
buf.fill(0);
let Some(nguid) = self.nguid else {
return;
};
let id = nvm::NamespaceIdentificationDescriptor::mut_from_prefix(buf)
.unwrap()
.0; // TODO: zerocopy: from-prefix (mut_from_prefix): use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
let mut nid = [0u8; 0x10];
if let Some(guid) = self.disk.disk_id() {
nid = guid;
}
*id = nvm::NamespaceIdentificationDescriptor {
nidt: nvm::NamespaceIdentifierType::NSGUID.0,
nidl: size_of_val(&nid) as u8,
nidl: size_of_val(&nguid) as u8,
rsvd: [0, 0],
nid,
nid: nguid,
};
}

Expand Down Expand Up @@ -277,12 +288,174 @@ fn map_disk_error(err: disk_backend::DiskError) -> NvmeError {

#[cfg(test)]
mod tests {
use super::Namespace;
use crate::error::CommandResult;
use crate::spec;
use crate::spec::nvm;
use super::*;
use disk_backend::Disk;
use disk_backend::DiskError;
use disk_backend::DiskIo;
use disk_backend::UnmapBehavior;
use scsi_buffers::RequestBuffers;

/// Minimal `DiskIo` shim used to feed a known `disk_id` (or `None`)
/// into `Namespace::identify` for testing. None of the IO methods are
/// expected to be called from `identify`; they panic if they ever are.
#[derive(Inspect)]
#[inspect(skip)]
struct TestDisk {
disk_id: Option<[u8; 16]>,
}

impl DiskIo for TestDisk {
fn disk_type(&self) -> &str {
"test"
}
fn sector_count(&self) -> u64 {
256
}
fn sector_size(&self) -> u32 {
512
}
fn disk_id(&self) -> Option<[u8; 16]> {
self.disk_id
}
fn physical_sector_size(&self) -> u32 {
512
}
fn is_fua_respected(&self) -> bool {
false
}
fn is_read_only(&self) -> bool {
false
}
fn unmap_behavior(&self) -> UnmapBehavior {
UnmapBehavior::Ignored
}
async fn unmap(&self, _: u64, _: u64, _: bool) -> Result<(), DiskError> {
unreachable!("Namespace::identify must not perform IO")
}
async fn read_vectored(&self, _: &RequestBuffers<'_>, _: u64) -> Result<(), DiskError> {
unreachable!("Namespace::identify must not perform IO")
}
async fn write_vectored(
&self,
_: &RequestBuffers<'_>,
_: u64,
_: bool,
) -> Result<(), DiskError> {
unreachable!("Namespace::identify must not perform IO")
}
async fn sync_cache(&self) -> Result<(), DiskError> {
unreachable!("Namespace::identify must not perform IO")
}
}

/// Byte offsets in the Identify Namespace data structure (NVMe Base
/// Specification Figure 312 / NVM Command Set Specification Figure 97).
const NGUID_OFFSET: usize = 104;
const NGUID_LEN: usize = 16;
const EUI64_OFFSET: usize = 120;
const EUI64_LEN: usize = 8;

/// Convenience: build a `Namespace` with a `TestDisk` backing, run
/// `Namespace::identify`, and return the 4 KiB response buffer.
fn identify_buf_for(nsid: u32, disk_id: Option<[u8; 16]>) -> Vec<u8> {
let disk = Disk::new(TestDisk { disk_id }).unwrap();
let mem = GuestMemory::empty();
let ns = Namespace::new(mem, nsid, disk);
let mut buf = vec![0u8; 4096];
ns.identify(&mut buf);
buf
}

/// Convenience: build a `Namespace` with a `TestDisk` backing, run
/// `Namespace::namespace_id_descriptor`, and return the 4 KiB
/// response buffer.
fn descriptor_buf_for(nsid: u32, disk_id: Option<[u8; 16]>) -> Vec<u8> {
let disk = Disk::new(TestDisk { disk_id }).unwrap();
let mem = GuestMemory::empty();
let ns = Namespace::new(mem, nsid, disk);
let mut buf = vec![0u8; 4096];
ns.namespace_id_descriptor(&mut buf);
buf
}

/// When the backing disk reports a 16-byte identifier, the inline
/// NGUID field of the Identify Namespace response (offset 104..120)
/// must contain those bytes verbatim. EUI64 (offset 120..128) is
/// independent and must remain zero -- there is no general way to
/// derive a unique 8-byte EUI from the backing disk.
#[test]
fn test_identify_namespace_populates_inline_nguid_from_disk_id() {
let want: [u8; 16] = [
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54,
0x32, 0x10,
];
let buf = identify_buf_for(1, Some(want));
assert_eq!(
&buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN],
&want,
"inline NGUID must echo the disk_id bytes when the backing disk supplies one"
);
assert_eq!(
&buf[EUI64_OFFSET..EUI64_OFFSET + EUI64_LEN],
&[0u8; EUI64_LEN],
"EUI64 must remain zero -- there is no defined derivation"
);
}

/// When the backing disk reports no identifier, the inline NGUID and EUI64
/// fields remain zero.
#[test]
fn test_identify_namespace_leaves_nguid_zero_when_disk_has_no_id() {
let buf = identify_buf_for(1, None);
assert_eq!(
&buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN],
&[0u8; NGUID_LEN]
);
assert_eq!(
&buf[EUI64_OFFSET..EUI64_OFFSET + EUI64_LEN],
&[0u8; EUI64_LEN]
);
}

/// A pathological all-zero backing ID is treated as absent.
#[test]
fn test_identify_namespace_treats_zero_disk_id_as_absent() {
let buf = identify_buf_for(5, Some([0u8; 16]));
assert_eq!(
&buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN],
&[0u8; NGUID_LEN]
);
Comment on lines +423 to +427
}

/// The NIDT=NSGUID (NGUID in the NVMe spec) descriptor returned by CNS=03h
/// must match the backing identity copied into the inline NGUID.
#[test]
fn test_namespace_id_descriptor_matches_inline_nguid_with_disk_id() {
let want: [u8; 16] = [
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
0xff, 0x00,
];
let inline = identify_buf_for(1, Some(want));
let desc = descriptor_buf_for(1, Some(want));
// Descriptor layout: byte 0 = NIDT, byte 1 = NIDL, bytes 2-3
// reserved, bytes 4..20 = NID.
assert_eq!(desc[0], nvm::NamespaceIdentifierType::NSGUID.0);
assert_eq!(desc[1] as usize, NGUID_LEN);
assert_eq!(&desc[4..4 + NGUID_LEN], &want);
assert_eq!(
&desc[4..4 + NGUID_LEN],
&inline[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]
);
}

/// Without a backing identity, CNS=03h contains no descriptor.
#[test]
fn test_namespace_id_descriptor_is_empty_without_disk_id() {
let desc = descriptor_buf_for(7, None);
assert!(desc.iter().all(|byte| *byte == 0));
}

use disklayer_ram::ram_disk;
use guestmem::GuestMemory;
use pal_async::async_test;
use zerocopy::FromZeros;
use zerocopy::IntoBytes;
Expand Down
114 changes: 112 additions & 2 deletions vm/devices/storage/nvme/src/tests/controller_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@ fn instantiate_controller(
driver: DefaultDriver,
gm: &GuestMemory,
int_controller: Option<&TestPciInterruptController>,
) -> NvmeController {
instantiate_controller_with_subsystem_id(driver, gm, int_controller, Guid::new_random())
}

/// Variant that pins the controller's subsystem_id so tests can predict
/// fields derived from it (e.g. the Identify Controller Serial Number).
fn instantiate_controller_with_subsystem_id(
driver: DefaultDriver,
gm: &GuestMemory,
int_controller: Option<&TestPciInterruptController>,
subsystem_id: Guid,
) -> NvmeController {
let mut mmio_reg = TestNvmeMmioRegistration {};
let vm_task_driver = &VmTaskDriverSource::new(SingleDriverBackend::new(driver));
Expand All @@ -51,7 +62,7 @@ fn instantiate_controller(
NvmeControllerCaps {
msix_count: 64,
max_io_queues: 64,
subsystem_id: Guid::new_random(),
subsystem_id,
},
);

Expand Down Expand Up @@ -118,7 +129,31 @@ pub async fn instantiate_and_build_admin_queue(
driver: DefaultDriver,
gm: &GuestMemory,
) -> NvmeController {
let mut nvmec = instantiate_controller(driver.clone(), gm, int_controller);
let nvmec = instantiate_controller(driver.clone(), gm, int_controller);
build_admin_queue_for_controller(
nvmec,
acq_buffer,
acq_entries,
asq_buffer,
asq_entries,
trigger_interrupt,
driver,
)
.await
}

/// Same as [`instantiate_and_build_admin_queue`] but takes an
/// already-built controller. Useful when the test needs to control
/// fields of [`NvmeControllerCaps`] (e.g. a fixed `subsystem_id`).
async fn build_admin_queue_for_controller(
mut nvmec: NvmeController,
acq_buffer: &PrpRange,
acq_entries: u32,
asq_buffer: &PrpRange,
asq_entries: u32,
trigger_interrupt: bool,
driver: DefaultDriver,
) -> NvmeController {
// Set the BARs.
nvmec
.pci_cfg_write(0x10, ByteEnabledDwordWrite::with_all_bytes_enabled(0))
Expand Down Expand Up @@ -961,6 +996,81 @@ async fn test_full_cq_does_not_leak_io_count(driver: DefaultDriver) {
);
}

/// Regression test: Identify Controller must report a Serial Number
/// derived from the configured NVM subsystem identifier
/// (`subsystem_id`) rather than the historical hard-coded
/// `"SN: 000001 "` literal.
///
/// NVMe defines SN as a per-NVM-subsystem field (Base section 4.7.1 /
/// Identify Controller Figure 328); collapsing every emulated
/// controller's SN to the same literal value defeats host-side
/// subsystem-identity tracking and unique-id derivation. This test
/// exercises the actual IDENTIFY_CONTROLLER admin command end-to-end
/// and verifies the SN bytes in the guest-memory response match the
/// expected derived value.
#[async_test]
async fn test_identify_controller_serial_number_is_derived(driver: DefaultDriver) {
let acq_buf = PrpRange::new(vec![0], 0, PAGE_SIZE64).unwrap();
let asq_buf = PrpRange::new(vec![0x1000], 0, PAGE_SIZE64).unwrap();
let gm = test_memory();
let int_controller = TestPciInterruptController::new();

// Pick a fixed subsystem_id so we can compute the expected SN.
let subsystem_id = Guid {
data1: 0x0001_0203,
data2: 0x0405,
data3: 0x0607,
data4: [0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f],
};
let nvmec = instantiate_controller_with_subsystem_id(
driver.clone(),
&gm,
Some(&int_controller),
subsystem_id,
);
let mut nvmec =
build_admin_queue_for_controller(nvmec, &acq_buf, 64, &asq_buf, 64, true, driver.clone())
.await;

// Place the Identify Controller response in a dedicated page so we
// can read it back as a typed structure. Page 0 = CQ, page 1 = SQ,
// page 2 (GPA 0x2000) is free.
const IDENTIFY_DATA_GPA: u64 = 0x2000;

let mut cmd = spec::Command::new_zeroed();
cmd.cdw0.set_opcode(spec::AdminOpcode::IDENTIFY.0);
cmd.cdw0.set_cid(901);
cmd.cdw10 = u32::from(spec::Cdw10Identify::new().with_cns(spec::Cns::CONTROLLER.0));
cmd.dptr[0] = IDENTIFY_DATA_GPA;
write_command_to_queue(&gm, &asq_buf, 0, &cmd);
nvmec.write_bar0(0x1000, 1u32.as_bytes()).unwrap();

wait_for_msi(driver.clone(), &int_controller, 1000, 0xfeed0000, 0x1111).await;
let cqe = read_completion_from_queue(&gm, &acq_buf, 0);
assert_eq!(cqe.cid, 901);
assert_eq!(cqe.status.status(), spec::Status::SUCCESS.0);

// Read the Identify Controller response back out of guest memory and
// check the SN bytes (field offset 4..24, length 20).
let identify: spec::IdentifyController = gm.read_plain(IDENTIFY_DATA_GPA).unwrap();
// Expected SN: first 10 bytes of SHA-256(subsystem_id) rendered as
// 20 lowercase ASCII hex chars. For the GUID configured above, the
// 16-byte SHA-256 input is [03, 02, 01, 00, 05, 04, 07, 06, 08, 09,
// 0a, 0b, 0c, 0d, 0e, 0f] (little-endian for data1/data2/data3, raw
// for data4); the first 10 bytes of its digest are 66 68 18 c7 e8 2e
// a3 bc 29 2b, hex-encoded to "666818c7e82ea3bc292b".
let expected_sn: [u8; 20] = *b"666818c7e82ea3bc292b";
let actual_sn: [u8; 20] = identify.sn.into();
assert_eq!(
actual_sn, expected_sn,
"Identify Controller SN must be derived from subsystem_id, not the \
legacy hard-coded literal"
);
// Defense in depth: explicitly verify we are not regressing to the
// old hard-coded value.
assert_ne!(actual_sn, *b"SN: 000001 ");
}

/// Regression test for the Asynchronous Event Configuration feature
/// (Set/Get Features FID 0Bh).
///
Expand Down
Loading
Loading