diff --git a/crates/stela-boot-core/src/amd_discovery.rs b/crates/stela-boot-core/src/amd_discovery.rs new file mode 100644 index 0000000000..9ebb287ecf --- /dev/null +++ b/crates/stela-boot-core/src/amd_discovery.rs @@ -0,0 +1,227 @@ +//! An AMD GPU's IP discovery table, which names the version of each of its +//! IP blocks, as amdgpu reads it at its probe (`amdgpu_discovery.c`). The +//! boot reads it before the GPU's reset so the firmware it gives amdgpu is +//! the files of those versions only. +//! +//! The table lies in the GPU's memory, 64 KiB below the top of its VRAM as +//! `RCC_CONFIG_MEMSIZE` gives it, or where the GPU's security processor +//! says in the driver scratch registers (`amdgpu_discovery_get_tmr_info`). +//! amdgpu reads it through the `MM_INDEX`/`MM_DATA` window, which needs no +//! mapping of the GPU's memory (`amdgpu_device_mm_access`). The checks here +//! are `amdgpu_discovery_init`'s; the walk is +//! `amdgpu_discovery_reg_base_init`'s. +use alloc::vec::Vec; + +/// Registers, as byte offsets in the register BAR (`amdgpu_discovery.c`: +/// "consistent across all the SOCs"). +pub const MM_INDEX: usize = 0; +pub const MM_DATA: usize = 4; +pub const MM_INDEX_HI: usize = 0x6 * 4; +pub const DRIVER_SCRATCH_0: usize = 0x94 * 4; +pub const DRIVER_SCRATCH_1: usize = 0x95 * 4; +pub const DRIVER_SCRATCH_2: usize = 0x96 * 4; +pub const RCC_CONFIG_MEMSIZE: usize = 0xde3 * 4; +pub const MP0_SMN_C2PMSG_33: usize = 0x16061 * 4; +/// The register window the read needs. +pub const REGISTER_BYTES: usize = MP0_SMN_C2PMSG_33 + 4; +/// `C2PMSG_33` bit 31: the GPU's firmware finished its start and placed the +/// table. +pub const FIRMWARE_READY: u32 = 1 << 31; + +/// `DISCOVERY_TMR_SIZE` and `DISCOVERY_TMR_OFFSET`. +pub const TABLE_BYTES: usize = 10 << 10; +pub const BELOW_TOP: u64 = 64 << 10; +/// The most a scratch-register size may ask to read. +const MOST_BYTES: usize = 64 << 10; + +pub const BINARY_SIGNATURE: u32 = 0x2821_1407; +const DISCOVERY_TABLE_SIGNATURE: u32 = 0x5344_4950; + +/// The hardware IDs of the blocks whose firmware amdgpu names after their +/// versions (`soc15_hw_ip.h`). +pub const MP1: u16 = 1; +pub const GC: u16 = 11; +pub const VCN: u16 = 12; +pub const VPE: u16 = 21; +pub const SDMA0: u16 = 42; +pub const DMU: u16 = 271; +pub const MP0: u16 = 255; +/// `HW_ID_MAX` and `HWIP_MAX_INSTANCE`: entries past these are skipped. +const HW_ID_MAX: u16 = 300; +const MAX_INSTANCE: u8 = 44; + +/// One IP block as the table lists it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Ip { + pub hw_id: u16, + pub instance: u8, + pub major: u8, + pub minor: u8, + pub revision: u8, +} + +/// Why the table was not read or not taken. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + /// `RCC_CONFIG_MEMSIZE` reads all ones: the GPU does not answer. + NoAnswer, + /// The GPU's firmware has not placed the table yet (`C2PMSG_33`). + NotReady, + /// The table is in system memory (no VRAM size and no scratch place), + /// where amdgpu finds it through ACPI. + InSystemMemory, + Signature, + Checksum, + Version(u16), + TableSignature, + TableChecksum, + Truncated, + DieId, +} + +/// Where to read the table: the VRAM offset and length. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Place { + pub offset: u64, + pub bytes: usize, +} + +/// Where the table lies, as `amdgpu_discovery_get_tmr_info` finds it on a +/// GPU that is no virtual function: `read` reads a register of the +/// register BAR, `signature_at` the dword at a VRAM offset. +pub fn place( + mut read: impl FnMut(usize) -> u32, + mut signature_at: impl FnMut(u64) -> u32, +) -> Result { + if read(MP0_SMN_C2PMSG_33) & FIRMWARE_READY == 0 { + return Err(Error::NotReady); + } + let vram_mib = read(RCC_CONFIG_MEMSIZE); + if vram_mib == u32::MAX { + return Err(Error::NoAnswer); + } + if vram_mib != 0 { + let offset = (u64::from(vram_mib) << 20).saturating_sub(BELOW_TOP); + if signature_at(offset) == BINARY_SIGNATURE { + return Ok(Place { + offset, + bytes: TABLE_BYTES, + }); + } + } + let size = read(DRIVER_SCRATCH_2); + if size != 0 { + return Ok(Place { + offset: u64::from(read(DRIVER_SCRATCH_1)) << 32 | u64::from(read(DRIVER_SCRATCH_0)), + bytes: (size as usize).min(MOST_BYTES), + }); + } + if vram_mib == 0 { + return Err(Error::InSystemMemory); + } + Ok(Place { + offset: (u64::from(vram_mib) << 20).saturating_sub(BELOW_TOP), + bytes: TABLE_BYTES, + }) +} + +fn u16_at(bytes: &[u8], at: usize) -> Result { + bytes + .get(at..at + 2) + .map(|word| u16::from_le_bytes([word[0], word[1]])) + .ok_or(Error::Truncated) +} + +fn u32_at(bytes: &[u8], at: usize) -> Result { + bytes + .get(at..at + 4) + .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + .ok_or(Error::Truncated) +} + +fn sum(bytes: &[u8]) -> u16 { + bytes + .iter() + .fold(0u16, |sum, &byte| sum.wrapping_add(u16::from(byte))) +} + +/// The IP blocks the table `binary` lists, with its binary and data table +/// checked as amdgpu checks them. VCN's revision loses its two capability +/// bits, as amdgpu masks them. +pub fn parse(binary: &[u8]) -> Result, Error> { + if u32_at(binary, 0)? != BINARY_SIGNATURE { + return Err(Error::Signature); + } + // The byte sum of the binary after its checksum field, to its size. + let checksum = u16_at(binary, 8)?; + let size = usize::from(u16_at(binary, 10)?); + let body = binary.get(10..size.max(10)).ok_or(Error::Truncated)?; + if sum(body) != checksum { + return Err(Error::Checksum); + } + // The IP discovery table's entry: version 0 and 1 list tables from 12, + // version 2 after a count and padding. + let entry = match u16_at(binary, 4)? { + 0 | 1 => 12, + 2 => 16, + version => return Err(Error::Version(version)), + }; + let offset = usize::from(u16_at(binary, entry)?); + let table_checksum = u16_at(binary, entry + 2)?; + if u32_at(binary, offset)? != DISCOVERY_TABLE_SIGNATURE { + return Err(Error::TableSignature); + } + let table_bytes = usize::from(u16_at(binary, offset + 6)?); + let table = binary + .get(offset..offset + table_bytes) + .ok_or(Error::Truncated)?; + if sum(table) != table_checksum { + return Err(Error::TableChecksum); + } + let version = u16_at(binary, offset + 4)?; + let dies = usize::from(u16_at(binary, offset + 12)?).min(16); + // After the 16 die entries, version 4's flag byte: 64-bit base + // addresses. + let wide = version == 4 && binary.get(offset + 14 + 16 * 4).ok_or(Error::Truncated)? & 1 != 0; + let mut ips = Vec::new(); + for die in 0..dies { + let die_offset = usize::from(u16_at(binary, offset + 14 + die * 4 + 2)?); + if usize::from(u16_at(binary, die_offset)?) != die { + return Err(Error::DieId); + } + let count = u16_at(binary, die_offset + 2)?; + let mut at = die_offset + 4; + for _ in 0..count { + let entry = binary.get(at..at + 8).ok_or(Error::Truncated)?; + let hw_id = u16::from_le_bytes([entry[0], entry[1]]); + let instance = entry[2]; + let bases = usize::from(entry[3]); + let mut revision = entry[6]; + if hw_id == VCN { + revision &= !0xc0; + } + if hw_id < HW_ID_MAX && instance < MAX_INSTANCE { + ips.push(Ip { + hw_id, + instance, + major: entry[4], + minor: entry[5], + revision, + }); + } + at += 8 + bases * if wide { 8 } else { 4 }; + } + } + Ok(ips) +} + +/// The version of the first instance of `hw_id`, if the table lists it. +pub fn version(ips: &[Ip], hw_id: u16) -> Option<(u8, u8, u8)> { + ips.iter() + .filter(|ip| ip.hw_id == hw_id) + .min_by_key(|ip| ip.instance) + .map(|ip| (ip.major, ip.minor, ip.revision)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-boot-core/src/amd_discovery/tests.rs b/crates/stela-boot-core/src/amd_discovery/tests.rs new file mode 100644 index 0000000000..65a485af05 --- /dev/null +++ b/crates/stela-boot-core/src/amd_discovery/tests.rs @@ -0,0 +1,130 @@ +use super::*; +use alloc::{vec, vec::Vec}; + +/// A version 1 binary whose one die lists `ips` (hw_id, major, minor, +/// revision), each with one base address, in an IP discovery table of +/// version `table_version`. +pub(crate) fn binary(ips: &[(u16, u8, u8, u8)], table_version: u16) -> Vec { + const TABLE: usize = 64; + const DIE: usize = TABLE + 80; + let mut bytes = vec![0u8; DIE + 4 + ips.len() * 12]; + let put16 = |bytes: &mut Vec, at: usize, value: u16| { + bytes[at..at + 2].copy_from_slice(&value.to_le_bytes()) + }; + let put32 = |bytes: &mut Vec, at: usize, value: u32| { + bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()) + }; + put32(&mut bytes, 0, BINARY_SIGNATURE); + put16(&mut bytes, 4, 1); + let total = bytes.len(); + put16(&mut bytes, 10, total as u16); + put16(&mut bytes, 12, TABLE as u16); + put32(&mut bytes, TABLE, DISCOVERY_TABLE_SIGNATURE); + put16(&mut bytes, TABLE + 4, table_version); + put16(&mut bytes, TABLE + 6, (total - TABLE) as u16); + put16(&mut bytes, TABLE + 12, 1); + put16(&mut bytes, TABLE + 16, DIE as u16); + put16(&mut bytes, DIE + 2, ips.len() as u16); + for (index, &(hw_id, major, minor, revision)) in ips.iter().enumerate() { + let at = DIE + 4 + index * 12; + put16(&mut bytes, at, hw_id); + bytes[at + 3] = 1; + bytes[at + 4] = major; + bytes[at + 5] = minor; + bytes[at + 6] = revision; + put32(&mut bytes, at + 8, 0x1234); + } + let table = sum(&bytes[TABLE..]); + put16(&mut bytes, 14, table); + let binary = sum(&bytes[10..]); + put16(&mut bytes, 8, binary); + bytes +} + +/// Raphael's blocks: Ryzen 7000's graphics. +pub(crate) const RAPHAEL: &[(u16, u8, u8, u8)] = &[ + (GC, 10, 3, 6), + (MP0, 13, 0, 5), + (MP1, 13, 0, 5), + (SDMA0, 5, 2, 6), + (VCN, 3, 1, 2), + (DMU, 3, 1, 5), +]; + +#[test] +fn the_table_lists_each_block_with_its_version() { + let ips = parse(&binary(RAPHAEL, 3)).unwrap(); + assert_eq!(ips.len(), RAPHAEL.len()); + assert_eq!(version(&ips, GC), Some((10, 3, 6))); + assert_eq!(version(&ips, DMU), Some((3, 1, 5))); + assert_eq!(version(&ips, VPE), None); + // VCN's capability bits are not its revision. + let ips = parse(&binary(&[(VCN, 4, 0, 0x85)], 3)).unwrap(); + assert_eq!(version(&ips, VCN), Some((4, 0, 5))); +} + +#[test] +fn a_damaged_table_is_refused() { + let good = binary(RAPHAEL, 3); + let mut bad = good.clone(); + bad[0] ^= 1; + assert_eq!(parse(&bad), Err(Error::Signature)); + let mut bad = good.clone(); + let last = bad.len() - 1; + bad[last] ^= 1; + assert_eq!(parse(&bad), Err(Error::Checksum)); + assert_eq!(parse(&good[..40]), Err(Error::Truncated)); +} + +#[test] +fn the_table_is_found_where_amdgpu_looks() { + let registers = |memsize: u32, scratch: [u32; 3], ready: bool| { + move |offset: usize| match offset { + MP0_SMN_C2PMSG_33 => { + if ready { + FIRMWARE_READY + } else { + 0 + } + } + RCC_CONFIG_MEMSIZE => memsize, + DRIVER_SCRATCH_0 => scratch[0], + DRIVER_SCRATCH_1 => scratch[1], + DRIVER_SCRATCH_2 => scratch[2], + _ => 0, + } + }; + // 8 GiB of VRAM with the table at its usual place. + let top = (8192u64 << 20) - BELOW_TOP; + assert_eq!( + place(registers(8192, [0; 3], true), |at| if at == top { + BINARY_SIGNATURE + } else { + 0 + }), + Ok(Place { + offset: top, + bytes: TABLE_BYTES + }) + ); + // Elsewhere, where the scratch registers say. + assert_eq!( + place(registers(8192, [0x1000, 1, 0x3000], true), |_| 0), + Ok(Place { + offset: 0x1_0000_1000, + bytes: 0x3000 + }) + ); + assert_eq!( + place(registers(8192, [0; 3], false), |_| 0), + Err(Error::NotReady) + ); + assert_eq!( + place(registers(0, [0; 3], true), |_| 0), + Err(Error::InSystemMemory) + ); + assert_eq!( + place(registers(u32::MAX, [0; 3], true), |_| 0), + Err(Error::NoAnswer) + ); +} diff --git a/crates/stela-boot-core/src/lib.rs b/crates/stela-boot-core/src/lib.rs index 1ad128c83f..70cc6123d5 100644 --- a/crates/stela-boot-core/src/lib.rs +++ b/crates/stela-boot-core/src/lib.rs @@ -10,6 +10,7 @@ pub use stela_contracts::Refusal; /// A refused request names the values that decided it. pub type Result = core::result::Result; +pub mod amd_discovery; pub mod aperture; #[cfg(target_arch = "x86_64")] pub mod apic; diff --git a/crates/stela-boot/src/engine/gpu.rs b/crates/stela-boot/src/engine/gpu.rs index ff318a5a90..2728d9e0f9 100644 --- a/crates/stela-boot/src/engine/gpu.rs +++ b/crates/stela-boot/src/engine/gpu.rs @@ -1284,6 +1284,7 @@ fn claim( isa_bridges, function, registers: ®isters, + register_bar: &resources[registers_at], }, catalog, )?; diff --git a/crates/stela-boot/src/engine/gpu/before.rs b/crates/stela-boot/src/engine/gpu/before.rs index 231cd93f02..2cc3e55713 100644 --- a/crates/stela-boot/src/engine/gpu/before.rs +++ b/crates/stela-boot/src/engine/gpu/before.rs @@ -49,6 +49,8 @@ pub(super) struct Observed<'a> { pub(super) function: &'a mut Function, /// The first page of the stack's register BAR, mapped read-only. pub(super) registers: &'a Mapping, + /// The stack's register BAR, for the reads a stack's part maps itself. + pub(super) register_bar: &'a owned::Resource, } /// One stack's part of the claim. @@ -118,17 +120,23 @@ static NOUVEAU: Before = Before { }; /// amdgpu: the files are those it may ask for on the PCI device ID's GPU, -/// as pinned: its family's for a device its table names, every file named -/// after an IP version for one it identifies by the device's own IP -/// discovery table. The driver loads every engine's firmware itself, so -/// nothing boots by itself after the reset and nothing waits here. +/// as pinned: its family's for a device its table names; for one it +/// identifies by the device's own IP discovery table, the files of the +/// block versions that table names, read here before the reset as amdgpu +/// reads it ([`ip_discovery`]), or every file named after an IP version +/// where it cannot be read. The driver loads every engine's firmware +/// itself, so nothing boots by itself after the reset and nothing waits +/// here. static AMDGPU: Before = Before { admits: |adapter, catalog| { - on_usb( - &amdgpu_files(adapter.device)?, - &format!("{:04x}", adapter.device), - catalog, - ) + use stela_loader::host_firmware::recipes::AmdGpu; + let files = amdgpu_files(adapter.device)?; + // A discovered GPU's files are known only from its table, which + // `identify` reads; it checks them there. + if AmdGpu::of(adapter.device) == AmdGpu::Discovered { + return Ok(()); + } + on_usb(&files, &format!("{:04x}", adapter.device), catalog) }, identify: |observed, catalog| { use stela_loader::host_firmware::recipes; @@ -138,8 +146,12 @@ static AMDGPU: Before = Before { .registers .read32(0) .map_err(ServiceError::Mapping)?; - let inventory = amdgpu_files(adapter.device)?; let name = format!("{:04x}", adapter.device); + let inventory = if recipes::AmdGpu::of(adapter.device) == recipes::AmdGpu::Discovered { + discovered_files(&observed)? + } else { + amdgpu_files(adapter.device)? + }; Ok(Identified { firmware: select_firmware(&inventory, &name, catalog, None)?, identity: None, @@ -312,6 +324,122 @@ fn amdgpu_files(device: u16) -> Result { Ok(inventory) } +/// The files amdgpu asks for on the AMD GPU it identifies by its IP +/// discovery table: those of the block versions the table names, else +/// every file named after an IP version, with a line saying which. +fn discovered_files(observed: &Observed<'_>) -> Result { + use stela_boot_core::amd_discovery::{self as discovery, Ip}; + use stela_loader::host_firmware::recipes::{self, DiscoveredIp}; + let address = observed.adapter.address; + let device = observed.adapter.device; + let ips = match ip_discovery(observed.services, observed.register_bar) { + Ok(ips) => ips, + Err(why) => { + output::arguments(format_args!( + "GPU {address}: its IP discovery table was not read before its reset ({why}); \ + its driver is given every firmware file named after an IP version\n" + )); + return amdgpu_files(device); + } + }; + let named: Vec = [ + ("GC", discovery::GC), + ("MP0", discovery::MP0), + ("MP1", discovery::MP1), + ("SDMA", discovery::SDMA0), + ("VCN", discovery::VCN), + ("VPE", discovery::VPE), + ("DCN", discovery::DMU), + ] + .iter() + .filter_map(|&(block, hw_id)| { + discovery::version(&ips, hw_id) + .map(|(major, minor, revision)| format!("{block} {major}.{minor}.{revision}")) + }) + .collect(); + output::arguments(format_args!( + "GPU {address}: its IP discovery table names {}; its driver is given those blocks' \ + firmware\n", + named.join(", ") + )); + let ips: Vec = ips + .iter() + .map( + |&Ip { + hw_id, + major, + minor, + revision, + .. + }| DiscoveredIp { + hw_id, + major, + minor, + revision, + }, + ) + .collect(); + let mut inventory = Inventory::default(); + recipes::require_amdgpu_discovered(&mut inventory, device, &ips) + .map_err(|_| ServiceError::Refused("the GPU's discovered firmware cannot be selected"))?; + Ok(inventory) +} + +/// The IP blocks of the AMD GPU whose register BAR is `registers`, from +/// its IP discovery table, read before the reset as amdgpu reads it at its +/// probe ([`stela_boot_core::amd_discovery`]): through the `MM_INDEX` and +/// `MM_DATA` registers, one dword at a time, whose index is put back after. +fn ip_discovery( + services: &dyn NativeServices, + registers: &owned::Resource, +) -> Result, String> { + use stela_boot_core::amd_discovery::{self as discovery, MM_DATA, MM_INDEX, MM_INDEX_HI}; + if (registers.physical_span().bytes() as usize) < discovery::REGISTER_BYTES { + return Err(String::from( + "its register BAR is smaller than amdgpu's discovery reads", + )); + } + let read = |offset| read_register(services, registers, offset).unwrap_or(u32::MAX); + let mut window = services + .authority() + .map_err(|error| format!("{error:?}"))? + .map( + registers.clone(), + 0, + PAGE as usize, + CacheAttribute::Uncached, + Protection::ReadWrite, + ) + .map_err(|error| format!("its index registers did not map ({error:?})"))?; + let index = (window.read32(MM_INDEX), window.read32(MM_INDEX_HI)); + let vram = |position: u64| -> u32 { + let read = window + .write32(MM_INDEX, position as u32 | 0x8000_0000) + .and_then(|()| window.write32(MM_INDEX_HI, (position >> 31) as u32)) + .and_then(|()| window.read32(MM_DATA)); + read.unwrap_or(u32::MAX) + }; + let result = discovery::place(read, &vram) + .map_err(|error| format!("{error:?}")) + .and_then(|place| { + let mut binary = Vec::new(); + binary + .try_reserve_exact(place.bytes) + .map_err(|_| String::from("no memory for the table"))?; + for at in (0..place.bytes as u64).step_by(4) { + binary.extend_from_slice(&vram(place.offset + at).to_le_bytes()); + } + discovery::parse(&binary).map_err(|error| format!("{error:?}")) + }); + if let (Ok(low), Ok(high)) = index { + let _ = window.write32(MM_INDEX, low); + let _ = window.write32(MM_INDEX_HI, high); + } + // SAFETY: the accesses above were this scoped mapping's only use. + unsafe { window.retire() }.map_err(|error| format!("{error:?}"))?; + result +} + /// The files xe and the display code ask for on the Intel GPU with PCI /// device ID `device`. fn xe_files(device: u16) -> Result { diff --git a/crates/stela-loader/src/host_firmware/recipes.rs b/crates/stela-loader/src/host_firmware/recipes.rs index 179eb2cdf8..30daca76af 100644 --- a/crates/stela-loader/src/host_firmware/recipes.rs +++ b/crates/stela-loader/src/host_firmware/recipes.rs @@ -1104,7 +1104,8 @@ pub const GSP: &[Recipe] = &[ mod amdgpu; pub use amdgpu::{ - AMDGPU, AmdGpu, UNPUBLISHED as AMDGPU_UNPUBLISHED, amd_gpu_family, require_amdgpu, + AMDGPU, AmdGpu, DiscoveredIp, UNPUBLISHED as AMDGPU_UNPUBLISHED, amd_gpu_family, + discovered_may_load, require_amdgpu, require_amdgpu_discovered, }; /// The Intel GPU files and their notices: linux-firmware 20261019, whose diff --git a/crates/stela-loader/src/host_firmware/recipes/amdgpu.rs b/crates/stela-loader/src/host_firmware/recipes/amdgpu.rs index fd5ca5ab73..a2d925c0e1 100644 --- a/crates/stela-loader/src/host_firmware/recipes/amdgpu.rs +++ b/crates/stela-loader/src/host_firmware/recipes/amdgpu.rs @@ -190,6 +190,113 @@ fn versioned(name: &str) -> bool { #[cfg(test)] mod tests; +/// One IP block as the device's IP discovery table lists it: its hardware +/// ID (`soc15_hw_ip.h`) and version. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct DiscoveredIp { + pub hw_id: u16, + pub major: u8, + pub minor: u8, + pub revision: u8, +} + +/// Each block of [`IP_BLOCKS`] named after one block's version, with that +/// block's hardware ID: graphics (GC), the security processor (MP0), power +/// management (MP1), DMA (SDMA0), video (VCN), video processing (VPE) and +/// the display microcontroller (DMU, `amdgpu_dm.c`'s DCN version). +const BLOCK_IPS: &[(&str, u16)] = &[ + ("gc", 11), + ("psp", 255), + ("smu", 1), + ("sdma", 42), + ("vcn", 12), + ("vpe", 21), + ("dcn", 271), +]; + +/// The media scheduler's file, which `amdgpu_umsch_mm.c` loads for VCN +/// 4.0.5 and 4.0.6. +const UMSCH: (&str, u16, &[(u8, u8, u8)]) = ("umsch_mm_4_0_0", 12, &[(4, 0, 5), (4, 0, 6)]); + +/// The families only discovery reaches, with the graphics version +/// amdgpu's discovery gives that family by (`amdgpu_discovery.c`: +/// GC 10.3.1 is `CHIP_VANGOGH`), whose files then carry its name +/// (`amdgpu_ucode_legacy_naming`). +const DISCOVERED_CHIPS: &[(&str, (u8, u8, u8))] = &[("VANGOGH", (10, 3, 1))]; + +/// The version a file named after a block's version carries: up to three +/// numbers after `_`, a missing revision being 0 +/// (`dcn_3_5_dmcub.bin` is DCN 3.5.0's). +fn file_version(rest: &str) -> Option<(u8, u8, u8)> { + let rest = rest.strip_suffix(".bin").unwrap_or(rest); + let mut numbers = rest.split('_').map_while(|token| token.parse::().ok()); + let major = numbers.next()?; + let minor = numbers.next()?; + Some((major, minor, numbers.next().unwrap_or(0))) +} + +/// Whether amdgpu asks a device whose discovery table lists `ips` for +/// `member`: a file named after a block's version when the table lists +/// that block at that version, the media scheduler's for its VCN versions, +/// and a discovery-only family's files when its graphics version is the +/// table's. +pub fn discovered_may_load(ips: &[DiscoveredIp], member: &str) -> bool { + let Some(name) = member.strip_prefix("amdgpu/") else { + return false; + }; + let listed = |hw_id: u16, version: (u8, u8, u8)| { + ips.iter() + .any(|ip| ip.hw_id == hw_id && (ip.major, ip.minor, ip.revision) == version) + }; + let (umsch, umsch_ip, umsch_versions) = UMSCH; + if named(name, umsch) { + return umsch_versions + .iter() + .any(|&version| listed(umsch_ip, version)); + } + for &(block, hw_id) in BLOCK_IPS { + if let Some(rest) = name + .strip_prefix(block) + .and_then(|rest| rest.strip_prefix('_')) + && let Some(version) = file_version(rest) + { + return listed(hw_id, version); + } + } + DISCOVERED_CHIPS.iter().any(|&(chip, graphics)| { + listed(11, graphics) + && CHIPS + .iter() + .find(|(known, _)| *known == chip) + .is_some_and(|(_, stems)| stems.iter().any(|stem| named(name, stem))) + }) +} + +/// Requires the files amdgpu asks for on the AMD GPU with PCI device ID +/// `device` whose IP discovery table lists `ips`: [`require_amdgpu`] for a +/// device its table names, which loads its family's files whatever its +/// discovery table says, else those of [`discovered_may_load`]. +pub fn require_amdgpu_discovered( + inventory: &mut Inventory, + device: u16, + ips: &[DiscoveredIp], +) -> Result<(), Error> { + if AmdGpu::of(device) != AmdGpu::Discovered { + return require_amdgpu(inventory, device); + } + for recipe in AMDGPU + .iter() + .filter(|recipe| discovered_may_load(ips, recipe.image.member)) + { + inventory.observe(Requirement { + name: recipe.image.member, + target: TARGET, + minimum_bytes: 1, + })?; + } + Ok(()) +} + /// The binding amdgpu's files take: Linux's names, as for nouveau's. const TARGET: Target<'static> = Target { driver: "amdgpu", diff --git a/crates/stela-loader/src/host_firmware/recipes/amdgpu/tests.rs b/crates/stela-loader/src/host_firmware/recipes/amdgpu/tests.rs index 34eef643cd..f8ece421c2 100644 --- a/crates/stela-loader/src/host_firmware/recipes/amdgpu/tests.rs +++ b/crates/stela-loader/src/host_firmware/recipes/amdgpu/tests.rs @@ -452,3 +452,120 @@ fn every_legacy_name_is_a_familys() { ); } } + +/// The files a discovered device with these blocks gets. +fn discovered(ips: &[(u16, u8, u8, u8)]) -> Vec<&'static str> { + let ips: Vec = ips + .iter() + .map(|&(hw_id, major, minor, revision)| DiscoveredIp { + hw_id, + major, + minor, + revision, + }) + .collect(); + AMDGPU + .iter() + .map(|recipe| recipe.image.member) + .filter(|member| discovered_may_load(&ips, member)) + .collect() +} + +#[test] +fn a_discovered_device_gets_only_its_blocks_versions_files() { + // Raphael: GC 10.3.6, PSP and SMU 13.0.5, SDMA 5.2.6, VCN 3.1.2, + // DCN 3.1.5. + let raphael = discovered(&[ + (11, 10, 3, 6), + (255, 13, 0, 5), + (1, 13, 0, 5), + (42, 5, 2, 6), + (12, 3, 1, 2), + (271, 3, 1, 5), + ]); + for member in [ + "amdgpu/gc_10_3_6_pfp.bin", + "amdgpu/gc_10_3_6_rlc.bin", + "amdgpu/psp_13_0_5_toc.bin", + "amdgpu/sdma_5_2_6.bin", + "amdgpu/vcn_3_1_2.bin", + "amdgpu/dcn_3_1_5_dmcub.bin", + ] { + assert!(raphael.contains(&member), "{member}"); + } + assert!( + raphael.iter().all(|member| { + [ + "gc_10_3_6_", + "psp_13_0_5_", + "smu_13_0_5", + "sdma_5_2_6", + "vcn_3_1_2", + "dcn_3_1_5_", + ] + .iter() + .any(|prefix| member["amdgpu/".len()..].starts_with(prefix)) + }), + "{raphael:?}" + ); + // Strix Point: a two-number DCN name, VPE and the media scheduler. + let strix = discovered(&[ + (11, 11, 5, 0), + (255, 14, 0, 0), + (42, 6, 1, 0), + (12, 4, 0, 5), + (21, 6, 1, 0), + (271, 3, 5, 0), + ]); + for member in [ + "amdgpu/gc_11_5_0_me.bin", + "amdgpu/psp_14_0_0_toc.bin", + "amdgpu/sdma_6_1_0.bin", + "amdgpu/vcn_4_0_5.bin", + "amdgpu/vpe_6_1_0.bin", + "amdgpu/dcn_3_5_dmcub.bin", + "amdgpu/umsch_mm_4_0_0.bin", + ] { + assert!(strix.contains(&member), "{member}"); + } + assert!(!strix.contains(&"amdgpu/dcn_3_5_1_dmcub.bin")); + assert!(!strix.iter().any(|member| member.contains("vangogh"))); + // Van Gogh's files by its graphics version. + let vangogh = discovered(&[(11, 10, 3, 1), (255, 11, 5, 0)]); + assert!(vangogh.contains(&"amdgpu/vangogh_pfp.bin")); + // A few files, against the superset of every IP-versioned file. + assert!(raphael.len() < 30 && strix.len() < 40); + assert!(names(AmdGpu::Discovered).len() > 150); +} + +#[test] +fn every_discovered_file_is_attributed_to_a_block_or_a_family() { + // Each file the superset holds is one some discovery table selects, so + // narrowing drops none a device could ask for. + for member in names(AmdGpu::Discovered) { + let name = &member["amdgpu/".len()..]; + let attributed = BLOCK_IPS.iter().any(|(block, _)| { + name.strip_prefix(block) + .and_then(|rest| rest.strip_prefix('_')) + .and_then(file_version) + .is_some() + }) || named(name, UMSCH.0) + || DISCOVERED_CHIPS.iter().any(|(chip, _)| { + CHIPS + .iter() + .find(|(known, _)| known == chip) + .is_some_and(|(_, stems)| stems.iter().any(|stem| named(name, stem))) + }); + assert!(attributed, "{member}"); + } + // Every family only discovery reaches has its graphics version here. + for (chip, _) in CHIPS + .iter() + .filter(|(chip, _)| !DEVICES.iter().any(|(_, named)| named == chip)) + { + assert!( + DISCOVERED_CHIPS.iter().any(|(known, _)| known == chip), + "{chip}" + ); + } +}