From a97ae135300bd40621d5569f325c77eec614dd7e Mon Sep 17 00:00:00 2001 From: Jeff Bromberger <6789497+jeffbromberger@users.noreply.github.com> Date: Fri, 5 Jun 2026 15:55:59 -0500 Subject: [PATCH 1/3] nvme: populate inline NGUID and derive per-subsystem SN Two independent correctness gaps in how the emulated NVMe controller surfaces identifiers to the host. * Inline NGUID in Identify Namespace was always zero. `Namespace::identify` (CNS=00h) never populated the inline NGUID field at offsets 104..120; the 16 bytes were left at their `FromZeros::new_zeroed()` default. Hosts that read NGUID from the inline data structure -- rather than from the descriptor in the Identification Descriptor List (CNS=03h) -- got zeros and fell through to weaker unique-id construction. The descriptor- list path was a little better: it populated the NID from `disk.disk_id()` when present, but emitted a NIDT=2 (NGUID) descriptor with a zero NID when `disk.disk_id()` was `None`, violating NVMe Base section 4.7.1.2 / Figure 326's normative `the controller shall not report a Namespace Identification Descriptor with a value of type 2h` when NGUID is zero. The fix caches a single 16-byte NGUID on `Namespace` at construction. The value is the backing `disk.disk_id()` when available; otherwise it is synthesized as the first 16 bytes of SHA-256(`subsystem_id` || `nsid` little-endian), giving every namespace a stable, non-zero NGUID that is unique within its subsystem and deterministic across reboots. Both the CNS=00h inline field and the CNS=03h NIDT=2 (NGUID) descriptor now report the same cached value, so the two views are byte-for-byte consistent. EUI64 is left as zero -- there is no general way to derive a unique 8-byte EUI from the backing disk. * Identify Controller Serial Number was a hard-coded literal. The SN field was always `SN: 000001` (space-padded) regardless of the controller's identity, collapsing the host's view of subsystem identity. NVMe defines SN as a per-NVM-subsystem field (Base section 4.7.1 / Identify Controller Figure 328): controllers that share a subsystem share an SN, and CNTLID distinguishes them. The fix derives the 20-byte SN as the first 10 bytes of SHA-256(`subsystem_id`) rendered as 20 lowercase ASCII hex characters. Hashing before truncating diffuses the entropy of the full 16-byte `subsystem_id` across every output byte (the same principle that makes Git short hashes reliable identifiers), so the truncated SN retains ~80 bits of effective entropy regardless of where the entropy in `subsystem_id` was concentrated. Controllers that share a `subsystem_id` (e.g. future multi-controller-per-subsystem emulation) will report the same SN by construction, matching the spec semantics. Nine unit tests pin both behaviors: NGUID populated from disk_id, NGUID synthesized when no disk_id is available, descriptor-list / inline NGUID byte-equality in both paths, synthesize_nguid determinism + intra/inter-subsystem distinctness, derive_serial_number format pin, derive_serial_number distinctness across different subsystem_ids, derive_serial_number using the full subsystem_id (not just a prefix), plus an integration test that issues IDENTIFY_CONTROLLER through the real controller pipeline and verifies the SN byte sequence in the response. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Cargo.lock | 1 + vm/devices/storage/nvme/Cargo.toml | 1 + vm/devices/storage/nvme/src/namespace.rs | 268 +++++++++++++++++- .../nvme/src/tests/controller_tests.rs | 114 +++++++- vm/devices/storage/nvme/src/workers/admin.rs | 120 +++++++- 5 files changed, 494 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 160d2fed594..473d9165659 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5006,6 +5006,7 @@ dependencies = [ "pci_core", "pci_resources", "scsi_buffers", + "sha2", "slab", "task_control", "thiserror 2.0.16", diff --git a/vm/devices/storage/nvme/Cargo.toml b/vm/devices/storage/nvme/Cargo.toml index 172a5aaeab8..d21ecd7bb7a 100644 --- a/vm/devices/storage/nvme/Cargo.toml +++ b/vm/devices/storage/nvme/Cargo.toml @@ -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 diff --git a/vm/devices/storage/nvme/src/namespace.rs b/vm/devices/storage/nvme/src/namespace.rs index ffd1662b662..bbf508380b0 100644 --- a/vm/devices/storage/nvme/src/namespace.rs +++ b/vm/devices/storage/nvme/src/namespace.rs @@ -12,6 +12,7 @@ use crate::spec; use crate::spec::nvm; use disk_backend::Disk; use guestmem::GuestMemory; +use guid::Guid; use inspect::Inspect; use scsi_buffers::RequestBuffers; use zerocopy::FromBytes; @@ -26,16 +27,59 @@ pub struct Namespace { mem: GuestMemory, block_shift: u32, pr: bool, + /// 16-byte unique identifier for this namespace, computed once at + /// construction. Prefers the backing disk's `disk_id()` when + /// available; otherwise synthesizes a stable identifier from the + /// containing subsystem and the nsid (see [`synthesize_nguid`]). + /// This ensures every namespace exposes a non-zero NGUID, which + /// lets hosts derive stable per-namespace unique identifiers and + /// keeps the inline NGUID consistent with the NIDT=2 (NGUID) + /// entry in the Identify Namespace Identification Descriptor List. + nguid: [u8; 16], +} + +/// Synthesize a 16-byte NGUID for a namespace whose backing disk does +/// not supply its own [`Disk::disk_id`]. The result is deterministic +/// in `(subsystem_id, nsid)`: stable across emulator restarts, distinct +/// per namespace within a subsystem, and distinct across subsystems. +/// +/// The NVMe Base specification (section 4.7.1.2 / NVM Command Set +/// section 5.1.13.7 Figure 97) describes NGUID as an EUI-64-based 16-byte +/// identifier that the controller "assigns to the namespace when the +/// namespace is created". For a software-emulated namespace whose backing +/// store carries no such identifier, deriving one from the controller's +/// stable subsystem identity and the namespace's nsid is a reasonable +/// drop-in: it satisfies the "stable, unique within the subsystem" +/// property the spec ascribes to NGUID, and it lets the inline NGUID and +/// the NIDT=2 (NGUID) descriptor in the Identification Descriptor List +/// be reported consistently and non-zero in all cases. +/// +/// Implementation: SHA-256 of `subsystem_id` bytes followed by `nsid` in +/// little-endian, truncated to the first 16 bytes. +fn synthesize_nguid(subsystem_id: Guid, nsid: u32) -> [u8; 16] { + use sha2::Digest; + let mut h = sha2::Sha256::new(); + let ss_bytes: [u8; 16] = subsystem_id.into(); + h.update(ss_bytes); + h.update(nsid.to_le_bytes()); + let digest = h.finalize(); + let mut out = [0u8; 16]; + out.copy_from_slice(&digest[..16]); + out } impl Namespace { - pub fn new(mem: GuestMemory, nsid: u32, disk: Disk) -> Self { + pub fn new(mem: GuestMemory, subsystem_id: Guid, nsid: u32, disk: Disk) -> Self { + let nguid = disk + .disk_id() + .unwrap_or_else(|| synthesize_nguid(subsystem_id, nsid)); Self { block_shift: disk.sector_size().trailing_zeros(), pr: disk.pr().is_some(), mem, disk, nsid, + nguid, } } @@ -63,6 +107,14 @@ impl Namespace { nlbaf: 0, flbas: nvm::Flbas::new().with_low_index(0), rescap, + // Populate the inline NGUID field of Identify Namespace (offset + // 104..120) so guests that read NGUID from the inline data + // structure -- rather than only from the Identify Namespace + // Identification Descriptor List (CNS 03h) -- get a real, + // non-zero unique identifier. EUI64 is left as zero; there is + // no general way to derive a unique 8-byte EUI from the backing + // disk. + nguid: self.nguid, ..FromZeros::new_zeroed() }; id.lbaf[0] = nvm::Lbaf::new().with_lbads(self.block_shift as u8); @@ -72,15 +124,17 @@ impl Namespace { 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; - } + // Always emit a single NIDT=2 (NGUID) descriptor carrying the + // cached 16-byte identifier. Per NVMe Base specification, a + // controller shall not report a NIDT=2 descriptor with a zero + // NID; the synthesized fallback in [`Namespace::new`] guarantees + // `nguid` is non-zero for every namespace, so this constraint + // is met unconditionally. *id = nvm::NamespaceIdentificationDescriptor { nidt: nvm::NamespaceIdentifierType::NSGUID.0, - nidl: size_of_val(&nid) as u8, + nidl: size_of_val(&self.nguid) as u8, rsvd: [0, 0], - nid, + nid: self.nguid, }; } @@ -257,3 +311,203 @@ fn map_disk_error(err: disk_backend::DiskError) -> NvmeError { disk_backend::DiskError::UnsupportedEject => spec::Status::INVALID_COMMAND_OPCODE.into(), } } + +#[cfg(test)] +mod tests { + 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(subsystem_id: Guid, nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { + let disk = Disk::new(TestDisk { disk_id }).unwrap(); + let mem = GuestMemory::empty(); + let ns = Namespace::new(mem, subsystem_id, 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(subsystem_id: Guid, nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { + let disk = Disk::new(TestDisk { disk_id }).unwrap(); + let mem = GuestMemory::empty(); + let ns = Namespace::new(mem, subsystem_id, 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(Guid::new_random(), 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 + /// field must still be non-zero (synthesized from the namespace's + /// `(subsystem_id, nsid)` pair). EUI64 stays zero. + #[test] + fn test_identify_namespace_synthesizes_inline_nguid_when_disk_has_no_id() { + let subsystem_id = Guid::new_random(); + let buf = identify_buf_for(subsystem_id, 1, None); + let nguid: &[u8] = &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]; + assert_ne!( + nguid, &[0u8; NGUID_LEN], + "inline NGUID must be synthesized to a non-zero value when the backing \ + disk has no identifier" + ); + // Must match the helper's output exactly. + assert_eq!(nguid, &synthesize_nguid(subsystem_id, 1)); + assert_eq!( + &buf[EUI64_OFFSET..EUI64_OFFSET + EUI64_LEN], + &[0u8; EUI64_LEN] + ); + } + + /// The NIDT=2 (NGUID) descriptor returned by CNS=03h must match + /// the inline NGUID byte-for-byte, regardless of whether the + /// underlying NGUID came from the backing disk or from the + /// synthesized fallback. + #[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 subsystem_id = Guid::new_random(); + let inline = identify_buf_for(subsystem_id, 1, Some(want)); + let desc = descriptor_buf_for(subsystem_id, 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] + ); + } + + /// Same consistency property when the NGUID had to be synthesized. + /// This is the case that previously violated the spec (zero NID in + /// a NIDT=2 (NGUID) descriptor): the synthesized non-zero NGUID + /// makes the descriptor list well-formed. + #[test] + fn test_namespace_id_descriptor_matches_inline_nguid_without_disk_id() { + let subsystem_id = Guid::new_random(); + let inline = identify_buf_for(subsystem_id, 7, None); + let desc = descriptor_buf_for(subsystem_id, 7, None); + assert_eq!(desc[0], nvm::NamespaceIdentifierType::NSGUID.0); + assert_eq!(desc[1] as usize, NGUID_LEN); + let nid = &desc[4..4 + NGUID_LEN]; + assert_ne!(nid, &[0u8; NGUID_LEN]); + assert_eq!(nid, &inline[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]); + assert_eq!(nid, &synthesize_nguid(subsystem_id, 7)); + } + + /// `synthesize_nguid` must be a pure function of `(subsystem_id, + /// nsid)`. Same inputs -> same output; any change in either input + /// produces a different output. + #[test] + fn test_synthesize_nguid_is_deterministic_and_distinct() { + let s1 = Guid::new_random(); + let s2 = Guid::new_random(); + + // Deterministic. + assert_eq!(synthesize_nguid(s1, 1), synthesize_nguid(s1, 1)); + + // Different nsid in the same subsystem -> different NGUID. + assert_ne!(synthesize_nguid(s1, 1), synthesize_nguid(s1, 2)); + + // Different subsystems with the same nsid -> different NGUIDs. + assert_ne!(synthesize_nguid(s1, 1), synthesize_nguid(s2, 1)); + + // And of course non-zero. + assert_ne!(synthesize_nguid(s1, 1), [0u8; 16]); + } +} diff --git a/vm/devices/storage/nvme/src/tests/controller_tests.rs b/vm/devices/storage/nvme/src/tests/controller_tests.rs index 831d4062cb9..89499c73710 100644 --- a/vm/devices/storage/nvme/src/tests/controller_tests.rs +++ b/vm/devices/storage/nvme/src/tests/controller_tests.rs @@ -32,6 +32,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)); @@ -44,7 +55,7 @@ fn instantiate_controller( NvmeControllerCaps { msix_count: 64, max_io_queues: 64, - subsystem_id: Guid::new_random(), + subsystem_id, }, ); @@ -111,7 +122,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, 0).unwrap(); nvmec.pci_cfg_write(0x20, BAR0_LEN as u32).unwrap(); @@ -749,3 +784,78 @@ async fn test_full_cq_does_not_leak_io_count(driver: DefaultDriver) { "missing FLUSH completions — likely io_count leak throttled the SQ" ); } + +/// 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 "); +} diff --git a/vm/devices/storage/nvme/src/workers/admin.rs b/vm/devices/storage/nvme/src/workers/admin.rs index a5714533052..0a2ea576867 100644 --- a/vm/devices/storage/nvme/src/workers/admin.rs +++ b/vm/devices/storage/nvme/src/workers/admin.rs @@ -332,6 +332,50 @@ enum Event { #[error("namespace id conflict for {0}")] pub struct NsidConflict(u32); +/// Derive a 20-byte NVMe Serial Number from the controller's subsystem identifier. +/// +/// In NVMe the Serial Number is a per-NVM-subsystem field (NVMe Base +/// section 4.7.1 / Identify Controller, Figure 328): all controllers in +/// a single subsystem report the same SN, and CNTLID distinguishes +/// controllers within that subsystem. A hard-coded SN therefore +/// collapses subsystem identity for host-side unique-id derivation. +/// +/// This helper renders the first 10 bytes of `SHA-256(subsystem_id)` +/// as 20 ASCII hex characters (lowercase, exactly the 20-byte fixed +/// length of the SN field). Hashing before truncating diffuses the +/// entropy of the full 16-byte `subsystem_id` across every output +/// byte; this is the same reasoning that lets a Git short-hash +/// distinguish commits reliably even when only a prefix is shown. +/// The 20-character output retains ~80 bits of effective entropy +/// regardless of where the entropy in `subsystem_id` was concentrated +/// (e.g. trailing bytes of a vendor-prefixed GUID), giving roughly +/// 2^40 birthday-collision resistance. +/// +/// Properties: +/// +/// * **Stable across reboots** for a given `subsystem_id`. +/// * **Derived from the NVM subsystem's identity.** Two controllers +/// that share a subsystem (e.g. future multi-controller-per- +/// subsystem emulation) produce the same SN by construction, +/// matching the NVMe per-subsystem semantics of this field. +/// * **Practically distinct across distinct subsystem_ids.** Two +/// `subsystem_id` values that differ at all -- in any byte +/// position -- produce SHA-256 outputs that differ throughout, +/// so the 20-character prefix collides only with negligible +/// probability. +fn derive_serial_number(subsystem_id: Guid) -> [u8; 20] { + use sha2::Digest; + let bytes: [u8; 16] = subsystem_id.into(); + let digest = sha2::Sha256::digest(bytes); + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = [b' '; 20]; + for (i, b) in digest.iter().take(10).enumerate() { + out[i * 2] = HEX[(*b >> 4) as usize]; + out[i * 2 + 1] = HEX[(*b & 0xf) as usize]; + } + out +} + impl AdminHandler { pub fn new(driver: VmTaskDriver, config: AdminConfig) -> Self { Self { @@ -350,6 +394,7 @@ impl AdminHandler { let namespace = &*match self.namespaces.entry(nsid) { btree_map::Entry::Vacant(entry) => entry.insert(Arc::new(Namespace::new( self.config.mem.clone(), + self.config.subsystem_id, nsid, disk, ))), @@ -600,7 +645,7 @@ impl AdminHandler { ieee: [0x74, 0xe2, 0x8c], // Microsoft fr: (*b"v1.00000").into(), mn: (*b"MSFT NVMe Accelerator v1.0 ").into(), - sn: (*b"SN: 000001 ").into(), + sn: derive_serial_number(self.config.subsystem_id).into(), aerl: MAX_ASYNC_EVENT_REQUESTS - 1, elpe: ERROR_LOG_PAGE_ENTRIES - 1, oaes: spec::Oaes::new().with_namespace_attribute(true), @@ -1030,3 +1075,76 @@ impl InspectTask for AdminHandler { req.respond().merge(self).merge(state); } } + +#[cfg(test)] +mod tests { + use super::derive_serial_number; + use guid::Guid; + + /// Pure-function test for the SN derivation. Pins the byte layout + /// (lower-case ASCII hex of the first 10 bytes of SHA-256 of the + /// GUID, no trailing padding) so a future refactor of the helper + /// can't silently change what the SN field looks like to a host. + #[test] + fn test_derive_serial_number_format() { + // GUID whose 16-byte representation under `Guid::into::<[u8; 16]>` + // is exactly [03, 02, 01, 00, 05, 04, 07, 06, 08, 09, 0a, 0b, + // 0c, 0d, 0e, 0f]. The first 10 bytes of SHA-256 of those bytes + // are 66 68 18 c7 e8 2e a3 bc 29 2b, which hex-encode to + // "666818c7e82ea3bc292b". + let g = Guid { + data1: 0x0001_0203, + data2: 0x0405, + data3: 0x0607, + data4: [0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f], + }; + let expected: [u8; 20] = *b"666818c7e82ea3bc292b"; + assert_eq!(derive_serial_number(g), expected); + } + + /// Two subsystem_ids that differ produce distinct SNs. The + /// helper hashes the full 16-byte subsystem_id with SHA-256 + /// before truncating, so any difference in the input -- in any + /// byte position -- propagates throughout the hash output and + /// shows up in the truncated SN with overwhelming probability. + #[test] + fn test_derive_serial_number_is_distinct_per_subsystem_id() { + let g1 = Guid { + data1: 0x1111_1111, + data2: 0x2222, + data3: 0x3333, + data4: [0x44; 8], + }; + let g2 = Guid { + data1: 0xaaaa_aaaa, + data2: 0xbbbb, + data3: 0xcccc, + data4: [0xdd; 8], + }; + assert_ne!(derive_serial_number(g1), derive_serial_number(g2)); + } + + /// Subsystem_ids that share their first 10 bytes but differ in + /// bytes 10..15 must still produce distinct SNs. This is the + /// property that motivates hashing the full GUID before + /// truncating: a naive "first 10 bytes of subsystem_id" encoding + /// would collide here, but hashing first diffuses the trailing- + /// byte difference across the entire output. + #[test] + fn test_derive_serial_number_uses_full_subsystem_id() { + let g1 = Guid { + data1: 0xdead_beef, + data2: 0xcafe, + data3: 0xbabe, + data4: [0x01, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66], + }; + let g2 = Guid { + data1: 0xdead_beef, + data2: 0xcafe, + data3: 0xbabe, + // Same first 10 bytes as g1; differs only in bytes 10..15. + data4: [0x01, 0x02, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], + }; + assert_ne!(derive_serial_number(g1), derive_serial_number(g2)); + } +} From f7585a60d611f7b0f4569541e1902dc93afebda3 Mon Sep 17 00:00:00 2001 From: Jeff Bromberger <6789497+jeffbromberger@users.noreply.github.com> Date: Fri, 5 Jun 2026 17:53:21 -0500 Subject: [PATCH 2/3] nvme: review feedback - zero-disk_id, comment wording, SN cache Address review comments on PR #3678: * Treat `Some([0u8; 16])` from `disk.disk_id()` the same as `None`: fall through to `synthesize_nguid` rather than caching and reporting an all-zero NGUID. An all-zero NGUID is indistinguishable from "no identifier" to a spec-following host, and would violate the rule against a NIDT=NSGUID descriptor with a zero NID. Added regression test `test_identify_namespace_treats_zero_disk_id_as_absent`. * Reword comments that said `NIDT=2 (NGUID)` to say `NIDT=NSGUID (NGUID in the NVMe spec)` instead. `NSGUID` is the existing variant name in `NamespaceIdentifierType::NSGUID`; the parenthetical clarifies it is the spec's NGUID (distinct from NUUID/IEEE) for readers working from the spec rather than the codebase. * Cache the derived Serial Number on `AdminHandler` at construction (`derive_serial_number` is a pure function of `subsystem_id`, which is fixed for the controller's lifetime). Avoids re-running SHA-256 on every IDENTIFY_CONTROLLER response. No behavioral change beyond the zero-disk_id correctness fix. All 21 nvme + nvme_spec unit tests pass (1 new + 20 unchanged). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- vm/devices/storage/nvme/src/namespace.rs | 70 ++++++++++++++------ vm/devices/storage/nvme/src/workers/admin.rs | 11 ++- 2 files changed, 60 insertions(+), 21 deletions(-) diff --git a/vm/devices/storage/nvme/src/namespace.rs b/vm/devices/storage/nvme/src/namespace.rs index bbf508380b0..c12a8468c00 100644 --- a/vm/devices/storage/nvme/src/namespace.rs +++ b/vm/devices/storage/nvme/src/namespace.rs @@ -33,8 +33,9 @@ pub struct Namespace { /// containing subsystem and the nsid (see [`synthesize_nguid`]). /// This ensures every namespace exposes a non-zero NGUID, which /// lets hosts derive stable per-namespace unique identifiers and - /// keeps the inline NGUID consistent with the NIDT=2 (NGUID) - /// entry in the Identify Namespace Identification Descriptor List. + /// keeps the inline NGUID consistent with the NIDT=NSGUID + /// (NGUID, in NVMe spec terms) entry in the Identify Namespace + /// Identification Descriptor List. nguid: [u8; 16], } @@ -51,8 +52,9 @@ pub struct Namespace { /// stable subsystem identity and the namespace's nsid is a reasonable /// drop-in: it satisfies the "stable, unique within the subsystem" /// property the spec ascribes to NGUID, and it lets the inline NGUID and -/// the NIDT=2 (NGUID) descriptor in the Identification Descriptor List -/// be reported consistently and non-zero in all cases. +/// the NIDT=NSGUID (NGUID in the NVMe spec) descriptor in the +/// Identification Descriptor List be reported consistently and +/// non-zero in all cases. /// /// Implementation: SHA-256 of `subsystem_id` bytes followed by `nsid` in /// little-endian, truncated to the first 16 bytes. @@ -70,9 +72,16 @@ fn synthesize_nguid(subsystem_id: Guid, nsid: u32) -> [u8; 16] { impl Namespace { pub fn new(mem: GuestMemory, subsystem_id: Guid, nsid: u32, disk: Disk) -> Self { - let nguid = disk - .disk_id() - .unwrap_or_else(|| synthesize_nguid(subsystem_id, nsid)); + // Treat both "no disk_id at all" and "disk_id is all zeros" as + // absent: an all-zero NGUID is indistinguishable from "no + // identifier" to a spec-following host, and would violate the + // NVMe rule that a NIDT=NSGUID (NGUID) descriptor must not + // carry a zero NID. In either case, fall through to the + // deterministic-from-(subsystem_id, nsid) synthesis. + let nguid = match disk.disk_id() { + Some(id) if id != [0u8; 16] => id, + _ => synthesize_nguid(subsystem_id, nsid), + }; Self { block_shift: disk.sector_size().trailing_zeros(), pr: disk.pr().is_some(), @@ -124,12 +133,13 @@ impl Namespace { 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) - // Always emit a single NIDT=2 (NGUID) descriptor carrying the - // cached 16-byte identifier. Per NVMe Base specification, a - // controller shall not report a NIDT=2 descriptor with a zero - // NID; the synthesized fallback in [`Namespace::new`] guarantees - // `nguid` is non-zero for every namespace, so this constraint - // is met unconditionally. + // Always emit a single NIDT=NSGUID (NGUID in the NVMe spec) + // descriptor carrying the cached 16-byte identifier. Per NVMe + // Base specification, a controller shall not report a + // NIDT=NSGUID descriptor with a zero NID; the + // synthesized/zero-rejecting logic in [`Namespace::new`] + // guarantees `nguid` is non-zero for every namespace, so + // this constraint is met unconditionally. *id = nvm::NamespaceIdentificationDescriptor { nidt: nvm::NamespaceIdentifierType::NSGUID.0, nidl: size_of_val(&self.nguid) as u8, @@ -449,10 +459,30 @@ mod tests { ); } - /// The NIDT=2 (NGUID) descriptor returned by CNS=03h must match - /// the inline NGUID byte-for-byte, regardless of whether the - /// underlying NGUID came from the backing disk or from the - /// synthesized fallback. + /// A pathological backing disk that returns `Some([0; 16])` from + /// `disk_id()` is treated the same as "no identifier" -- the + /// emulator must fall through to the synthesized NGUID rather + /// than caching and reporting an all-zero NGUID (which would + /// violate the spec rule against a NIDT=NSGUID descriptor with + /// a zero NID). + #[test] + fn test_identify_namespace_treats_zero_disk_id_as_absent() { + let subsystem_id = Guid::new_random(); + let buf = identify_buf_for(subsystem_id, 5, Some([0u8; 16])); + let nguid: &[u8] = &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]; + assert_ne!( + nguid, &[0u8; NGUID_LEN], + "inline NGUID must not be zero even when disk_id() returns Some([0; 16])" + ); + // Must match what synthesize_nguid would produce for the same + // (subsystem_id, nsid) pair. + assert_eq!(nguid, &synthesize_nguid(subsystem_id, 5)); + } + + /// The NIDT=NSGUID (NGUID in the NVMe spec) descriptor returned + /// by CNS=03h must match the inline NGUID byte-for-byte, + /// regardless of whether the underlying NGUID came from the + /// backing disk or from the synthesized fallback. #[test] fn test_namespace_id_descriptor_matches_inline_nguid_with_disk_id() { let want: [u8; 16] = [ @@ -474,9 +504,9 @@ mod tests { } /// Same consistency property when the NGUID had to be synthesized. - /// This is the case that previously violated the spec (zero NID in - /// a NIDT=2 (NGUID) descriptor): the synthesized non-zero NGUID - /// makes the descriptor list well-formed. + /// This is the case that previously violated the spec (zero NID + /// in a NIDT=NSGUID (NGUID) descriptor): the synthesized non-zero + /// NGUID makes the descriptor list well-formed. #[test] fn test_namespace_id_descriptor_matches_inline_nguid_without_disk_id() { let subsystem_id = Guid::new_random(); diff --git a/vm/devices/storage/nvme/src/workers/admin.rs b/vm/devices/storage/nvme/src/workers/admin.rs index 0a2ea576867..71555cf3809 100644 --- a/vm/devices/storage/nvme/src/workers/admin.rs +++ b/vm/devices/storage/nvme/src/workers/admin.rs @@ -82,6 +82,13 @@ pub struct AdminHandler { config: AdminConfig, #[inspect(iter_by_key)] namespaces: BTreeMap>, + /// 20-byte Identify Controller Serial Number, derived once from + /// `config.subsystem_id` at construction (see + /// [`derive_serial_number`]). Cached so repeated IDENTIFY_CONTROLLER + /// responses don't re-run SHA-256 -- the value is a pure function + /// of `subsystem_id`, which is fixed for the controller's lifetime. + #[inspect(skip)] + serial_number: [u8; 20], } #[derive(Inspect)] @@ -378,10 +385,12 @@ fn derive_serial_number(subsystem_id: Guid) -> [u8; 20] { impl AdminHandler { pub fn new(driver: VmTaskDriver, config: AdminConfig) -> Self { + let serial_number = derive_serial_number(config.subsystem_id); Self { driver, config, namespaces: Default::default(), + serial_number, } } @@ -645,7 +654,7 @@ impl AdminHandler { ieee: [0x74, 0xe2, 0x8c], // Microsoft fr: (*b"v1.00000").into(), mn: (*b"MSFT NVMe Accelerator v1.0 ").into(), - sn: derive_serial_number(self.config.subsystem_id).into(), + sn: self.serial_number.into(), aerl: MAX_ASYNC_EVENT_REQUESTS - 1, elpe: ERROR_LOG_PAGE_ENTRIES - 1, oaes: spec::Oaes::new().with_namespace_attribute(true), From eee4333f2a571dd3ba7a54d2fc5c8db3e815aaf6 Mon Sep 17 00:00:00 2001 From: Jeff Bromberger <6789497+jeffbromberger@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:48:20 -0600 Subject: [PATCH 3/3] nvme: avoid synthesizing namespace media identity Report NGUID only when the backing disk supplies a nonzero stable ID. Leave the inline field zero and omit the CNS=03h descriptor otherwise, avoiding attachment-slot identities that survive backing replacement. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 02787e20-8e70-4f92-8124-63ecdbb4e322 --- vm/devices/storage/nvme/src/namespace.rs | 203 ++++--------------- vm/devices/storage/nvme/src/workers/admin.rs | 1 - 2 files changed, 44 insertions(+), 160 deletions(-) diff --git a/vm/devices/storage/nvme/src/namespace.rs b/vm/devices/storage/nvme/src/namespace.rs index 4c12c25d40a..be997087c2f 100644 --- a/vm/devices/storage/nvme/src/namespace.rs +++ b/vm/devices/storage/nvme/src/namespace.rs @@ -12,7 +12,6 @@ use crate::spec; use crate::spec::nvm; use disk_backend::Disk; use guestmem::GuestMemory; -use guid::Guid; use inspect::Inspect; use scsi_buffers::RequestBuffers; use zerocopy::FromBytes; @@ -27,61 +26,17 @@ pub struct Namespace { mem: GuestMemory, block_shift: u32, pr: bool, - /// 16-byte unique identifier for this namespace, computed once at - /// construction. Prefers the backing disk's `disk_id()` when - /// available; otherwise synthesizes a stable identifier from the - /// containing subsystem and the nsid (see [`synthesize_nguid`]). - /// This ensures every namespace exposes a non-zero NGUID, which - /// lets hosts derive stable per-namespace unique identifiers and - /// keeps the inline NGUID consistent with the NIDT=NSGUID - /// (NGUID, in NVMe spec terms) entry in the Identify Namespace - /// Identification Descriptor List. - nguid: [u8; 16], -} - -/// Synthesize a 16-byte NGUID for a namespace whose backing disk does -/// not supply its own [`Disk::disk_id`]. The result is deterministic -/// in `(subsystem_id, nsid)`: stable across emulator restarts, distinct -/// per namespace within a subsystem, and distinct across subsystems. -/// -/// The NVMe Base specification (section 4.7.1.2 / NVM Command Set -/// section 5.1.13.7 Figure 97) describes NGUID as an EUI-64-based 16-byte -/// identifier that the controller "assigns to the namespace when the -/// namespace is created". For a software-emulated namespace whose backing -/// store carries no such identifier, deriving one from the controller's -/// stable subsystem identity and the namespace's nsid is a reasonable -/// drop-in: it satisfies the "stable, unique within the subsystem" -/// property the spec ascribes to NGUID, and it lets the inline NGUID and -/// the NIDT=NSGUID (NGUID in the NVMe spec) descriptor in the -/// Identification Descriptor List be reported consistently and -/// non-zero in all cases. -/// -/// Implementation: SHA-256 of `subsystem_id` bytes followed by `nsid` in -/// little-endian, truncated to the first 16 bytes. -fn synthesize_nguid(subsystem_id: Guid, nsid: u32) -> [u8; 16] { - use sha2::Digest; - let mut h = sha2::Sha256::new(); - let ss_bytes: [u8; 16] = subsystem_id.into(); - h.update(ss_bytes); - h.update(nsid.to_le_bytes()); - let digest = h.finalize(); - let mut out = [0u8; 16]; - out.copy_from_slice(&digest[..16]); - out + /// 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, subsystem_id: Guid, nsid: u32, disk: Disk) -> Self { - // Treat both "no disk_id at all" and "disk_id is all zeros" as - // absent: an all-zero NGUID is indistinguishable from "no - // identifier" to a spec-following host, and would violate the - // NVMe rule that a NIDT=NSGUID (NGUID) descriptor must not - // carry a zero NID. In either case, fall through to the - // deterministic-from-(subsystem_id, nsid) synthesis. - let nguid = match disk.disk_id() { - Some(id) if id != [0u8; 16] => id, - _ => synthesize_nguid(subsystem_id, nsid), - }; + 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(), @@ -116,14 +71,9 @@ impl Namespace { nlbaf: 0, flbas: nvm::Flbas::new().with_low_index(0), rescap, - // Populate the inline NGUID field of Identify Namespace (offset - // 104..120) so guests that read NGUID from the inline data - // structure -- rather than only from the Identify Namespace - // Identification Descriptor List (CNS 03h) -- get a real, - // non-zero unique identifier. EUI64 is left as zero; there is - // no general way to derive a unique 8-byte EUI from the backing - // disk. - nguid: self.nguid, + // 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() }; @@ -131,21 +81,18 @@ impl Namespace { } 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) - // Always emit a single NIDT=NSGUID (NGUID in the NVMe spec) - // descriptor carrying the cached 16-byte identifier. Per NVMe - // Base specification, a controller shall not report a - // NIDT=NSGUID descriptor with a zero NID; the - // synthesized/zero-rejecting logic in [`Namespace::new`] - // guarantees `nguid` is non-zero for every namespace, so - // this constraint is met unconditionally. *id = nvm::NamespaceIdentificationDescriptor { nidt: nvm::NamespaceIdentifierType::NSGUID.0, - nidl: size_of_val(&self.nguid) as u8, + nidl: size_of_val(&nguid) as u8, rsvd: [0, 0], - nid: self.nguid, + nid: nguid, }; } @@ -410,10 +357,10 @@ mod tests { /// Convenience: build a `Namespace` with a `TestDisk` backing, run /// `Namespace::identify`, and return the 4 KiB response buffer. - fn identify_buf_for(subsystem_id: Guid, nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { + fn identify_buf_for(nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { let disk = Disk::new(TestDisk { disk_id }).unwrap(); let mem = GuestMemory::empty(); - let ns = Namespace::new(mem, subsystem_id, nsid, disk); + let ns = Namespace::new(mem, nsid, disk); let mut buf = vec![0u8; 4096]; ns.identify(&mut buf); buf @@ -422,10 +369,10 @@ mod tests { /// Convenience: build a `Namespace` with a `TestDisk` backing, run /// `Namespace::namespace_id_descriptor`, and return the 4 KiB /// response buffer. - fn descriptor_buf_for(subsystem_id: Guid, nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { + fn descriptor_buf_for(nsid: u32, disk_id: Option<[u8; 16]>) -> Vec { let disk = Disk::new(TestDisk { disk_id }).unwrap(); let mem = GuestMemory::empty(); - let ns = Namespace::new(mem, subsystem_id, nsid, disk); + let ns = Namespace::new(mem, nsid, disk); let mut buf = vec![0u8; 4096]; ns.namespace_id_descriptor(&mut buf); buf @@ -442,7 +389,7 @@ mod tests { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, ]; - let buf = identify_buf_for(Guid::new_random(), 1, Some(want)); + let buf = identify_buf_for(1, Some(want)); assert_eq!( &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN], &want, @@ -455,60 +402,41 @@ mod tests { ); } - /// When the backing disk reports no identifier, the inline NGUID - /// field must still be non-zero (synthesized from the namespace's - /// `(subsystem_id, nsid)` pair). EUI64 stays zero. + /// When the backing disk reports no identifier, the inline NGUID and EUI64 + /// fields remain zero. #[test] - fn test_identify_namespace_synthesizes_inline_nguid_when_disk_has_no_id() { - let subsystem_id = Guid::new_random(); - let buf = identify_buf_for(subsystem_id, 1, None); - let nguid: &[u8] = &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]; - assert_ne!( - nguid, &[0u8; NGUID_LEN], - "inline NGUID must be synthesized to a non-zero value when the backing \ - disk has no identifier" + 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] ); - // Must match the helper's output exactly. - assert_eq!(nguid, &synthesize_nguid(subsystem_id, 1)); assert_eq!( &buf[EUI64_OFFSET..EUI64_OFFSET + EUI64_LEN], &[0u8; EUI64_LEN] ); } - /// A pathological backing disk that returns `Some([0; 16])` from - /// `disk_id()` is treated the same as "no identifier" -- the - /// emulator must fall through to the synthesized NGUID rather - /// than caching and reporting an all-zero NGUID (which would - /// violate the spec rule against a NIDT=NSGUID descriptor with - /// a zero NID). + /// A pathological all-zero backing ID is treated as absent. #[test] fn test_identify_namespace_treats_zero_disk_id_as_absent() { - let subsystem_id = Guid::new_random(); - let buf = identify_buf_for(subsystem_id, 5, Some([0u8; 16])); - let nguid: &[u8] = &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]; - assert_ne!( - nguid, &[0u8; NGUID_LEN], - "inline NGUID must not be zero even when disk_id() returns Some([0; 16])" + let buf = identify_buf_for(5, Some([0u8; 16])); + assert_eq!( + &buf[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN], + &[0u8; NGUID_LEN] ); - // Must match what synthesize_nguid would produce for the same - // (subsystem_id, nsid) pair. - assert_eq!(nguid, &synthesize_nguid(subsystem_id, 5)); } - /// The NIDT=NSGUID (NGUID in the NVMe spec) descriptor returned - /// by CNS=03h must match the inline NGUID byte-for-byte, - /// regardless of whether the underlying NGUID came from the - /// backing disk or from the synthesized fallback. + /// 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 subsystem_id = Guid::new_random(); - let inline = identify_buf_for(subsystem_id, 1, Some(want)); - let desc = descriptor_buf_for(subsystem_id, 1, Some(want)); + 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); @@ -520,49 +448,14 @@ mod tests { ); } - /// Same consistency property when the NGUID had to be synthesized. - /// This is the case that previously violated the spec (zero NID - /// in a NIDT=NSGUID (NGUID) descriptor): the synthesized non-zero - /// NGUID makes the descriptor list well-formed. + /// Without a backing identity, CNS=03h contains no descriptor. #[test] - fn test_namespace_id_descriptor_matches_inline_nguid_without_disk_id() { - let subsystem_id = Guid::new_random(); - let inline = identify_buf_for(subsystem_id, 7, None); - let desc = descriptor_buf_for(subsystem_id, 7, None); - assert_eq!(desc[0], nvm::NamespaceIdentifierType::NSGUID.0); - assert_eq!(desc[1] as usize, NGUID_LEN); - let nid = &desc[4..4 + NGUID_LEN]; - assert_ne!(nid, &[0u8; NGUID_LEN]); - assert_eq!(nid, &inline[NGUID_OFFSET..NGUID_OFFSET + NGUID_LEN]); - assert_eq!(nid, &synthesize_nguid(subsystem_id, 7)); + fn test_namespace_id_descriptor_is_empty_without_disk_id() { + let desc = descriptor_buf_for(7, None); + assert!(desc.iter().all(|byte| *byte == 0)); } - /// `synthesize_nguid` must be a pure function of `(subsystem_id, - /// nsid)`. Same inputs -> same output; any change in either input - /// produces a different output. - #[test] - fn test_synthesize_nguid_is_deterministic_and_distinct() { - let s1 = Guid::new_random(); - let s2 = Guid::new_random(); - - // Deterministic. - assert_eq!(synthesize_nguid(s1, 1), synthesize_nguid(s1, 1)); - - // Different nsid in the same subsystem -> different NGUID. - assert_ne!(synthesize_nguid(s1, 1), synthesize_nguid(s1, 2)); - - // Different subsystems with the same nsid -> different NGUIDs. - assert_ne!(synthesize_nguid(s1, 1), synthesize_nguid(s2, 1)); - - // And of course non-zero. - assert_ne!(synthesize_nguid(s1, 1), [0u8; 16]); - } - use super::Namespace; - use crate::error::CommandResult; - use crate::spec; - use crate::spec::nvm; use disklayer_ram::ram_disk; - use guestmem::GuestMemory; use pal_async::async_test; use zerocopy::FromZeros; use zerocopy::IntoBytes; @@ -573,10 +466,7 @@ mod tests { fn read_only_namespace() -> (GuestMemory, Namespace) { let mem = GuestMemory::allocate(0x2000); let disk = ram_disk(1 << 20, true).unwrap(); - ( - mem.clone(), - Namespace::new(mem, Guid::new_random(), 1, disk), - ) + (mem.clone(), Namespace::new(mem, 1, disk)) } /// Builds a command for `opcode` with its data buffer at `DATA_GPA`. @@ -620,12 +510,7 @@ mod tests { fn identify_reports_read_only_as_write_protected() { for read_only in [false, true] { let mem = GuestMemory::allocate(0x1000); - let namespace = Namespace::new( - mem, - Guid::new_random(), - 1, - ram_disk(1 << 20, read_only).unwrap(), - ); + let namespace = Namespace::new(mem, 1, ram_disk(1 << 20, read_only).unwrap()); let mut id = nvm::IdentifyNamespace::new_zeroed(); namespace.identify(id.as_mut_bytes()); assert_eq!( diff --git a/vm/devices/storage/nvme/src/workers/admin.rs b/vm/devices/storage/nvme/src/workers/admin.rs index a9fc9640ddf..22489b10c4a 100644 --- a/vm/devices/storage/nvme/src/workers/admin.rs +++ b/vm/devices/storage/nvme/src/workers/admin.rs @@ -486,7 +486,6 @@ impl AdminHandler { let namespace = &*match self.namespaces.entry(nsid) { btree_map::Entry::Vacant(entry) => entry.insert(Arc::new(Namespace::new( self.config.mem.clone(), - self.config.subsystem_id, nsid, disk, ))),