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/patches/7b28624588ade8b9 # 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 ## GitHub aien-dev/aienux#125 (code only) closed derived `7b28624588ade8b9` #125 Imported from GitHub aien-dev/aienux#125 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `4dd5726e6dedf6c7ddfdb2095e241063bfae98dc` · Head `f0993e55ae6c7953cffc31851f4cc16d16f488ec` ### Apply it ``` git checkout -b patch-7b28624588ade8b9 4dd5726e6dedf6c7ddfdb2095e241063bfae98dc curl -fsSL https://interplane.io/drakestapleton/aienux/patches/7b28624588ade8b9.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 125 f0993e55ae6c7953cffc31851f4cc16d16f488ec ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":125,"url":"https://github.com/aien-dev/aienux/pull/125","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:46Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aienos-accel/src/lib.rs b/crates/aienos-accel/src/lib.rs index e9df2492..0a6bcab3 100644 --- a/crates/aienos-accel/src/lib.rs +++ b/crates/aienos-accel/src/lib.rs @@ -2,6 +2,10 @@ use core::fmt::Write; +pub mod pci; +pub mod profile; +pub mod registers; + /// PCI identity observed for the GB10 GPU in the DGX Spark. pub const NVIDIA_VENDOR_ID: u16 = 0x10de; pub const GB10_DEVICE_ID: u16 = 0x2e12; diff --git a/crates/aienos-accel/src/pci.rs b/crates/aienos-accel/src/pci.rs new file mode 100644 index 00000000..1e348e89 --- /dev/null +++ b/crates/aienos-accel/src/pci.rs @@ -0,0 +1,875 @@ +//! Pure, read-only decoders for PCI configuration space. +//! +//! Every function in this module interprets a byte slice supplied by the +//! caller. Nothing here performs a PCI configuration read, a PCI configuration +//! write, or an MMIO access. The bytes come from firmware services, from the +//! Linux sysfs `config` file, or from a synthetic fixture; these decoders only +//! interpret them. +//! +//! Malformed input is rejected, never guessed at. A truncated slice, an +//! out-of-bounds offset, an invalid BAR encoding, a capability loop, and an +//! overlong capability chain each return an error. Absence of a capability is +//! not the same as an all-zero capability and is represented as `None`. + +pub const CONFIG_HEADER_SIZE: usize = 64; +pub const CONFIG_SPACE_SIZE: usize = 256; +pub const CONFIG_EXTENDED_SIZE: usize = 4096; + +/// Status register bit 4: the capability list is present. +pub const STATUS_CAPABILITIES_LIST: u16 = 0x0010; + +pub const CAP_ID_POWER_MANAGEMENT: u8 = 0x01; +pub const CAP_ID_MSI: u8 = 0x05; +pub const CAP_ID_VENDOR: u8 = 0x09; +pub const CAP_ID_PCIE: u8 = 0x10; +pub const CAP_ID_MSIX: u8 = 0x11; + +const MAX_CAPABILITIES: usize = 48; +const MAX_EXTENDED_CAPABILITIES: usize = 64; +const MAX_EXTENDED_WORDS: usize = 64; + +/// A rejection reason from a decoder. Distinct variants let a caller tell a +/// truncated read from a genuinely malformed value. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum PciError { + /// The supplied slice is shorter than the structure being decoded. + Truncated, + /// An offset or capability pointer points outside the supplied slice. + OutOfBounds, + /// A BAR encoding is reserved or otherwise impossible. + InvalidBar, + /// A capability pointer revisited an offset already visited. + CapabilityLoop, + /// More capabilities than the bounded chain permits. + TooManyCapabilities, + /// The standard header is not a type 0 endpoint header. + InvalidHeaderType, + /// A capability decoder was handed a different capability id. + WrongCapability, +} + +fn add(base: usize, delta: usize) -> Result { + base.checked_add(delta).ok_or(PciError::OutOfBounds) +} + +fn read_u8(bytes: &[u8], offset: usize) -> Result { + bytes.get(offset).copied().ok_or(PciError::OutOfBounds) +} + +fn read_u16(bytes: &[u8], offset: usize) -> Result { + let end = add(offset, 2)?; + let slice = bytes.get(offset..end).ok_or(PciError::OutOfBounds)?; + Ok(u16::from_le_bytes([slice[0], slice[1]])) +} + +fn read_u32(bytes: &[u8], offset: usize) -> Result { + let end = add(offset, 4)?; + let slice = bytes.get(offset..end).ok_or(PciError::OutOfBounds)?; + Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) +} + +/// A decoded Base Address Register. `None` marks an unimplemented or a high +/// dword consumed by the preceding 64-bit BAR. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Bar { + None, + Memory(MemoryBar), + Io(IoBar), +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MemoryBar { + pub base: u64, + pub is_64_bit: bool, + pub prefetchable: bool, + pub size: BarSize, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct IoBar { + pub base: u32, + pub size: BarSize, +} + +/// A BAR size is only known when a size probe produced it. Probing requires +/// writing all ones to the BAR, so a read-only observation leaves it unknown. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum BarSize { + Known(u64), + Unknown, +} + +/// A decoded type 0 PCI header (endpoint). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Header { + pub vendor_id: u16, + pub device_id: u16, + pub command: u16, + pub status: u16, + pub revision: u8, + pub prog_if: u8, + pub subclass: u8, + pub class_code: u8, + pub header_type: u8, + pub multifunction: bool, + pub bars: [Bar; 6], + pub subsystem_vendor_id: u16, + pub subsystem_id: u16, + pub capability_pointer: u8, + pub interrupt_line: u8, + pub interrupt_pin: u8, +} + +impl Header { + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() < CONFIG_HEADER_SIZE { + return Err(PciError::Truncated); + } + let header_type = read_u8(bytes, 0x0e)?; + if header_type & 0x7f != 0x00 { + return Err(PciError::InvalidHeaderType); + } + Ok(Self { + vendor_id: read_u16(bytes, 0x00)?, + device_id: read_u16(bytes, 0x02)?, + command: read_u16(bytes, 0x04)?, + status: read_u16(bytes, 0x06)?, + revision: read_u8(bytes, 0x08)?, + prog_if: read_u8(bytes, 0x09)?, + subclass: read_u8(bytes, 0x0a)?, + class_code: read_u8(bytes, 0x0b)?, + header_type, + multifunction: header_type & 0x80 != 0, + bars: decode_bars(bytes, 0x10)?, + subsystem_vendor_id: read_u16(bytes, 0x2c)?, + subsystem_id: read_u16(bytes, 0x2e)?, + capability_pointer: read_u8(bytes, 0x34)?, + interrupt_line: read_u8(bytes, 0x3c)?, + interrupt_pin: read_u8(bytes, 0x3d)?, + }) + } + + /// Memory decoding enabled (PCI command register bit 1). + pub fn memory_enabled(&self) -> bool { + self.command & 0x0002 != 0 + } + + pub fn has_capability_list(&self) -> bool { + self.status & STATUS_CAPABILITIES_LIST != 0 + } +} + +/// Decode the six standard type 0 BAR slots starting at `offset`. +fn decode_bars(bytes: &[u8], offset: usize) -> Result<[Bar; 6], PciError> { + let mut bars = [Bar::None; 6]; + let mut index = 0usize; + while index < 6 { + let low_offset = offset.checked_add(index * 4).ok_or(PciError::OutOfBounds)?; + let low = read_u32(bytes, low_offset)?; + if low == 0 { + index += 1; + continue; + } + if low & 0x1 == 0x1 { + // IO BAR: bits [2:1] are reserved and must be zero. + if low & 0x6 != 0 { + return Err(PciError::InvalidBar); + } + bars[index] = Bar::Io(IoBar { + base: low & !0x3, + size: BarSize::Unknown, + }); + index += 1; + continue; + } + match (low >> 1) & 0x3 { + 0b00 => { + bars[index] = Bar::Memory(MemoryBar { + base: u64::from(low & !0xf), + is_64_bit: false, + prefetchable: low & 0x8 != 0, + size: BarSize::Unknown, + }); + index += 1; + } + 0b10 => { + // A 64-bit memory BAR consumes the next slot for its high + // dword. The last slot cannot start one. + if index + 1 >= 6 { + return Err(PciError::InvalidBar); + } + let high = read_u32(bytes, low_offset + 4)?; + bars[index] = Bar::Memory(MemoryBar { + base: (u64::from(high) << 32) | u64::from(low & !0xf), + is_64_bit: true, + prefetchable: low & 0x8 != 0, + size: BarSize::Unknown, + }); + index += 2; + } + // 0b01 and 0b11 are reserved encodings. + _ => return Err(PciError::InvalidBar), + } + } + Ok(bars) +} + +/// Decode a memory BAR size from the all-ones readback a size probe produces. +/// +/// This is a pure decoder for a probe result the caller already has. It does +/// not perform the probe: writing all ones to a BAR is a PCI configuration +/// write and lies outside AIENOS's read-only characterization boundary. A +/// non-power-of-two or out-of-range mask returns `None` rather than a size. +pub fn memory_bar_size(low: u32, high: u32, is_64_bit: bool) -> Option { + // A probe writes all ones; the device returns ones for every unimplemented + // bit, so size = !(readback & !0xf) + 1 within the BAR's address width. + if is_64_bit { + let mask = (u64::from(high) << 32) | u64::from(low & !0xf); + if mask == 0 || mask == u64::MAX { + return None; + } + let size = (!mask).checked_add(1)?; + if !size.is_power_of_two() || size > (1u64 << 46) { + return None; + } + Some(size) + } else { + let mask = low & !0xf; + if mask == 0 || mask == u32::MAX { + return None; + } + let size = u64::from((!mask).checked_add(1)?); + if !size.is_power_of_two() || size > (1u64 << 32) { + return None; + } + Some(size) + } +} + +/// Decode an IO BAR size from an all-ones readback. See `memory_bar_size`. +pub fn io_bar_size(low: u32) -> Option { + let mask = low & !0x3; + if mask == 0 || mask == u32::MAX { + return None; + } + let size = u64::from((!mask).checked_add(1)?); + if !size.is_power_of_two() || size > (1u64 << 32) { + return None; + } + Some(size) +} + +/// One entry in the standard capability linked list. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Capability { + pub id: u8, + pub offset: u8, + pub next: u8, +} + +/// A bounded, loop-checked standard capability list. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct CapabilityList { + entries: [Capability; MAX_CAPABILITIES], + len: usize, +} + +impl CapabilityList { + pub const fn empty() -> Self { + Self { + entries: [Capability { + id: 0, + offset: 0, + next: 0, + }; MAX_CAPABILITIES], + len: 0, + } + } + + pub fn entries(&self) -> &[Capability] { + &self.entries[..self.len] + } + + pub fn find(&self, id: u8) -> Option { + self.entries().iter().copied().find(|entry| entry.id == id) + } + + fn push(&mut self, entry: Capability) -> Result<(), PciError> { + if self.len == MAX_CAPABILITIES { + return Err(PciError::TooManyCapabilities); + } + self.entries[self.len] = entry; + self.len += 1; + Ok(()) + } +} + +/// Walk the standard capability linked list in a 256-byte configuration space. +/// +/// Returns an empty list when the status register reports no capability list or +/// the capability pointer is zero. Rejects pointers below `0x40`, unaligned +/// pointers, offsets past the end, revisited offsets (loops), and chains +/// longer than the bound. +pub fn walk_capabilities(bytes: &[u8]) -> Result { + if bytes.len() < CONFIG_SPACE_SIZE { + return Err(PciError::Truncated); + } + let mut list = CapabilityList::empty(); + let status = read_u16(bytes, 0x06)?; + if status & STATUS_CAPABILITIES_LIST == 0 { + return Ok(list); + } + let mut offset = read_u8(bytes, 0x34)?; + let mut seen = [0u64; 4]; + while offset != 0 { + let index = usize::from(offset); + if index < 0x40 || !index.is_multiple_of(4) { + return Err(PciError::OutOfBounds); + } + if add(index, 2)? > CONFIG_SPACE_SIZE { + return Err(PciError::OutOfBounds); + } + let word = index / 64; + let bit = 1u64 << (index % 64); + if seen[word] & bit != 0 { + return Err(PciError::CapabilityLoop); + } + seen[word] |= bit; + let id = read_u8(bytes, index)?; + let next = read_u8(bytes, add(index, 1)?)?; + list.push(Capability { id, offset, next })?; + offset = next; + } + Ok(list) +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MsiCapability { + pub offset: u8, + pub enabled: bool, + pub capable_vectors: u16, + pub enabled_vectors: u16, + pub is_64_bit: bool, + pub maskable: bool, + pub address: u64, + pub data: u16, +} + +impl MsiCapability { + pub fn decode(bytes: &[u8], capability: Capability) -> Result { + if capability.id != CAP_ID_MSI { + return Err(PciError::WrongCapability); + } + let offset = usize::from(capability.offset); + let control = read_u16(bytes, add(offset, 2)?)?; + let is_64_bit = control & 0x0080 != 0; + let capable_vectors = 1u16 << ((control >> 1) & 0x7); + let enabled_vectors = 1u16 << ((control >> 4) & 0x7); + let address_low = read_u32(bytes, add(offset, 4)?)?; + let (address, data_offset) = if is_64_bit { + let address_high = read_u32(bytes, add(offset, 8)?)?; + ( + (u64::from(address_high) << 32) | u64::from(address_low), + add(offset, 12)?, + ) + } else { + (u64::from(address_low), add(offset, 8)?) + }; + Ok(Self { + offset: capability.offset, + enabled: control & 0x0001 != 0, + capable_vectors, + enabled_vectors, + is_64_bit, + maskable: control & 0x0100 != 0, + address, + data: read_u16(bytes, data_offset)?, + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MsixCapability { + pub offset: u8, + pub enabled: bool, + pub function_masked: bool, + /// Number of table entries. The configuration field stores N-1. + pub vectors: u16, + pub table_bir: u8, + pub table_offset: u32, + pub pba_bir: u8, + pub pba_offset: u32, +} + +impl MsixCapability { + pub fn decode(bytes: &[u8], capability: Capability) -> Result { + if capability.id != CAP_ID_MSIX { + return Err(PciError::WrongCapability); + } + let offset = usize::from(capability.offset); + let control = read_u16(bytes, add(offset, 2)?)?; + let table = read_u32(bytes, add(offset, 4)?)?; + let pba = read_u32(bytes, add(offset, 8)?)?; + Ok(Self { + offset: capability.offset, + enabled: control & 0x8000 != 0, + function_masked: control & 0x4000 != 0, + vectors: (control & 0x07ff) + 1, + table_bir: (table & 0x0000_0007) as u8, + table_offset: table & !0x0000_0007, + pba_bir: (pba & 0x0000_0007) as u8, + pba_offset: pba & !0x0000_0007, + }) + } +} + +/// PCI Express link speed encoding from the Link Capabilities register. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum LinkSpeed { + Unknown, + Gen1, + Gen2, + Gen3, + Gen4, + Gen5, + Gen6, +} + +impl LinkSpeed { + pub fn from_encoding(encoding: u8) -> Self { + match encoding { + 1 => LinkSpeed::Gen1, + 2 => LinkSpeed::Gen2, + 3 => LinkSpeed::Gen3, + 4 => LinkSpeed::Gen4, + 5 => LinkSpeed::Gen5, + 6 => LinkSpeed::Gen6, + _ => LinkSpeed::Unknown, + } + } + + pub fn gigatransfers(self) -> Option { + match self { + LinkSpeed::Unknown => None, + LinkSpeed::Gen1 => Some(2), + LinkSpeed::Gen2 => Some(5), + LinkSpeed::Gen3 => Some(8), + LinkSpeed::Gen4 => Some(16), + LinkSpeed::Gen5 => Some(32), + LinkSpeed::Gen6 => Some(64), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct PcieLink { + pub max_speed: LinkSpeed, + pub max_width: u8, + /// Raw supported-link-speeds bitmap from Link Capabilities 2, or 0 when the + /// function does not expose a second link capability register. + pub supported_speeds: u16, + pub current_speed: LinkSpeed, + pub current_width: u8, + pub downgraded: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct PcieCapability { + pub offset: u8, + pub version: u8, + pub device_type: u8, + pub slot_implemented: bool, + /// Payload size in bytes derived from the device capabilities field. + pub max_payload_bytes: u16, + pub link: Option, +} + +impl PcieCapability { + pub fn decode(bytes: &[u8], capability: Capability) -> Result { + if capability.id != CAP_ID_PCIE { + return Err(PciError::WrongCapability); + } + let offset = usize::from(capability.offset); + let cap = read_u16(bytes, add(offset, 2)?)?; + let device_type = ((cap >> 4) & 0x000f) as u8; + let device_caps = read_u32(bytes, add(offset, 4)?)?; + let max_payload_bytes = 128u16 << ((device_caps & 0x7) as u16); + // Root Complex Integrated Endpoints (8) and Event Collectors (9) do + // not implement the Link Capabilities register; every other type does. + let link = if matches!(device_type, 0x8 | 0x9) { + None + } else { + Some(decode_pcie_link(bytes, offset)?) + }; + Ok(Self { + offset: capability.offset, + version: (cap & 0x000f) as u8, + device_type, + slot_implemented: cap & 0x0100 != 0, + max_payload_bytes, + link, + }) + } +} + +fn decode_pcie_link(bytes: &[u8], offset: usize) -> Result { + let link_caps = read_u32(bytes, add(offset, 0x0c)?)?; + let link_status = read_u16(bytes, add(offset, 0x12)?)?; + let max_speed = LinkSpeed::from_encoding((link_caps & 0x000f) as u8); + let max_width = ((link_caps >> 4) & 0x003f) as u8; + let current_speed = LinkSpeed::from_encoding((link_status & 0x000f) as u8); + let current_width = ((link_status >> 4) & 0x003f) as u8; + let supported_speeds = if add(offset, 0x20)? <= bytes.len() { + (read_u32(bytes, add(offset, 0x1c)?)? & 0x0000_007f) as u16 + } else { + 0 + }; + let speed_downgraded = max_speed != LinkSpeed::Unknown + && current_speed != LinkSpeed::Unknown + && current_speed != max_speed; + Ok(PcieLink { + max_speed, + max_width, + supported_speeds, + current_speed, + current_width, + downgraded: speed_downgraded || current_width < max_width, + }) +} + +/// One extended capability header (PCI Express, configuration offset >= 0x100). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct ExtendedCapability { + pub id: u16, + pub version: u8, + pub offset: u16, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct ExtendedCapabilityList { + entries: [ExtendedCapability; MAX_EXTENDED_CAPABILITIES], + len: usize, +} + +impl ExtendedCapabilityList { + pub const fn empty() -> Self { + Self { + entries: [ExtendedCapability { + id: 0, + version: 0, + offset: 0, + }; MAX_EXTENDED_CAPABILITIES], + len: 0, + } + } + + pub fn entries(&self) -> &[ExtendedCapability] { + &self.entries[..self.len] + } + + pub fn find(&self, id: u16) -> Option { + self.entries().iter().copied().find(|entry| entry.id == id) + } +} + +/// Walk the extended capability list starting at `0x100`. +/// +/// Returns an empty list when the slice stops at or before `0x100`, so a +/// 64-byte or 256-byte read yields no extended capabilities rather than an +/// error. Rejects out-of-bounds next pointers, revisited offsets, and chains +/// longer than the bound. +pub fn walk_extended_capabilities(bytes: &[u8]) -> Result { + let mut list = ExtendedCapabilityList::empty(); + if add(CONFIG_SPACE_SIZE, 4)? > bytes.len() { + return Ok(list); + } + let mut offset = CONFIG_SPACE_SIZE; + let mut seen = [0u64; MAX_EXTENDED_WORDS]; + let mut count = 0usize; + while offset != 0 { + if !offset.is_multiple_of(4) || add(offset, 4)? > CONFIG_EXTENDED_SIZE { + return Err(PciError::OutOfBounds); + } + if add(offset, 4)? > bytes.len() { + return Err(PciError::OutOfBounds); + } + let word = offset / 64; + let bit = 1u64 << (offset % 64); + if seen[word] & bit != 0 { + return Err(PciError::CapabilityLoop); + } + seen[word] |= bit; + let header = read_u32(bytes, offset)?; + let id = (header & 0xffff) as u16; + let version = ((header >> 16) & 0x000f) as u8; + let next = ((header >> 20) & 0x0fff) as usize; + if count == MAX_EXTENDED_CAPABILITIES { + return Err(PciError::TooManyCapabilities); + } + list.entries[list.len] = ExtendedCapability { + id, + version, + offset: offset as u16, + }; + list.len += 1; + count += 1; + if id == 0xffff { + break; + } + offset = next; + } + Ok(list) +} + +/// A decoded type 1 PCI-to-PCI bridge header, enough to follow a firmware bus +/// window from a root bridge to a downstream device. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct BridgeHeader { + pub vendor_id: u16, + pub device_id: u16, + pub class_code: u8, + pub subclass: u8, + pub secondary_bus: u8, + pub subordinate_bus: u8, +} + +impl BridgeHeader { + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() < CONFIG_HEADER_SIZE { + return Err(PciError::Truncated); + } + let header_type = read_u8(bytes, 0x0e)?; + if header_type & 0x7f != 0x01 { + return Err(PciError::InvalidHeaderType); + } + Ok(Self { + vendor_id: read_u16(bytes, 0x00)?, + device_id: read_u16(bytes, 0x02)?, + class_code: read_u8(bytes, 0x0b)?, + subclass: read_u8(bytes, 0x0a)?, + secondary_bus: read_u8(bytes, 0x19)?, + subordinate_bus: read_u8(bytes, 0x1a)?, + }) + } + + /// A usable bus window is one where the secondary bus is not zero and the + /// subordinate bus is at or above it. + pub fn has_bus_window(&self) -> bool { + self.secondary_bus != 0 && self.subordinate_bus >= self.secondary_bus + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn base_header() -> [u8; CONFIG_SPACE_SIZE] { + let mut bytes = [0u8; CONFIG_SPACE_SIZE]; + bytes[0x00..0x02].copy_from_slice(&0x10deu16.to_le_bytes()); + bytes[0x02..0x04].copy_from_slice(&0x2e12u16.to_le_bytes()); + bytes[0x04..0x06].copy_from_slice(&0x0007u16.to_le_bytes()); + bytes[0x06..0x08].copy_from_slice(&0x0010u16.to_le_bytes()); + bytes[0x08] = 0xa1; + bytes[0x0b] = 0x03; + bytes + } + + #[test] + fn decodes_standard_header_and_64_bit_bar() { + let mut bytes = base_header(); + bytes[0x10..0x14].copy_from_slice(&0x2400_000cu32.to_le_bytes()); + bytes[0x14..0x18].copy_from_slice(&0x0000_0001u32.to_le_bytes()); + bytes[0x2c..0x2e].copy_from_slice(&0x10deu16.to_le_bytes()); + let header = Header::parse(&bytes).unwrap(); + assert_eq!(header.vendor_id, 0x10de); + assert_eq!(header.device_id, 0x2e12); + assert_eq!(header.class_code, 0x03); + assert!(header.memory_enabled()); + match header.bars[0] { + Bar::Memory(bar) => { + assert_eq!(bar.base, 0x0000_0001_2400_0000); + assert!(bar.is_64_bit); + assert!(bar.prefetchable); + } + other => panic!("expected memory bar, got {other:?}"), + } + assert_eq!(header.bars[1], Bar::None); + } + + #[test] + fn rejects_reserved_bar_encodings() { + let mut bytes = base_header(); + bytes[0x10..0x14].copy_from_slice(&0x0000_0006u32.to_le_bytes()); + assert!(Header::parse(&bytes).is_err()); + let mut bytes = base_header(); + bytes[0x24..0x28].copy_from_slice(&0x0000_000au32.to_le_bytes()); + assert!(Header::parse(&bytes).is_err()); + } + + #[test] + fn rejects_truncated_header_and_bridge_type() { + let bytes = [0u8; 16]; + assert_eq!(Header::parse(&bytes), Err(PciError::Truncated)); + let mut bytes = base_header(); + bytes[0x0e] = 0x01; + assert_eq!(Header::parse(&bytes), Err(PciError::InvalidHeaderType)); + } + + #[test] + fn rejects_capability_loop_and_out_of_bounds() { + let mut bytes = base_header(); + bytes[0x34] = 0x40; + bytes[0x40] = CAP_ID_MSI; + bytes[0x41] = 0x40; // points at itself + assert_eq!(walk_capabilities(&bytes), Err(PciError::CapabilityLoop)); + + let mut bytes = base_header(); + bytes[0x34] = 0xff; + assert_eq!(walk_capabilities(&bytes), Err(PciError::OutOfBounds)); + + let mut bytes = base_header(); + bytes[0x34] = 0x42; // unaligned + assert_eq!(walk_capabilities(&bytes), Err(PciError::OutOfBounds)); + + let truncated = [0u8; CONFIG_HEADER_SIZE]; + assert_eq!(walk_capabilities(&truncated), Err(PciError::Truncated)); + } + + #[test] + fn capability_list_absence_is_empty_not_error() { + let mut bytes = base_header(); + bytes[0x06..0x08].copy_from_slice(&0u16.to_le_bytes()); + assert!(walk_capabilities(&bytes).unwrap().entries().is_empty()); + let bytes = [0u8; CONFIG_SPACE_SIZE]; + assert!(walk_capabilities(&bytes).unwrap().entries().is_empty()); + } + + #[test] + fn decodes_msi_msix_and_pcie() { + let mut bytes = base_header(); + bytes[0x34] = 0x40; + // MSI at 0x40: id 0x05, next 0x50, control 0x0388 (64-bit, maskable). + bytes[0x40] = CAP_ID_MSI; + bytes[0x41] = 0x50; + bytes[0x42..0x44].copy_from_slice(&0x0388u16.to_le_bytes()); + bytes[0x44..0x48].copy_from_slice(&0xfee0_0000u32.to_le_bytes()); + bytes[0x4c..0x4e].copy_from_slice(&0x0041u16.to_le_bytes()); + // PCIe at 0x50: id 0x10, next 0x80, cap 0x0002, link caps/status. + bytes[0x50] = CAP_ID_PCIE; + bytes[0x51] = 0x80; + bytes[0x52..0x54].copy_from_slice(&0x0002u16.to_le_bytes()); + bytes[0x54..0x58].copy_from_slice(&0x0000_0003u32.to_le_bytes()); + bytes[0x5c..0x60].copy_from_slice(&0x0045_7901u32.to_le_bytes()); + bytes[0x62..0x64].copy_from_slice(&0x8010u16.to_le_bytes()); + // MSI-X at 0x80: id 0x11, next 0, control 0x8008, table, pba. + bytes[0x80] = CAP_ID_MSIX; + bytes[0x81] = 0x00; + bytes[0x82..0x84].copy_from_slice(&0x8008u16.to_le_bytes()); + bytes[0x84..0x88].copy_from_slice(&0x00b9_0000u32.to_le_bytes()); + bytes[0x88..0x8c].copy_from_slice(&0x00ba_0000u32.to_le_bytes()); + + let list = walk_capabilities(&bytes).unwrap(); + assert_eq!(list.entries().len(), 3); + let msi = MsiCapability::decode(&bytes, list.find(CAP_ID_MSI).unwrap()).unwrap(); + assert!(msi.is_64_bit && msi.maskable && !msi.enabled); + assert_eq!(msi.capable_vectors, 16); + assert_eq!(msi.data, 0x0041); + let pcie = PcieCapability::decode(&bytes, list.find(CAP_ID_PCIE).unwrap()).unwrap(); + let link = pcie.link.unwrap(); + assert_eq!(link.max_speed, LinkSpeed::Gen1); + assert_eq!(link.max_width, 16); + assert_eq!(link.current_width, 1); + assert!(link.downgraded); + assert_eq!(pcie.max_payload_bytes, 1024); + let msix = MsixCapability::decode(&bytes, list.find(CAP_ID_MSIX).unwrap()).unwrap(); + assert!(msix.enabled && !msix.function_masked); + assert_eq!(msix.vectors, 9); + assert_eq!(msix.table_bir, 0); + assert_eq!(msix.table_offset, 0x00b9_0000); + assert_eq!(msix.pba_offset, 0x00ba_0000); + + assert_eq!( + MsiCapability::decode(&bytes, list.find(CAP_ID_MSIX).unwrap()), + Err(PciError::WrongCapability) + ); + } + + #[test] + fn decodes_bridge_header_and_window() { + let mut bytes = base_header(); + bytes[0x0e] = 0x01; + bytes[0x19] = 0x01; + bytes[0x1a] = 0x0f; + let bridge = BridgeHeader::parse(&bytes).unwrap(); + assert_eq!(bridge.secondary_bus, 1); + assert_eq!(bridge.subordinate_bus, 0x0f); + assert!(bridge.has_bus_window()); + bytes[0x19] = 0x00; + assert!(!BridgeHeader::parse(&bytes).unwrap().has_bus_window()); + assert_eq!( + BridgeHeader::parse(&base_header()), + Err(PciError::InvalidHeaderType) + ); + } + + #[test] + fn walks_extended_capabilities_with_loop_and_bounds_checks() { + let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; + // Secondary PCI Express (0x19) at 0x100, then AER (0x01) at 0x12c. + let first = 0x19u32 | (1 << 16) | (0x12cu32 << 20); + bytes[0x100..0x104].copy_from_slice(&first.to_le_bytes()); + let second = 0x01u32 | (2 << 16); + bytes[0x12c..0x130].copy_from_slice(&second.to_le_bytes()); + let list = walk_extended_capabilities(&bytes).unwrap(); + assert_eq!(list.entries().len(), 2); + assert_eq!(list.find(0x19).unwrap().version, 1); + assert_eq!(list.find(0x01).unwrap().version, 2); + + // A loop: first entry next points at itself. + let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; + let looped = 0x19u32 | (0x100u32 << 20); + bytes[0x100..0x104].copy_from_slice(&looped.to_le_bytes()); + assert_eq!( + walk_extended_capabilities(&bytes), + Err(PciError::CapabilityLoop) + ); + + // A next pointer past the 4096-byte space is rejected. + let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; + let out = 0x19u32 | (0xfffu32 << 20); + bytes[0x100..0x104].copy_from_slice(&out.to_le_bytes()); + assert_eq!( + walk_extended_capabilities(&bytes), + Err(PciError::OutOfBounds) + ); + + // A slice at or below 0x100 has no extended capabilities. + assert!(walk_extended_capabilities(&[0u8; CONFIG_SPACE_SIZE]) + .unwrap() + .entries() + .is_empty()); + } + + #[test] + fn decodes_bar_sizes_with_bounds() { + assert_eq!( + memory_bar_size(0xf000_0004, 0xffff_ffff, true), + Some(0x1000_0000) + ); + assert_eq!(memory_bar_size(0xf000_0004, 0, false), Some(0x1000_0000)); + assert_eq!( + memory_bar_size(0x0000_0004, 0xffff_ffff, true), + Some(0x1_0000_0000) + ); + assert_eq!( + memory_bar_size(0xfff0_0004, 0xffff_ffff, true), + Some(0x10_0000) + ); + assert_eq!(memory_bar_size(0x2400_000c, 0, false), None); + assert_eq!(memory_bar_size(0x0000_0000, 0, false), None); + assert_eq!(memory_bar_size(0xffff_f004, 0, false), Some(0x1000)); + assert_eq!(memory_bar_size(0xf000_1004, 0xffff_ffff, true), None); + assert_eq!(io_bar_size(0xffff_f001), Some(0x1000)); + assert_eq!(io_bar_size(0x0000_0001), None); + } +} diff --git a/crates/aienos-accel/src/profile.rs b/crates/aienos-accel/src/profile.rs new file mode 100644 index 00000000..1587bba6 --- /dev/null +++ b/crates/aienos-accel/src/profile.rs @@ -0,0 +1,701 @@ +//! Typed, provenance-tagged GB10 hardware characterization facts. +//! +//! The profile keeps three states apart instead of collapsing them: +//! +//! - `Observed`: a value read from a named source. +//! - `Derived`: a value computed from observed values, not read directly. +//! - `Unknown`: no value was obtained. Absence of evidence is never a zero or +//! a default hardware property. +//! +//! Every value also carries its source, and a flag for whether native AIENOS +//! has independently verified it. A value observed through Linux sysfs is not +//! the same claim as a value decoded by native AIENOS PCI enumeration, and the +//! type keeps them distinct. + +use crate::pci::{ + Bar, CapabilityList, Header, MsiCapability, MsixCapability, PciError, PcieCapability, PcieLink, + CAP_ID_MSI, CAP_ID_MSIX, CAP_ID_PCIE, +}; +use crate::{Gb10Bar, PciLocation, GB10_DEVICE_ID, NVIDIA_VENDOR_ID}; +use core::fmt::{Debug, Write}; + +/// Where a fact came from. The source is part of the fact, not a footnote. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Source { + /// Read through UEFI firmware services before `ExitBootServices`. + UefiFirmwareService, + /// Decoded by native AIENOS PCI enumeration. + AienosNativePci, + /// Read from a Linux sysfs attribute. + LinuxSysfs, + /// Read from a Linux procfs attribute. + LinuxProcfs, + /// Parsed from an ACPI table exposed by the kernel. + LinuxAcpi, + /// Built by a test from synthetic bytes. + SyntheticFixture, + /// Computed from other facts rather than read from hardware. + Derived, +} + +impl Source { + pub const fn name(self) -> &'static str { + match self { + Source::UefiFirmwareService => "uefi-firmware-service", + Source::AienosNativePci => "aienos-native-pci", + Source::LinuxSysfs => "linux-sysfs", + Source::LinuxProcfs => "linux-procfs", + Source::LinuxAcpi => "linux-acpi", + Source::SyntheticFixture => "synthetic-fixture", + Source::Derived => "derived", + } + } + + /// True when Linux, not AIENOS, interpreted the value. + pub const fn linux_interpreted(self) -> bool { + matches!( + self, + Source::LinuxSysfs | Source::LinuxProcfs | Source::LinuxAcpi + ) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum State { + Observed, + Derived, + Unknown, +} + +/// One immutable characterization fact. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Fact { + state: State, + value: Option, + source: Option, + native_verified: bool, +} + +impl Fact { + pub const fn unknown() -> Self { + Self { + state: State::Unknown, + value: None, + source: None, + native_verified: false, + } + } + + pub const fn observed(value: T, source: Source) -> Self { + Self { + state: State::Observed, + value: Some(value), + source: Some(source), + native_verified: matches!(source, Source::AienosNativePci), + } + } + + pub const fn derived(value: T, source: Source) -> Self { + Self { + state: State::Derived, + value: Some(value), + source: Some(source), + native_verified: false, + } + } + + pub const fn marked_native_verified(self) -> Self { + Self { + state: self.state, + value: self.value, + source: self.source, + native_verified: true, + } + } + + pub const fn with_source(self, source: Source) -> Self { + Self { + state: self.state, + value: self.value, + source: Some(source), + native_verified: self.native_verified, + } + } + + pub fn state(&self) -> State { + self.state + } + + pub fn value(&self) -> Option { + self.value + } + + pub fn source(&self) -> Option { + self.source + } + + pub fn native_verified(&self) -> bool { + self.native_verified + } + + pub fn is_known(&self) -> bool { + self.value.is_some() + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct ClassCode { + pub base: u8, + pub subclass: u8, + pub prog_if: u8, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum BarKind { + None, + Memory, + Io, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct BarFacts { + pub index: u8, + pub kind: BarKind, + pub base: u64, + pub is_64_bit: bool, + pub prefetchable: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct PcieFacts { + pub present: bool, + pub max_payload_bytes: u16, + pub link: Option, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MsiFacts { + pub present: bool, + pub enabled: bool, + pub is_64_bit: bool, + pub maskable: bool, + pub capable_vectors: u16, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MsixFacts { + pub present: bool, + pub enabled: bool, + pub function_masked: bool, + pub vectors: u16, + pub table_bir: u8, + pub table_offset: u32, + pub pba_bir: u8, + pub pba_offset: u32, +} + +const NO_PCIE: PcieFacts = PcieFacts { + present: false, + max_payload_bytes: 0, + link: None, +}; + +const NO_MSI: MsiFacts = MsiFacts { + present: false, + enabled: false, + is_64_bit: false, + maskable: false, + capable_vectors: 0, +}; + +const NO_MSIX: MsixFacts = MsixFacts { + present: false, + enabled: false, + function_masked: false, + vectors: 0, + table_bir: 0, + table_offset: 0, + pba_bir: 0, + pba_offset: 0, +}; + +/// The immutable profile. PCI-derived fields come from a configuration-space +/// read; firmware, IOMMU, NUMA, and PMC fields are filled only from sources +/// that actually expose them. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Gb10Profile { + pub location: PciLocation, + pub vendor_id: Fact, + pub device_id: Fact, + pub subsystem_vendor_id: Fact, + pub subsystem_id: Fact, + pub revision: Fact, + pub class: Fact, + pub command: Fact, + pub status: Fact, + pub bars: [Fact; 6], + pub bar_sizes: [Fact; 6], + pub pcie: Fact, + pub msi: Fact, + pub msix: Fact, + pub iommu_group: Fact, + pub numa_node: Fact, + pub firmware_path: Fact<&'static str>, + pub pmc_boot_0: Fact, + pub pmc_boot_42: Fact, +} + +impl Gb10Profile { + /// A profile with every fact unknown. Use this when discovery has not run. + pub const fn unknown(location: PciLocation) -> Self { + Self { + location, + vendor_id: Fact::unknown(), + device_id: Fact::unknown(), + subsystem_vendor_id: Fact::unknown(), + subsystem_id: Fact::unknown(), + revision: Fact::unknown(), + class: Fact::unknown(), + command: Fact::unknown(), + status: Fact::unknown(), + bars: [Fact::unknown(); 6], + bar_sizes: [Fact::unknown(); 6], + pcie: Fact::unknown(), + msi: Fact::unknown(), + msix: Fact::unknown(), + iommu_group: Fact::unknown(), + numa_node: Fact::unknown(), + firmware_path: Fact::unknown(), + pmc_boot_0: Fact::unknown(), + pmc_boot_42: Fact::unknown(), + } + } + + /// Decode the PCI-derived facts from raw configuration-space bytes. Facts + /// that configuration space cannot answer stay `Unknown`. + pub fn from_pci_config( + location: PciLocation, + bytes: &[u8], + source: Source, + ) -> Result { + let header = Header::parse(bytes)?; + let mut profile = Self::unknown(location); + profile.vendor_id = Fact::observed(header.vendor_id, source); + profile.device_id = Fact::observed(header.device_id, source); + profile.subsystem_vendor_id = Fact::observed(header.subsystem_vendor_id, source); + profile.subsystem_id = Fact::observed(header.subsystem_id, source); + profile.revision = Fact::observed(header.revision, source); + profile.class = Fact::observed( + ClassCode { + base: header.class_code, + subclass: header.subclass, + prog_if: header.prog_if, + }, + source, + ); + profile.command = Fact::observed(header.command, source); + profile.status = Fact::observed(header.status, source); + for (index, bar) in header.bars.iter().enumerate() { + profile.bars[index] = Fact::observed(bar_facts(index, *bar), source); + } + + let capabilities = crate::pci::walk_capabilities(bytes)?; + profile.pcie = Fact::observed(decode_pcie(&capabilities, bytes), source); + profile.msi = Fact::observed(decode_msi(&capabilities, bytes), source); + profile.msix = Fact::observed(decode_msix(&capabilities, bytes), source); + Ok(profile) + } + + pub fn write(&self, out: &mut impl Write) { + let _ = writeln!( + out, + "gb10.profile.location: segment {} bus {} device {} function {}", + self.location.segment, self.location.bus, self.location.device, self.location.function + ); + write_fact(out, "gb10.profile.vendor_id", self.vendor_id); + write_fact(out, "gb10.profile.device_id", self.device_id); + write_fact( + out, + "gb10.profile.subsystem_vendor_id", + self.subsystem_vendor_id, + ); + write_fact(out, "gb10.profile.subsystem_id", self.subsystem_id); + write_fact(out, "gb10.profile.revision", self.revision); + write_fact(out, "gb10.profile.class", self.class); + write_fact(out, "gb10.profile.command", self.command); + write_fact(out, "gb10.profile.status", self.status); + for (index, bar) in self.bars.iter().enumerate() { + write_indexed_fact(out, "gb10.profile.bar", index, *bar); + } + for (index, size) in self.bar_sizes.iter().enumerate() { + write_indexed_fact(out, "gb10.profile.bar_size", index, *size); + } + write_fact(out, "gb10.profile.pcie", self.pcie); + write_fact(out, "gb10.profile.msi", self.msi); + write_fact(out, "gb10.profile.msix", self.msix); + write_fact(out, "gb10.profile.iommu_group", self.iommu_group); + write_fact(out, "gb10.profile.numa_node", self.numa_node); + write_fact(out, "gb10.profile.firmware_path", self.firmware_path); + write_fact(out, "gb10.profile.pmc_boot_0", self.pmc_boot_0); + write_fact(out, "gb10.profile.pmc_boot_42", self.pmc_boot_42); + } +} + +fn bar_facts(index: usize, bar: Bar) -> BarFacts { + match bar { + Bar::None => BarFacts { + index: index as u8, + kind: BarKind::None, + base: 0, + is_64_bit: false, + prefetchable: false, + }, + Bar::Memory(memory) => BarFacts { + index: index as u8, + kind: BarKind::Memory, + base: memory.base, + is_64_bit: memory.is_64_bit, + prefetchable: memory.prefetchable, + }, + Bar::Io(io) => BarFacts { + index: index as u8, + kind: BarKind::Io, + base: u64::from(io.base), + is_64_bit: false, + prefetchable: false, + }, + } +} + +fn decode_pcie(capabilities: &CapabilityList, bytes: &[u8]) -> PcieFacts { + match capabilities.find(CAP_ID_PCIE) { + Some(capability) => match PcieCapability::decode(bytes, capability) { + Ok(pcie) => PcieFacts { + present: true, + max_payload_bytes: pcie.max_payload_bytes, + link: pcie.link, + }, + Err(_) => NO_PCIE, + }, + None => NO_PCIE, + } +} + +fn decode_msi(capabilities: &CapabilityList, bytes: &[u8]) -> MsiFacts { + match capabilities.find(CAP_ID_MSI) { + Some(capability) => match MsiCapability::decode(bytes, capability) { + Ok(msi) => MsiFacts { + present: true, + enabled: msi.enabled, + is_64_bit: msi.is_64_bit, + maskable: msi.maskable, + capable_vectors: msi.capable_vectors, + }, + Err(_) => NO_MSI, + }, + None => NO_MSI, + } +} + +fn decode_msix(capabilities: &CapabilityList, bytes: &[u8]) -> MsixFacts { + match capabilities.find(CAP_ID_MSIX) { + Some(capability) => match MsixCapability::decode(bytes, capability) { + Ok(msix) => MsixFacts { + present: true, + enabled: msix.enabled, + function_masked: msix.function_masked, + vectors: msix.vectors, + table_bir: msix.table_bir, + table_offset: msix.table_offset, + pba_bir: msix.pba_bir, + pba_offset: msix.pba_offset, + }, + Err(_) => NO_MSIX, + }, + None => NO_MSIX, + } +} + +fn write_indexed_fact( + out: &mut impl Write, + prefix: &str, + index: usize, + fact: Fact, +) { + match (fact.state(), fact.value(), fact.source()) { + (State::Observed, Some(value), Some(source)) => { + let _ = writeln!( + out, + "{prefix}[{index}]: {value:?} [observed source={} native_verified={}]", + source.name(), + fact.native_verified() + ); + } + (State::Derived, Some(value), Some(source)) => { + let _ = writeln!( + out, + "{prefix}[{index}]: {value:?} [derived source={} native_verified={}]", + source.name(), + fact.native_verified() + ); + } + _ => { + let _ = writeln!(out, "{prefix}[{index}]: unknown"); + } + } +} + +fn write_fact(out: &mut impl Write, name: &str, fact: Fact) { + match (fact.state(), fact.value(), fact.source()) { + (State::Observed, Some(value), Some(source)) => { + let _ = writeln!( + out, + "{name}: {value:?} [observed source={} native_verified={}]", + source.name(), + fact.native_verified() + ); + } + (State::Derived, Some(value), Some(source)) => { + let _ = writeln!( + out, + "{name}: {value:?} [derived source={} native_verified={}]", + source.name(), + fact.native_verified() + ); + } + _ => { + let _ = writeln!(out, "{name}: unknown"); + } + } +} + +/// Why a GB10 candidate did not satisfy the contract. Each variant names the +/// exact property that failed so a report can distinguish a wrong device from +/// a device whose memory decoding or BAR0 is not yet usable. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Gb10Rejection { + NotNvidia, + WrongDevice, + MemoryDecodeDisabled, + Bar0Missing, + Bar0NotMemory, + Bar0Unprogrammed, + Bar0Not64Bit, +} + +/// A GB10 endpoint that satisfies the typed contract. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Gb10Match { + pub location: PciLocation, + pub bar0: crate::pci::MemoryBar, +} + +/// Validate a decoded endpoint header against the GB10 contract using device +/// properties only. No bus, device, or function number is assumed: a relocated +/// GB10 matches exactly as the observed one does. +pub fn match_gb10(location: PciLocation, header: &Header) -> Result { + if header.vendor_id != NVIDIA_VENDOR_ID { + return Err(Gb10Rejection::NotNvidia); + } + if header.device_id != GB10_DEVICE_ID { + return Err(Gb10Rejection::WrongDevice); + } + if !header.memory_enabled() { + return Err(Gb10Rejection::MemoryDecodeDisabled); + } + match header.bars[0] { + Bar::None => Err(Gb10Rejection::Bar0Missing), + Bar::Io(_) => Err(Gb10Rejection::Bar0NotMemory), + Bar::Memory(memory) => { + if memory.base == 0 { + Err(Gb10Rejection::Bar0Unprogrammed) + } else if !memory.is_64_bit { + Err(Gb10Rejection::Bar0Not64Bit) + } else { + Ok(Gb10Match { + location, + bar0: memory, + }) + } + } + } +} + +impl Gb10Bar { + /// Validate the legacy handoff register values against the GB10 contract + /// and name why a candidate was rejected. Keeping the contract here means + /// the boot handoff and the host profile check the same properties. + pub fn from_header( + location: PciLocation, + vendor_device: u32, + command_status: u32, + bar0_low: u32, + bar0_high: u32, + ) -> Result { + if (vendor_device & 0xffff) as u16 != NVIDIA_VENDOR_ID { + return Err(Gb10Rejection::NotNvidia); + } + if (vendor_device >> 16) as u16 != GB10_DEVICE_ID { + return Err(Gb10Rejection::WrongDevice); + } + if command_status & 0x0002 == 0 { + return Err(Gb10Rejection::MemoryDecodeDisabled); + } + if bar0_low & 0x1 == 0x1 { + return Err(Gb10Rejection::Bar0NotMemory); + } + if bar0_low == 0 && bar0_high == 0 { + return Err(Gb10Rejection::Bar0Unprogrammed); + } + if bar0_low & 0x7 != 0x4 { + return Err(Gb10Rejection::Bar0Not64Bit); + } + let physical_base = (u64::from(bar0_high) << 32) | u64::from(bar0_low & !0xf); + if physical_base == 0 { + return Err(Gb10Rejection::Bar0Unprogrammed); + } + Ok(Self { + location, + physical_base, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(crate) fn gb10_config() -> [u8; crate::pci::CONFIG_SPACE_SIZE] { + let mut bytes = [0u8; crate::pci::CONFIG_SPACE_SIZE]; + bytes[0x00..0x02].copy_from_slice(&0x10deu16.to_le_bytes()); + bytes[0x02..0x04].copy_from_slice(&0x2e12u16.to_le_bytes()); + bytes[0x04..0x06].copy_from_slice(&0x0007u16.to_le_bytes()); + bytes[0x06..0x08].copy_from_slice(&0x0010u16.to_le_bytes()); + bytes[0x08] = 0xa1; + bytes[0x0b] = 0x03; + bytes[0x10..0x14].copy_from_slice(&0x2400_000cu32.to_le_bytes()); + bytes[0x14..0x18].copy_from_slice(&0x0000_0000u32.to_le_bytes()); + bytes[0x34] = 0x40; + bytes[0x40] = CAP_ID_MSI; + bytes[0x41] = 0x50; + bytes[0x42..0x44].copy_from_slice(&0x0388u16.to_le_bytes()); + bytes[0x50] = CAP_ID_PCIE; + bytes[0x51] = 0x80; + bytes[0x52..0x54].copy_from_slice(&0x0002u16.to_le_bytes()); + bytes[0x54..0x58].copy_from_slice(&0x0000_0003u32.to_le_bytes()); + bytes[0x5c..0x60].copy_from_slice(&0x0045_7901u32.to_le_bytes()); + bytes[0x62..0x64].copy_from_slice(&0x8010u16.to_le_bytes()); + bytes[0x80] = CAP_ID_MSIX; + bytes[0x81] = 0x00; + bytes[0x82..0x84].copy_from_slice(&0x8008u16.to_le_bytes()); + bytes[0x84..0x88].copy_from_slice(&0x00b9_0000u32.to_le_bytes()); + bytes[0x88..0x8c].copy_from_slice(&0x00ba_0000u32.to_le_bytes()); + bytes + } + + fn location() -> PciLocation { + PciLocation { + segment: 15, + bus: 1, + device: 0, + function: 0, + } + } + + #[test] + fn profile_classifies_source_and_native_verification() { + let bytes = gb10_config(); + let linux = Gb10Profile::from_pci_config(location(), &bytes, Source::LinuxSysfs).unwrap(); + assert_eq!(linux.vendor_id.value(), Some(0x10de)); + assert_eq!(linux.vendor_id.source(), Some(Source::LinuxSysfs)); + assert!(!linux.vendor_id.native_verified()); + assert!(Source::LinuxSysfs.linux_interpreted()); + assert!(!Source::AienosNativePci.linux_interpreted()); + + let native = + Gb10Profile::from_pci_config(location(), &bytes, Source::AienosNativePci).unwrap(); + assert!(native.vendor_id.native_verified()); + assert_eq!(native.msix.value().unwrap().vectors, 9); + assert!(native.pcie.value().unwrap().link.unwrap().downgraded); + // Sources configuration space cannot answer stay unknown. + assert_eq!(native.iommu_group.state(), State::Unknown); + assert_eq!(native.numa_node.state(), State::Unknown); + assert_eq!(native.bar_sizes[0].state(), State::Unknown); + } + + #[test] + fn profile_renders_deterministically() { + extern crate std; + use std::string::String; + let bytes = gb10_config(); + let profile = + Gb10Profile::from_pci_config(location(), &bytes, Source::AienosNativePci).unwrap(); + let mut text = String::new(); + profile.write(&mut text); + assert!(text.contains( + "gb10.profile.vendor_id: 4318 [observed source=aienos-native-pci native_verified=true]" + )); + assert!(text.contains("gb10.profile.iommu_group: unknown")); + assert!(text.contains("gb10.profile.bar_size[0]: unknown")); + } + + #[test] + fn match_gb10_is_property_based_not_bdf_based() { + let bytes = gb10_config(); + let header = Header::parse(&bytes).unwrap(); + // Same device at a completely different location still matches. + let relocated = PciLocation { + segment: 0, + bus: 0x44, + device: 0x1f, + function: 7, + }; + let matched = match_gb10(relocated, &header).unwrap(); + assert_eq!(matched.location, relocated); + assert_eq!(matched.bar0.base, 0x2400_0000); + + let mut wrong_device = bytes; + wrong_device[0x02..0x04].copy_from_slice(&0x2684u16.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&wrong_device).unwrap()), + Err(Gb10Rejection::WrongDevice) + ); + + let mut forbidden = bytes; + forbidden[0x00..0x02].copy_from_slice(&0x1234u16.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&forbidden).unwrap()), + Err(Gb10Rejection::NotNvidia) + ); + + let mut no_mem = bytes; + no_mem[0x04..0x06].copy_from_slice(&0x0005u16.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&no_mem).unwrap()), + Err(Gb10Rejection::MemoryDecodeDisabled) + ); + + let mut no_bar = bytes; + no_bar[0x10..0x14].copy_from_slice(&0u32.to_le_bytes()); + no_bar[0x14..0x18].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&no_bar).unwrap()), + Err(Gb10Rejection::Bar0Missing) + ); + + let mut io_bar = bytes; + io_bar[0x10..0x14].copy_from_slice(&0x0000_c001u32.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&io_bar).unwrap()), + Err(Gb10Rejection::Bar0NotMemory) + ); + + let mut bar32 = bytes; + bar32[0x10..0x14].copy_from_slice(&0x2400_0000u32.to_le_bytes()); + bar32[0x14..0x18].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!( + match_gb10(location(), &Header::parse(&bar32).unwrap()), + Err(Gb10Rejection::Bar0Not64Bit) + ); + } +} diff --git a/crates/aienos-accel/src/registers.rs b/crates/aienos-accel/src/registers.rs new file mode 100644 index 00000000..5cd59358 --- /dev/null +++ b/crates/aienos-accel/src/registers.rs @@ -0,0 +1,152 @@ +//! Source-backed GB10 register inventory. +//! +//! This is a knowledge ledger, not a driver. It records only registers the +//! repository can point at a source for. At present that is exactly two: the +//! PMC registers `BOOT_0` and `BOOT_42`, whose offsets the existing UEFI +//! handoff already reads. Their semantic meaning is not established here, and +//! an absent entry is not an inferred register: unknown registers stay +//! unknown. +//! +//! Nothing in this module reads or writes a register. It carries metadata. + +use core::fmt::Write; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum RegisterAccess { + ReadOnly, + ReadWrite, + Unknown, +} + +/// Whether reading the register is inside the established safe set. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum RegisterSafety { + /// The repository already reads it through an established path. + EstablishedRead, + /// A read would need explicit, separate approval before it is attempted. + RequiresApproval, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct RegisterSpec { + pub block: &'static str, + pub name: &'static str, + pub offset: u64, + pub width_bits: u8, + pub access: RegisterAccess, + /// Where the offset is recorded. A repository or public source, never a + /// guess from the register name. + pub evidence: &'static str, + /// A value observed by any AIENOS path, if one exists. + pub observed_value: Option, + /// The path that observed `observed_value`, if any. + pub observed_by: Option<&'static str>, + pub safe_to_read: RegisterSafety, + /// Native AIENOS has decoded this register on hardware. + pub native_observed: bool, + /// The register's meaning is established. + pub semantics_known: bool, +} + +pub const PMC_BLOCK: &str = "GB10 PMC"; +const PMC_EVIDENCE: &str = + "crates/aienos-accel PMC_BOOT_0/PMC_BOOT_42 offsets used by the UEFI handoff; meaning not established"; + +/// The complete known-register set. It has two entries by design. +pub const GB10_REGISTERS: [RegisterSpec; 2] = [ + RegisterSpec { + block: PMC_BLOCK, + name: "BOOT_0", + offset: 0x0000, + width_bits: 32, + access: RegisterAccess::ReadOnly, + evidence: PMC_EVIDENCE, + observed_value: None, + observed_by: None, + safe_to_read: RegisterSafety::EstablishedRead, + native_observed: false, + semantics_known: false, + }, + RegisterSpec { + block: PMC_BLOCK, + name: "BOOT_42", + offset: 0x0a00, + width_bits: 32, + access: RegisterAccess::ReadOnly, + evidence: PMC_EVIDENCE, + observed_value: None, + observed_by: None, + safe_to_read: RegisterSafety::EstablishedRead, + native_observed: false, + semantics_known: false, + }, +]; + +pub fn find(name: &str) -> Option<&'static RegisterSpec> { + GB10_REGISTERS.iter().find(|spec| spec.name == name) +} + +/// Write the ledger deterministically. One line per register. +pub fn write_ledger(out: &mut impl Write) { + for spec in &GB10_REGISTERS { + let _ = write!( + out, + "gb10.register {}.{}: offset {:#06x} width {} access {:?} safety {:?} native_observed {} semantics_known {}", + spec.block, + spec.name, + spec.offset, + spec.width_bits, + spec.access, + spec.safe_to_read, + spec.native_observed, + spec.semantics_known, + ); + match spec.observed_value { + Some(value) => { + let _ = write!(out, " observed_value {value:#010x}"); + } + None => { + let _ = write!(out, " observed_value unknown"); + } + } + match spec.observed_by { + Some(path) => { + let _ = writeln!(out, " observed_by {path:?} evidence {:?}", spec.evidence); + } + None => { + let _ = writeln!(out, " observed_by none evidence {:?}", spec.evidence); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ledger_is_exactly_the_two_established_offsets() { + assert_eq!(GB10_REGISTERS.len(), 2); + assert_eq!(find("BOOT_0").unwrap().offset, crate::PMC_BOOT_0); + assert_eq!(find("BOOT_42").unwrap().offset, crate::PMC_BOOT_42); + assert!(find("BOOT_1").is_none()); + for spec in &GB10_REGISTERS { + assert_eq!(spec.safe_to_read, RegisterSafety::EstablishedRead); + assert!(!spec.native_observed); + assert!(!spec.semantics_known); + assert!(spec.observed_value.is_none()); + } + } + + #[test] + fn ledger_renders_without_claiming_semantics() { + extern crate std; + use std::string::String; + let mut text = String::new(); + write_ledger(&mut text); + assert_eq!(text.lines().count(), 2); + assert!(text.contains("GB10 PMC.BOOT_0: offset 0x0000")); + assert!(text.contains("semantics_known false")); + assert!(text.contains("native_observed false")); + } +} diff --git a/crates/aienos-accel/tests/gb10_fixtures.rs b/crates/aienos-accel/tests/gb10_fixtures.rs new file mode 100644 index 00000000..a2656ab2 --- /dev/null +++ b/crates/aienos-accel/tests/gb10_fixtures.rs @@ -0,0 +1,306 @@ +//! Synthetic PCI configuration fixtures for GB10 discovery. +//! +//! These tests prove that discovery identifies the GB10 from device +//! properties, not from a hard-coded bus/device/function. They use only +//! in-memory byte fixtures and pure decoders: no physical device, no PCI +//! configuration write, no MMIO, no GPU execution. + +use aienos_accel::pci::{ + BridgeHeader, Header, MsiCapability, MsixCapability, PciError, PcieCapability, CAP_ID_MSI, + CAP_ID_MSIX, CAP_ID_PCIE, CONFIG_EXTENDED_SIZE, CONFIG_SPACE_SIZE, +}; +use aienos_accel::profile::{match_gb10, Gb10Profile, Gb10Rejection, Source}; +use aienos_accel::PciLocation; + +const CONFIG_HEADER: usize = 64; + +fn location(segment: u32, bus: u8, device: u8, function: u8) -> PciLocation { + PciLocation { + segment, + bus, + device, + function, + } +} + +fn write_u16(bytes: &mut [u8], offset: usize, value: u16) { + bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); +} + +fn write_u32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +/// A GB10-like endpoint: NVIDIA 10de:2e12, 64-bit prefetchable BAR0, PCIe, +/// MSI and MSI-X capabilities. +fn gb10_endpoint() -> [u8; CONFIG_SPACE_SIZE] { + let mut bytes = [0u8; CONFIG_SPACE_SIZE]; + write_u16(&mut bytes, 0x00, 0x10de); + write_u16(&mut bytes, 0x02, 0x2e12); + write_u16(&mut bytes, 0x04, 0x0007); // IO + memory + bus master + write_u16(&mut bytes, 0x06, 0x0010); // capabilities list present + bytes[0x08] = 0xa1; // revision + bytes[0x0b] = 0x03; // class: display controller + write_u32(&mut bytes, 0x10, 0x2400_000c); // BAR0 low: 64-bit prefetchable + write_u32(&mut bytes, 0x14, 0x0000_0000); // BAR0 high + write_u16(&mut bytes, 0x2c, 0x10de); // subsystem vendor + write_u16(&mut bytes, 0x2e, 0x0000); // subsystem id + bytes[0x34] = 0x40; // capability pointer + + bytes[0x40] = CAP_ID_MSI; + bytes[0x41] = 0x50; + write_u16(&mut bytes, 0x42, 0x0388); // 64-bit, maskable, 16 vectors + write_u32(&mut bytes, 0x44, 0xfee0_0000); + + bytes[0x50] = CAP_ID_PCIE; + bytes[0x51] = 0x80; + write_u16(&mut bytes, 0x52, 0x0002); // version 2, endpoint + write_u32(&mut bytes, 0x54, 0x0000_0003); // max payload 1024 + write_u32(&mut bytes, 0x5c, 0x0045_7901); // max speed gen1, width x16 + write_u16(&mut bytes, 0x62, 0x8010); // current speed gen1, width x1 + + bytes[0x80] = CAP_ID_MSIX; + bytes[0x81] = 0x00; + write_u16(&mut bytes, 0x82, 0x8008); // enabled, 9 vectors + write_u32(&mut bytes, 0x84, 0x00b9_0000); // table in BAR0 + write_u32(&mut bytes, 0x88, 0x00ba_0000); // PBA in BAR0 + + bytes +} + +#[test] +fn identifies_gb10_from_properties_under_bdf_relocation() { + let bytes = gb10_endpoint(); + let header = Header::parse(&bytes).unwrap(); + let locations = [ + location(15, 1, 0, 0), + location(0, 0, 0, 0), + location(3, 0x44, 0x1f, 7), + location(0xffff, 0xff, 0x1f, 7), + ]; + for relocated in locations { + let matched = match_gb10(relocated, &header).unwrap(); + assert_eq!(matched.location, relocated); + assert_eq!(matched.bar0.base, 0x2400_0000); + assert!(matched.bar0.is_64_bit); + assert!(matched.bar0.prefetchable); + } +} + +#[test] +fn rejects_wrong_vendor_and_wrong_device() { + let mut wrong_device = gb10_endpoint(); + write_u16(&mut wrong_device, 0x02, 0x2684); + assert_eq!( + match_gb10( + location(15, 1, 0, 0), + &Header::parse(&wrong_device).unwrap() + ), + Err(Gb10Rejection::WrongDevice) + ); + + let mut wrong_vendor = gb10_endpoint(); + write_u16(&mut wrong_vendor, 0x00, 0x1234); + assert_eq!( + match_gb10( + location(15, 1, 0, 0), + &Header::parse(&wrong_vendor).unwrap() + ), + Err(Gb10Rejection::NotNvidia) + ); +} + +#[test] +fn rejects_disabled_memory_decoding_unprogrammed_and_32_bit_bar() { + let mut no_mem = gb10_endpoint(); + write_u16(&mut no_mem, 0x04, 0x0005); // memory bit clear + assert_eq!( + match_gb10(location(15, 1, 0, 0), &Header::parse(&no_mem).unwrap()), + Err(Gb10Rejection::MemoryDecodeDisabled) + ); + + let mut unprogrammed = gb10_endpoint(); + write_u32(&mut unprogrammed, 0x10, 0x0000_0000); + write_u32(&mut unprogrammed, 0x14, 0x0000_0000); + assert_eq!( + match_gb10( + location(15, 1, 0, 0), + &Header::parse(&unprogrammed).unwrap() + ), + Err(Gb10Rejection::Bar0Missing) + ); + + let mut only_high = gb10_endpoint(); + write_u32(&mut only_high, 0x10, 0x0000_0004); + write_u32(&mut only_high, 0x14, 0x0000_0000); + assert_eq!( + match_gb10(location(15, 1, 0, 0), &Header::parse(&only_high).unwrap()), + Err(Gb10Rejection::Bar0Unprogrammed) + ); + + let mut bar32 = gb10_endpoint(); + write_u32(&mut bar32, 0x10, 0x2400_0000); // 32-bit memory BAR + write_u32(&mut bar32, 0x14, 0x0000_0000); + assert_eq!( + match_gb10(location(15, 1, 0, 0), &Header::parse(&bar32).unwrap()), + Err(Gb10Rejection::Bar0Not64Bit) + ); + + let mut io_bar = gb10_endpoint(); + write_u32(&mut io_bar, 0x10, 0x0000_c001); + assert_eq!( + match_gb10(location(15, 1, 0, 0), &Header::parse(&io_bar).unwrap()), + Err(Gb10Rejection::Bar0NotMemory) + ); +} + +#[test] +fn selects_the_gb10_among_multiple_nvidia_devices() { + // A fixture set with a wrong NVIDIA function and the GB10. Only the GB10 + // must satisfy the contract. + let mut other = gb10_endpoint(); + write_u16(&mut other, 0x02, 0x2684); + let gb10 = gb10_endpoint(); + let candidates = [ + Header::parse(&other).unwrap(), + Header::parse(&gb10).unwrap(), + ]; + let matches: Vec<_> = candidates + .iter() + .filter_map(|header| match_gb10(location(15, 1, 0, 0), header).ok()) + .collect(); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].bar0.base, 0x2400_0000); +} + +#[test] +fn follows_a_secondary_bus_window_to_a_downstream_gb10() { + // Root bridge bus 0, bridge secondary 1..0x0f, GB10 behind bus 1. + let mut bridge = [0u8; CONFIG_HEADER]; + write_u16(&mut bridge, 0x00, 0x10de); + write_u16(&mut bridge, 0x02, 0x22d1); + bridge[0x0b] = 0x06; // bridge class + bridge[0x0e] = 0x01; // type 1 header + bridge[0x19] = 0x01; // secondary bus + bridge[0x1a] = 0x0f; // subordinate bus + let bridge = BridgeHeader::parse(&bridge).unwrap(); + assert!(bridge.has_bus_window()); + assert!(bridge.secondary_bus <= 1 && 1 <= bridge.subordinate_bus); + + let downstream = gb10_endpoint(); + let on_bus_one = match_gb10(location(15, 1, 0, 0), &Header::parse(&downstream).unwrap()); + assert!(on_bus_one.is_ok()); +} + +#[test] +fn rejects_malformed_capability_loops() { + let mut bytes = gb10_endpoint(); + bytes[0x41] = 0x40; // MSI next points at itself + assert_eq!( + aienos_accel::pci::walk_capabilities(&bytes), + Err(PciError::CapabilityLoop) + ); + + let mut bytes = gb10_endpoint(); + bytes[0x34] = 0x40; + bytes[0x40] = CAP_ID_MSI; + bytes[0x41] = 0x30; // below 0x40 header boundary + assert_eq!( + aienos_accel::pci::walk_capabilities(&bytes), + Err(PciError::OutOfBounds) + ); +} + +#[test] +fn reports_missing_msi_and_msix_as_absent_not_zero() { + // Skip the MSI capability: the header pointer goes straight to PCIe. + let mut no_msi = gb10_endpoint(); + no_msi[0x34] = 0x50; + let list = aienos_accel::pci::walk_capabilities(&no_msi).unwrap(); + assert!(list.find(CAP_ID_MSI).is_none()); + assert!(list.find(CAP_ID_PCIE).is_some()); + let profile = + Gb10Profile::from_pci_config(location(15, 1, 0, 0), &no_msi, Source::SyntheticFixture) + .unwrap(); + assert!(!profile.msi.value().unwrap().present); + assert_eq!(profile.msix.value().unwrap().vectors, 9); + + // Drop MSI-X: PCIe becomes the last capability in the chain. + let mut no_msix = gb10_endpoint(); + no_msix[0x51] = 0x00; + let profile = + Gb10Profile::from_pci_config(location(15, 1, 0, 0), &no_msix, Source::SyntheticFixture) + .unwrap(); + assert!(!profile.msix.value().unwrap().present); + assert!(profile.msi.value().unwrap().present); + assert_eq!(profile.msix.value().unwrap().vectors, 0); +} + +#[test] +fn decodes_capabilities_from_full_config_space() { + let bytes = gb10_endpoint(); + let list = aienos_accel::pci::walk_capabilities(&bytes).unwrap(); + assert_eq!(list.entries().len(), 3); + + let msi = MsiCapability::decode(&bytes, list.find(CAP_ID_MSI).unwrap()).unwrap(); + assert!(msi.is_64_bit && msi.maskable); + assert_eq!(msi.capable_vectors, 16); + + let pcie = PcieCapability::decode(&bytes, list.find(CAP_ID_PCIE).unwrap()).unwrap(); + let link = pcie.link.unwrap(); + assert_eq!(link.max_width, 16); + assert_eq!(link.current_width, 1); + assert!(link.downgraded); + assert_eq!(pcie.max_payload_bytes, 1024); + + let msix = MsixCapability::decode(&bytes, list.find(CAP_ID_MSIX).unwrap()).unwrap(); + assert!(msix.enabled); + assert_eq!(msix.vectors, 9); + assert_eq!(msix.table_bir, 0); + assert_eq!(msix.pba_offset, 0x00ba_0000); +} + +#[test] +fn handles_large_bar_and_extended_space_bounds() { + // A 64 GB BAR: probe readback low 0x00000004, high 0xFFFFFFF0. + let size = aienos_accel::pci::memory_bar_size(0x0000_0004, 0xffff_fff0, true); + assert_eq!(size, Some(0x10_0000_0000)); + + // Extended capability space: a valid chain and a loop. + let mut extended = [0u8; CONFIG_EXTENDED_SIZE]; + let first = 0x19u32 | (1 << 16) | (0x12cu32 << 20); + write_u32(&mut extended, 0x100, first); + let second = 0x01u32 | (2 << 16); + write_u32(&mut extended, 0x12c, second); + let list = aienos_accel::pci::walk_extended_capabilities(&extended).unwrap(); + assert_eq!(list.entries().len(), 2); + + let mut looped = [0u8; CONFIG_EXTENDED_SIZE]; + write_u32(&mut looped, 0x100, 0x19u32 | (0x100u32 << 20)); + assert_eq!( + aienos_accel::pci::walk_extended_capabilities(&looped), + Err(PciError::CapabilityLoop) + ); +} + +#[test] +fn profile_decodes_bar_kinds_and_keeps_sizes_unknown() { + let bytes = gb10_endpoint(); + let profile = + Gb10Profile::from_pci_config(location(15, 1, 0, 0), &bytes, Source::SyntheticFixture) + .unwrap(); + let bar0 = profile.bars[0].value().unwrap(); + assert_eq!(bar0.kind, aienos_accel::profile::BarKind::Memory); + assert!(bar0.is_64_bit); + assert!(bar0.prefetchable); + assert_eq!(bar0.base, 0x2400_0000); + // Size requires a probe write, so it must stay unknown. + for size in profile.bar_sizes { + assert!(!size.is_known()); + } + // A 64-bit BAR consumed slot 1; it is not an independent BAR. + assert_eq!( + profile.bars[1].value().unwrap().kind, + aienos_accel::profile::BarKind::None + ); +} diff --git a/docs/GB10_HARDWARE_PROFILE.md b/docs/GB10_HARDWARE_PROFILE.md new file mode 100644 index 00000000..7b741d7d --- /dev/null +++ b/docs/GB10_HARDWARE_PROFILE.md @@ -0,0 +1,132 @@ +# GB10 hardware profile v1 + +This document defines the typed GB10 characterization used by AIENOS and the +read-only Linux collector that fills it. It is characterization only. Nothing +here initializes the GPU, talks to GSP, submits a command, allocates GPU +memory, executes a kernel, or performs inference. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[GB10_NATIVE_STATUS.md](GB10_NATIVE_STATUS.md), +[GB10_PLATFORM_TOPOLOGY.md](GB10_PLATFORM_TOPOLOGY.md), +[GB10_NATIVE_ACCELERATOR_BOUNDARY.md](GB10_NATIVE_ACCELERATOR_BOUNDARY.md). + +## Evidence classes + +Every fact in the profile is one of three states, never collapsed into a +default: + +- `Observed`: a value read from a named source. +- `Derived`: a value computed from observed values, not read directly. +- `Unknown`: no value was obtained. Absence of evidence is not a zero, not a + default, and not a hardware property. + +Every observed value also records: + +- its `source` (UEFI firmware service, native AIENOS PCI enumeration, Linux + sysfs, Linux procfs, Linux ACPI, a synthetic fixture, or derived); +- whether Linux interpreted the value (`true` for a kernel sysfs attribute that + the kernel decoded, `false` for raw configuration bytes this project decodes + itself); +- whether native AIENOS has independently verified the value. + +`BAR0 base observed through Linux sysfs` and `BAR0 base independently decoded +by native AIENOS PCI enumeration` are different claims, and the type keeps +them different. + +## Where it lives + +| Item | Location | +| --- | --- | +| Pure PCI configuration decoders | `crates/aienos-accel/src/pci.rs` | +| Typed profile, provenance, GB10 contract match | `crates/aienos-accel/src/profile.rs` | +| Register knowledge ledger | `crates/aienos-accel/src/registers.rs` | +| Read-only Linux collector | `scripts/gb10_profile.sh` | +| Synthetic fixture tests | `crates/aienos-accel/tests/gb10_fixtures.rs` | + +## Representable facts + +The profile can represent at least the following, with `Fact` carrying the +state, source, and native-verification flag. A value configuration space cannot +answer stays `Unknown` rather than zero. + +| Fact | Type | Source when known | +| --- | --- | --- | +| PCI segment / domain, bus, device, function | `PciLocation` | enumeration path | +| Vendor ID, device ID | `Fact` | config 0x00 | +| Subsystem vendor / device | `Fact` | config 0x2c | +| Class, subclass, programming interface | `Fact` | config 0x0b | +| Revision | `Fact` | config 0x08 | +| PCI command and status | `Fact` | config 0x04 | +| BAR count, type, base, prefetchability, 32 vs 64 bit | `Fact` and `Fact` sizes | config 0x10, `resource` | +| BAR size when reliably observable | `Fact` | Linux `resource`; a probe is never performed | +| PCIe capability presence | `Fact` | config capability list | +| Negotiated and maximum link width and speed | inside `PcieFacts` | PCIe capability registers, sysfs | +| MSI and MSI-X capability presence | `Fact`, `Fact` | config capability list | +| MSI-X table and PBA BAR indicator and offsets | inside `MsixFacts` | MSI-X capability | +| IOMMU / SMMU grouping | `Fact` | `iommu_group` sysfs | +| NUMA association | `Fact` | `numa_node` sysfs | +| Firmware / ACPI relationship | `Fact<&'static str>` | `firmware_node` sysfs | +| Known safe PMC observation values | `Fact` | UEFI handoff only, see the register ledger | +| Provenance for every observation | `Source`, collection method | always recorded | + +BAR size deserves a note. A PCI BAR size is normally found by writing all ones +and reading the mask back. That is a configuration-space write and lies outside +the read-only characterization boundary. The profile therefore reports a size +only when a source supplies one (the Linux kernel already sized the BAR and +exposes it in the `resource` file) or when a synthetic fixture supplies a probe +result to the pure `memory_bar_size` decoder. It is never produced by baking a +default. + +## Native contract match + +`profile::match_gb10` validates a decoded endpoint header against the GB10 +contract using device properties only: + +- vendor `0x10de`, device `0x2e12`; +- memory decoding enabled; +- BAR0 present, memory (not IO), programmed, and 64-bit. + +It returns the exact rejection reason otherwise +(`NotNvidia`, `WrongDevice`, `MemoryDecodeDisabled`, `Bar0Missing`, +`Bar0NotMemory`, `Bar0Unprogrammed`, `Bar0Not64Bit`). No bus, device, or +function number is assumed, so a relocated GB10 matches exactly as the observed +one does. `Gb10Bar::from_header` applies the same contract to the legacy +register values the boot handoff already reads. + +## Read-only Linux collector + +``` +bash scripts/gb10_profile.sh [--json PATH] [--report PATH] [--allow-sudo] [--generated-at S] +``` + +The collector only reads. It never writes configuration space, changes a PCI +command bit, resizes a BAR, resets a device, unbinds or rebinds a driver, writes +MMIO, or opens `/dev/mem`. + +- Default: unprivileged. It reads sysfs attributes, `/proc/cmdline`, and the + first 64 bytes of configuration space, which excludes the capability list. +- `--allow-sudo` or `GB10_PROFILE_ALLOW_SUDO=1`: performs two specific, + strictly read-only privileged reads through `sudo -n`: the 256-byte + configuration space (for the capability list) and the ACPI table copies + (for presence, size, and SHA-256). This privilege is required because the + kernel exposes only 64 config bytes to unprivileged readers and marks the + ACPI table copies root-only. Each field records whether this was used. +- `--generated-at` fixes the timestamp. Without it the timestamp is omitted so + repeated runs on unchanged hardware are byte-identical. + +Output is a deterministic structured profile (JSON) and a human report. It +records only the GB10 device, its PCIe topology, IOMMU grouping, and the +firmware tables relevant to reaching it. It does not collect secrets or +unrelated machine data. + +An example committed run on Machine 1 is +`evidence/gb10_linux_profile_2026-09-25.json`, summarized in +[`evidence/gb10_linux_readonly_2026-09-25.md`](../evidence/gb10_linux_readonly_2026-09-25.md). + +## What this is not + +The Linux collector observes facts through Linux. Those facts are Linux +observations, not native AIENOS proofs. The current UEFI discovery path +observes a subset (identity, BAR0, and two PMC registers); those are UEFI +observations. Nothing here claims GSP ownership, GPU initialization, command +submission, GPU DMA readiness, native Blackwell execution, or native inference. diff --git a/docs/GB10_HARDWARE_QUALIFICATION.md b/docs/GB10_HARDWARE_QUALIFICATION.md new file mode 100644 index 00000000..a1380a20 --- /dev/null +++ b/docs/GB10_HARDWARE_QUALIFICATION.md @@ -0,0 +1,120 @@ +# GB10 hardware qualification procedure (prepared, not executed) + +This procedure prepares the eventual attended, read-only GB10 characterization +on Machine 1. It is not to be executed as part of this characterization phase. +It exists so the operator run, when authorized, collects only approved +read-only facts and returns the machine to Linux unchanged. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md), +[HARDWARE_TEST_RIG.md](HARDWARE_TEST_RIG.md), +[GB10_PLATFORM_TOPOLOGY.md](GB10_PLATFORM_TOPOLOGY.md). + +## Scope + +Read-only characterization only: + +- `scripts/gb10_profile.sh` run against the running Linux system; +- the existing `aienos-handoff` pre-exit report, if and when a separate native + boot milestone authorizes a boot, which this procedure does not; +- collection of the pre-run and post-run Linux state listed below. + +This procedure does not initialize the GPU, contact GSP, submit a command, +allocate GPU memory, execute a kernel, perform inference, write PCI +configuration space, change a command bit, resize a BAR, reset the GPU, perform +FLR, unbind or rebind the NVIDIA driver, change power state, write MMIO, access +`/dev/mem`, load firmware, create GPU channels, map GPU memory, or change the +SMMU configuration. + +## Preconditions + +1. The operator approves the run. It runs under + `aien-proof hold --resource machine-1`. +2. Secure Boot stays on. TPM state is untouched. +3. Linux storage is untouched. The procedure writes only to a temporary + directory and to the evidence output paths the operator names. +4. BootOrder is untouched. No boot entry is created, removed, or reordered. +5. The checkout is clean and maps to one commit. The run records that commit. + +## Steps + +1. Record the pre-run state: + + ```bash + cd + git rev-parse HEAD + git status --porcelain + cat /proc/sys/kernel/osrelease + cat /proc/cmdline + ``` + +2. Collect the read-only GB10 profile. Both invocations are read-only; the + second uses the documented `sudo -n` reads for configuration space above 64 + bytes and the ACPI table copies. + + ```bash + bash scripts/gb10_profile.sh \ + --json evidence/gb10_linux_profile_.json \ + --report evidence/gb10_linux_report_.txt + + bash scripts/gb10_profile.sh --allow-sudo \ + --generated-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --json evidence/gb10_linux_profile_full_.json \ + --report evidence/gb10_linux_report_full_.txt + ``` + +3. Verify the structured output parses and that the expected device is present: + + ```bash + jq -e '.schema == "aienos.gb10.profile.v1"' evidence/gb10_linux_profile_full_.json + jq -e '.gb10_device_count >= 1' evidence/gb10_linux_profile_full_.json + ``` + +4. Record the image or tool digest. If the existing handoff image is involved + in a separately authorized native boot, record the image SHA-256 and the + commit, and compare them with `\EFI\AIENOS\STAGED.TXT` exactly as + [NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md) specifies. + +5. Record the post-run state, identical to step 1, and confirm it is unchanged. + +6. Return normally. The machine stays in Linux. Nothing reboots it. + +## Evidence to record + +| Evidence | Source | +| --- | --- | +| Exact commit | `git rev-parse HEAD` before and after | +| Working tree clean | `git status --porcelain` empty | +| Kernel and command line | `/proc/sys/kernel/osrelease`, `/proc/cmdline` | +| GB10 identity and location | structured profile `gb10_devices[].vendor_id`, `.device_id`, `.location` | +| BAR layout | structured profile `gb10_devices[].bars` | +| PCIe capability and link | structured profile `gb10_devices[].pcie`, `current_link_speed` | +| MSI / MSI-X | structured profile `gb10_devices[].msi`, `.msix` | +| IOMMU grouping | structured profile `gb10_devices[].iommu_group` | +| ACPI table hashes | structured profile `acpi_tables` | +| MCFG segment map | structured profile `mcfg_segments` | +| Privilege used | structured profile `collector.sudo_used` | +| Pre and post Linux state | the two state captures | + +The full `aien-proof hold` output is the ledger event, as with every Machine 1 +hardware run. + +## Facts that are out of scope and marked NOT QUALIFIED + +Anything that would require a write, reset, driver unbind, arbitrary MMIO read, +or trust mutation is marked: + +`NOT QUALIFIED - REQUIRES LATER DEVICE-OWNERSHIP MILESTONE` + +This includes, without exception: + +- the PMC `BOOT_0` and `BOOT_42` values read natively by AIENOS (only the UEFI + handoff path may read them, and only in a separately authorized native boot); +- any BAR MMIO read outside the established safe set; +- any GPU reset, FLR, or power state change; +- any NVIDIA driver unbind or rebind; +- any PCI configuration write, command bit change, or BAR resize; +- any GSP contact, firmware load, GPU channel, or GPU memory mapping. + +The procedure does not work around that boundary. It records the boundary as +the answer. diff --git a/docs/GB10_NATIVE_ACCELERATOR_BOUNDARY.md b/docs/GB10_NATIVE_ACCELERATOR_BOUNDARY.md new file mode 100644 index 00000000..e0538980 --- /dev/null +++ b/docs/GB10_NATIVE_ACCELERATOR_BOUNDARY.md @@ -0,0 +1,123 @@ +# GB10 native accelerator boundary + +This document freezes the layering a future native GB10 driver must fit into. +It does not design the driver. It defines the boundary so that GPU work can be +built against a capability-bound contract instead of ambient hardware access. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[GB10_HARDWARE_PROFILE.md](GB10_HARDWARE_PROFILE.md), +[GB10_PLATFORM_TOPOLOGY.md](GB10_PLATFORM_TOPOLOGY.md), +[ARCHITECTURE.md](ARCHITECTURE.md). + +## Frozen layering + +``` +PCI/ACPI discovery + | + v +device identity/profile + | + v +kernel MMIO mapping authority + | + v +SMMU/DMA authority + | + v +interrupt resource + | + v +GB10 device lifecycle + | + v +GSP transport [FUTURE] + | + v +GPU memory manager [FUTURE] + | + v +channel/queue submit [FUTURE] + | + v +compute execution [FUTURE] +``` + +The upper six layers are the subject of this characterization phase and the +milestone that follows it. The lower four are marked future and must not be +claimed until each has hardware evidence. + +## The key contract + +`aienos-accel` must never obtain ambient physical-memory or DMA authority. + +Today `aienos-accel` is pure decoding: it turns byte slices into typed facts +and validates the GB10 contract. That property is permanent. When accelerator +code eventually needs MMIO, interrupts, or DMA, it receives them as explicit +capabilities granted through AEGIS, exactly like every other AIENOS physical +resource. There is to be no global "map physical memory" call, no +`/dev/mem`-style escape, and no untyped physical address that a device driver +can dereference on its own. + +Concretely: + +- Discovery produces a `Gb10Profile`, not a mapped pointer. The profile is + immutable facts. +- Mapping MMIO is a separate, capability-gated kernel service. The discovery + layer cannot map. +- DMA is a separate, capability-gated SMMU service. A device cannot DMA until + AIENOS programs its stream table entry. +- An interrupt line or MSI-X vector is an interrupt capability, distinct from + the MMIO capability that contains the MSI-X table. + +## Required future capabilities + +These are described conceptually so the eventual implementation has a target. +Only the generic capability substrate, if it already exists, is reused; none of +these accelerator capabilities is implemented in this phase. + +| Capability | Grants | Does not grant | +| --- | --- | --- | +| Accelerator MMIO region | read/write of a bounded BAR window | DMA, interrupts, execution | +| Accelerator interrupt | receive one device interrupt or vector | MMIO, DMA | +| Accelerator DMA domain | participate in an SMMU translation context | MMIO, execution | +| Firmware object | load a named, verified firmware image | MMIO, DMA, execution | +| Compute queue | create and submit a queue | authority over other queues | + +Each is resource-specific and revocable. A compute queue capability without a +DMA domain cannot move data. A DMA domain without an MMIO region cannot be +programmed. Composition is explicit. + +## Layer responsibilities + +- **PCI/ACPI discovery.** Enumerate firmware-declared ECAM ranges, find the + GB10 by property, decode identity and capabilities. No side effects. This is + implemented in `aienos-accel` (pure) and, later, a native enumerator. +- **device identity/profile.** `Gb10Profile` with provenance. Read only. +- **kernel MMIO mapping authority.** Create a bounded mapping for a granted + accelerator MMIO region. The mapping is the only path to device registers. +- **SMMU/DMA authority.** Program the GB10 stream table entry under a granted + DMA domain. No bypass mode. +- **interrupt resource.** Bind the MSI-X vector or legacy interrupt through the + GIC/ITS to the owner. Distinct capability. +- **GB10 device lifecycle.** Reset, power, and firmware-load state machine + under operator and AEGIS policy. This is the first layer that mutates the + device, and it requires a later milestone. +- **GSP transport (future).** The command/RPC channel to GSP. Requires the + lifecycle layer and the firmware object. +- **GPU memory manager (future).** VRAM allocation and mappings. Requires the + DMA domain. +- **channel/queue submit (future).** Requires the compute queue capability. +- **compute execution (future).** Requires the queue and memory manager. + +## Safety boundary for this phase + +This characterization phase stops at layer two. It does not initialize the +GPU, communicate with GSP, submit commands, allocate GPU memory, execute +kernels, or perform inference. It does not write PCI configuration space, +change command bits, resize BARs, reset the GPU, perform FLR, rebind the +NVIDIA driver, change power state, write BAR/MMIO registers, access `/dev/mem`, +issue GSP RPC, load alternate firmware, create GPU channels, or map GPU +memory. + +The step from layer two to layer three is the next device-ownership milestone +and needs its own authorization, evidence, and rollback plan. diff --git a/docs/GB10_PLATFORM_TOPOLOGY.md b/docs/GB10_PLATFORM_TOPOLOGY.md new file mode 100644 index 00000000..67d53c38 --- /dev/null +++ b/docs/GB10_PLATFORM_TOPOLOGY.md @@ -0,0 +1,173 @@ +# GB10 platform topology and discovery cross-check + +This document maps the physical interfaces that reach the GB10 on Machine 1, +and compares them against what the existing AIENOS UEFI discovery path already +assumes. It is a Linux and firmware observation exercise. It does not +initialize the GPU or submit a command. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[GB10_HARDWARE_PROFILE.md](GB10_HARDWARE_PROFILE.md), +[GB10_NATIVE_STATUS.md](GB10_NATIVE_STATUS.md). + +All values below are Linux observed (sysfs and ACPI tables read read-only) on +the current Machine 1 Linux boot. They are not native AIENOS observations. + +## Observed platform path + +``` +ACPI MCFG segment 15 + | + v +PCI root bridge 000f:00:00.0 (ACPI PNP0A08:0b) + | + v +GB10 endpoint 000f:01:00.0 (ACPI device, firmware_node + .../PNP0A08:0b/device:1b/device:1c) +``` + +| Item | Observed value | Source | +| --- | --- | --- | +| ACPI root bridge path | `PNP0A08:0b` | `firmware_node` sysfs, Linux | +| Root bridge function | `000f:00:00.0`, class `0x060400` | sysfs, Linux | +| GB10 endpoint | `000f:01:00.0` | sysfs, Linux | +| Segment / domain | 15 (`0x000f`) | sysfs path, Linux | +| Bus / device / function | 1 / 0 / 0 | sysfs path, Linux | +| Vendor / device | `0x10de` / `0x2e12` | config, Linux | +| Subsystem | `0x10de:0x0000` | config, Linux | +| Class / revision | `0x030000` display controller / `0xa1` | config, Linux | +| Command / status | `0x0407` / `0x0010` | raw config, decoded by this project | +| BAR0 | 64-bit prefetchable memory at `0x24000000`, 64 MiB | `resource`, Linux | +| IOMMU group | 20 (only `000f:01:00.0`) | sysfs, Linux | +| NUMA node | `-1` (not exposed) | sysfs, Linux | +| Kernel driver | `nvidia` | sysfs, Linux | +| Legacy IRQ | 427 | sysfs, Linux | +| MSI-X vectors | 9 (table), 8 exposed in `msi_irqs` | config, sysfs, Linux | +| PCIe link | current 2.5 GT/s x1, max 2.5 GT/s x16 | sysfs and config, Linux | + +## ACPI MCFG / ECAM + +The MCFG table is 300 bytes and declares 16 PCI segments, each with an ECAM +window and bus range. Segments 0 to 14 use base `0xF300000000` plus a +`0x10000000` stride and cover buses 0 to 15. Segment 15, the GB10 segment, has +ECAM base `0x29000000` and covers buses 0 to 1: + +| Segment | ECAM base | Bus range | +| --- | --- | --- | +| 0 to 10 | `0xF300000000` to `0xF3A0000000` | 0 to 15 | +| 11 to 14 | `0xF3B0000000` to `0xF3E0000000` | 0 to 255 | +| 15 (GB10) | `0x29000000` | 0 to 1 | + +The GB10 is on segment 15 bus 1, inside the declared window. A native AIENOS +ECAM mapper would compute the configuration address as +`ecam_base + (bus - start_bus) * 1 MiB + device * 32 KiB + function * 4 KiB`, +so `000f:01:00.0` maps to `0x29000000 + 0x100000`. + +Provenance: `MCFG` ACPI table, parsed read-only by +`scripts/gb10_profile.sh`; SHA-256 recorded in the evidence JSON. + +## IORT / SMMUv3 + +The IORT table is present (3904 bytes). The kernel reports an Arm SMMUv3 with +40-bit output address size, a 2-level stream table covering 25 of 32 stream ID +bits, and a default DMA domain type of Translated (`iommu.passthrough=0`). The +GB10 sits alone in IOMMU group 20, so its stream is isolated from every other +endpoint in the observed group listing. + +Provenance: `IORT` ACPI table presence and size, kernel command line, and the +kernel IOMMU group layout, all Linux observed. The IORT stream-to-SID mapping +for the GB10 is not yet decoded by this project, and is listed as an unknown +below. + +## Interrupt topology + +The GB10 exposes one legacy interrupt (427) and an enabled MSI-X capability +with a 9-entry vector table at BAR0 offset `0x00b90000` and a PBA at BAR0 +offset `0x00ba0000`, both in BAR0 (BIR 0). MSI is present, 64-bit capable, and +maskable, but disabled; MSI-X is enabled. + +One discrepancy is recorded rather than smoothed over: the MSI-X table size +field reports 9 vectors, and the kernel exposes 8 entries under `msi_irqs` +(429 to 436). The ninth vector's disposition is an unresolved unknown. + +## NUMA and proximity + +`numa_node` reads `-1` for the GB10. Linux does not expose a NUMA association +for this device. This is recorded as an observed value (`-1`), not converted +into node 0. + +## What AIENOS must own after ExitBootServices + +To discover, map, isolate, and eventually interrupt-drive this GB10 natively, +AIENOS must own exactly these physical interfaces: + +1. **ECAM discovery.** The MCFG segment 15 window at `0x29000000` covering + buses 0 to 1, to reach `000f:01:00.0` and its root bridge without firmware + services. +2. **Configuration access.** Read access to the endpoint header and capability + list, decoded by `aienos-accel` pure functions. +3. **MMIO mapping authority.** A kernel-owned mapping of the BAR0 64 MiB + region at `0x24000000`, granted through a capability, not ambient physical + memory access. Reading or writing it is outside this characterization phase. +4. **SMMU / DMA authority.** The stream table entry that maps the GB10's + stream ID to a translation context. AIENOS must program this through the + SMMUv3, bound to a capability, before any DMA. It must not bypass the SMMU. +5. **Interrupt resource.** The MSI-X table and PBA in BAR0, plus the GIC ITS/MSI + path that delivers the vectors. This is a separate capability from MMIO. +6. **Firmware objects.** The GB10 firmware image and the GSP transport once a + later milestone authorizes them. + +## Cross-check against existing AIENOS discovery + +The existing UEFI handoff discovery (`crates/aienos-boot/src/handoff.rs`) and +`aienos-accel` were checked against the observed profile. + +| Existing expectation | Observed on Machine 1 | Status | +| --- | --- | --- | +| Vendor/device `10de:2e12` | `10de:2e12` | matches | +| BDF fast path segment 15 bus 1 device 0 function 0 | `000f:01:00.0` | matches | +| Programmed 64-bit memory BAR0 | 64-bit prefetchable at `0x24000000` | matches | +| PCI memory decoding enabled | command bit 1 set (`0x0407`) | matches | +| BAR0 large enough for PMC offsets 0 and `0x0a00` | BAR0 is 64 MiB | offsets in range | +| Firmware bus range covers the device bus | ECAM segment 15 covers buses 0 to 1 | matches | + +### Hard-coded assumptions found + +1. `handoff.rs` compares `vendor_device` against the literal `0x2e12_10de` + rather than the named constants in `aienos-accel`. Behaviourally correct, + but a second source of truth. +2. `handoff.rs::scan_root` tries segment 15, bus 1, device 0, function 0 first + as a shortcut before scanning firmware bus ranges. The fallback scan makes + this an optimization rather than a hard dependency, but it encodes the + current Machine 1 BDF. +3. The pre-exit discovery reads only config offsets 0x00, 0x04, 0x10, and 0x14. + It cannot report capability presence, PCIe link state, IOMMU grouping, or + MSI/MSI-X, so the boot report is silent on interrupt and isolation facts. +4. `Gb10Bar::from_config` requires `physical_base != 0` and a 64-bit memory + BAR0. Both hold, and the rejection reasons are now typed in + `profile::Gb10Bar::from_header`. + +### Scoped follow-ups, not edits to shared boot files + +These are proposed as separate changes to avoid conflicting with active lanes +on the boot and handoff code: + +- Have `read_candidate` use `NVIDIA_VENDOR_ID` and `GB10_DEVICE_ID` from + `aienos-accel`. +- Replace the inline BAR validation in `probe_gb10` with + `Gb10Bar::from_header`, keeping the same raw values in + `rejected_candidate` so diagnostics are unchanged. +- Extend native discovery to decode the capability list with `pci.rs` and + carry MSI-X presence, table offset, and vector count across handoff, once a + lane owns `handoff.rs`. + +## Unresolved unknowns + +- The IORT stream ID and SMMUv3 stream table entry for the GB10. +- The disposition of the ninth MSI-X vector. +- Whether the negotiated PCIe width stays at x1 after link training settles, + and why the current speed reads 2.5 GT/s while the link can go wider. Kernel + boot logged `0.000 Gb/s available PCIe bandwidth, limited by Unknown x0 link` + at `000f:00:00.0`; sysfs later read x1. The negotiated state is dynamic and + is recorded as observed, not derived. +- The PMC register values. They are read only through the UEFI handoff path, + never through Linux in this phase. diff --git a/docs/GB10_REGISTER_LEDGER.md b/docs/GB10_REGISTER_LEDGER.md new file mode 100644 index 00000000..087e16d2 --- /dev/null +++ b/docs/GB10_REGISTER_LEDGER.md @@ -0,0 +1,59 @@ +# GB10 register knowledge ledger + +This is a source-backed inventory of GB10 registers AIENOS can point at a +source for. It is not a driver and it does not read any register. Unknown +registers stay unknown. Meanings are not inferred from register names or from +Linux driver behaviour. + +The repository supports exactly two GB10 registers today: PMC `BOOT_0` and PMC +`BOOT_42`. There are no others. If a future milestone establishes more, they +are added here with their own evidence. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[GB10_HARDWARE_PROFILE.md](GB10_HARDWARE_PROFILE.md), +[GB10_NATIVE_ACCELERATOR_BOUNDARY.md](GB10_NATIVE_ACCELERATOR_BOUNDARY.md). + +The machine-readable form is `GB10_REGISTERS` in +`crates/aienos-accel/src/registers.rs`. + +## Ledger + +| Block | Register | Offset | Width | Access | Evidence source | Observed value | Confidence / status | Safe to read | Native AIENOS observed | Semantics known | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| GB10 PMC | `BOOT_0` | `0x0000` | 32 bit | read only (per current use) | `crates/aienos-accel` offset used by the UEFI handoff | none recorded here | offset established in the repository; meaning not established | established read through the UEFI handoff path | no | no | +| GB10 PMC | `BOOT_42` | `0x0a00` | 32 bit | read only (per current use) | `crates/aienos-accel` offset used by the UEFI handoff | none recorded here | offset established in the repository; meaning not established | established read through the UEFI handoff path | no | no | + +## Notes on each column + +- **Offset.** The absolute offset from BAR0. The UEFI handoff reads + `bar.physical_base + offset` before `ExitBootServices`. +- **Access.** The repository only ever reads these two. No write path exists, + and none is proposed here. +- **Observed value.** Left empty. The register values are read at boot into the + handoff report and the firmware variable, but no native AIENOS observation of + them exists yet, so there is nothing verified to record. A Linux read was + deliberately not performed: reading BAR MMIO outside the established safe set + needs separate approval. +- **Confidence / status.** The offsets are established in this repository. The + meaning of each register is not. +- **Safe to read.** Both are inside the set the existing handoff already reads + through the UEFI root bridge memory protocol. A read outside this set would + need explicit, separate approval, on the principle that a register being + readable is not evidence that it is safe to read. +- **Native AIENOS observed.** False for both. Only UEFI firmware services have + read them so far. + +## Rules for adding a register + +1. Cite a source. A source is a repository file, a public specification whose + licensing and provenance are clear, or recorded hardware evidence. A name + that looks meaningful is not a source. +2. Never copy proprietary documentation or incompatibly licensed source into + the trusted base. +3. Record the access type. If it is unknown, say unknown. +4. Mark safe-to-read separately from the offset. An offset is not a safety + argument. +5. Leave semantics unknown until there is evidence to establish them. Do not + guess a bit layout from a downstream driver's use. +6. Set native-observed only after a native AIENOS path actually reads the + register on hardware. diff --git a/evidence/gb10_linux_profile_2026-09-25.json b/evidence/gb10_linux_profile_2026-09-25.json new file mode 100644 index 00000000..fa3e9bb0 --- /dev/null +++ b/evidence/gb10_linux_profile_2026-09-25.json @@ -0,0 +1,441 @@ +{ + "acpi_tables": [ + { + "name": "MCFG", + "sha256": "a505684308aee98536d42300d0e120575d454328f5b6650cf945f1362e40812a", + "size_bytes": 300 + }, + { + "name": "IORT", + "sha256": "5e0096a2be83ce2025c5c6395455c6814c16e01ff433791e8057c245f4939cb1", + "size_bytes": 3904 + }, + { + "name": "PPTT", + "sha256": "27a03b81cb8fbe6a078a3d3c0d5d8b7e1c76d10a5e3057900d3057e8a9dd9044", + "size_bytes": 2232 + }, + { + "name": "SPCR", + "sha256": "18bb88b0d04ebb20d5c254acf63728c8c94cb3f4d49fe2b78bc8602fddd09c87", + "size_bytes": 80 + }, + { + "name": "GTDT", + "sha256": "83d3e5bf264d32e57847873f73847519485d6af09643cf0a3bfff837f601fb7f", + "size_bytes": 472 + }, + { + "name": "APIC", + "sha256": "5e902f4bc9235fbbff53850a191585bd4e089e5fdeb71be9e62dccfe924cabef", + "size_bytes": 1704 + }, + { + "name": "DSDT", + "sha256": "2871cbcb8992f7bd3915d6f19e7cfab577e068dcad58b6f00317a9f2d4e1b28e", + "size_bytes": 70143 + }, + { + "name": "TPM2", + "sha256": "7e461f53e5a29af53a42d322d811148c6577132f9f2ff0ec5e889a309d2c503b", + "size_bytes": 76 + }, + { + "name": "WSMT", + "sha256": "397ff541a0a051c219a6268237477db7cbcc65e9002a0280c0a593524b2a072e", + "size_bytes": 40 + } + ], + "collector": { + "git_commit": "71cb1703484cbc9d56eabe43402a6f9bf62b1028", + "name": "scripts/gb10_profile.sh", + "read_only": true, + "sudo_used": true + }, + "gb10_device_count": 1, + "gb10_devices": [ + { + "bar_size_note": "kernel resource size; native AIENOS has not independently decoded it", + "bars": [ + { + "base": 603979776, + "base_hex": "0x24000000", + "index": 0, + "is_64_bit": true, + "kind": "memory", + "linux_interpreted": true, + "method": "read resource (kernel-sized)", + "native_verified": false, + "prefetchable": true, + "size": 67108864, + "source": "linux-sysfs" + } + ], + "bdf": "000f:01:00.0", + "capabilities": [ + { + "id": 1, + "offset": 64 + }, + { + "id": 5, + "offset": 72 + }, + { + "id": 16, + "offset": 96 + }, + { + "id": 9, + "offset": 156 + }, + { + "id": 17, + "offset": 176 + } + ], + "capability_status": "decoded", + "class": { + "linux_interpreted": true, + "method": "read class", + "native_verified": false, + "source": "linux-sysfs", + "value": "0x030000" + }, + "command": { + "linux_interpreted": false, + "method": "raw config dword at 0x04", + "native_verified": false, + "source": "linux-sysfs", + "value": 1031 + }, + "config_bytes_read": 256, + "current_link_speed": { + "linux_interpreted": true, + "method": "read current_link_speed", + "native_verified": false, + "source": "linux-sysfs", + "value": "2.5 GT/s PCIe" + }, + "current_link_width": { + "linux_interpreted": true, + "method": "read current_link_width", + "native_verified": false, + "source": "linux-sysfs", + "value": "1" + }, + "device_hex": "0x2e12", + "device_id": { + "linux_interpreted": true, + "method": "read device", + "native_verified": false, + "source": "linux-sysfs", + "value": 11794 + }, + "driver": { + "linux_interpreted": true, + "method": "readlink driver", + "native_verified": false, + "source": "linux-sysfs", + "value": "nvidia" + }, + "firmware_node": { + "linux_interpreted": true, + "method": "readlink firmware_node", + "native_verified": false, + "source": "linux-sysfs", + "value": "/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:0b/device:1b/device:1c" + }, + "iommu_group": { + "linux_interpreted": true, + "method": "readlink iommu_group", + "native_verified": false, + "source": "linux-sysfs", + "value": 20 + }, + "irq": { + "linux_interpreted": true, + "method": "read irq", + "native_verified": false, + "source": "linux-sysfs", + "value": 427 + }, + "location": { + "bus": 1, + "device": 0, + "domain": 15, + "function": 0, + "linux_interpreted": true, + "method": "sysfs device path", + "source": "linux-sysfs" + }, + "max_link_speed": { + "linux_interpreted": true, + "method": "read max_link_speed", + "native_verified": false, + "source": "linux-sysfs", + "value": "2.5 GT/s PCIe" + }, + "max_link_width": { + "linux_interpreted": true, + "method": "read max_link_width", + "native_verified": false, + "source": "linux-sysfs", + "value": "16" + }, + "msi": { + "capable_vectors": 16, + "enabled": 0, + "is_64_bit": 1, + "linux_interpreted": false, + "maskable": 1, + "method": "raw config capability decode", + "native_verified": false, + "present": true, + "source": "linux-sysfs" + }, + "msi_irq_count": { + "linux_interpreted": true, + "method": "count msi_irqs", + "native_verified": false, + "source": "linux-sysfs", + "value": 8 + }, + "msix": { + "enabled": 1, + "function_masked": 0, + "linux_interpreted": false, + "method": "raw config capability decode", + "native_verified": false, + "pba_bir": 0, + "pba_offset": 12189696, + "present": true, + "source": "linux-sysfs", + "table_bir": 0, + "table_offset": 12124160, + "vectors": 9 + }, + "numa_node": { + "linux_interpreted": true, + "method": "read numa_node", + "native_verified": false, + "source": "linux-sysfs", + "value": -1 + }, + "pcie": { + "current_speed": "2.5 GT/s", + "current_width": 1, + "device_type": 0, + "linux_interpreted": false, + "max_payload_bytes": 256, + "max_speed": "2.5 GT/s", + "max_width": 16, + "method": "raw config capability decode", + "native_verified": false, + "present": true, + "source": "linux-sysfs", + "version": 2 + }, + "revision": { + "linux_interpreted": true, + "method": "read revision", + "native_verified": false, + "source": "linux-sysfs", + "value": 161 + }, + "status": { + "linux_interpreted": false, + "method": "raw config dword at 0x04", + "native_verified": false, + "source": "linux-sysfs", + "value": 16 + }, + "subsystem_id": { + "linux_interpreted": true, + "method": "read subsystem_device", + "native_verified": false, + "source": "linux-sysfs", + "value": 0 + }, + "subsystem_vendor_id": { + "linux_interpreted": true, + "method": "read subsystem_vendor", + "native_verified": false, + "source": "linux-sysfs", + "value": 4318 + }, + "vendor_hex": "0x10de", + "vendor_id": { + "linux_interpreted": true, + "method": "read vendor", + "native_verified": false, + "source": "linux-sysfs", + "value": 4318 + } + } + ], + "generated_at_utc": "2026-09-25T11:58:06Z", + "iommu_kernel_parameters": [ + "iommu.passthrough=0" + ], + "machine_identity_note": "Linux-observed facts only; not a native AIENOS proof.", + "mcfg_segments": [ + { + "ecam_base": 1043677052928, + "ecam_base_hex": "0xf300000000", + "end_bus": 15, + "segment": 0, + "start_bus": 0 + }, + { + "ecam_base": 1043945488384, + "ecam_base_hex": "0xf310000000", + "end_bus": 15, + "segment": 1, + "start_bus": 0 + }, + { + "ecam_base": 1044213923840, + "ecam_base_hex": "0xf320000000", + "end_bus": 15, + "segment": 2, + "start_bus": 0 + }, + { + "ecam_base": 1044482359296, + "ecam_base_hex": "0xf330000000", + "end_bus": 15, + "segment": 3, + "start_bus": 0 + }, + { + "ecam_base": 1044750794752, + "ecam_base_hex": "0xf340000000", + "end_bus": 15, + "segment": 4, + "start_bus": 0 + }, + { + "ecam_base": 1045019230208, + "ecam_base_hex": "0xf350000000", + "end_bus": 15, + "segment": 5, + "start_bus": 0 + }, + { + "ecam_base": 1045287665664, + "ecam_base_hex": "0xf360000000", + "end_bus": 15, + "segment": 6, + "start_bus": 0 + }, + { + "ecam_base": 1045556101120, + "ecam_base_hex": "0xf370000000", + "end_bus": 15, + "segment": 7, + "start_bus": 0 + }, + { + "ecam_base": 1045824536576, + "ecam_base_hex": "0xf380000000", + "end_bus": 15, + "segment": 8, + "start_bus": 0 + }, + { + "ecam_base": 1046092972032, + "ecam_base_hex": "0xf390000000", + "end_bus": 15, + "segment": 9, + "start_bus": 0 + }, + { + "ecam_base": 1046361407488, + "ecam_base_hex": "0xf3a0000000", + "end_bus": 15, + "segment": 10, + "start_bus": 0 + }, + { + "ecam_base": 1046629842944, + "ecam_base_hex": "0xf3b0000000", + "end_bus": 255, + "segment": 11, + "start_bus": 0 + }, + { + "ecam_base": 1046898278400, + "ecam_base_hex": "0xf3c0000000", + "end_bus": 255, + "segment": 12, + "start_bus": 0 + }, + { + "ecam_base": 1047166713856, + "ecam_base_hex": "0xf3d0000000", + "end_bus": 255, + "segment": 13, + "start_bus": 0 + }, + { + "ecam_base": 1047435149312, + "ecam_base_hex": "0xf3e0000000", + "end_bus": 255, + "segment": 14, + "start_bus": 0 + }, + { + "ecam_base": 687865856, + "ecam_base_hex": "0x29000000", + "end_bus": 1, + "segment": 15, + "start_bus": 0 + } + ], + "pci_bridge_topology": [ + { + "bdf": "0000:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + }, + { + "bdf": "0002:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + }, + { + "bdf": "0004:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + }, + { + "bdf": "0007:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + }, + { + "bdf": "0009:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + }, + { + "bdf": "000f:00:00.0", + "class": "0x060400", + "linux_interpreted": true, + "source": "linux-sysfs" + } + ], + "platform": { + "linux_interpreted": true, + "product_name": "NVIDIA_DGX_Spark", + "source": "linux-sysfs", + "system_vendor": "NVIDIA" + }, + "schema": "aienos.gb10.profile.v1" +} diff --git a/evidence/gb10_linux_readonly_2026-09-25.md b/evidence/gb10_linux_readonly_2026-09-25.md new file mode 100644 index 00000000..e062d0a4 --- /dev/null +++ b/evidence/gb10_linux_readonly_2026-09-25.md @@ -0,0 +1,124 @@ +# GB10 read-only characterization evidence (2026-09-25) + +This report records what is known about the Machine 1 GB10 after the read-only +characterization phase. It separates observation classes explicitly. A Linux +observation is never written as a native AIENOS proof, and no emulator result +is written as GB10 hardware behaviour. + +Governing: issue [#36](https://github.com/aien-dev/aienos/issues/36), +[GB10_HARDWARE_PROFILE.md](../docs/GB10_HARDWARE_PROFILE.md), +[GB10_PLATFORM_TOPOLOGY.md](../docs/GB10_PLATFORM_TOPOLOGY.md), +[GB10_HARDWARE_QUALIFICATION.md](../docs/GB10_HARDWARE_QUALIFICATION.md). + +## Artifacts + +| Artifact | SHA-256 | +| --- | --- | +| `evidence/gb10_linux_profile_2026-09-25.json` | `774e342a979ea9a514f5a2c1f5f7551ae6620af1331b73ba00a5d156ec553605` | +| `evidence/gb10_linux_report_2026-09-25.txt` | `71eb09a2f508e8c8d43031a5ddb500ad3362dc0f39d98d0d46015b21338b2d3e` | + +Collection: `bash scripts/gb10_profile.sh --allow-sudo`, read-only, on +Machine 1 (`NVIDIA_DGX_Spark`), at 2026-09-25T11:58:06Z. The collector used the +documented `sudo -n` reads for the 256-byte configuration space and the ACPI +table copies only. It performed no write. + +## 1. Linux-observed facts + +Source: `scripts/gb10_profile.sh`, reading sysfs, a 256-byte raw configuration +read decoded by this project, and ACPI table copies. These are Linux +observations. None of them is a native AIENOS proof. + +| Fact | Value | +| --- | --- | +| Device | NVIDIA `0x10de:0x2e12` at `000f:01:00.0` | +| Location | segment 15, bus 1, device 0, function 0 | +| Subsystem | `0x10de:0x0000` | +| Class / revision | `0x030000` / `0xa1` | +| Command / status | `0x0407` / `0x0010` (raw config, decoded here) | +| BAR0 | 64-bit prefetchable memory, base `0x24000000`, size 64 MiB | +| Capabilities | PM `0x40`, MSI `0x48`, PCIe `0x60`, vendor `0x9c`, MSI-X `0xb0` | +| PCIe link | current 2.5 GT/s x1, max 2.5 GT/s x16, max payload 256 bytes | +| MSI | present, disabled, 64-bit capable, maskable, 16 vectors | +| MSI-X | enabled, 9 table entries, table BAR0 offset `0xb90000`, PBA BAR0 offset `0xba0000` | +| IOMMU group | 20 (the GB10 alone) | +| NUMA node | `-1` (not exposed) | +| Kernel driver | `nvidia` | +| Firmware node | `.../PNP0A08:0b/device:1b/device:1c` | +| Legacy IRQ | 427 | +| `msi_irqs` entries | 8 (429 to 436) | +| MCFG | 16 segments; segment 15 ECAM `0x29000000`, buses 0 to 1 | +| IORT | present, 3904 bytes | +| ACPI hashes | recorded in the profile `acpi_tables` array | + +Every field in the JSON records its source, its collection method, whether +Linux interpreted the value, and `native_verified: false`. + +## 2. UEFI-observed facts + +Source: the `aienos-handoff` UEFI image. + +- On the M2 first native boot (commit `52109bcb334a95bdd33410b4d22c59dee8c917f4`, + image SHA-256 `79505373088d2464b82181c06f07e18e20e4e9b2b55dbc9fc46e3f0a2e2e3ada`), + the pre-exit GB10 discovery found no match and reported `gb10: unavailable`, + even though Linux sees `10de:2e12` at `000f:01:00.0`. No PMC value was read + through the UEFI path on that boot. See + [m2_first_boot_2026-09-24.md](m2_first_boot_2026-09-24.md). +- The updated multi-root, bus-range discovery path at baseline + `71cb1703484cbc9d56eabe43402a6f9bf62b1028` has been built but not booted on + hardware. Its UEFI observations are therefore unqualified. See + [GB10_NATIVE_STATUS.md](../docs/GB10_NATIVE_STATUS.md). + +## 3. Native-AIENOS-observed facts + +There are none for the GB10. No native AIENOS path has observed any GB10 +property on hardware. + +The only native AIENOS observations from the M2 boot are CPU, exception level, +and memory map facts, not GB10 facts. The register ledger records both PMC +registers as `native_observed: false`. + +## 4. QEMU and synthetic-test facts + +Source: `crates/aienos-accel/tests/gb10_fixtures.rs` and the unit tests in +`crates/aienos-accel/src/pci.rs`. + +The synthetic fixtures prove the decoders and the discovery contract, not GB10 +hardware behaviour: + +- a valid GB10-like 64-bit BAR layout is accepted; +- a 32-bit BAR0 is rejected as `Bar0Not64Bit`; +- disabled memory decoding is rejected as `MemoryDecodeDisabled`; +- an unprogrammed BAR0 is rejected as `Bar0Missing` or `Bar0Unprogrammed`; +- malformed capability lists, loops, and out-of-bounds pointers are rejected; +- multiple NVIDIA devices resolve to the GB10 by property; +- a correct device behind a secondary bus is reached through a bridge window; +- the GB10 matches under BDF relocation, proving discovery is property-based; +- missing MSI or MSI-X is reported as absent, not as zero; +- large BAR arithmetic and bounds are checked. + +These are QEMU or in-memory test facts and are not GB10 hardware facts. + +## 5. Inferred and derived relationships + +- The GB10's path from MCFG segment 15 ECAM at `0x29000000`, through root + bridge `000f:00:00.0`, to endpoint `000f:01:00.0` is derived from the + observed segment, bus, and MCFG window. It is a consistent path, not a + separately observed transaction. +- The ECAM configuration address for `000f:01:00.0` (`0x29000000 + 0x100000`) + is derived from the MCFG base and bus, not read from that address. +- BAR0 being large enough for PMC offsets 0 and `0x0a00` is derived from the + observed 64 MiB size. + +## 6. Unresolved unknowns + +- The IORT stream ID and SMMUv3 stream table entry for the GB10. +- The disposition of the ninth MSI-X vector (table reports 9, `msi_irqs` + exposes 8). +- The dynamic PCIe link state. Kernel boot logged an x0 link at + `000f:00:00.0`; sysfs later read x1 against a maximum of x16. The negotiated + state is recorded as observed, not explained. +- The PMC `BOOT_0` and `BOOT_42` values and their meaning. Reading them + natively or through Linux is out of scope for this phase. +- Any GPU behaviour. GSP ownership, GPU initialization, command submission, + GPU DMA readiness, native Blackwell execution, and native inference are not + claimed by this phase. diff --git a/evidence/gb10_linux_report_2026-09-25.txt b/evidence/gb10_linux_report_2026-09-25.txt new file mode 100644 index 00000000..b8eb449b --- /dev/null +++ b/evidence/gb10_linux_report_2026-09-25.txt @@ -0,0 +1,22 @@ +# GB10 read-only hardware characterization (Linux-observed) + +schema: aienos.gb10.profile.v1 +collector commit: 71cb1703484cbc9d56eabe43402a6f9bf62b1028 +sudo used for read-only config/ACPI: yes +GB10 devices found: 1 + +## 000f:01:00.0 + vendor:device 0x10de:0x2e12 class 0x030000 + location domain=15 bus=1 device=0 function=0 + iommu_group 20 + driver nvidia + numa_node -1 + firmware_node /sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:0b/device:1b/device:1c + pcie link current 2.5 GT/s PCIe x1 max 2.5 GT/s PCIe x16 + capability status decoded + BARs: + [0] memory base=0x24000000 size=67108864 64bit=true prefetch=true + +The structured profile records source, method, whether Linux interpreted +the value, and whether AIENOS independently verified it. No observation +here is a native AIENOS proof, and none of it involved a GPU command. diff --git a/scripts/gb10_profile.sh b/scripts/gb10_profile.sh new file mode 100755 index 00000000..05487157 --- /dev/null +++ b/scripts/gb10_profile.sh @@ -0,0 +1,538 @@ +#!/usr/bin/env bash +# Read-only GB10 hardware characterization collector for Linux (Machine 1). +# +# This script only reads. It opens no sysfs attribute for writing, changes no +# PCI command bit, resizes no BAR, resets no device, unbinds no driver, writes +# no MMIO, and touches no /dev/mem. Every source is a kernel-exposed read-only +# interface. +# +# Output is a deterministic structured profile (JSON) plus a human-readable +# report. Every field records: +# - the value +# - the source (which kernel interface) +# - the collection method +# - whether Linux interpreted the value (true for sysfs attributes, false for +# raw configuration-space bytes that this script decodes itself) +# - whether native AIENOS has independently verified it (always false here; +# this collector runs under Linux) +# +# Privilege: by default the collector runs unprivileged and reads only the +# first 64 bytes of PCI configuration space, which excludes the capability +# list. Extended configuration space (256 bytes) and the ACPI table copies are +# readable only by root on this platform. Pass --allow-sudo (or set +# GB10_PROFILE_ALLOW_SUDO=1) to perform those specific, strictly read-only +# reads through `sudo -n`. Nothing else is escalated. + +set -euo pipefail + +SCHEMA="aienos.gb10.profile.v1" +GB10_VENDOR="0x10de" +GB10_DEVICE="0x2e12" + +JSON_OUT="-" +REPORT_OUT="/dev/stderr" +ALLOW_SUDO="${GB10_PROFILE_ALLOW_SUDO:-0}" +EMIT_TIMESTAMP=0 +GENERATED_AT="${GB10_PROFILE_GENERATED_AT:-}" + +usage() { + cat <<'EOF' +usage: bash scripts/gb10_profile.sh [options] + + --json PATH write the structured profile to PATH ('-' for stdout; default -) + --report PATH write the human report to PATH (default stderr) + --allow-sudo allow the specific read-only privileged reads described above + --generated-at S set a fixed collection timestamp; default is omitted so + repeated runs on unchanged hardware are byte-identical + -h, --help show this help + +This collector is read-only. It never writes configuration space, MMIO, driver +state, firmware variables, or storage. +EOF +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --json) JSON_OUT="$2"; shift 2 ;; + --report) REPORT_OUT="$2"; shift 2 ;; + --allow-sudo) ALLOW_SUDO=1; shift ;; + --generated-at) GENERATED_AT="$2"; EMIT_TIMESTAMP=1; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;; + esac +done + +if [[ "$ALLOW_SUDO" == "1" ]]; then + if ! sudo -n true 2>/dev/null; then + echo "warning: --allow-sudo requested but sudo -n is unavailable; continuing unprivileged" >&2 + ALLOW_SUDO=0 + fi +fi + +TMP_CONFIG="$(mktemp "${TMPDIR:-/tmp}/gb10-config.XXXXXX")" +TMP_ACPI="$(mktemp "${TMPDIR:-/tmp}/gb10-acpi.XXXXXX")" +TMP_PROFILE="$(mktemp "${TMPDIR:-/tmp}/gb10-profile.XXXXXX")" +cleanup() { rm -f "$TMP_CONFIG" "$TMP_ACPI" "$TMP_PROFILE"; } +trap cleanup EXIT + +# --- small helpers --------------------------------------------------------- + +read_attr() { # dir name + local path="$1/$2" + [[ -r "$path" ]] && tr -d '\n' < "$path" || true +} + +read_attr_or_null() { # dir name -> JSON null when absent + local value + value="$(read_attr "$1" "$2")" + if [[ -z "$value" ]]; then printf 'null'; else printf '"%s"' "$value"; fi +} + +read_resource_line() { # dir index -> "start end flags" (empty when absent) + local file="$1/resource" + [[ -r "$file" ]] || return 0 + awk -v n="$2" 'NR == n+1 { print $1, $2, $3 }' "$file" +} + +attr_present() { [[ -e "$1/$2" ]]; } + +config_byte() { # offset -> hex byte from TMP_CONFIG + od -An -tx1 -j "$1" -N 1 "$TMP_CONFIG" 2>/dev/null | tr -d ' \n' +} + +# --- capability decoding from raw configuration bytes ---------------------- +# The capability list lives above offset 0x40 and needs a 256-byte read, which +# requires --allow-sudo. When only 64 bytes are available these decode to +# unknown rather than to zero. + +CFG=() +load_config() { # dir bytes + local dir="$1" count="$2" + : > "$TMP_CONFIG" + if [[ "$ALLOW_SUDO" == "1" ]]; then + sudo -n dd if="$dir/config" bs=1 count="$count" status=none 2>/dev/null > "$TMP_CONFIG" || true + else + dd if="$dir/config" bs=1 count="$count" status=none 2>/dev/null > "$TMP_CONFIG" || true + fi + mapfile -t CFG < <(od -An -tx1 -v "$TMP_CONFIG" 2>/dev/null | tr -s ' ' '\n' | grep -E '^[0-9a-f]{2}$' || true) +} + +cfg_len() { printf '%s' "${#CFG[@]}"; } + +cfg_u8() { # offset + printf '%s' "${CFG[$1]:-}" +} + +cfg_u16() { # offset + local lo hi + lo="$(cfg_u8 "$1")"; hi="$(cfg_u8 "$(($1 + 1))")" + [[ -n "$lo" && -n "$hi" ]] || { printf ''; return; } + printf '%s' "$(( 16#$lo + 16#$hi * 256 ))" +} + +cfg_u32() { # offset + local b0 b1 b2 b3 + b0="$(cfg_u8 "$1")"; b1="$(cfg_u8 "$(($1 + 1))")" + b2="$(cfg_u8 "$(($1 + 2))")"; b3="$(cfg_u8 "$(($1 + 3))")" + [[ -n "$b0" && -n "$b1" && -n "$b2" && -n "$b3" ]] || { printf ''; return; } + printf '%s' "$(( 16#$b0 + 16#$b1 * 256 + 16#$b2 * 65536 + 16#$b3 * 16777216 ))" +} + +speed_name() { # pcie link speed encoding + case "$1" in + 1) printf '2.5 GT/s' ;; 2) printf '5.0 GT/s' ;; 3) printf '8.0 GT/s' ;; + 4) printf '16.0 GT/s' ;; 5) printf '32.0 GT/s' ;; 6) printf '64.0 GT/s' ;; + *) printf 'unknown' ;; + esac +} + +# Walk the standard capability list. Sets CAP_IDS, CAP_PCIE, CAP_MSI, CAP_MSIX +# (as "present offset", or empty) so the caller can build JSON. +decode_capabilities() { + CAP_IDS=""; CAP_PCIE=""; CAP_MSI=""; CAP_MSIX="" + if [[ "$(cfg_len)" -lt 256 ]]; then + CAP_STATUS="requires-256-byte-config-read" + return + fi + local status + status="$(cfg_u16 0x06)" + if [[ -z "$status" ]]; then CAP_STATUS="unreadable"; return; fi + if (( (status & 0x10) == 0 )); then CAP_STATUS="capability-list-absent"; return; fi + local pointer + pointer="$(cfg_u8 0x34)" + [[ -n "$pointer" ]] || { CAP_STATUS="unreadable"; return; } + [[ "$pointer" == "00" ]] && { CAP_STATUS="capability-list-absent"; return; } + CAP_STATUS="decoded" + local offset=$((16#$pointer)) steps=0 seen="" + while (( offset != 0 )); do + if (( steps >= 48 )); then CAP_STATUS="too-many-capabilities"; return; fi + if (( offset < 0x40 || offset % 4 != 0 || offset + 2 > 256 )); then + CAP_STATUS="malformed-capability-pointer"; return + fi + case ",$seen," in *",$offset,"*) CAP_STATUS="capability-loop"; return ;; esac + seen="$seen,$offset" + local id next + id="$(cfg_u8 "$offset")" + next="$(cfg_u8 "$((offset + 1))")" + [[ -n "$id" && -n "$next" ]] || { CAP_STATUS="unreadable"; return; } + CAP_IDS="$CAP_IDS $id:$offset" + case "$id" in + 05) CAP_MSI="$offset" ;; + 10) CAP_PCIE="$offset" ;; + 11) CAP_MSIX="$offset" ;; + esac + offset=$((16#$next)) + steps=$((steps + 1)) + done +} + +# --- per-device extraction ------------------------------------------------- + +device_profile() { # sysfs device dir + local dir="$1" + local bdf; bdf="$(basename "$dir")" + local domain_hex="${bdf%%:*}" + local rest="${bdf#*:}" + local bus_hex="${rest%%:*}" + local devfn="${rest#*:}" + local device_hex="${devfn%%.*}" + local function_hex="${devfn#*.}" + local domain=$((16#$domain_hex)) bus=$((16#$bus_hex)) + local device=$((16#$device_hex)) function=$((16#$function_hex)) + + load_config "$dir" 256 + decode_capabilities + + local vendor device_id class revision sub_vendor sub_device + vendor="$(read_attr "$dir" vendor)" + device_id="$(read_attr "$dir" device)" + class="$(read_attr "$dir" class)" + revision="$(read_attr "$dir" revision)" + sub_vendor="$(read_attr "$dir" subsystem_vendor)" + sub_device="$(read_attr "$dir" subsystem_device)" + + # Convert the "0x...." sysfs hex strings to numbers for the structured + # profile. An unreadable attribute stays null. + hex_to_num() { + local value="$1" + if [[ "$value" == 0x* && ${#value} -le 6 ]]; then + printf '%s' "$((16#${value#0x}))" + else + printf 'null' + fi + } + local vendor_num device_num revision_num sub_vendor_num sub_device_num + vendor_num="$(hex_to_num "$vendor")" + device_num="$(hex_to_num "$device_id")" + revision_num="$(hex_to_num "$revision")" + sub_vendor_num="$(hex_to_num "$sub_vendor")" + sub_device_num="$(hex_to_num "$sub_device")" + + local command="null" status="null" + local raw_cmd; raw_cmd="$(od -An -tx4 -j 4 -N 4 "$TMP_CONFIG" 2>/dev/null | tr -d ' \n')" + if [[ -n "$raw_cmd" ]]; then + command="$((16#$raw_cmd & 0xffff))" + status="$(( (16#$raw_cmd >> 16) & 0xffff ))" + fi + + # BARs from the kernel resource file: base, size, and flags are already + # decoded by Linux, so they are a Linux-observed fact. + local bars="[]" + local index line start end flags size kind prefetch is64 + for index in 0 1 2 3 4 5; do + line="$(read_resource_line "$dir" "$index" || true)" + [[ -n "$line" ]] || continue + read -r start end flags <<< "$line" + if [[ "$end" == "0x0000000000000000" ]]; then + continue + fi + start=$((start)); end=$((end)); flags=$((flags)) + size=$((end - start + 1)) + kind="memory"; prefetch=false; is64=false + if (( flags & 0x100 )); then kind="io"; fi + if (( flags & 0x2000 )); then prefetch=true; fi + if (( flags & 0x100000 )); then is64=true; fi + bars="$(jq -c --argjson i "$index" --argjson base "$start" --arg base_hex "$(printf '0x%x' "$start")" \ + --argjson size "$size" --arg kind "$kind" --argjson prefetch "$prefetch" --argjson is64 "$is64" \ + '. + [{index:$i, base:$base, base_hex:$base_hex, size:$size, kind:$kind, prefetchable:$prefetch, is_64_bit:$is64}]' <<<"$bars")" + done + + local pcie="null" msi="null" msix="null" + if [[ -n "$CAP_PCIE" ]]; then + local cap lc ls dev_caps max_speed max_width cur_speed cur_width dtype + dev_caps="$(cfg_u32 "$((CAP_PCIE + 4))")" + cap="$(cfg_u16 "$((CAP_PCIE + 2))")" + dtype=$(( (cap >> 4) & 0x0f )) + lc="$(cfg_u32 "$((CAP_PCIE + 0x0c))")" + ls="$(cfg_u16 "$((CAP_PCIE + 0x12))")" + max_speed=$((lc & 0x0f)); max_width=$(( (lc >> 4) & 0x3f )) + cur_speed=$((ls & 0x0f)); cur_width=$(( (ls >> 4) & 0x3f )) + pcie="$(jq -n --argjson ver "$((cap & 0x0f))" --argjson dtype "$dtype" \ + --argjson max_payload "$((128 << (dev_caps & 7)))" \ + --arg max_speed "$(speed_name "$max_speed")" --argjson max_width "$max_width" \ + --arg cur_speed "$(speed_name "$cur_speed")" --argjson cur_width "$cur_width" \ + '{present:true, version:$ver, device_type:$dtype, max_payload_bytes:$max_payload, + max_speed:$max_speed, max_width:$max_width, current_speed:$cur_speed, current_width:$cur_width}')" + fi + if [[ -n "$CAP_MSI" ]]; then + local mc + mc="$(cfg_u16 "$((CAP_MSI + 2))")" + msi="$(jq -n --argjson enabled "$(( (mc & 1) != 0 ))" --argjson is64 "$(( (mc & 0x80) != 0 ))" \ + --argjson maskable "$(( (mc & 0x100) != 0 ))" \ + --argjson capable "$(( 1 << ((mc >> 1) & 7) ))" \ + '{present:true, enabled:$enabled, is_64_bit:$is64, maskable:$maskable, capable_vectors:$capable}')" + fi + if [[ -n "$CAP_MSIX" ]]; then + local mc table pba + mc="$(cfg_u16 "$((CAP_MSIX + 2))")" + table="$(cfg_u32 "$((CAP_MSIX + 4))")" + pba="$(cfg_u32 "$((CAP_MSIX + 8))")" + msix="$(jq -n --argjson enabled "$(( (mc & 0x8000) != 0 ))" \ + --argjson masked "$(( (mc & 0x4000) != 0 ))" --argjson vectors "$(( (mc & 0x7ff) + 1 ))" \ + --argjson bir "$((table & 7))" --argjson toff "$((table & ~7))" \ + --argjson pbir "$((pba & 7))" --argjson poff "$((pba & ~7))" \ + '{present:true, enabled:$enabled, function_masked:$masked, vectors:$vectors, + table_bir:$bir, table_offset:$toff, pba_bir:$pbir, pba_offset:$poff}')" + fi + + local iommu_group="" numa="" driver="" firmware="" irq="" msi_count=0 + [[ -e "$dir/iommu_group" ]] && iommu_group="$(basename "$(readlink -f "$dir/iommu_group")")" + numa="$(read_attr "$dir" numa_node)" + [[ -e "$dir/driver" ]] && driver="$(basename "$(readlink -f "$dir/driver")")" + [[ -e "$dir/firmware_node" ]] && firmware="$(readlink -f "$dir/firmware_node")" + irq="$(read_attr "$dir" irq)" + if [[ -d "$dir/msi_irqs" ]]; then + msi_count="$(find "$dir/msi_irqs" -mindepth 1 -maxdepth 1 2>/dev/null | wc -l | tr -d ' ')" + fi + + local cur_link_speed max_link_speed cur_link_width max_link_width + cur_link_speed="$(read_attr "$dir" current_link_speed)" + max_link_speed="$(read_attr "$dir" max_link_speed)" + cur_link_width="$(read_attr "$dir" current_link_width)" + max_link_width="$(read_attr "$dir" max_link_width)" + + local cap_ids_json="[]" + if [[ -n "$CAP_IDS" ]]; then + local pair id off + for pair in $CAP_IDS; do + id="${pair%%:*}"; off="${pair#*:}" + cap_ids_json="$(jq -c --argjson id "$((16#$id))" --argjson off "$off" \ + '. + [{id:$id, offset:$off}]' <<<"$cap_ids_json")" + done + fi + + jq -n \ + --arg bdf "$bdf" --argjson domain "$domain" --argjson bus "$bus" \ + --argjson device "$device" --argjson function "$function" \ + --argjson vendor "$vendor_num" --argjson device_id "$device_num" \ + --arg vendor_hex "$vendor" --arg device_hex "$device_id" \ + --arg class "$class" --argjson revision "$revision_num" \ + --argjson sub_vendor "$sub_vendor_num" --argjson sub_device "$sub_device_num" \ + --argjson command "$command" --argjson status "$status" \ + --argjson bars "$bars" --arg cap_status "$CAP_STATUS" --argjson cap_ids "$cap_ids_json" \ + --argjson pcie "$pcie" --argjson msi "$msi" --argjson msix "$msix" \ + --argjson config_bytes "$(cfg_len)" \ + --argjson iommu_group "${iommu_group:-null}" --argjson numa "${numa:-null}" \ + --arg driver "$driver" --arg firmware "$firmware" --argjson irq "${irq:-null}" \ + --argjson msi_count "$msi_count" \ + --arg cur_link_speed "$cur_link_speed" --arg max_link_speed "$max_link_speed" \ + --arg cur_link_width "$cur_link_width" --arg max_link_width "$max_link_width" \ + 'def obs(v; s; m; li): {value:v, source:s, method:m, linux_interpreted:li, native_verified:false}; + def unk(r): {value:null, source:null, method:null, linux_interpreted:false, native_verified:false, state:"unknown", reason:r}; + { + bdf:$bdf, + vendor_hex:$vendor_hex, + device_hex:$device_hex, + location:{domain:$domain, bus:$bus, device:$device, function:$function, + source:"linux-sysfs", method:"sysfs device path", linux_interpreted:true}, + vendor_id:obs($vendor; "linux-sysfs"; "read vendor"; true), + device_id:obs($device_id; "linux-sysfs"; "read device"; true), + class:obs($class; "linux-sysfs"; "read class"; true), + revision:obs($revision; "linux-sysfs"; "read revision"; true), + subsystem_vendor_id:obs($sub_vendor; "linux-sysfs"; "read subsystem_vendor"; true), + subsystem_id:obs($sub_device; "linux-sysfs"; "read subsystem_device"; true), + command:obs($command; "linux-sysfs"; "raw config dword at 0x04"; false), + status:obs($status; "linux-sysfs"; "raw config dword at 0x04"; false), + bars:($bars | map(. + {source:"linux-sysfs", method:"read resource (kernel-sized)", linux_interpreted:true, native_verified:false})), + bar_size_note:"kernel resource size; native AIENOS has not independently decoded it", + capability_status:$cap_status, + capabilities:$cap_ids, + pcie:(if $pcie == null then unk($cap_status) else ($pcie + {source:"linux-sysfs", method:"raw config capability decode", linux_interpreted:false, native_verified:false}) end), + msi:(if $msi == null then unk($cap_status) else ($msi + {source:"linux-sysfs", method:"raw config capability decode", linux_interpreted:false, native_verified:false}) end), + msix:(if $msix == null then unk($cap_status) else ($msix + {source:"linux-sysfs", method:"raw config capability decode", linux_interpreted:false, native_verified:false}) end), + iommu_group:(if $iommu_group == null then unk("no iommu_group attribute") else {value:$iommu_group, source:"linux-sysfs", method:"readlink iommu_group", linux_interpreted:true, native_verified:false} end), + numa_node:(if $numa == null then unk("no numa_node attribute") else {value:$numa, source:"linux-sysfs", method:"read numa_node", linux_interpreted:true, native_verified:false} end), + driver:(if $driver == "" then unk("no driver bound") else {value:$driver, source:"linux-sysfs", method:"readlink driver", linux_interpreted:true, native_verified:false} end), + firmware_node:(if $firmware == "" then unk("no ACPI firmware node") else {value:$firmware, source:"linux-sysfs", method:"readlink firmware_node", linux_interpreted:true, native_verified:false} end), + irq:(if $irq == null then unk("no irq attribute") else {value:$irq, source:"linux-sysfs", method:"read irq", linux_interpreted:true, native_verified:false} end), + msi_irq_count:(if $msi_count == 0 then unk("no msi_irqs") else {value:$msi_count, source:"linux-sysfs", method:"count msi_irqs", linux_interpreted:true, native_verified:false} end), + current_link_speed:(if $cur_link_speed == "" then unk("not exposed") else {value:$cur_link_speed, source:"linux-sysfs", method:"read current_link_speed", linux_interpreted:true, native_verified:false} end), + max_link_speed:(if $max_link_speed == "" then unk("not exposed") else {value:$max_link_speed, source:"linux-sysfs", method:"read max_link_speed", linux_interpreted:true, native_verified:false} end), + current_link_width:(if $cur_link_width == "" then unk("not exposed") else {value:$cur_link_width, source:"linux-sysfs", method:"read current_link_width", linux_interpreted:true, native_verified:false} end), + max_link_width:(if $max_link_width == "" then unk("not exposed") else {value:$max_link_width, source:"linux-sysfs", method:"read max_link_width", linux_interpreted:true, native_verified:false} end), + config_bytes_read:$config_bytes + }' +} + +# --- firmware topology ----------------------------------------------------- + +acpi_presence() { + local dir="/sys/firmware/acpi/tables" + local table list="[]" + [[ -d "$dir" ]] || { printf '[]'; return; } + for table in MCFG IORT PPTT SPCR GTDT APIC DSDT TPM2 WSMT; do + if [[ -e "$dir/$table" ]]; then + local size digest + size="$(stat -c %s "$dir/$table" 2>/dev/null || printf 'null')" + digest="" + if [[ "$ALLOW_SUDO" == "1" ]]; then + digest="$(sudo -n sha256sum "$dir/$table" 2>/dev/null | awk '{print $1}' || true)" + fi + list="$(jq -c --arg name "$table" --argjson size "${size:-null}" --arg digest "$digest" \ + '. + [{name:$name, size_bytes:$size, sha256:(if $digest == "" then null else $digest end)}]' <<<"$list")" + fi + done + printf '%s' "$list" +} + +# Parse the MCFG base-address allocation entries: each maps a PCI segment to an +# ECAM base and a bus range. Requires a privileged read-only table copy. +mcfg_segments() { + local table="/sys/firmware/acpi/tables/MCFG" + if [[ "$ALLOW_SUDO" != "1" ]]; then + printf 'null'; return + fi + if [[ ! -e "$table" ]]; then + printf 'null'; return + fi + : > "$TMP_ACPI" + sudo -n dd if="$table" bs=1 status=none 2>/dev/null > "$TMP_ACPI" || { printf 'null'; return; } + local length + length="$(od -An -tu4 -j 4 -N 4 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + [[ -n "$length" ]] || { printf 'null'; return; } + local count=$(( (length - 44) / 16 )) + local entries="[]" i off + for (( i = 0; i < count; i++ )); do + off=$((44 + i * 16)) + local base_lo base_hi base segment start end + base_lo="$(od -An -tu4 -j "$off" -N 4 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + base_hi="$(od -An -tu4 -j "$((off + 4))" -N 4 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + segment="$(od -An -tu2 -j "$((off + 8))" -N 2 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + start="$(od -An -tu1 -j "$((off + 10))" -N 1 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + end="$(od -An -tu1 -j "$((off + 11))" -N 1 "$TMP_ACPI" 2>/dev/null | tr -d ' \n')" + base=$(( base_lo + base_hi * 4294967296 )) + entries="$(jq -c --argjson seg "$segment" --argjson base "$base" \ + --argjson start "$start" --argjson end "$end" \ + --arg base_hex "$(printf '0x%x' "$base")" \ + '. + [{segment:$seg, ecam_base:$base, ecam_base_hex:$base_hex, start_bus:$start, end_bus:$end}]' <<<"$entries")" + done + printf '%s' "$entries" +} + +bridge_topology() { + local list="[]" dir class + for dir in /sys/bus/pci/devices/*; do + [[ -r "$dir/class" ]] || continue + class="$(read_attr "$dir" class)" + case "$class" in + 0x0604*|0x0600*) ;; # PCI bridge, host bridge + *) continue ;; + esac + list="$(jq -c --arg bdf "$(basename "$dir")" --arg class "$class" \ + '. + [{bdf:$bdf, class:$class, source:"linux-sysfs", linux_interpreted:true}]' <<<"$list")" + done + jq -c 'sort_by(.bdf)' <<<"$list" +} + +gb10_devices() { + local list="[]" dir vendor device_id + for dir in /sys/bus/pci/devices/*; do + [[ -r "$dir/vendor" && -r "$dir/device" ]] || continue + vendor="$(read_attr "$dir" vendor)" + device_id="$(read_attr "$dir" device)" + if [[ "$vendor" == "$GB10_VENDOR" && "$device_id" == "$GB10_DEVICE" ]]; then + list="$(jq -c --argjson dev "$(device_profile "$dir")" '. + [$dev]' <<<"$list")" + fi + done + jq -c 'sort_by(.bdf)' <<<"$list" +} + +# --- assemble -------------------------------------------------------------- + +DEVICES="$(gb10_devices)" +DEVICE_COUNT="$(jq 'length' <<<"$DEVICES")" + +if [[ "$EMIT_TIMESTAMP" == "1" ]]; then + TIMESTAMP_FIELD="$GENERATED_AT" +else + TIMESTAMP_FIELD="" +fi + +GIT_COMMIT="" +if git -C "$(dirname "$0")/.." rev-parse HEAD >/dev/null 2>&1; then + GIT_COMMIT="$(git -C "$(dirname "$0")/.." rev-parse HEAD)" +fi + +PROFILE="$(jq -n \ + --arg schema "$SCHEMA" \ + --arg product "$(read_attr /sys/class/dmi/id product_name)" \ + --arg sys_vendor "$(read_attr /sys/class/dmi/id sys_vendor)" \ + --arg commit "$GIT_COMMIT" \ + --argjson sudo "$([[ "$ALLOW_SUDO" == "1" ]] && echo true || echo false)" \ + --arg timestamp "${TIMESTAMP_FIELD}" \ + --argjson cmdline_iommu "$(tr ' ' '\n' < /proc/cmdline 2>/dev/null | grep -i iommu | jq -Rsc 'split("\n") | map(select(length>0))' || printf '[]')" \ + --argjson devices "$DEVICES" \ + --argjson acpi "$(acpi_presence)" \ + --argjson mcfg "$(mcfg_segments)" \ + --argjson bridges "$(bridge_topology)" \ + '{ + schema:$schema, + generated_at_utc:(if $timestamp == "" then null else $timestamp end), + collector:{name:"scripts/gb10_profile.sh", git_commit:$commit, read_only:true, sudo_used:$sudo}, + platform:{product_name:$product, system_vendor:$sys_vendor, source:"linux-sysfs", linux_interpreted:true}, + machine_identity_note:"Linux-observed facts only; not a native AIENOS proof.", + iommu_kernel_parameters:$cmdline_iommu, + acpi_tables:$acpi, + mcfg_segments:$mcfg, + pci_bridge_topology:$bridges, + gb10_device_count:$devices|length, + gb10_devices:$devices + }' | jq -S '.')" + +printf '%s' "$PROFILE" > "$TMP_PROFILE" +if [[ "$JSON_OUT" == "-" ]]; then + printf '%s\n' "$PROFILE" +else + printf '%s\n' "$PROFILE" > "$JSON_OUT" +fi + +{ + echo "# GB10 read-only hardware characterization (Linux-observed)" + echo + echo "schema: $SCHEMA" + echo "collector commit: ${GIT_COMMIT:-unknown}" + echo "sudo used for read-only config/ACPI: $([[ "$ALLOW_SUDO" == "1" ]] && echo yes || echo no)" + echo "GB10 devices found: $DEVICE_COUNT" + echo + if [[ "$DEVICE_COUNT" == "0" ]]; then + echo "No NVIDIA 10de:2e12 device is present in /sys/bus/pci/devices." + else + jq -r '.gb10_devices[] | + "## \(.bdf)", + " vendor:device \(.vendor_hex):\(.device_hex) class \(.class.value)", + " location domain=\(.location.domain) bus=\(.location.bus) device=\(.location.device) function=\(.location.function)", + " iommu_group \(.iommu_group.value // "unknown")", + " driver \(.driver.value // "none")", + " numa_node \(.numa_node.value // "unknown")", + " firmware_node \(.firmware_node.value // "unknown")", + " pcie link current \(.current_link_speed.value // "?") x\(.current_link_width.value // "?") max \(.max_link_speed.value // "?") x\(.max_link_width.value // "?")", + " capability status \(.capability_status)", + " BARs:" , + ( .bars[] | " [\(.index)] \(.kind) base=\(.base_hex) size=\(.size) 64bit=\(.is_64_bit) prefetch=\(.prefetchable)" ), + ""' "$TMP_PROFILE" + fi + echo "The structured profile records source, method, whether Linux interpreted" + echo "the value, and whether AIENOS independently verified it. No observation" + echo "here is a native AIENOS proof, and none of it involved a GPU command." +} > "$REPORT_OUT" +rm -f "$TMP_PROFILE" ```