feat(gpu): integrate sealed native compiler and resource cuts
This commit is contained in:
1 parent
149c571944
commit
5cf18d3cbb
277 files changed
+37047
-4181
No files matched your search
Generated
+7
@@ -1622,6 +1622,13 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stela-metal-input"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stela-runtime"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -4,6 +4,7 @@ members = [
|
||||
"crates/stela-loader",
|
||||
"crates/stela-compiler",
|
||||
"crates/stela-drivers",
|
||||
"crates/stela-drivers/src/gpu/metal/input",
|
||||
"crates/stela-runtime",
|
||||
"xtask",
|
||||
]
|
||||
|
||||
@@ -6,11 +6,6 @@ edition.workspace = true
|
||||
# GPL/ISC notices and the Intel shared initialization also retains BSD terms.
|
||||
license = "MIT AND BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND BSD-3-Clause-Clear AND ISC"
|
||||
|
||||
[dependencies]
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
# Fallible native mapping metadata; the maintained owner supports alloc-only UEFI.
|
||||
triomphe = { version = "=0.1.16", default-features = false }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -23,13 +18,32 @@ ram-disk = []
|
||||
nvidia-port = ["dep:cc"]
|
||||
# Native Xe command/page-table support; not an initialized Intel GPU driver.
|
||||
intel-port = ["dep:cc"]
|
||||
# Native CPU page-entry updates; requires the real GPU mapping/GMC owner.
|
||||
# Native AMD page-entry and BAR support; requires real mapping/GMC owners.
|
||||
amd-port = ["dep:cc"]
|
||||
# Hosted AMD encoder build; its C runtime is not yet ported to UEFI.
|
||||
amd-commands = []
|
||||
# Shared Metal library input validation, independent of a physical GPU backend.
|
||||
metal = []
|
||||
|
||||
[dependencies]
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
# Fallible native mapping metadata; the maintained owner supports alloc-only UEFI.
|
||||
triomphe = { version = "=0.1.16", default-features = false }
|
||||
|
||||
[build-dependencies]
|
||||
cc = { version = "1", optional = true }
|
||||
|
||||
[[test]]
|
||||
name = "nvidia_mmio"
|
||||
path = "src/gpu/nvidia/stela/tests/mmio.rs"
|
||||
required-features = ["nvidia-port"]
|
||||
|
||||
[[test]]
|
||||
name = "amd_native_mmio"
|
||||
path = "src/gpu/amd/tests/native_mmio.rs"
|
||||
required-features = ["amd-port"]
|
||||
|
||||
[[test]]
|
||||
name = "intel_activation"
|
||||
path = "src/gpu/intel/stela/tests/activation.rs"
|
||||
required-features = ["intel-port"]
|
||||
@@ -20,7 +20,31 @@ fn main() {
|
||||
#[cfg(feature = "amd-port")]
|
||||
{
|
||||
let mut build = native::configure();
|
||||
build.file("src/gpu/amd/stela/vm_cpu.c").std("c11");
|
||||
build
|
||||
.file("src/gpu/amd/stela/vm_cpu.c")
|
||||
.file("src/gpu/amd/stela/native_bar.c")
|
||||
.file("src/gpu/amd/stela/discovery_binary.c")
|
||||
.file("src/gpu/amd/stela/discovery_file.c")
|
||||
.file("src/gpu/amd/stela/discovery_tmr.c")
|
||||
.file("src/gpu/amd/stela/vram_mm.c")
|
||||
.include("src/gpu/common/linux/include")
|
||||
.std("c11");
|
||||
// Preserve the original IP walk's signed counter semantics locally.
|
||||
native::configure()
|
||||
.file("src/gpu/amd/stela/discovery_ip.c")
|
||||
.include("src/gpu/common/linux/include")
|
||||
.flag("-fwrapv")
|
||||
.std("c11")
|
||||
.compile("stela-amd-ip");
|
||||
// Only the original PCI table's shorthand initializers and ARRAY_SIZE
|
||||
// comparison need these warning exceptions; other native TUs keep them.
|
||||
native::configure()
|
||||
.file("src/gpu/amd/stela/pci_match.c")
|
||||
.include("src/gpu/common/linux/include")
|
||||
.flag("-Wno-missing-field-initializers")
|
||||
.flag("-Wno-sign-compare")
|
||||
.std("c11")
|
||||
.compile("stela-amd-pci");
|
||||
// Build the pure C ABI/original-value test helper separately. Only the
|
||||
// cfg(test) Rust link attribute selects it; production links the port.
|
||||
let mut model = native::configure();
|
||||
@@ -29,11 +53,44 @@ fn main() {
|
||||
.std("c11")
|
||||
.cargo_metadata(false)
|
||||
.compile("stela-amd-vm-test");
|
||||
// The donor model uses hosted assertions/stdio; production policy is
|
||||
// freestanding and builds above for both the host and UEFI targets.
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("uefi") {
|
||||
let mut bars = native::configure();
|
||||
bars.file("src/gpu/amd/tests/native_bar_test.c")
|
||||
.include("src/gpu/common/linux/include")
|
||||
.define("STELA_AMD_BAR_TEST_LIBRARY", None)
|
||||
.flag("-Wno-unused-function")
|
||||
.std("c11")
|
||||
.cargo_metadata(false)
|
||||
.compile("stela-amd-bar-test");
|
||||
}
|
||||
for path in [
|
||||
"src/gpu/amd/stela",
|
||||
"src/gpu/amd/amdgpu/amdgpu_vm_cpu_entries.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_gmc_pte.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_mm_access_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_ip_types.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_pci_match_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h",
|
||||
"src/gpu/amd/include/amd_chip_flags.h",
|
||||
"src/gpu/amd/include/asic_reg/bif/bif_4_1_d.h",
|
||||
"src/gpu/amd/tests/vm_ram_test.c",
|
||||
"src/gpu/amd/tests/native_bar_test.c",
|
||||
"src/gpu/common/linux/include/drm/amd_asic_type.h",
|
||||
"src/gpu/amd/include/discovery.h",
|
||||
"src/gpu/amd/include/soc15_hw_ip.h",
|
||||
"src/gpu/amd/amdgpu/amdgpu_ip_limits.h",
|
||||
"src/gpu/common/linux/include/uapi/linux/stddef.h",
|
||||
"src/gpu/common/linux/include/linux/device-id/pci.h",
|
||||
"src/gpu/common/linux/include/linux/pci_ids.h",
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={path}");
|
||||
}
|
||||
@@ -54,6 +111,26 @@ fn main() {
|
||||
#[cfg(feature = "nvidia-port")]
|
||||
fn nvidia() {
|
||||
let source = "src/gpu/nvidia";
|
||||
let version_mk = format!("{source}/version.mk");
|
||||
let version = std::fs::read_to_string(&version_mk).expect("read NVIDIA version.mk");
|
||||
let version = version
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("NVIDIA_VERSION = "))
|
||||
.expect("NVIDIA_VERSION in retained version.mk");
|
||||
assert!(
|
||||
version
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || byte == b'.')
|
||||
);
|
||||
let generated =
|
||||
std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("nvidia-include");
|
||||
std::fs::create_dir_all(&generated).expect("create NVIDIA generated include");
|
||||
std::fs::write(
|
||||
generated.join("version.h"),
|
||||
format!("#define NVIDIA_VERSION \"{version}\"\n"),
|
||||
)
|
||||
.expect("generate NVIDIA version.h");
|
||||
println!("cargo:rerun-if-changed={version_mk}");
|
||||
let mut build = native::configure();
|
||||
build
|
||||
.define("NV_STELA", None)
|
||||
@@ -61,15 +138,46 @@ fn nvidia() {
|
||||
.file(format!("{source}/stela/memory.c"))
|
||||
.file(format!("{source}/stela/stela_ram_mapping.c"))
|
||||
.file(format!("{source}/stela/stela_pages.c"))
|
||||
.file(format!("{source}/stela/stela_page_geometry.c"))
|
||||
.file(format!("{source}/stela/stela_ordering.c"))
|
||||
.file(format!("{source}/stela/stela_mmio.c"))
|
||||
.file(format!("{source}/stela/stela_firmware.c"))
|
||||
.file(format!("{source}/stela/stela_primitives.c"))
|
||||
.file(format!("{source}/stela/stela_nvlink_primitives.c"))
|
||||
.file(format!("{source}/stela/stela_nvswitch_primitives.c"))
|
||||
.file(format!("{source}/stela/stela_nvlink_memory.c"))
|
||||
.file(format!("{source}/stela/stela_nvkms_primitives.c"))
|
||||
.file(format!("{source}/stela/stela_nvkms_memory.c"))
|
||||
.include(&generated)
|
||||
.include(format!("{source}/stela"))
|
||||
.include(format!("{source}/src/common/sdk/nvidia/inc"))
|
||||
.include(format!("{source}/src/nvidia/arch/nvalloc/unix/include"))
|
||||
.include(format!("{source}/src/nvidia/arch/nvalloc/common/inc"))
|
||||
.include(format!("{source}/src/nvidia/inc/kernel"));
|
||||
.include(format!("{source}/src/nvidia/inc/kernel"))
|
||||
.include(format!("{source}/src/common/inc"))
|
||||
.include(format!("{source}/src/common/inc/swref"))
|
||||
.include(format!("{source}/src/common/uproc/os/common/include"))
|
||||
.include(format!("{source}/src/common/nvlink/interface"))
|
||||
.include(format!("{source}/src/common/unix/common/inc"))
|
||||
.include(format!("{source}/src/nvidia-modeset/os-interface/include"))
|
||||
.include(format!("{source}/src/nvidia-modeset/kapi/interface"))
|
||||
.include(format!("{source}/src/nvidia-modeset/interface"));
|
||||
println!("cargo:rerun-if-changed={source}/stela");
|
||||
println!("cargo:rerun-if-changed={source}/src/common/sdk/nvidia/inc");
|
||||
println!("cargo:rerun-if-changed={source}/src/nvidia/arch/nvalloc/unix/include");
|
||||
println!("cargo:rerun-if-changed={source}/src/nvidia/arch/nvalloc/common/inc");
|
||||
println!("cargo:rerun-if-changed={source}/src/nvidia/inc/kernel/os");
|
||||
println!("cargo:rerun-if-changed={source}/src/common/inc/nvctassert.h");
|
||||
println!("cargo:rerun-if-changed={source}/src/common/inc/swref/published/nv_arch.h");
|
||||
println!("cargo:rerun-if-changed={source}/src/common/uproc/os/common/include/libelf.h");
|
||||
for directory in [
|
||||
"src/common/nvlink/interface",
|
||||
"src/common/unix/common/inc",
|
||||
"src/nvidia-modeset/os-interface/include",
|
||||
"src/nvidia-modeset/kapi/interface",
|
||||
"src/nvidia-modeset/interface",
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={source}/{directory}");
|
||||
}
|
||||
build.compile("stela-nvidia-port");
|
||||
}
|
||||
@@ -8,10 +8,17 @@ pub fn configure(build: &mut cc::Build) {
|
||||
build
|
||||
.define("STELA_NATIVE", None)
|
||||
.include(format!("{source}/xe"))
|
||||
.include("src/gpu/common/linux/include")
|
||||
.file(format!("{source}/xe/xe_pt_walk.c"))
|
||||
.file(format!("{source}/stela/pt_walk.c"))
|
||||
.file(format!("{source}/stela/commands.c"))
|
||||
.file(format!("{source}/stela/ct.c"))
|
||||
.file(format!("{source}/stela/activation.c"))
|
||||
.file(format!("{source}/stela/guc_reset.c"))
|
||||
.file(format!("{source}/stela/firmware.c"))
|
||||
.file(format!("{source}/stela/wopcm.c"))
|
||||
.file(format!("{source}/stela/ggtt_probe.c"))
|
||||
.file(format!("{source}/stela/pat.c"))
|
||||
.file(format!("{source}/stela/i915_commands.c"));
|
||||
for path in [
|
||||
"stela",
|
||||
@@ -21,17 +28,166 @@ pub fn configure(build: &mut cc::Build) {
|
||||
"xe/xe_guc_ct_message.h",
|
||||
"xe/abi",
|
||||
"xe/regs/xe_guc_ct_regs.h",
|
||||
"xe/xe_pci_device_info.h",
|
||||
"xe/xe_pci_runtime.h",
|
||||
"xe/xe_pci_types.h",
|
||||
"xe/xe_platform_types.h",
|
||||
"xe/xe_engine_ids.h",
|
||||
"xe/xe_scalar_types.h",
|
||||
"xe/xe_gt_type.h",
|
||||
"xe/xe_cache_level.h",
|
||||
"xe/xe_pat.h",
|
||||
"xe/xe_pat_tables.h",
|
||||
"xe/xe_pat_select.h",
|
||||
"xe/xe_pat_program.h",
|
||||
"xe/xe_uc_fw_catalog.h",
|
||||
"xe/xe_uc_fw_css.h",
|
||||
"xe/xe_uc_fw_cpd.h",
|
||||
"xe/xe_uc_fw_types.h",
|
||||
"xe/xe_uc_fw_version.h",
|
||||
"xe/xe_wopcm_core.h",
|
||||
"xe/xe_wopcm_size.h",
|
||||
"xe/xe_ggtt_probe_core.h",
|
||||
"xe/regs/xe_gtt_defs.h",
|
||||
"xe/xe_wopcm_types.h",
|
||||
"xe/xe_mmio_verify.h",
|
||||
"xe/xe_huc_role.h",
|
||||
"xe/regs/xe_guc_regs.h",
|
||||
"xe/xe_force_wake_core.h",
|
||||
"xe/xe_force_wake_gt.h",
|
||||
"xe/xe_force_wake_domain_types.h",
|
||||
"xe/xe_mmio_poll.h",
|
||||
"xe/xe_guc_reset_core.h",
|
||||
"xe/xe_gen_wa_oob.c",
|
||||
"xe/xe_wa_oob.rules",
|
||||
"xe/regs/xe_gt_regs.h",
|
||||
"xe/regs/xe_regs.h",
|
||||
"xe/regs/xe_reg_defs.h",
|
||||
"xe/regs/xe_reg_type.h",
|
||||
"i915/gt/intel_gpu_commands.h",
|
||||
"i915/gt/intel_batch_emit.h",
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={source}/{path}");
|
||||
}
|
||||
println!("cargo:rerun-if-changed=src/gpu/common/linux/include/drm/intel/pciids.h");
|
||||
println!("cargo:rerun-if-changed=src/gpu/common/linux/include/vdso/align.h");
|
||||
println!("cargo:rerun-if-changed=src/gpu/common/linux/include/vdso/const.h");
|
||||
println!("cargo:rerun-if-env-changed=STELA_GPU_PYTHON");
|
||||
let output = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo supplies OUT_DIR"));
|
||||
let python = PathBuf::from(env::var_os("STELA_GPU_PYTHON").unwrap_or_else(|| "python3".into()));
|
||||
configure_ggtt(build, &output);
|
||||
configure_pat(build, &output);
|
||||
configure_guc_reset(build, &output);
|
||||
configure_dispatch(build, &output, &python);
|
||||
}
|
||||
|
||||
/// Use the unchanged original host generator and its complete rule input.
|
||||
/// The native reset TU verifies that this actual WA excludes its admitted GTs.
|
||||
fn configure_guc_reset(build: &mut cc::Build, output: &std::path::Path) {
|
||||
use std::{env, fs, process::Command};
|
||||
let source = "src/gpu/intel/xe";
|
||||
let output = output.join("intel-guc-reset");
|
||||
fs::create_dir_all(&output).expect("create GuC reset generation directory");
|
||||
let host = env::var("HOST").expect("Cargo supplies host triple");
|
||||
let generator = output.join(if host.contains("windows") {
|
||||
"xe_gen_wa_oob.exe"
|
||||
} else {
|
||||
"xe_gen_wa_oob"
|
||||
});
|
||||
let compiler = cc::Build::new()
|
||||
.host(&host)
|
||||
.target(&host)
|
||||
.cargo_metadata(false)
|
||||
.get_compiler();
|
||||
let result = compiler
|
||||
.to_command()
|
||||
.args(["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror"])
|
||||
.arg(format!("{source}/xe_gen_wa_oob.c"))
|
||||
.arg("-o")
|
||||
.arg(&generator)
|
||||
.output()
|
||||
.expect("compile original GuC WA generator");
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"original GuC WA generator compilation failed: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
let generated = output.join("xe_wa_oob.c");
|
||||
let result = Command::new(&generator)
|
||||
.arg(format!("{source}/xe_wa_oob.rules"))
|
||||
.arg(&generated)
|
||||
.arg(output.join("xe_wa_oob.h"))
|
||||
.output()
|
||||
.expect("run original GuC WA generator");
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"original GuC WA generation failed: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
let contents = fs::read_to_string(generated).expect("read original GuC WA output");
|
||||
let start = "{ XE_RTP_NAME(\"14025883347\"),";
|
||||
assert_eq!(
|
||||
contents.matches(start).count(),
|
||||
1,
|
||||
"changed original GuC reset WA entry"
|
||||
);
|
||||
let (_, entry) = contents.split_once(start).expect("original reset WA entry");
|
||||
let (entry, _) = entry
|
||||
.split_once(") },")
|
||||
.expect("original reset WA terminator");
|
||||
fs::write(
|
||||
output.join("guc_reset_wa.inc"),
|
||||
format!("{start}{entry}) }},\n"),
|
||||
)
|
||||
.expect("write original reset WA entry");
|
||||
build.include(output);
|
||||
}
|
||||
|
||||
/// Retain the original compile-time checks without importing Linux services.
|
||||
/// Address selection still uses the actual drm/intel/pick.h implementation.
|
||||
fn configure_pat(build: &mut cc::Build, output: &std::path::Path) {
|
||||
use std::fs;
|
||||
let compiler = "src/gpu/common/linux/include/linux/compiler.h";
|
||||
let bug = "src/gpu/common/linux/include/linux/build_bug.h";
|
||||
let source = fs::read_to_string(compiler).expect("read original compile-time definitions");
|
||||
let mut header = format!(
|
||||
"{}\n",
|
||||
source.lines().next().expect("original compiler license")
|
||||
);
|
||||
for (path, name, required) in [
|
||||
(compiler, "__BUILD_BUG_ON_ZERO_MSG", "_Static_assert"),
|
||||
(compiler, "__is_constexpr", ""),
|
||||
(bug, "BUILD_BUG_ON_ZERO", ""),
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={path}");
|
||||
let source = fs::read_to_string(path).expect("read original compile-time macro");
|
||||
let lines: Vec<_> = source.lines().collect();
|
||||
let prefix = format!("#define {name}(");
|
||||
let matches: Vec<_> = lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, line)| line.starts_with(&prefix) && line.contains(required))
|
||||
.collect();
|
||||
assert_eq!(matches.len(), 1, "changed original PAT macro {name}");
|
||||
let mut index = matches[0].0;
|
||||
loop {
|
||||
let line = lines.get(index).expect("unterminated original PAT macro");
|
||||
header.push_str(line);
|
||||
header.push('\n');
|
||||
if !line.trim_end().ends_with('\\') {
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
println!("cargo:rerun-if-changed=src/gpu/common/linux/include/drm/intel/pick.h");
|
||||
let output = output.join("intel-pat");
|
||||
fs::create_dir_all(&output).expect("create PAT compile-time output directory");
|
||||
fs::write(output.join("pat_compile_defs.h"), header)
|
||||
.expect("write original PAT compile-time macros");
|
||||
build.include(output);
|
||||
}
|
||||
|
||||
fn configure_dispatch(build: &mut cc::Build, output: &std::path::Path, python: &std::path::Path) {
|
||||
use std::{fs, process::Command};
|
||||
|
||||
@@ -82,3 +238,49 @@ fn configure_dispatch(build: &mut cc::Build, output: &std::path::Path, python: &
|
||||
println!("cargo:rerun-if-changed={genxml}");
|
||||
println!("cargo:rerun-if-changed=src/gpu/common/mesa/src/util/bitpack_uint.h");
|
||||
}
|
||||
|
||||
/// Copy only the nine original scalar definitions needed by the native probe.
|
||||
/// The full headers require Linux services; no hardware values are mirrored.
|
||||
fn configure_ggtt(build: &mut cc::Build, output: &std::path::Path) {
|
||||
use std::fs;
|
||||
let original = "src/gpu/common/linux/include/drm/intel/i915_drm.h";
|
||||
let drm = fs::read_to_string(original).expect("read original Intel GMCH definitions");
|
||||
let mut header = drm
|
||||
.split_once("#ifndef _I915_DRM_H_")
|
||||
.expect("original Intel header guard")
|
||||
.0
|
||||
.to_owned();
|
||||
for (path, names) in [
|
||||
(
|
||||
original,
|
||||
["SNB_GMCH_CTRL", "BDW_GMCH_GGMS_SHIFT", "BDW_GMCH_GGMS_MASK"],
|
||||
),
|
||||
(
|
||||
"src/gpu/intel/xe/xe_bo.h",
|
||||
["XE_PTE_SHIFT", "XE_PAGE_SIZE", "XE_PTE_MASK"],
|
||||
),
|
||||
(
|
||||
"src/gpu/common/linux/include/linux/sizes.h",
|
||||
["SZ_1M", "SZ_8M", "SZ_2M"],
|
||||
),
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={path}");
|
||||
let source = fs::read_to_string(path).expect("read original GGTT scalar header");
|
||||
for name in names {
|
||||
let mut lines = source.lines().filter(|line| {
|
||||
let mut words = line.split_whitespace();
|
||||
words.next() == Some("#define") && words.next() == Some(name)
|
||||
});
|
||||
header.push_str(lines.next().expect("missing original GGTT scalar define"));
|
||||
header.push('\n');
|
||||
assert!(
|
||||
lines.next().is_none(),
|
||||
"duplicate original GGTT define {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let output = output.join("intel-ggtt");
|
||||
fs::create_dir_all(&output).expect("create GGTT scalar output directory");
|
||||
fs::write(output.join("ggtt_probe_defs.h"), header).expect("write original GGTT scalar header");
|
||||
build.include(output);
|
||||
}
|
||||
@@ -5,5 +5,13 @@ mod commands;
|
||||
#[cfg(feature = "amd-commands")]
|
||||
pub use commands::*;
|
||||
|
||||
#[cfg(feature = "amd-port")]
|
||||
pub mod discovery;
|
||||
#[cfg(feature = "amd-port")]
|
||||
pub mod native_mmio;
|
||||
#[cfg(feature = "amd-port")]
|
||||
pub mod pci;
|
||||
#[cfg(feature = "amd-port")]
|
||||
pub mod vm;
|
||||
#[cfg(feature = "amd-port")]
|
||||
pub mod vram;
|
||||
@@ -49,6 +49,8 @@ subdir-ccflags-y += -Wno-override-init
|
||||
subdir-ccflags-$(CONFIG_DRM_AMDGPU_WERROR) += -Werror
|
||||
|
||||
amdgpu-y := amdgpu_drv.o
|
||||
# Pure discovery validation shared with the native attachment path.
|
||||
amdgpu-y += ../stela/discovery_binary.o
|
||||
|
||||
# add KMS driver
|
||||
amdgpu-y += amdgpu_device.o amdgpu_reg_access.o amdgpu_doorbell_mgr.o amdgpu_kms.o \
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright 2008 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_APU_FLAGS_CORE_H
|
||||
#define AMDGPU_APU_FLAGS_CORE_H
|
||||
#include "../../common/linux/include/drm/amd_asic_type.h"
|
||||
#include "../include/amd_chip_flags.h"
|
||||
static inline unsigned long amdgpu_initial_apu_flags(unsigned long flags,
|
||||
enum amd_asic_type asic_type, unsigned short device, unsigned long apu_flags)
|
||||
{
|
||||
if (!(flags & AMD_IS_APU) ||
|
||||
asic_type < CHIP_RAVEN)
|
||||
return apu_flags;
|
||||
|
||||
switch (asic_type) {
|
||||
case CHIP_RAVEN:
|
||||
if (device == 0x15dd)
|
||||
apu_flags |= AMD_APU_IS_RAVEN;
|
||||
if (device == 0x15d8)
|
||||
apu_flags |= AMD_APU_IS_PICASSO;
|
||||
break;
|
||||
case CHIP_RENOIR:
|
||||
if ((device == 0x1636) ||
|
||||
(device == 0x164c))
|
||||
apu_flags |= AMD_APU_IS_RENOIR;
|
||||
else
|
||||
apu_flags |= AMD_APU_IS_GREEN_SARDINE;
|
||||
break;
|
||||
case CHIP_VANGOGH:
|
||||
apu_flags |= AMD_APU_IS_VANGOGH;
|
||||
break;
|
||||
case CHIP_YELLOW_CARP:
|
||||
break;
|
||||
case CHIP_CYAN_SKILLFISH:
|
||||
if ((device == 0x13FE) ||
|
||||
(device == 0x143F))
|
||||
apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return apu_flags;
|
||||
}
|
||||
#endif
|
||||
@@ -48,6 +48,9 @@
|
||||
#include <linux/vga_switcheroo.h>
|
||||
#include <linux/efi.h>
|
||||
#include "amdgpu.h"
|
||||
#include "amdgpu_apu_flags_core.h"
|
||||
#include "amdgpu_discovery_source_core.h"
|
||||
#include "../stela/native_bar.h"
|
||||
#include "amdgpu_trace.h"
|
||||
#include "amdgpu_i2c.h"
|
||||
#include "atom.h"
|
||||
@@ -696,6 +699,22 @@ bool amdgpu_device_supports_smart_shift(struct amdgpu_device *adev)
|
||||
* VRAM access helper functions
|
||||
*/
|
||||
|
||||
#include "amdgpu_mm_access_core.h"
|
||||
|
||||
static uint32_t amdgpu_mm_access_read32(void *context, uint32_t reg)
|
||||
{
|
||||
struct amdgpu_device *adev = context;
|
||||
|
||||
return RREG32_NO_KIQ(reg);
|
||||
}
|
||||
|
||||
static void amdgpu_mm_access_write32(void *context, uint32_t reg, uint32_t value)
|
||||
{
|
||||
struct amdgpu_device *adev = context;
|
||||
|
||||
WREG32_NO_KIQ(reg, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* amdgpu_device_mm_access - access vram by MM_INDEX/MM_DATA
|
||||
*
|
||||
@@ -708,10 +727,10 @@ bool amdgpu_device_supports_smart_shift(struct amdgpu_device *adev)
|
||||
void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos,
|
||||
void *buf, size_t size, bool write)
|
||||
{
|
||||
static const struct amdgpu_mm_access_ops ops = {
|
||||
amdgpu_mm_access_read32, amdgpu_mm_access_write32,
|
||||
};
|
||||
unsigned long flags;
|
||||
uint32_t hi = ~0, tmp = 0;
|
||||
uint32_t *data = buf;
|
||||
uint64_t last;
|
||||
int idx;
|
||||
|
||||
if (!drm_dev_enter(adev_to_drm(adev), &idx))
|
||||
@@ -725,19 +744,7 @@ void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos,
|
||||
}
|
||||
|
||||
spin_lock_irqsave(&adev->mmio_idx_lock, flags);
|
||||
for (last = pos + size; pos < last; pos += 4) {
|
||||
tmp = pos >> 31;
|
||||
|
||||
WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
|
||||
if (tmp != hi) {
|
||||
WREG32_NO_KIQ(mmMM_INDEX_HI, tmp);
|
||||
hi = tmp;
|
||||
}
|
||||
if (write)
|
||||
WREG32_NO_KIQ(mmMM_DATA, *data++);
|
||||
else
|
||||
*data++ = RREG32_NO_KIQ(mmMM_DATA);
|
||||
}
|
||||
amdgpu_mm_access_core(&ops, adev, pos, buf, size, write);
|
||||
|
||||
spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
|
||||
drm_dev_exit(idx);
|
||||
@@ -1559,38 +1566,8 @@ def_value:
|
||||
|
||||
static int amdgpu_device_init_apu_flags(struct amdgpu_device *adev)
|
||||
{
|
||||
if (!(adev->flags & AMD_IS_APU) ||
|
||||
adev->asic_type < CHIP_RAVEN)
|
||||
return 0;
|
||||
|
||||
switch (adev->asic_type) {
|
||||
case CHIP_RAVEN:
|
||||
if (adev->pdev->device == 0x15dd)
|
||||
adev->apu_flags |= AMD_APU_IS_RAVEN;
|
||||
if (adev->pdev->device == 0x15d8)
|
||||
adev->apu_flags |= AMD_APU_IS_PICASSO;
|
||||
break;
|
||||
case CHIP_RENOIR:
|
||||
if ((adev->pdev->device == 0x1636) ||
|
||||
(adev->pdev->device == 0x164c))
|
||||
adev->apu_flags |= AMD_APU_IS_RENOIR;
|
||||
else
|
||||
adev->apu_flags |= AMD_APU_IS_GREEN_SARDINE;
|
||||
break;
|
||||
case CHIP_VANGOGH:
|
||||
adev->apu_flags |= AMD_APU_IS_VANGOGH;
|
||||
break;
|
||||
case CHIP_YELLOW_CARP:
|
||||
break;
|
||||
case CHIP_CYAN_SKILLFISH:
|
||||
if ((adev->pdev->device == 0x13FE) ||
|
||||
(adev->pdev->device == 0x143F))
|
||||
adev->apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
adev->apu_flags = amdgpu_initial_apu_flags(adev->flags, adev->asic_type,
|
||||
adev->pdev->device, adev->apu_flags);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2020,13 +1997,9 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
|
||||
return r;
|
||||
}
|
||||
|
||||
switch (adev->asic_type) {
|
||||
switch (amdgpu_initial_ip_path(adev->asic_type)) {
|
||||
#ifdef CONFIG_DRM_AMDGPU_SI
|
||||
case CHIP_VERDE:
|
||||
case CHIP_TAHITI:
|
||||
case CHIP_PITCAIRN:
|
||||
case CHIP_OLAND:
|
||||
case CHIP_HAINAN:
|
||||
case AMDGPU_INITIAL_IP_SI:
|
||||
adev->family = AMDGPU_FAMILY_SI;
|
||||
r = si_set_ip_blocks(adev);
|
||||
if (r)
|
||||
@@ -2034,11 +2007,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
|
||||
break;
|
||||
#endif
|
||||
#ifdef CONFIG_DRM_AMDGPU_CIK
|
||||
case CHIP_BONAIRE:
|
||||
case CHIP_HAWAII:
|
||||
case CHIP_KAVERI:
|
||||
case CHIP_KABINI:
|
||||
case CHIP_MULLINS:
|
||||
case AMDGPU_INITIAL_IP_CIK:
|
||||
if (adev->flags & AMD_IS_APU)
|
||||
adev->family = AMDGPU_FAMILY_KV;
|
||||
else
|
||||
@@ -2049,15 +2018,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
|
||||
return r;
|
||||
break;
|
||||
#endif
|
||||
case CHIP_TOPAZ:
|
||||
case CHIP_TONGA:
|
||||
case CHIP_FIJI:
|
||||
case CHIP_POLARIS10:
|
||||
case CHIP_POLARIS11:
|
||||
case CHIP_POLARIS12:
|
||||
case CHIP_VEGAM:
|
||||
case CHIP_CARRIZO:
|
||||
case CHIP_STONEY:
|
||||
case AMDGPU_INITIAL_IP_VI:
|
||||
if (adev->flags & AMD_IS_APU)
|
||||
adev->family = AMDGPU_FAMILY_CZ;
|
||||
else
|
||||
@@ -3894,13 +3855,9 @@ int amdgpu_device_init(struct amdgpu_device *adev,
|
||||
|
||||
/* Registers mapping */
|
||||
/* TODO: block userspace mapping of io register */
|
||||
if (adev->asic_type >= CHIP_BONAIRE) {
|
||||
adev->rmmio_base = pci_resource_start(adev->pdev, 5);
|
||||
adev->rmmio_size = pci_resource_len(adev->pdev, 5);
|
||||
} else {
|
||||
adev->rmmio_base = pci_resource_start(adev->pdev, 2);
|
||||
adev->rmmio_size = pci_resource_len(adev->pdev, 2);
|
||||
}
|
||||
i = amdgpu_native_register_bar(adev->asic_type);
|
||||
adev->rmmio_base = pci_resource_start(adev->pdev, i);
|
||||
adev->rmmio_size = pci_resource_len(adev->pdev, i);
|
||||
|
||||
for (i = 0; i < AMD_IP_BLOCK_TYPE_NUM; i++)
|
||||
atomic_set(&adev->pm.pwr_state[i], POWER_STATE_UNKNOWN);
|
||||
|
||||
@@ -24,9 +24,12 @@
|
||||
#include <linux/firmware.h>
|
||||
|
||||
#include "amdgpu.h"
|
||||
#include "amdgpu_discovery_source_core.h"
|
||||
#include "amdgpu_discovery_file_core.h"
|
||||
#include "amdgpu_discovery.h"
|
||||
#include "soc15_hw_ip.h"
|
||||
#include "discovery.h"
|
||||
#include "../stela/discovery_binary.h"
|
||||
#include "amdgpu_ras.h"
|
||||
|
||||
#include "soc15.h"
|
||||
@@ -137,16 +140,12 @@ MODULE_FIRMWARE("amdgpu/arcturus_ip_discovery.bin");
|
||||
MODULE_FIRMWARE("amdgpu/aldebaran_ip_discovery.bin");
|
||||
|
||||
/* Note: These registers are consistent across all the SOCs */
|
||||
#include "amdgpu_discovery_tmr_core.h"
|
||||
#define mmIP_DISCOVERY_VERSION 0x16A00
|
||||
#define mmRCC_CONFIG_MEMSIZE 0xde3
|
||||
#define mmMP0_SMN_C2PMSG_33 0x16061
|
||||
#define mmMM_INDEX 0x0
|
||||
#define mmMM_INDEX_HI 0x6
|
||||
#define mmMM_DATA 0x1
|
||||
|
||||
#define mmDRIVER_SCRATCH_0 0x94
|
||||
#define mmDRIVER_SCRATCH_1 0x95
|
||||
#define mmDRIVER_SCRATCH_2 0x96
|
||||
|
||||
static const char *hw_id_names[HW_ID_MAX] = {
|
||||
[MP1_HWID] = "MP1",
|
||||
@@ -230,126 +229,98 @@ static const char *hw_id_names[HW_ID_MAX] = {
|
||||
[AIGC_HWID] = "AIGC",
|
||||
};
|
||||
|
||||
static int hw_id_map[MAX_HWIP] = {
|
||||
[GC_HWIP] = GC_HWID,
|
||||
[HDP_HWIP] = HDP_HWID,
|
||||
[SDMA0_HWIP] = SDMA0_HWID,
|
||||
[SDMA1_HWIP] = SDMA1_HWID,
|
||||
[SDMA2_HWIP] = SDMA2_HWID,
|
||||
[SDMA3_HWIP] = SDMA3_HWID,
|
||||
[LSDMA_HWIP] = LSDMA_HWID,
|
||||
[MMHUB_HWIP] = MMHUB_HWID,
|
||||
[ATHUB_HWIP] = ATHUB_HWID,
|
||||
[NBIO_HWIP] = NBIF_HWID,
|
||||
[MP0_HWIP] = MP0_HWID,
|
||||
[MP1_HWIP] = MP1_HWID,
|
||||
[UVD_HWIP] = UVD_HWID,
|
||||
[VCE_HWIP] = VCE_HWID,
|
||||
[DF_HWIP] = DF_HWID,
|
||||
[DCE_HWIP] = DMU_HWID,
|
||||
[OSSSYS_HWIP] = OSSSYS_HWID,
|
||||
[SMUIO_HWIP] = SMUIO_HWID,
|
||||
[PWR_HWIP] = PWR_HWID,
|
||||
[NBIF_HWIP] = NBIF_HWID,
|
||||
[THM_HWIP] = THM_HWID,
|
||||
[CLK_HWIP] = CLKA_HWID,
|
||||
[UMC_HWIP] = UMC_HWID,
|
||||
[XGMI_HWIP] = XGMI_HWID,
|
||||
[DCI_HWIP] = DCI_HWID,
|
||||
[PCIE_HWIP] = PCIE_HWID,
|
||||
[VPE_HWIP] = VPE_HWID,
|
||||
[ISP_HWIP] = ISP_HWID,
|
||||
[ATU_HWIP] = ATU_HWID,
|
||||
};
|
||||
#include "amdgpu_discovery_ip_core.h"
|
||||
|
||||
static int amdgpu_discovery_get_tmr_info(struct amdgpu_device *adev,
|
||||
bool *is_tmr_in_sysmem)
|
||||
static void amdgpu_discovery_ip_debug(void *context, const char *format, ...)
|
||||
{
|
||||
u64 vram_size, tmr_offset, tmr_size;
|
||||
u32 msg, tmr_offset_lo, tmr_offset_hi;
|
||||
int i, ret;
|
||||
va_list args;
|
||||
struct va_format vaf = { .fmt = format, .va = &args };
|
||||
(void)context;
|
||||
va_start(args, format);
|
||||
DRM_DEBUG("%pV", &vaf);
|
||||
va_end(args);
|
||||
}
|
||||
static void amdgpu_discovery_ip_drm_error(void *context, const char *format, ...)
|
||||
{
|
||||
va_list args;
|
||||
struct va_format vaf = { .fmt = format, .va = &args };
|
||||
(void)context;
|
||||
va_start(args, format);
|
||||
DRM_ERROR("%pV", &vaf);
|
||||
va_end(args);
|
||||
}
|
||||
static void amdgpu_discovery_ip_error(void *context, const char *format, ...)
|
||||
{
|
||||
struct amdgpu_device *adev = context;
|
||||
va_list args;
|
||||
struct va_format vaf = { .fmt = format, .va = &args };
|
||||
va_start(args, format);
|
||||
dev_err(adev->dev, "%pV", &vaf);
|
||||
va_end(args);
|
||||
}
|
||||
static void amdgpu_discovery_ip_bind(void *context, unsigned hw_ip, unsigned instance,
|
||||
uint32_t *base, unsigned count)
|
||||
{
|
||||
struct amdgpu_device *adev = context;
|
||||
(void)count;
|
||||
adev->reg_offset[hw_ip][instance] = base;
|
||||
}
|
||||
|
||||
if (!amdgpu_sriov_vf(adev)) {
|
||||
/* It can take up to two second for IFWI init to complete on some dGPUs,
|
||||
* but generally it should be in the 60-100ms range. Normally this starts
|
||||
* as soon as the device gets power so by the time the OS loads this has long
|
||||
* completed. However, when a card is hotplugged via e.g., USB4, we need to
|
||||
* wait for this to complete. Once the C2PMSG is updated, we can
|
||||
* continue.
|
||||
*/
|
||||
|
||||
for (i = 0; i < 2000; i++) {
|
||||
msg = RREG32(mmMP0_SMN_C2PMSG_33);
|
||||
if (msg & 0x80000000)
|
||||
break;
|
||||
msleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
vram_size = RREG32(mmRCC_CONFIG_MEMSIZE);
|
||||
if (vram_size == U32_MAX)
|
||||
return -ENXIO;
|
||||
else if (!vram_size)
|
||||
*is_tmr_in_sysmem = true;
|
||||
else
|
||||
*is_tmr_in_sysmem = false;
|
||||
|
||||
/* init the default tmr size and offset */
|
||||
adev->discovery.size = DISCOVERY_TMR_SIZE;
|
||||
if (vram_size)
|
||||
adev->discovery.offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET;
|
||||
|
||||
if (amdgpu_sriov_vf(adev)) {
|
||||
if (adev->virt.is_dynamic_crit_regn_enabled) {
|
||||
adev->discovery.offset =
|
||||
adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset;
|
||||
adev->discovery.size =
|
||||
adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10;
|
||||
if (!adev->discovery.size)
|
||||
return -EINVAL;
|
||||
} else {
|
||||
goto out;
|
||||
}
|
||||
} else {
|
||||
if (adev->discovery.offset) {
|
||||
u32 signature;
|
||||
|
||||
/* If VRAM holds a valid discovery signature at the default
|
||||
* discovery offset, use it as-is.
|
||||
*/
|
||||
amdgpu_device_vram_access(adev, adev->discovery.offset,
|
||||
&signature, sizeof(signature),
|
||||
false);
|
||||
if (le32_to_cpu(signature) == BINARY_SIGNATURE)
|
||||
goto out;
|
||||
}
|
||||
|
||||
tmr_size = RREG32(mmDRIVER_SCRATCH_2);
|
||||
if (tmr_size) {
|
||||
/* It's preferred to transition to PSP mailbox reg interface
|
||||
* for both bare-metal and passthrough if available */
|
||||
adev->discovery.size = (u32)tmr_size;
|
||||
tmr_offset_lo = RREG32(mmDRIVER_SCRATCH_0);
|
||||
tmr_offset_hi = RREG32(mmDRIVER_SCRATCH_1);
|
||||
adev->discovery.offset = ((u64)le32_to_cpu(tmr_offset_hi) << 32 |
|
||||
le32_to_cpu(tmr_offset_lo));
|
||||
} else if (!vram_size) {
|
||||
/* fall back to apci approach to query tmr offset if vram_size is 0 */
|
||||
ret = amdgpu_acpi_get_tmr_info(adev, &tmr_offset, &tmr_size);
|
||||
if (ret)
|
||||
return ret;
|
||||
adev->discovery.size = DISCOVERY_TMR_SIZE;
|
||||
adev->discovery.offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET;
|
||||
}
|
||||
}
|
||||
out:
|
||||
adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL);
|
||||
if (!adev->discovery.bin)
|
||||
return -ENOMEM;
|
||||
adev->discovery.debugfs_blob.data = adev->discovery.bin;
|
||||
adev->discovery.debugfs_blob.size = adev->discovery.size;
|
||||
|
||||
return 0;
|
||||
static uint32_t amdgpu_discovery_tmr_read32(void *context, uint32_t reg)
|
||||
{
|
||||
struct amdgpu_device *adev = context;
|
||||
return RREG32(reg);
|
||||
}
|
||||
static void amdgpu_discovery_tmr_sleep_ms(void *context, unsigned milliseconds)
|
||||
{
|
||||
(void)context;
|
||||
msleep(milliseconds);
|
||||
}
|
||||
static int amdgpu_discovery_tmr_read_vram(void *context, uint64_t offset,
|
||||
uint32_t *data, size_t size)
|
||||
{
|
||||
amdgpu_device_vram_access(context, offset, data, size, false);
|
||||
/* The original transport is void; this reports no additional local error,
|
||||
* not device acknowledgement. All original hardware guards remain in it. */
|
||||
return 0;
|
||||
}
|
||||
static int amdgpu_discovery_tmr_acpi(void *context, uint64_t *offset, uint64_t *size)
|
||||
{
|
||||
return amdgpu_acpi_get_tmr_info(context, offset, size);
|
||||
}
|
||||
static int amdgpu_discovery_get_tmr_info(struct amdgpu_device *adev,
|
||||
bool *is_tmr_in_sysmem)
|
||||
{
|
||||
const struct amdgpu_discovery_tmr_ops ops = {
|
||||
amdgpu_discovery_tmr_read32, amdgpu_discovery_tmr_sleep_ms,
|
||||
amdgpu_discovery_tmr_read_vram, amdgpu_discovery_tmr_acpi,
|
||||
};
|
||||
struct amdgpu_discovery_tmr_state state = {
|
||||
.offset = adev->discovery.offset,
|
||||
.size = adev->discovery.size,
|
||||
.is_sysmem = false,
|
||||
};
|
||||
bool is_vf = amdgpu_sriov_vf(adev);
|
||||
bool dynamic = is_vf && adev->virt.is_dynamic_crit_regn_enabled;
|
||||
int ret = amdgpu_discovery_tmr_query_core(&ops, adev, is_vf, dynamic,
|
||||
dynamic ? adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset : 0,
|
||||
dynamic ? adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10 : 0,
|
||||
&state);
|
||||
/* Preserve the original policy's partial device/output updates on error. */
|
||||
adev->discovery.offset = state.offset;
|
||||
adev->discovery.size = state.size;
|
||||
if (state.has_memory_size)
|
||||
*is_tmr_in_sysmem = state.is_sysmem;
|
||||
if (ret)
|
||||
return ret;
|
||||
adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL);
|
||||
if (!adev->discovery.bin)
|
||||
return -ENOMEM;
|
||||
adev->discovery.debugfs_blob.data = adev->discovery.bin;
|
||||
adev->discovery.debugfs_blob.size = adev->discovery.size;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int amdgpu_discovery_read_binary_from_sysmem(struct amdgpu_device *adev, uint8_t *binary)
|
||||
@@ -409,24 +380,25 @@ static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev,
|
||||
return r;
|
||||
}
|
||||
|
||||
if (fw->size > adev->discovery.size) {
|
||||
switch (amdgpu_discovery_file_validate(fw->data, fw->size,
|
||||
adev->discovery.size)) {
|
||||
case AMDGPU_DISCOVERY_FILE_TOO_LARGE:
|
||||
dev_err(adev->dev,
|
||||
"ip discovery firmware \"%s\" too large (%zu > %u)\n",
|
||||
fw_name, fw->size, adev->discovery.size);
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
/* Ensure the firmware is at least large enough to contain the
|
||||
* binary header fields.
|
||||
*/
|
||||
if (fw->size < offsetof(struct binary_header, binary_size) +
|
||||
sizeof(((struct binary_header *)0)->binary_size)) {
|
||||
case AMDGPU_DISCOVERY_FILE_TOO_SMALL:
|
||||
dev_err(adev->dev,
|
||||
"ip discovery firmware \"%s\" too small (%zu)\n",
|
||||
fw_name, fw->size);
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
case AMDGPU_DISCOVERY_FILE_INVALID:
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
case AMDGPU_DISCOVERY_FILE_OK:
|
||||
break;
|
||||
}
|
||||
|
||||
memcpy((u8 *)binary, (u8 *)fw->data, fw->size);
|
||||
@@ -435,17 +407,6 @@ static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev,
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint16_t amdgpu_discovery_calculate_checksum(uint8_t *data, uint32_t size)
|
||||
{
|
||||
uint16_t checksum = 0;
|
||||
int i;
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
checksum += data[i];
|
||||
|
||||
return checksum;
|
||||
}
|
||||
|
||||
static inline bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev,
|
||||
uint8_t *data, uint32_t size,
|
||||
uint16_t expected)
|
||||
@@ -463,14 +424,6 @@ static inline bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev,
|
||||
return true;
|
||||
}
|
||||
|
||||
static inline bool amdgpu_discovery_verify_binary_signature(uint8_t *binary)
|
||||
{
|
||||
struct binary_header *bhdr;
|
||||
bhdr = (struct binary_header *)binary;
|
||||
|
||||
return (le32_to_cpu(bhdr->binary_signature) == BINARY_SIGNATURE);
|
||||
}
|
||||
|
||||
static void amdgpu_discovery_harvest_config_quirk(struct amdgpu_device *adev)
|
||||
{
|
||||
/*
|
||||
@@ -529,151 +482,32 @@ static const char *amdgpu_discovery_get_fw_name(struct amdgpu_device *adev)
|
||||
if (amdgpu_discovery == 2) {
|
||||
/* Assume there is valid discovery TMR in VRAM even if binary is sideloaded */
|
||||
adev->discovery.reserve_tmr = true;
|
||||
return "amdgpu/ip_discovery.bin";
|
||||
}
|
||||
|
||||
switch (adev->asic_type) {
|
||||
case CHIP_VEGA10:
|
||||
return "amdgpu/vega10_ip_discovery.bin";
|
||||
case CHIP_VEGA12:
|
||||
return "amdgpu/vega12_ip_discovery.bin";
|
||||
case CHIP_RAVEN:
|
||||
if (adev->apu_flags & AMD_APU_IS_RAVEN2)
|
||||
return "amdgpu/raven2_ip_discovery.bin";
|
||||
else if (adev->apu_flags & AMD_APU_IS_PICASSO)
|
||||
return "amdgpu/picasso_ip_discovery.bin";
|
||||
else
|
||||
return "amdgpu/raven_ip_discovery.bin";
|
||||
case CHIP_VEGA20:
|
||||
return "amdgpu/vega20_ip_discovery.bin";
|
||||
case CHIP_ARCTURUS:
|
||||
return "amdgpu/arcturus_ip_discovery.bin";
|
||||
case CHIP_ALDEBARAN:
|
||||
return "amdgpu/aldebaran_ip_discovery.bin";
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
return amdgpu_discovery_fw_name(adev->asic_type, adev->apu_flags,
|
||||
amdgpu_discovery);
|
||||
}
|
||||
|
||||
static int amdgpu_discovery_get_table_info(struct amdgpu_device *adev,
|
||||
struct table_info **info,
|
||||
uint16_t table_id)
|
||||
{
|
||||
struct binary_header *bhdr =
|
||||
(struct binary_header *)adev->discovery.bin;
|
||||
struct binary_header_v2 *bhdrv2;
|
||||
const struct table_info *entry;
|
||||
|
||||
switch (bhdr->version_major) {
|
||||
case 2:
|
||||
bhdrv2 = (struct binary_header_v2 *)adev->discovery.bin;
|
||||
*info = &bhdrv2->table_list[table_id];
|
||||
break;
|
||||
case 1:
|
||||
case 0:
|
||||
*info = &bhdr->table_list[table_id];
|
||||
break;
|
||||
default:
|
||||
dev_err(adev->dev, "Invalid ip discovery table version %d\n",bhdr->version_major);
|
||||
entry = amdgpu_discovery_binary_table(adev->discovery.bin,
|
||||
adev->discovery.size, table_id);
|
||||
if (!entry)
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int amdgpu_discovery_table_check(struct amdgpu_device *adev,
|
||||
uint8_t *discovery_bin,
|
||||
uint16_t table_id)
|
||||
{
|
||||
int r, act_val, exp_val, table_size;
|
||||
uint16_t offset, checksum;
|
||||
struct table_info *info;
|
||||
bool check_table = true;
|
||||
char *table_name;
|
||||
|
||||
r = amdgpu_discovery_get_table_info(adev, &info, table_id);
|
||||
if (r)
|
||||
return r;
|
||||
offset = le16_to_cpu(info->offset);
|
||||
checksum = le16_to_cpu(info->checksum);
|
||||
|
||||
switch (table_id) {
|
||||
case IP_DISCOVERY: {
|
||||
struct ip_discovery_header *ihdr =
|
||||
(struct ip_discovery_header *)(discovery_bin + offset);
|
||||
act_val = le32_to_cpu(ihdr->signature);
|
||||
exp_val = DISCOVERY_TABLE_SIGNATURE;
|
||||
table_size = le16_to_cpu(ihdr->size);
|
||||
table_name = "data table";
|
||||
break;
|
||||
}
|
||||
case GC: {
|
||||
struct gpu_info_header *ghdr =
|
||||
(struct gpu_info_header *)(discovery_bin + offset);
|
||||
act_val = le32_to_cpu(ghdr->table_id);
|
||||
exp_val = GC_TABLE_ID;
|
||||
table_size = le16_to_cpu(ghdr->size);
|
||||
table_name = "gc table";
|
||||
break;
|
||||
}
|
||||
case HARVEST_INFO: {
|
||||
struct harvest_info_header *hhdr =
|
||||
(struct harvest_info_header *)(discovery_bin + offset);
|
||||
act_val = le32_to_cpu(hhdr->signature);
|
||||
exp_val = HARVEST_TABLE_SIGNATURE;
|
||||
table_size = sizeof(struct harvest_table);
|
||||
table_name = "harvest table";
|
||||
break;
|
||||
}
|
||||
case VCN_INFO: {
|
||||
struct vcn_info_header *vhdr =
|
||||
(struct vcn_info_header *)(discovery_bin + offset);
|
||||
act_val = le32_to_cpu(vhdr->table_id);
|
||||
exp_val = VCN_INFO_TABLE_ID;
|
||||
table_size = le32_to_cpu(vhdr->size_bytes);
|
||||
table_name = "vcn table";
|
||||
break;
|
||||
}
|
||||
case MALL_INFO: {
|
||||
struct mall_info_header *mhdr =
|
||||
(struct mall_info_header *)(discovery_bin + offset);
|
||||
act_val = le32_to_cpu(mhdr->table_id);
|
||||
exp_val = MALL_INFO_TABLE_ID;
|
||||
table_size = le32_to_cpu(mhdr->size_bytes);
|
||||
table_name = "mall table";
|
||||
check_table = false;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
dev_err(adev->dev, "invalid ip discovery table id %d specified\n", table_id);
|
||||
check_table = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (check_table && offset) {
|
||||
if (act_val != exp_val) {
|
||||
dev_err(adev->dev, "invalid ip discovery %s signature\n", table_name);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset,
|
||||
table_size, checksum)) {
|
||||
dev_err(adev->dev, "invalid ip discovery %s checksum\n", table_name);
|
||||
return -EINVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* The original private allocation remains mutable for register-base
|
||||
* conversion. The checked directory lookup itself never mutates it.
|
||||
*/
|
||||
*info = (struct table_info *)entry;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int amdgpu_discovery_init(struct amdgpu_device *adev)
|
||||
{
|
||||
struct binary_header *bhdr;
|
||||
uint8_t *discovery_bin;
|
||||
const char *fw_name;
|
||||
uint16_t offset;
|
||||
uint16_t size;
|
||||
uint16_t checksum;
|
||||
uint16_t table_id;
|
||||
bool is_tmr_in_sysmem;
|
||||
int r;
|
||||
|
||||
@@ -698,34 +532,16 @@ static int amdgpu_discovery_init(struct amdgpu_device *adev)
|
||||
goto out;
|
||||
}
|
||||
|
||||
/* check the ip discovery binary signature */
|
||||
if (!amdgpu_discovery_verify_binary_signature(discovery_bin)) {
|
||||
dev_err(adev->dev,
|
||||
"get invalid ip discovery binary signature\n");
|
||||
/* Validate the real private acquisition before any original table/IP
|
||||
* walk or in-place register-base conversion can consume it.
|
||||
*/
|
||||
if (amdgpu_discovery_binary_validate(discovery_bin, adev->discovery.size) !=
|
||||
AMDGPU_DISCOVERY_BINARY_OK) {
|
||||
dev_err(adev->dev, "invalid or out-of-bounds ip discovery binary\n");
|
||||
r = -EINVAL;
|
||||
goto out;
|
||||
}
|
||||
|
||||
bhdr = (struct binary_header *)discovery_bin;
|
||||
|
||||
offset = offsetof(struct binary_header, binary_checksum) +
|
||||
sizeof(bhdr->binary_checksum);
|
||||
size = le16_to_cpu(bhdr->binary_size) - offset;
|
||||
checksum = le16_to_cpu(bhdr->binary_checksum);
|
||||
|
||||
if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, size,
|
||||
checksum)) {
|
||||
dev_err(adev->dev, "invalid ip discovery binary checksum\n");
|
||||
r = -EINVAL;
|
||||
goto out;
|
||||
}
|
||||
|
||||
for (table_id = 0; table_id <= MALL_INFO; table_id++) {
|
||||
r = amdgpu_discovery_table_check(adev, discovery_bin, table_id);
|
||||
if (r)
|
||||
goto out;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
out:
|
||||
@@ -749,27 +565,17 @@ void amdgpu_discovery_fini(struct amdgpu_device *adev)
|
||||
static int amdgpu_discovery_validate_ip(struct amdgpu_device *adev,
|
||||
uint8_t instance, uint16_t hw_id)
|
||||
{
|
||||
if (instance >= HWIP_MAX_INSTANCE) {
|
||||
dev_err(adev->dev,
|
||||
"Unexpected instance_number (%d) from ip discovery blob\n",
|
||||
instance);
|
||||
return -EINVAL;
|
||||
}
|
||||
if (hw_id >= HW_ID_MAX) {
|
||||
dev_err(adev->dev,
|
||||
"Unexpected hw_id (%d) from ip discovery blob\n",
|
||||
hw_id);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
const struct amdgpu_discovery_ip_ops ops = {
|
||||
.context = adev, .error = amdgpu_discovery_ip_error,
|
||||
};
|
||||
return amdgpu_discovery_ip_valid(&ops, instance, hw_id);
|
||||
}
|
||||
|
||||
static void amdgpu_discovery_read_harvest_bit_per_ip(struct amdgpu_device *adev,
|
||||
uint32_t *vcn_harvest_count)
|
||||
{
|
||||
uint8_t *discovery_bin = adev->discovery.bin;
|
||||
struct binary_header *bhdr;
|
||||
struct table_info *info;
|
||||
struct ip_discovery_header *ihdr;
|
||||
struct die_header *dhdr;
|
||||
struct ip *ip;
|
||||
@@ -778,10 +584,11 @@ static void amdgpu_discovery_read_harvest_bit_per_ip(struct amdgpu_device *adev,
|
||||
uint8_t inst;
|
||||
int i, j;
|
||||
|
||||
bhdr = (struct binary_header *)discovery_bin;
|
||||
ihdr = (struct ip_discovery_header
|
||||
*)(discovery_bin +
|
||||
le16_to_cpu(bhdr->table_list[IP_DISCOVERY].offset));
|
||||
if (amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY))
|
||||
return;
|
||||
ihdr = (struct ip_discovery_header *)(discovery_bin +
|
||||
le16_to_cpu(info->offset));
|
||||
|
||||
num_dies = le16_to_cpu(ihdr->num_dies);
|
||||
|
||||
/* scan harvest bit of all IP data structures */
|
||||
@@ -1497,28 +1304,15 @@ void amdgpu_discovery_dump(struct amdgpu_device *adev, struct drm_printer *p)
|
||||
|
||||
static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev)
|
||||
{
|
||||
uint8_t num_base_address, subrev, variant;
|
||||
struct table_info *info;
|
||||
struct ip_discovery_header *ihdr;
|
||||
struct die_header *dhdr;
|
||||
uint8_t *discovery_bin;
|
||||
struct ip_v4 *ip;
|
||||
uint16_t die_offset;
|
||||
uint16_t ip_offset;
|
||||
uint16_t num_dies;
|
||||
uint32_t wafl_ver;
|
||||
uint16_t num_ips;
|
||||
uint16_t hw_id;
|
||||
uint8_t inst;
|
||||
int hw_ip;
|
||||
int i, j, k;
|
||||
int r;
|
||||
|
||||
r = amdgpu_discovery_init(adev);
|
||||
if (r)
|
||||
return r;
|
||||
discovery_bin = adev->discovery.bin;
|
||||
wafl_ver = 0;
|
||||
adev->gfx.xcc_mask = 0;
|
||||
adev->sdma.sdma_mask = 0;
|
||||
adev->vcn.inst_mask = 0;
|
||||
@@ -1526,175 +1320,23 @@ static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev)
|
||||
r = amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY);
|
||||
if (r)
|
||||
return r;
|
||||
ihdr = (struct ip_discovery_header
|
||||
*)(discovery_bin +
|
||||
le16_to_cpu(info->offset));
|
||||
num_dies = le16_to_cpu(ihdr->num_dies);
|
||||
|
||||
DRM_DEBUG("number of dies: %d\n", num_dies);
|
||||
|
||||
for (i = 0; i < num_dies; i++) {
|
||||
die_offset = le16_to_cpu(ihdr->die_info[i].die_offset);
|
||||
dhdr = (struct die_header *)(discovery_bin + die_offset);
|
||||
num_ips = le16_to_cpu(dhdr->num_ips);
|
||||
ip_offset = die_offset + sizeof(*dhdr);
|
||||
|
||||
if (le16_to_cpu(dhdr->die_id) != i) {
|
||||
DRM_ERROR("invalid die id %d, expected %d\n",
|
||||
le16_to_cpu(dhdr->die_id), i);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
DRM_DEBUG("number of hardware IPs on die%d: %d\n",
|
||||
le16_to_cpu(dhdr->die_id), num_ips);
|
||||
|
||||
for (j = 0; j < num_ips; j++) {
|
||||
ip = (struct ip_v4 *)(discovery_bin + ip_offset);
|
||||
|
||||
inst = ip->instance_number;
|
||||
hw_id = le16_to_cpu(ip->hw_id);
|
||||
if (amdgpu_discovery_validate_ip(adev, inst, hw_id))
|
||||
goto next_ip;
|
||||
|
||||
num_base_address = ip->num_base_address;
|
||||
|
||||
DRM_DEBUG("%s(%d) #%d v%d.%d.%d:\n",
|
||||
hw_id_names[le16_to_cpu(ip->hw_id)],
|
||||
le16_to_cpu(ip->hw_id),
|
||||
ip->instance_number,
|
||||
ip->major, ip->minor,
|
||||
ip->revision);
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VCN_HWID) {
|
||||
/* Bit [5:0]: original revision value
|
||||
* Bit [7:6]: en/decode capability:
|
||||
* 0b00 : VCN function normally
|
||||
* 0b10 : encode is disabled
|
||||
* 0b01 : decode is disabled
|
||||
*/
|
||||
if (adev->vcn.num_vcn_inst <
|
||||
AMDGPU_MAX_VCN_INSTANCES) {
|
||||
adev->vcn.inst[adev->vcn.num_vcn_inst].vcn_config =
|
||||
ip->revision & 0xc0;
|
||||
adev->vcn.num_vcn_inst++;
|
||||
adev->vcn.inst_mask |=
|
||||
(1U << ip->instance_number);
|
||||
adev->jpeg.inst_mask |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
dev_err(adev->dev, "Too many VCN instances: %d vs %d\n",
|
||||
adev->vcn.num_vcn_inst + 1,
|
||||
AMDGPU_MAX_VCN_INSTANCES);
|
||||
}
|
||||
ip->revision &= ~0xc0;
|
||||
}
|
||||
if (le16_to_cpu(ip->hw_id) == SDMA0_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA1_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA2_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA3_HWID) {
|
||||
if (adev->sdma.num_instances <
|
||||
AMDGPU_MAX_SDMA_INSTANCES) {
|
||||
adev->sdma.num_instances++;
|
||||
adev->sdma.sdma_mask |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
dev_err(adev->dev, "Too many SDMA instances: %d vs %d\n",
|
||||
adev->sdma.num_instances + 1,
|
||||
AMDGPU_MAX_SDMA_INSTANCES);
|
||||
}
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VPE_HWID) {
|
||||
if (adev->vpe.num_instances < AMDGPU_MAX_VPE_INSTANCES)
|
||||
adev->vpe.num_instances++;
|
||||
else
|
||||
dev_err(adev->dev, "Too many VPE instances: %d vs %d\n",
|
||||
adev->vpe.num_instances + 1,
|
||||
AMDGPU_MAX_VPE_INSTANCES);
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == UMC_HWID) {
|
||||
adev->gmc.num_umc++;
|
||||
adev->umc.node_inst_num++;
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == GC_HWID)
|
||||
adev->gfx.xcc_mask |=
|
||||
(1U << ip->instance_number);
|
||||
|
||||
if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID)
|
||||
wafl_ver = IP_VERSION_FULL(ip->major, ip->minor,
|
||||
ip->revision, 0, 0);
|
||||
|
||||
for (k = 0; k < num_base_address; k++) {
|
||||
/*
|
||||
* convert the endianness of base addresses in place,
|
||||
* so that we don't need to convert them when accessing adev->reg_offset.
|
||||
*/
|
||||
if (ihdr->base_addr_64_bit)
|
||||
/* Truncate the 64bit base address from ip discovery
|
||||
* and only store lower 32bit ip base in reg_offset[].
|
||||
* Bits > 32 follows ASIC specific format, thus just
|
||||
* discard them and handle it within specific ASIC.
|
||||
* By this way reg_offset[] and related helpers can
|
||||
* stay unchanged.
|
||||
* The base address is in dwords, thus clear the
|
||||
* highest 2 bits to store.
|
||||
*/
|
||||
ip->base_address[k] =
|
||||
lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF;
|
||||
else
|
||||
ip->base_address[k] = le32_to_cpu(ip->base_address[k]);
|
||||
DRM_DEBUG("\t0x%08x\n", ip->base_address[k]);
|
||||
}
|
||||
|
||||
for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) {
|
||||
if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) &&
|
||||
hw_id_map[hw_ip] != 0) {
|
||||
DRM_DEBUG("set register base offset for %s\n",
|
||||
hw_id_names[le16_to_cpu(ip->hw_id)]);
|
||||
adev->reg_offset[hw_ip][ip->instance_number] =
|
||||
ip->base_address;
|
||||
/* Instance support is somewhat inconsistent.
|
||||
* SDMA is a good example. Sienna cichlid has 4 total
|
||||
* SDMA instances, each enumerated separately (HWIDs
|
||||
* 42, 43, 68, 69). Arcturus has 8 total SDMA instances,
|
||||
* but they are enumerated as multiple instances of the
|
||||
* same HWIDs (4x HWID 42, 4x HWID 43). UMC is another
|
||||
* example. On most chips there are multiple instances
|
||||
* with the same HWID.
|
||||
*/
|
||||
|
||||
if (ihdr->version < 3) {
|
||||
subrev = 0;
|
||||
variant = 0;
|
||||
} else {
|
||||
subrev = ip->sub_revision;
|
||||
variant = ip->variant;
|
||||
}
|
||||
|
||||
adev->ip_versions[hw_ip]
|
||||
[ip->instance_number] =
|
||||
IP_VERSION_FULL(ip->major,
|
||||
ip->minor,
|
||||
ip->revision,
|
||||
variant,
|
||||
subrev);
|
||||
}
|
||||
}
|
||||
|
||||
next_ip:
|
||||
if (ihdr->base_addr_64_bit)
|
||||
ip_offset += struct_size(ip, base_address_64, ip->num_base_address);
|
||||
else
|
||||
ip_offset += struct_size(ip, base_address, ip->num_base_address);
|
||||
}
|
||||
}
|
||||
|
||||
if (wafl_ver && !adev->ip_versions[XGMI_HWIP][0])
|
||||
adev->ip_versions[XGMI_HWIP][0] = wafl_ver;
|
||||
|
||||
return 0;
|
||||
ihdr = (struct ip_discovery_header *)(discovery_bin + le16_to_cpu(info->offset));
|
||||
struct amdgpu_discovery_ip_targets targets = {
|
||||
.xcc_mask = &adev->gfx.xcc_mask, .sdma_mask = &adev->sdma.sdma_mask,
|
||||
.vcn_mask = &adev->vcn.inst_mask, .jpeg_mask = &adev->jpeg.inst_mask,
|
||||
.vcn_count = &adev->vcn.num_vcn_inst, .sdma_count = &adev->sdma.num_instances,
|
||||
.vpe_count = &adev->vpe.num_instances, .umc_count = &adev->gmc.num_umc,
|
||||
.node_count = &adev->umc.node_inst_num, .ip_versions = adev->ip_versions,
|
||||
};
|
||||
for (int i = 0; i < AMDGPU_MAX_VCN_INSTANCES; i++)
|
||||
targets.vcn_config[i] = &adev->vcn.inst[i].vcn_config;
|
||||
const struct amdgpu_discovery_ip_ops ops = {
|
||||
.context = adev, .bind = amdgpu_discovery_ip_bind,
|
||||
.debug = amdgpu_discovery_ip_debug, .error = amdgpu_discovery_ip_error,
|
||||
.drm_error = amdgpu_discovery_ip_drm_error,
|
||||
.hw_id_names = hw_id_names,
|
||||
};
|
||||
return amdgpu_discovery_ip_walk(discovery_bin, ihdr, &targets, &ops);
|
||||
}
|
||||
|
||||
static void amdgpu_discovery_harvest_ip(struct amdgpu_device *adev)
|
||||
@@ -1981,41 +1623,85 @@ union nps_info {
|
||||
static int amdgpu_discovery_refresh_nps_info(struct amdgpu_device *adev,
|
||||
union nps_info *nps_data)
|
||||
{
|
||||
uint64_t vram_size, pos, offset;
|
||||
struct nps_info_header *nhdr;
|
||||
struct binary_header bhdr;
|
||||
struct binary_header_v2 bhdrv2;
|
||||
uint16_t checksum;
|
||||
struct binary_header_v2 header __aligned(sizeof(u32)) = {0};
|
||||
struct binary_header_v2 observed_header __aligned(sizeof(u32)) = {0};
|
||||
struct table_info info __aligned(sizeof(u32)) = {0};
|
||||
struct table_info observed_info __aligned(sizeof(u32)) = {0};
|
||||
struct nps_info_header nhdr __aligned(sizeof(u32)) = {0};
|
||||
struct amdgpu_discovery_directory directory;
|
||||
union nps_info data __aligned(sizeof(u32)) = {0};
|
||||
u64 pos, vram_size;
|
||||
u32 memory_mib, size, read_size, count;
|
||||
u16 offset;
|
||||
|
||||
vram_size = (uint64_t)RREG32(mmRCC_CONFIG_MEMSIZE) << 20;
|
||||
pos = vram_size - DISCOVERY_TMR_OFFSET;
|
||||
amdgpu_device_vram_access(adev, pos, &bhdr, sizeof(bhdr), false);
|
||||
|
||||
switch (bhdr.version_major) {
|
||||
case 2:
|
||||
amdgpu_device_vram_access(adev, pos, &bhdrv2, sizeof(bhdrv2), false);
|
||||
offset = le16_to_cpu(bhdrv2.table_list[NPS_INFO].offset);
|
||||
checksum = le16_to_cpu(bhdrv2.table_list[NPS_INFO].checksum);
|
||||
break;
|
||||
case 1:
|
||||
offset = le16_to_cpu(bhdr.table_list[NPS_INFO].offset);
|
||||
checksum = le16_to_cpu(bhdr.table_list[NPS_INFO].checksum);
|
||||
break;
|
||||
default:
|
||||
/* The original GMC reset caller serializes this live acquisition. Use
|
||||
* the region actually acquired/reserved by discovery, including mailbox
|
||||
* and dynamic offsets; never substitute VRAM-end minus a fixed offset.
|
||||
* Sysmem-only discovery needs its own genuine acquisition path. */
|
||||
if (!nps_data || !adev->discovery.bin || !adev->discovery.reserve_tmr ||
|
||||
adev->discovery.size < sizeof(header) ||
|
||||
amdgpu_device_skip_hw_access(adev))
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
amdgpu_device_vram_access(adev, (pos + offset), nps_data,
|
||||
sizeof(*nps_data), false);
|
||||
|
||||
nhdr = (struct nps_info_header *)(nps_data);
|
||||
if (!amdgpu_discovery_verify_checksum(adev, (uint8_t *)nps_data,
|
||||
le32_to_cpu(nhdr->size_bytes),
|
||||
checksum)) {
|
||||
dev_err(adev->dev, "nps data refresh, checksum mismatch\n");
|
||||
memory_mib = RREG32(mmRCC_CONFIG_MEMSIZE);
|
||||
if (!memory_mib || memory_mib == U32_MAX)
|
||||
return -EINVAL;
|
||||
vram_size = (u64)memory_mib << 20;
|
||||
pos = adev->discovery.offset;
|
||||
if (pos > vram_size || adev->discovery.size > vram_size - pos)
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
/* v2's flexible table_list is not part of this stack prefix. Read the
|
||||
* single original entry only after validating its directory geometry. */
|
||||
amdgpu_device_vram_access(adev, pos, &header, sizeof(header), false);
|
||||
if (le32_to_cpu(header.binary_signature) != BINARY_SIGNATURE ||
|
||||
(le16_to_cpu(header.version_major) != 1 &&
|
||||
le16_to_cpu(header.version_major) != 2) ||
|
||||
amdgpu_discovery_binary_directory((const u8 *)&header, sizeof(header),
|
||||
adev->discovery.size, NPS_INFO, &directory))
|
||||
return -EINVAL;
|
||||
amdgpu_device_vram_access(adev, pos + directory.entry_offset, &info,
|
||||
sizeof(info), false);
|
||||
offset = le16_to_cpu(info.offset);
|
||||
if (!offset)
|
||||
return -ENOENT;
|
||||
if (offset < directory.directory_bytes ||
|
||||
offset > directory.binary_bytes ||
|
||||
sizeof(nhdr) > directory.binary_bytes - offset)
|
||||
return -EINVAL;
|
||||
amdgpu_device_vram_access(adev, pos + offset, &nhdr, sizeof(nhdr), false);
|
||||
size = le32_to_cpu(nhdr.size_bytes);
|
||||
if (le32_to_cpu(nhdr.table_id) != NPS_INFO_TABLE_ID ||
|
||||
le16_to_cpu(nhdr.version_major) != 1 ||
|
||||
size < offsetof(struct nps_info_v1_0, instance_info) ||
|
||||
size > sizeof(data) || size > directory.binary_bytes - offset)
|
||||
return -EINVAL;
|
||||
/* The original MM fallback transfers DWORDs even when the checksum span
|
||||
* is not a multiple of four. Padding may only come from our retained
|
||||
* region and must fit the private destination; it is never published. */
|
||||
read_size = (u32)ALIGN(size, sizeof(u32));
|
||||
if (read_size > sizeof(data) || read_size > adev->discovery.size - offset)
|
||||
return -EINVAL;
|
||||
amdgpu_device_vram_access(adev, pos + offset, &data, read_size, false);
|
||||
memset((u8 *)&data + size, 0, sizeof(data) - size);
|
||||
count = le32_to_cpu(data.v1.count);
|
||||
if (memcmp(&data.v1.header, &nhdr, sizeof(nhdr)) ||
|
||||
count > NPS_INFO_TABLE_MAX_NUM_INSTANCES ||
|
||||
count > (size - offsetof(struct nps_info_v1_0, instance_info)) /
|
||||
sizeof(struct nps_instance_info_v1_0) ||
|
||||
!amdgpu_discovery_verify_checksum(adev, (u8 *)&data, size,
|
||||
le16_to_cpu(info.checksum)))
|
||||
return -EINVAL;
|
||||
|
||||
/* VRAM access has a void ABI. Initialized private buffers and bounded
|
||||
* consistency/integrity checks do not invent a read-success result. */
|
||||
amdgpu_device_vram_access(adev, pos, &observed_header,
|
||||
sizeof(observed_header), false);
|
||||
amdgpu_device_vram_access(adev, pos + directory.entry_offset,
|
||||
&observed_info, sizeof(observed_info), false);
|
||||
if (memcmp(&header, &observed_header, sizeof(header)) ||
|
||||
memcmp(&info, &observed_info, sizeof(info)))
|
||||
return -EINVAL;
|
||||
*nps_data = data;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2842,7 +2528,7 @@ int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *adev)
|
||||
{
|
||||
int r;
|
||||
|
||||
switch (adev->asic_type) {
|
||||
switch (amdgpu_discovery_static_asic(adev->asic_type)) {
|
||||
case CHIP_VEGA10:
|
||||
/* This is not fatal. We only need the discovery
|
||||
* binary for sysfs. We don't need it for a
|
||||
@@ -3048,7 +2734,7 @@ int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *adev)
|
||||
adev->ip_versions[XGMI_HWIP][0] = IP_VERSION(6, 1, 0);
|
||||
break;
|
||||
case CHIP_CYAN_SKILLFISH:
|
||||
if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2) {
|
||||
if (amdgpu_discovery_cyan_skillfish2(adev->apu_flags)) {
|
||||
r = amdgpu_discovery_reg_base_init(adev);
|
||||
if (r)
|
||||
return -EINVAL;
|
||||
|
||||
@@ -26,8 +26,7 @@
|
||||
|
||||
#include <linux/debugfs.h>
|
||||
|
||||
#define DISCOVERY_TMR_SIZE (10 << 10)
|
||||
#define DISCOVERY_TMR_OFFSET (64 << 10)
|
||||
#include "amdgpu_discovery_tmr_limits.h"
|
||||
|
||||
struct ip_discovery_top;
|
||||
struct drm_printer;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_DISCOVERY_FILE_CORE_H
|
||||
#define AMDGPU_DISCOVERY_FILE_CORE_H
|
||||
#include "../stela/discovery_binary.h"
|
||||
|
||||
enum amdgpu_discovery_file_status {
|
||||
AMDGPU_DISCOVERY_FILE_OK,
|
||||
AMDGPU_DISCOVERY_FILE_TOO_LARGE,
|
||||
AMDGPU_DISCOVERY_FILE_TOO_SMALL,
|
||||
AMDGPU_DISCOVERY_FILE_INVALID,
|
||||
};
|
||||
/* Actual preferred-file span before copy into the zeroed TMR-sized allocation.
|
||||
* The original caller keeps request/log/copy/release and outer source policy.
|
||||
* Readable immutable actual file bytes are required. No pointer retained. */
|
||||
static inline enum amdgpu_discovery_file_status
|
||||
amdgpu_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity)
|
||||
{
|
||||
if (bytes > capacity)
|
||||
return AMDGPU_DISCOVERY_FILE_TOO_LARGE;
|
||||
/* Ensure the firmware is at least large enough to contain the
|
||||
* binary header fields.
|
||||
*/
|
||||
if (bytes < offsetof(struct binary_header, binary_size) +
|
||||
sizeof(((struct binary_header *)0)->binary_size))
|
||||
return AMDGPU_DISCOVERY_FILE_TOO_SMALL;
|
||||
/* A short file must not borrow zero-filled TMR padding as firmware data. */
|
||||
if (amdgpu_discovery_binary_validate(data, bytes) != AMDGPU_DISCOVERY_BINARY_OK)
|
||||
return AMDGPU_DISCOVERY_FILE_INVALID;
|
||||
return AMDGPU_DISCOVERY_FILE_OK;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,308 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_DISCOVERY_IP_CORE_H
|
||||
#define AMDGPU_DISCOVERY_IP_CORE_H
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#include <linux/errno.h>
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "../../common/linux/include/uapi/asm-generic/errno-base.h"
|
||||
/* Native Stela owns these little-endian snapshots. */
|
||||
#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
|
||||
#error "Native AMD discovery requires little-endian target"
|
||||
#endif
|
||||
#define le16_to_cpu(x) (x)
|
||||
#define le32_to_cpu(x) (x)
|
||||
#define le64_to_cpu(x) (x)
|
||||
#define lower_32_bits(x) ((uint32_t)(x))
|
||||
#define struct_size(p, member, n) (sizeof(*(p)) + sizeof((p)->member[0]) * (n))
|
||||
#endif
|
||||
#include "../include/discovery.h"
|
||||
#include "../include/soc15_hw_ip.h"
|
||||
#include "amdgpu_ip_types.h"
|
||||
#include "amdgpu_ip_limits.h"
|
||||
#include "amdgpu_ip_instance_limits.h"
|
||||
|
||||
static int hw_id_map[MAX_HWIP] = {
|
||||
[GC_HWIP] = GC_HWID,
|
||||
[HDP_HWIP] = HDP_HWID,
|
||||
[SDMA0_HWIP] = SDMA0_HWID,
|
||||
[SDMA1_HWIP] = SDMA1_HWID,
|
||||
[SDMA2_HWIP] = SDMA2_HWID,
|
||||
[SDMA3_HWIP] = SDMA3_HWID,
|
||||
[LSDMA_HWIP] = LSDMA_HWID,
|
||||
[MMHUB_HWIP] = MMHUB_HWID,
|
||||
[ATHUB_HWIP] = ATHUB_HWID,
|
||||
[NBIO_HWIP] = NBIF_HWID,
|
||||
[MP0_HWIP] = MP0_HWID,
|
||||
[MP1_HWIP] = MP1_HWID,
|
||||
[UVD_HWIP] = UVD_HWID,
|
||||
[VCE_HWIP] = VCE_HWID,
|
||||
[DF_HWIP] = DF_HWID,
|
||||
[DCE_HWIP] = DMU_HWID,
|
||||
[OSSSYS_HWIP] = OSSSYS_HWID,
|
||||
[SMUIO_HWIP] = SMUIO_HWID,
|
||||
[PWR_HWIP] = PWR_HWID,
|
||||
[NBIF_HWIP] = NBIF_HWID,
|
||||
[THM_HWIP] = THM_HWID,
|
||||
[CLK_HWIP] = CLKA_HWID,
|
||||
[UMC_HWIP] = UMC_HWID,
|
||||
[XGMI_HWIP] = XGMI_HWID,
|
||||
[DCI_HWIP] = DCI_HWID,
|
||||
[PCIE_HWIP] = PCIE_HWID,
|
||||
[VPE_HWIP] = VPE_HWID,
|
||||
[ISP_HWIP] = ISP_HWID,
|
||||
[ATU_HWIP] = ATU_HWID,
|
||||
};
|
||||
|
||||
/* Direct pointers preserve actual original field types and intermediate writes.
|
||||
* This is a bounded decode target, not an amdgpu_device or hardware owner. */
|
||||
struct amdgpu_discovery_ip_targets {
|
||||
uint16_t *xcc_mask, *vcn_mask, *jpeg_mask;
|
||||
uint32_t *sdma_mask, *vpe_count, *node_count;
|
||||
int *sdma_count, *umc_count;
|
||||
uint8_t *vcn_count, *vcn_config[AMDGPU_MAX_VCN_INSTANCES];
|
||||
uint32_t (*ip_versions)[HWIP_MAX_INSTANCE];
|
||||
};
|
||||
struct amdgpu_discovery_ip_ops {
|
||||
void *context;
|
||||
void (*bind)(void *context, unsigned hw_ip, unsigned instance,
|
||||
uint32_t *base, unsigned count);
|
||||
/* NULL diagnostic callbacks explicitly disable diagnostic output only. */
|
||||
void (*debug)(void *context, const char *format, ...);
|
||||
void (*error)(void *context, const char *format, ...);
|
||||
void (*drm_error)(void *context, const char *format, ...);
|
||||
const char *const *hw_id_names;
|
||||
};
|
||||
#define AMDGPU_IP_DEBUG(ops, ...) do { if ((ops)->debug) (ops)->debug((ops)->context, __VA_ARGS__); } while (0)
|
||||
#define AMDGPU_IP_ERROR(ops, ...) do { if ((ops)->error) (ops)->error((ops)->context, __VA_ARGS__); } while (0)
|
||||
#define AMDGPU_IP_DRM_ERROR(ops, ...) do { if ((ops)->drm_error) (ops)->drm_error((ops)->context, __VA_ARGS__); } while (0)
|
||||
|
||||
static inline int amdgpu_discovery_ip_valid(const struct amdgpu_discovery_ip_ops *ops,
|
||||
uint8_t instance, uint16_t hw_id)
|
||||
{
|
||||
if (instance >= HWIP_MAX_INSTANCE) {
|
||||
AMDGPU_IP_ERROR(ops,
|
||||
"Unexpected instance_number (%d) from ip discovery blob\n",
|
||||
instance);
|
||||
return -EINVAL;
|
||||
}
|
||||
if (hw_id >= HW_ID_MAX) {
|
||||
AMDGPU_IP_ERROR(ops,
|
||||
"Unexpected hw_id (%d) from ip discovery blob\n",
|
||||
hw_id);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Caller has validated immutable original geometry before its private copy is
|
||||
* mutated. Run once; preserve original32/64 strides and packed accesses. Linux
|
||||
* caller retains its acquisition/mask reset/table-error ordering and targets. */
|
||||
static inline int amdgpu_discovery_ip_walk(uint8_t *discovery_bin,
|
||||
struct ip_discovery_header *ihdr,
|
||||
const struct amdgpu_discovery_ip_targets *targets,
|
||||
const struct amdgpu_discovery_ip_ops *ops)
|
||||
{
|
||||
uint8_t num_base_address, subrev, variant;
|
||||
struct die_header *dhdr;
|
||||
struct ip_v4 *ip;
|
||||
uint16_t die_offset, ip_offset, num_dies, num_ips, hw_id;
|
||||
uint32_t wafl_ver = 0;
|
||||
uint8_t inst;
|
||||
int hw_ip, i, j, k;
|
||||
num_dies = le16_to_cpu(ihdr->num_dies);
|
||||
|
||||
AMDGPU_IP_DEBUG(ops, "number of dies: %d\n", num_dies);
|
||||
|
||||
for (i = 0; i < num_dies; i++) {
|
||||
die_offset = le16_to_cpu(ihdr->die_info[i].die_offset);
|
||||
dhdr = (struct die_header *)(discovery_bin + die_offset);
|
||||
num_ips = le16_to_cpu(dhdr->num_ips);
|
||||
ip_offset = die_offset + sizeof(*dhdr);
|
||||
|
||||
if (le16_to_cpu(dhdr->die_id) != i) {
|
||||
AMDGPU_IP_DRM_ERROR(ops, "invalid die id %d, expected %d\n",
|
||||
le16_to_cpu(dhdr->die_id), i);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
AMDGPU_IP_DEBUG(ops, "number of hardware IPs on die%d: %d\n",
|
||||
le16_to_cpu(dhdr->die_id), num_ips);
|
||||
|
||||
for (j = 0; j < num_ips; j++) {
|
||||
ip = (struct ip_v4 *)(discovery_bin + ip_offset);
|
||||
|
||||
inst = ip->instance_number;
|
||||
hw_id = le16_to_cpu(ip->hw_id);
|
||||
if (amdgpu_discovery_ip_valid(ops, inst, hw_id))
|
||||
goto next_ip;
|
||||
|
||||
num_base_address = ip->num_base_address;
|
||||
|
||||
AMDGPU_IP_DEBUG(ops, "%s(%d) #%d v%d.%d.%d:\n",
|
||||
ops->hw_id_names[le16_to_cpu(ip->hw_id)],
|
||||
le16_to_cpu(ip->hw_id),
|
||||
ip->instance_number,
|
||||
ip->major, ip->minor,
|
||||
ip->revision);
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VCN_HWID) {
|
||||
/* Bit [5:0]: original revision value
|
||||
* Bit [7:6]: en/decode capability:
|
||||
* 0b00 : VCN function normally
|
||||
* 0b10 : encode is disabled
|
||||
* 0b01 : decode is disabled
|
||||
*/
|
||||
if ((*targets->vcn_count) <
|
||||
AMDGPU_MAX_VCN_INSTANCES) {
|
||||
(*targets->vcn_config[(*targets->vcn_count)]) =
|
||||
ip->revision & 0xc0;
|
||||
(*targets->vcn_count)++;
|
||||
(*targets->vcn_mask) |=
|
||||
(1U << ip->instance_number);
|
||||
(*targets->jpeg_mask) |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
AMDGPU_IP_ERROR(ops, "Too many VCN instances: %d vs %d\n",
|
||||
(*targets->vcn_count) + 1,
|
||||
AMDGPU_MAX_VCN_INSTANCES);
|
||||
}
|
||||
ip->revision &= ~0xc0;
|
||||
}
|
||||
if (le16_to_cpu(ip->hw_id) == SDMA0_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA1_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA2_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA3_HWID) {
|
||||
if ((*targets->sdma_count) <
|
||||
AMDGPU_MAX_SDMA_INSTANCES) {
|
||||
(*targets->sdma_count)++;
|
||||
(*targets->sdma_mask) |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
AMDGPU_IP_ERROR(ops, "Too many SDMA instances: %d vs %d\n",
|
||||
(*targets->sdma_count) + 1,
|
||||
AMDGPU_MAX_SDMA_INSTANCES);
|
||||
}
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VPE_HWID) {
|
||||
if ((*targets->vpe_count) < AMDGPU_MAX_VPE_INSTANCES)
|
||||
(*targets->vpe_count)++;
|
||||
else
|
||||
AMDGPU_IP_ERROR(ops, "Too many VPE instances: %d vs %d\n",
|
||||
(*targets->vpe_count) + 1,
|
||||
AMDGPU_MAX_VPE_INSTANCES);
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == UMC_HWID) {
|
||||
(*targets->umc_count)++;
|
||||
(*targets->node_count)++;
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == GC_HWID)
|
||||
(*targets->xcc_mask) |=
|
||||
(1U << ip->instance_number);
|
||||
|
||||
if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID)
|
||||
wafl_ver = IP_VERSION_FULL((uint32_t)ip->major, (uint32_t)ip->minor,
|
||||
(uint32_t)ip->revision, 0, 0);
|
||||
|
||||
for (k = 0; k < num_base_address; k++) {
|
||||
/*
|
||||
* convert the endianness of base addresses in place,
|
||||
* so that we don't need to convert them when accessing adev->reg_offset.
|
||||
*/
|
||||
if (ihdr->base_addr_64_bit)
|
||||
/* Truncate the 64bit base address from ip discovery
|
||||
* and only store lower 32bit ip base in reg_offset[].
|
||||
* Bits > 32 follows ASIC specific format, thus just
|
||||
* discard them and handle it within specific ASIC.
|
||||
* By this way reg_offset[] and related helpers can
|
||||
* stay unchanged.
|
||||
* The base address is in dwords, thus clear the
|
||||
* highest 2 bits to store.
|
||||
*/
|
||||
ip->base_address[k] =
|
||||
lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF;
|
||||
else
|
||||
ip->base_address[k] = le32_to_cpu(ip->base_address[k]);
|
||||
AMDGPU_IP_DEBUG(ops, "\t0x%08x\n", ip->base_address[k]);
|
||||
}
|
||||
|
||||
for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) {
|
||||
if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) &&
|
||||
hw_id_map[hw_ip] != 0) {
|
||||
AMDGPU_IP_DEBUG(ops, "set register base offset for %s\n",
|
||||
ops->hw_id_names[le16_to_cpu(ip->hw_id)]);
|
||||
ops->bind(ops->context, hw_ip, ip->instance_number,
|
||||
ip->base_address, num_base_address);
|
||||
/* Instance support is somewhat inconsistent.
|
||||
* SDMA is a good example. Sienna cichlid has 4 total
|
||||
* SDMA instances, each enumerated separately (HWIDs
|
||||
* 42, 43, 68, 69). Arcturus has 8 total SDMA instances,
|
||||
* but they are enumerated as multiple instances of the
|
||||
* same HWIDs (4x HWID 42, 4x HWID 43). UMC is another
|
||||
* example. On most chips there are multiple instances
|
||||
* with the same HWID.
|
||||
*/
|
||||
|
||||
if (ihdr->version < 3) {
|
||||
subrev = 0;
|
||||
variant = 0;
|
||||
} else {
|
||||
subrev = ip->sub_revision;
|
||||
variant = ip->variant;
|
||||
}
|
||||
|
||||
targets->ip_versions[hw_ip]
|
||||
[ip->instance_number] =
|
||||
IP_VERSION_FULL((uint32_t)ip->major,
|
||||
(uint32_t)ip->minor,
|
||||
(uint32_t)ip->revision,
|
||||
variant,
|
||||
subrev);
|
||||
}
|
||||
}
|
||||
|
||||
next_ip:
|
||||
if (ihdr->base_addr_64_bit)
|
||||
ip_offset += struct_size(ip, base_address_64, ip->num_base_address);
|
||||
else
|
||||
ip_offset += struct_size(ip, base_address, ip->num_base_address);
|
||||
}
|
||||
}
|
||||
|
||||
if (wafl_ver && !targets->ip_versions[XGMI_HWIP][0])
|
||||
targets->ip_versions[XGMI_HWIP][0] = wafl_ver;
|
||||
|
||||
return 0;
|
||||
}
|
||||
#undef AMDGPU_IP_DEBUG
|
||||
#undef AMDGPU_IP_ERROR
|
||||
#undef AMDGPU_IP_DRM_ERROR
|
||||
#endif
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Copyright 2008 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_DISCOVERY_SOURCE_CORE_H
|
||||
#define AMDGPU_DISCOVERY_SOURCE_CORE_H
|
||||
#include "../../common/linux/include/drm/amd_asic_type.h"
|
||||
#include "../include/amd_chip_flags.h"
|
||||
/* Exact original early-init case groups; SI/CIK build admission is separate. */
|
||||
enum amdgpu_initial_ip_path {
|
||||
AMDGPU_INITIAL_IP_DISCOVERY,
|
||||
AMDGPU_INITIAL_IP_SI,
|
||||
AMDGPU_INITIAL_IP_CIK,
|
||||
AMDGPU_INITIAL_IP_VI,
|
||||
};
|
||||
static inline enum amdgpu_initial_ip_path amdgpu_initial_ip_path(enum amd_asic_type asic_type)
|
||||
{
|
||||
switch (asic_type) {
|
||||
case CHIP_VERDE:
|
||||
case CHIP_TAHITI:
|
||||
case CHIP_PITCAIRN:
|
||||
case CHIP_OLAND:
|
||||
case CHIP_HAINAN:
|
||||
return AMDGPU_INITIAL_IP_SI;
|
||||
case CHIP_BONAIRE:
|
||||
case CHIP_HAWAII:
|
||||
case CHIP_KAVERI:
|
||||
case CHIP_KABINI:
|
||||
case CHIP_MULLINS:
|
||||
return AMDGPU_INITIAL_IP_CIK;
|
||||
case CHIP_TOPAZ:
|
||||
case CHIP_TONGA:
|
||||
case CHIP_FIJI:
|
||||
case CHIP_POLARIS10:
|
||||
case CHIP_POLARIS11:
|
||||
case CHIP_POLARIS12:
|
||||
case CHIP_VEGAM:
|
||||
case CHIP_CARRIZO:
|
||||
case CHIP_STONEY:
|
||||
return AMDGPU_INITIAL_IP_VI;
|
||||
default:
|
||||
return AMDGPU_INITIAL_IP_DISCOVERY;
|
||||
}
|
||||
}
|
||||
/* The original switch has these static arms and one default dynamic arm. */
|
||||
static inline enum amd_asic_type amdgpu_discovery_static_asic(enum amd_asic_type asic_type)
|
||||
{
|
||||
switch (asic_type) {
|
||||
case CHIP_VEGA10:
|
||||
case CHIP_VEGA12:
|
||||
case CHIP_RAVEN:
|
||||
case CHIP_VEGA20:
|
||||
case CHIP_ARCTURUS:
|
||||
case CHIP_ALDEBARAN:
|
||||
case CHIP_CYAN_SKILLFISH:
|
||||
return asic_type;
|
||||
default:
|
||||
return CHIP_LAST;
|
||||
}
|
||||
}
|
||||
static inline int amdgpu_discovery_cyan_skillfish2(unsigned long apu_flags)
|
||||
{
|
||||
return (apu_flags & AMD_APU_IS_CYAN_SKILLFISH2) != 0;
|
||||
}
|
||||
static inline const char *amdgpu_discovery_fw_name(enum amd_asic_type asic_type,
|
||||
unsigned long apu_flags, int discovery_option)
|
||||
{
|
||||
if (discovery_option == 2) {
|
||||
return "amdgpu/ip_discovery.bin";
|
||||
}
|
||||
|
||||
switch (asic_type) {
|
||||
case CHIP_VEGA10:
|
||||
return "amdgpu/vega10_ip_discovery.bin";
|
||||
case CHIP_VEGA12:
|
||||
return "amdgpu/vega12_ip_discovery.bin";
|
||||
case CHIP_RAVEN:
|
||||
if (apu_flags & AMD_APU_IS_RAVEN2)
|
||||
return "amdgpu/raven2_ip_discovery.bin";
|
||||
else if (apu_flags & AMD_APU_IS_PICASSO)
|
||||
return "amdgpu/picasso_ip_discovery.bin";
|
||||
else
|
||||
return "amdgpu/raven_ip_discovery.bin";
|
||||
case CHIP_VEGA20:
|
||||
return "amdgpu/vega20_ip_discovery.bin";
|
||||
case CHIP_ARCTURUS:
|
||||
return "amdgpu/arcturus_ip_discovery.bin";
|
||||
case CHIP_ALDEBARAN:
|
||||
return "amdgpu/aldebaran_ip_discovery.bin";
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright 2018 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_DISCOVERY_TMR_CORE_H
|
||||
#define AMDGPU_DISCOVERY_TMR_CORE_H
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#include <linux/limits.h>
|
||||
#include <linux/errno.h>
|
||||
#define AMDGPU_TMR_U32_MAX U32_MAX
|
||||
#define AMDGPU_TMR_ENXIO ENXIO
|
||||
#define AMDGPU_TMR_EINVAL EINVAL
|
||||
#define AMDGPU_TMR_LE32(value) le32_to_cpu(value)
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#define AMDGPU_TMR_U32_MAX UINT32_MAX
|
||||
#define AMDGPU_TMR_ENXIO 6
|
||||
#define AMDGPU_TMR_EINVAL 22
|
||||
#define AMDGPU_TMR_LE32(value) (value) /* Native consumer is x86-64 little endian. */
|
||||
#endif
|
||||
#include "amdgpu_discovery_tmr_limits.h"
|
||||
#include "../include/discovery.h"
|
||||
/* These original bootstrap register offsets are consistent across the SoCs. */
|
||||
#define mmRCC_CONFIG_MEMSIZE 0xde3
|
||||
#define mmMP0_SMN_C2PMSG_33 0x16061
|
||||
#define mmDRIVER_SCRATCH_0 0x94
|
||||
#define mmDRIVER_SCRATCH_1 0x95
|
||||
#define mmDRIVER_SCRATCH_2 0x96
|
||||
struct amdgpu_discovery_tmr_state {
|
||||
uint64_t offset;
|
||||
uint32_t size;
|
||||
bool is_sysmem;
|
||||
bool has_memory_size; /* Original bool output is untouched on RCC all-ones. */
|
||||
};
|
||||
struct amdgpu_discovery_tmr_ops {
|
||||
uint32_t (*read32)(void *, uint32_t);
|
||||
void (*sleep_ms)(void *, unsigned);
|
||||
/* Status covers caller preflight/services only. Original void VRAM reads
|
||||
* have no transport acknowledgement; Linux invokes the actual void reader. */
|
||||
int (*read_vram)(void *, uint64_t, uint32_t *, size_t);
|
||||
int (*acpi_tmr)(void *, uint64_t *, uint64_t *);
|
||||
};
|
||||
/* Original ordered policy, including nonfatal IFWI poll exhaustion and partial
|
||||
* state on error. All callbacks are real caller services, never optional stubs.
|
||||
* Native callers must bound every register/range and retain the actual owner.
|
||||
*/
|
||||
static inline int amdgpu_discovery_tmr_query_core(
|
||||
const struct amdgpu_discovery_tmr_ops *ops, void *context,
|
||||
bool is_vf, bool dynamic_region, uint64_t critical_offset,
|
||||
uint32_t critical_size, struct amdgpu_discovery_tmr_state *state)
|
||||
{
|
||||
uint64_t vram_size, tmr_offset, tmr_size;
|
||||
uint32_t msg, tmr_offset_lo, tmr_offset_hi;
|
||||
int i, ret;
|
||||
|
||||
if (!is_vf) {
|
||||
/* It can take up to two second for IFWI init to complete on some dGPUs,
|
||||
* but generally it should be in the 60-100ms range. Normally this starts
|
||||
* as soon as the device gets power so by the time the OS loads this has long
|
||||
* completed. However, when a card is hotplugged via e.g., USB4, we need to
|
||||
* wait for this to complete. Once the C2PMSG is updated, we can
|
||||
* continue.
|
||||
*/
|
||||
|
||||
for (i = 0; i < 2000; i++) {
|
||||
msg = ops->read32(context, mmMP0_SMN_C2PMSG_33);
|
||||
if (msg & 0x80000000)
|
||||
break;
|
||||
ops->sleep_ms(context, 1);
|
||||
}
|
||||
}
|
||||
|
||||
vram_size = ops->read32(context, mmRCC_CONFIG_MEMSIZE);
|
||||
if (vram_size == AMDGPU_TMR_U32_MAX)
|
||||
return -AMDGPU_TMR_ENXIO;
|
||||
else if (!vram_size)
|
||||
state->is_sysmem = true;
|
||||
else
|
||||
state->is_sysmem = false;
|
||||
|
||||
state->has_memory_size = true;
|
||||
/* init the default tmr size and offset */
|
||||
state->size = DISCOVERY_TMR_SIZE;
|
||||
if (vram_size)
|
||||
state->offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET;
|
||||
|
||||
if (is_vf) {
|
||||
if (dynamic_region) {
|
||||
state->offset =
|
||||
critical_offset;
|
||||
state->size =
|
||||
critical_size;
|
||||
if (!state->size)
|
||||
return -AMDGPU_TMR_EINVAL;
|
||||
} else {
|
||||
goto out;
|
||||
}
|
||||
} else {
|
||||
if (state->offset) {
|
||||
uint32_t signature;
|
||||
|
||||
/* If VRAM holds a valid discovery signature at the default
|
||||
* discovery offset, use it as-is.
|
||||
*/
|
||||
ret = ops->read_vram(context, state->offset, &signature, sizeof(signature));
|
||||
if (ret)
|
||||
return ret;
|
||||
if (AMDGPU_TMR_LE32(signature) == BINARY_SIGNATURE)
|
||||
goto out;
|
||||
}
|
||||
|
||||
tmr_size = ops->read32(context, mmDRIVER_SCRATCH_2);
|
||||
if (tmr_size) {
|
||||
/* It's preferred to transition to PSP mailbox reg interface
|
||||
* for both bare-metal and passthrough if available */
|
||||
state->size = (uint32_t)tmr_size;
|
||||
tmr_offset_lo = ops->read32(context, mmDRIVER_SCRATCH_0);
|
||||
tmr_offset_hi = ops->read32(context, mmDRIVER_SCRATCH_1);
|
||||
state->offset = ((uint64_t)AMDGPU_TMR_LE32(tmr_offset_hi) << 32 |
|
||||
AMDGPU_TMR_LE32(tmr_offset_lo));
|
||||
} else if (!vram_size) {
|
||||
/* fall back to apci approach to query tmr offset if vram_size is 0 */
|
||||
ret = ops->acpi_tmr(context, &tmr_offset, &tmr_size);
|
||||
if (ret)
|
||||
return ret;
|
||||
state->size = DISCOVERY_TMR_SIZE;
|
||||
state->offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET;
|
||||
}
|
||||
}
|
||||
out:
|
||||
return 0;
|
||||
}
|
||||
#undef AMDGPU_TMR_ENXIO
|
||||
#undef AMDGPU_TMR_EINVAL
|
||||
#undef AMDGPU_TMR_U32_MAX
|
||||
#undef AMDGPU_TMR_LE32
|
||||
#endif
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2018 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_DISCOVERY_TMR_LIMITS_H
|
||||
#define AMDGPU_DISCOVERY_TMR_LIMITS_H
|
||||
#define DISCOVERY_TMR_SIZE (10 << 10)
|
||||
#define DISCOVERY_TMR_OFFSET (64 << 10)
|
||||
#endif
|
||||
@@ -23,6 +23,7 @@
|
||||
*/
|
||||
|
||||
#include "amdgpu.h"
|
||||
#include "../stela/native_bar.h"
|
||||
|
||||
/**
|
||||
* amdgpu_mm_rdoorbell - read a doorbell dword
|
||||
@@ -156,7 +157,8 @@ int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev)
|
||||
return 0;
|
||||
|
||||
/* Reserve first num_kernel_doorbells (page-aligned) for kernel ops */
|
||||
size = ALIGN(adev->doorbell.num_kernel_doorbells * sizeof(u32), PAGE_SIZE);
|
||||
size = amdgpu_native_kernel_doorbell_storage_bytes(adev->doorbell.num_kernel_doorbells,
|
||||
PAGE_SIZE);
|
||||
|
||||
/* Allocate an extra page for MES kernel usages (ring test) */
|
||||
adev->mes.db_start_dw_offset = size / sizeof(u32);
|
||||
@@ -211,21 +213,11 @@ int amdgpu_doorbell_init(struct amdgpu_device *adev)
|
||||
adev->doorbell.size = pci_resource_len(adev->pdev, 2);
|
||||
|
||||
adev->doorbell.num_kernel_doorbells =
|
||||
min_t(u32, adev->doorbell.size / sizeof(u32),
|
||||
adev->doorbell_index.max_assignment + 1);
|
||||
amdgpu_native_kernel_doorbell_count(adev->asic_type, adev->doorbell.size,
|
||||
adev->doorbell_index.max_assignment);
|
||||
if (adev->doorbell.num_kernel_doorbells == 0)
|
||||
return -EINVAL;
|
||||
|
||||
/*
|
||||
* For Vega, reserve and map two pages on doorbell BAR since SDMA
|
||||
* paging queue doorbell use the second page. The
|
||||
* AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the
|
||||
* doorbells are in the first page. So with paging queue enabled,
|
||||
* the max num_kernel_doorbells should + 1 page (0x400 in dword)
|
||||
*/
|
||||
if (adev->asic_type >= CHIP_VEGA10)
|
||||
adev->doorbell.num_kernel_doorbells += 0x400;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,64 +25,11 @@
|
||||
#define __AMDGPU_IP_H__
|
||||
|
||||
#include "amd_shared.h"
|
||||
#include "amdgpu_ip_limits.h"
|
||||
|
||||
struct amdgpu_device;
|
||||
|
||||
/* Define the HW IP blocks will be used in driver , add more if necessary */
|
||||
enum amd_hw_ip_block_type {
|
||||
GC_HWIP = 1,
|
||||
HDP_HWIP,
|
||||
SDMA0_HWIP,
|
||||
SDMA1_HWIP,
|
||||
SDMA2_HWIP,
|
||||
SDMA3_HWIP,
|
||||
SDMA4_HWIP,
|
||||
SDMA5_HWIP,
|
||||
SDMA6_HWIP,
|
||||
SDMA7_HWIP,
|
||||
LSDMA_HWIP,
|
||||
MMHUB_HWIP,
|
||||
ATHUB_HWIP,
|
||||
NBIO_HWIP,
|
||||
MP0_HWIP,
|
||||
MP1_HWIP,
|
||||
UVD_HWIP,
|
||||
VCN_HWIP = UVD_HWIP,
|
||||
JPEG_HWIP = VCN_HWIP,
|
||||
VCN1_HWIP,
|
||||
VCE_HWIP,
|
||||
VPE_HWIP,
|
||||
DF_HWIP,
|
||||
DCE_HWIP,
|
||||
OSSSYS_HWIP,
|
||||
SMUIO_HWIP,
|
||||
PWR_HWIP,
|
||||
NBIF_HWIP,
|
||||
THM_HWIP,
|
||||
CLK_HWIP,
|
||||
UMC_HWIP,
|
||||
RSMU_HWIP,
|
||||
XGMI_HWIP,
|
||||
DCI_HWIP,
|
||||
PCIE_HWIP,
|
||||
ISP_HWIP,
|
||||
ATU_HWIP,
|
||||
AIGC_HWIP,
|
||||
MAX_HWIP
|
||||
};
|
||||
|
||||
#define HWIP_MAX_INSTANCE 48
|
||||
|
||||
#define HW_ID_MAX 300
|
||||
#define IP_VERSION_FULL(mj, mn, rv, var, srev) \
|
||||
(((mj) << 24) | ((mn) << 16) | ((rv) << 8) | ((var) << 4) | (srev))
|
||||
#define IP_VERSION(mj, mn, rv) IP_VERSION_FULL(mj, mn, rv, 0, 0)
|
||||
#define IP_VERSION_MAJ(ver) ((ver) >> 24)
|
||||
#define IP_VERSION_MIN(ver) (((ver) >> 16) & 0xFF)
|
||||
#define IP_VERSION_REV(ver) (((ver) >> 8) & 0xFF)
|
||||
#define IP_VERSION_VARIANT(ver) (((ver) >> 4) & 0xF)
|
||||
#define IP_VERSION_SUBREV(ver) ((ver) & 0xF)
|
||||
#define IP_VERSION_MAJ_MIN_REV(ver) ((ver) >> 8)
|
||||
#include "amdgpu_ip_types.h"
|
||||
|
||||
struct amdgpu_ip_map_info {
|
||||
/* Map of logical to actual dev instances/mask */
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2025 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_IP_INSTANCE_LIMITS_H
|
||||
#define AMDGPU_IP_INSTANCE_LIMITS_H
|
||||
#define AMDGPU_MAX_VCN_INSTANCES 4
|
||||
#define AMDGPU_MAX_SDMA_INSTANCES 16
|
||||
#define AMDGPU_MAX_VPE_INSTANCES 2
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2025 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_IP_LIMITS_H
|
||||
#define AMDGPU_IP_LIMITS_H
|
||||
|
||||
/* Original driver array bounds, shared by discovery and its consumers. */
|
||||
#define HWIP_MAX_INSTANCE 48
|
||||
#define HW_ID_MAX 300
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2025 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_IP_TYPES_H
|
||||
#define AMDGPU_IP_TYPES_H
|
||||
|
||||
/* Define the HW IP blocks will be used in driver , add more if necessary */
|
||||
enum amd_hw_ip_block_type {
|
||||
GC_HWIP = 1,
|
||||
HDP_HWIP,
|
||||
SDMA0_HWIP,
|
||||
SDMA1_HWIP,
|
||||
SDMA2_HWIP,
|
||||
SDMA3_HWIP,
|
||||
SDMA4_HWIP,
|
||||
SDMA5_HWIP,
|
||||
SDMA6_HWIP,
|
||||
SDMA7_HWIP,
|
||||
LSDMA_HWIP,
|
||||
MMHUB_HWIP,
|
||||
ATHUB_HWIP,
|
||||
NBIO_HWIP,
|
||||
MP0_HWIP,
|
||||
MP1_HWIP,
|
||||
UVD_HWIP,
|
||||
VCN_HWIP = UVD_HWIP,
|
||||
JPEG_HWIP = VCN_HWIP,
|
||||
VCN1_HWIP,
|
||||
VCE_HWIP,
|
||||
VPE_HWIP,
|
||||
DF_HWIP,
|
||||
DCE_HWIP,
|
||||
OSSSYS_HWIP,
|
||||
SMUIO_HWIP,
|
||||
PWR_HWIP,
|
||||
NBIF_HWIP,
|
||||
THM_HWIP,
|
||||
CLK_HWIP,
|
||||
UMC_HWIP,
|
||||
RSMU_HWIP,
|
||||
XGMI_HWIP,
|
||||
DCI_HWIP,
|
||||
PCIE_HWIP,
|
||||
ISP_HWIP,
|
||||
ATU_HWIP,
|
||||
AIGC_HWIP,
|
||||
MAX_HWIP
|
||||
};
|
||||
|
||||
#define IP_VERSION_FULL(mj, mn, rv, var, srev) \
|
||||
(((mj) << 24) | ((mn) << 16) | ((rv) << 8) | ((var) << 4) | (srev))
|
||||
#define IP_VERSION(mj, mn, rv) IP_VERSION_FULL(mj, mn, rv, 0, 0)
|
||||
#define IP_VERSION_MAJ(ver) ((ver) >> 24)
|
||||
#define IP_VERSION_MIN(ver) (((ver) >> 16) & 0xFF)
|
||||
#define IP_VERSION_REV(ver) (((ver) >> 8) & 0xFF)
|
||||
#define IP_VERSION_VARIANT(ver) (((ver) >> 4) & 0xF)
|
||||
#define IP_VERSION_SUBREV(ver) ((ver) & 0xF)
|
||||
#define IP_VERSION_MAJ_MIN_REV(ver) ((ver) >> 8)
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,73 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2008 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_MM_ACCESS_CORE_H
|
||||
#define AMDGPU_MM_ACCESS_CORE_H
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#else
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
/* Callers include the original BIF register definitions. No default hardware
|
||||
* access, lock, lifetime, allocator or synthetic device context is supplied.
|
||||
* Original Linux wrapper retains drm_dev_enter and IRQ-safe MM-index locking;
|
||||
* the native owner must provide genuine equivalent exclusion before entry.
|
||||
*/
|
||||
struct amdgpu_mm_access_ops {
|
||||
uint32_t (*read32)(void *, uint32_t);
|
||||
void (*write32)(void *, uint32_t, uint32_t);
|
||||
};
|
||||
/* Preserve the original signed loff_t/unsigned last comparison and conversion;
|
||||
* the native entry preflights the complete nonnegative signed range. */
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wsign-compare"
|
||||
static inline void amdgpu_mm_access_core(const struct amdgpu_mm_access_ops *ops,
|
||||
void *context, int64_t pos, uint32_t *data, size_t size, bool write)
|
||||
{
|
||||
uint32_t hi = ~0, tmp = 0;
|
||||
uint64_t last;
|
||||
for (last = pos + size; pos < last; pos += 4) {
|
||||
tmp = pos >> 31;
|
||||
|
||||
ops->write32(context, mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
|
||||
if (tmp != hi) {
|
||||
ops->write32(context, mmMM_INDEX_HI, tmp);
|
||||
hi = tmp;
|
||||
}
|
||||
if (write)
|
||||
ops->write32(context, mmMM_DATA, *data++);
|
||||
else
|
||||
*data++ = ops->read32(context, mmMM_DATA);
|
||||
}
|
||||
|
||||
}
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,7 +26,7 @@
|
||||
#include "amdgpu_ras.h"
|
||||
|
||||
/* max number of IP instances */
|
||||
#define AMDGPU_MAX_SDMA_INSTANCES 16
|
||||
#include "amdgpu_ip_instance_limits.h"
|
||||
|
||||
enum amdgpu_sdma_irq {
|
||||
AMDGPU_SDMA_IRQ_INSTANCE0 = 0,
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
#define AMDGPU_VCN_FIRMWARE_OFFSET 256
|
||||
#define AMDGPU_VCN_MAX_ENC_RINGS 3
|
||||
|
||||
#define AMDGPU_MAX_VCN_INSTANCES 4
|
||||
#include "amdgpu_ip_instance_limits.h"
|
||||
#define AMDGPU_MAX_VCN_ENC_RINGS (AMDGPU_VCN_MAX_ENC_RINGS * AMDGPU_MAX_VCN_INSTANCES)
|
||||
|
||||
#define AMDGPU_VCN_HARVEST_VCN0 (1 << 0)
|
||||
|
||||
@@ -902,25 +902,11 @@ static u32 amdgpu_virt_init_detect_asic(struct amdgpu_device *adev)
|
||||
{
|
||||
uint32_t reg;
|
||||
|
||||
switch (adev->asic_type) {
|
||||
case CHIP_TONGA:
|
||||
case CHIP_FIJI:
|
||||
reg = RREG32(mmBIF_IOV_FUNC_IDENTIFIER);
|
||||
break;
|
||||
case CHIP_VEGA10:
|
||||
case CHIP_VEGA20:
|
||||
case CHIP_NAVI10:
|
||||
case CHIP_NAVI12:
|
||||
case CHIP_SIENNA_CICHLID:
|
||||
case CHIP_ARCTURUS:
|
||||
case CHIP_ALDEBARAN:
|
||||
case CHIP_IP_DISCOVERY:
|
||||
reg = RREG32(mmRCC_IOV_FUNC_IDENTIFIER);
|
||||
break;
|
||||
default: /* other chip doesn't support SRIOV */
|
||||
reg = 0;
|
||||
break;
|
||||
}
|
||||
uint32_t identifier;
|
||||
if (amdgpu_virt_bootstrap_iov_register(adev->asic_type, &identifier))
|
||||
reg = RREG32(identifier);
|
||||
else
|
||||
reg = 0;
|
||||
|
||||
if (reg & 1)
|
||||
adev->virt.caps |= AMDGPU_SRIOV_CAPS_IS_VF;
|
||||
|
||||
@@ -56,10 +56,7 @@
|
||||
#define AMDGPU_RLCG_VFI_STAT__INV_ADDR 0x3
|
||||
#define AMDGPU_RLCG_VFI_STAT__ERR 0xFF
|
||||
|
||||
/* all asic after AI use this offset */
|
||||
#define mmRCC_IOV_FUNC_IDENTIFIER 0xDE5
|
||||
/* tonga/fiji use this offset */
|
||||
#define mmBIF_IOV_FUNC_IDENTIFIER 0x1503
|
||||
#include "amdgpu_virt_bootstrap_core.h"
|
||||
|
||||
#define AMDGPU_VF2PF_UPDATE_MAX_RETRY_LIMIT 2
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2016 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AMDGPU_VIRT_BOOTSTRAP_CORE_H
|
||||
#define AMDGPU_VIRT_BOOTSTRAP_CORE_H
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#include <drm/amd_asic_type.h>
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "../../common/linux/include/drm/amd_asic_type.h"
|
||||
#endif
|
||||
/* all asic after AI use this offset */
|
||||
#define mmRCC_IOV_FUNC_IDENTIFIER 0xDE5
|
||||
/* tonga/fiji use this offset */
|
||||
#define mmBIF_IOV_FUNC_IDENTIFIER 0x1503
|
||||
/* Exact original selector only; no SR-IOV/PF capability or host-mode claim. */
|
||||
static inline bool amdgpu_virt_bootstrap_iov_register(enum amd_asic_type asic_type,
|
||||
uint32_t *reg)
|
||||
{
|
||||
switch (asic_type) {
|
||||
case CHIP_TONGA:
|
||||
case CHIP_FIJI:
|
||||
*reg = mmBIF_IOV_FUNC_IDENTIFIER;
|
||||
return true;
|
||||
case CHIP_VEGA10:
|
||||
case CHIP_VEGA20:
|
||||
case CHIP_NAVI10:
|
||||
case CHIP_NAVI12:
|
||||
case CHIP_SIENNA_CICHLID:
|
||||
case CHIP_ARCTURUS:
|
||||
case CHIP_ALDEBARAN:
|
||||
case CHIP_IP_DISCOVERY:
|
||||
*reg = mmRCC_IOV_FUNC_IDENTIFIER;
|
||||
return true;
|
||||
default: /* other chip doesn't support SRIOV */
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -27,7 +27,7 @@
|
||||
#include "amdgpu_irq.h"
|
||||
#include "vpe_6_1_fw_if.h"
|
||||
|
||||
#define AMDGPU_MAX_VPE_INSTANCES 2
|
||||
#include "amdgpu_ip_instance_limits.h"
|
||||
|
||||
struct amdgpu_vpe;
|
||||
|
||||
|
||||
@@ -0,0 +1,689 @@
|
||||
//! Actual original PF GPU-VRAM discovery acquisition. System firmware RAM and
|
||||
//! VF protocols remain unavailable until their genuine native owners exist.
|
||||
use super::{
|
||||
native_mmio::{
|
||||
AttachedBars, DynamicHardware, Error as WindowError, FileSource, Identity, RegisterWindow,
|
||||
},
|
||||
vram,
|
||||
};
|
||||
use crate::Clock;
|
||||
|
||||
// Exact private discovery_tmr.h enum ABI; C/Rust owner fixtures exercise both.
|
||||
const TMR_VF_OWNER_UNAVAILABLE: c_int = 3;
|
||||
const TMR_SYSTEM_OWNER_UNAVAILABLE: c_int = 4;
|
||||
use alloc::vec::Vec;
|
||||
use core::{
|
||||
ffi::{c_int, c_uint, c_void},
|
||||
marker::PhantomData,
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Window(WindowError),
|
||||
ClockUnavailable,
|
||||
/// Before a region is acquired; may follow real query reads/index writes.
|
||||
Query(c_int),
|
||||
VfOwnerUnavailable,
|
||||
SystemFirmwareOwnerUnavailable,
|
||||
/// Query already ran. Allocation failure never rolls back its effects.
|
||||
PostQueryAllocation,
|
||||
InvalidRegion,
|
||||
Read(vram::Error),
|
||||
Validation(c_int),
|
||||
/// Snapshot already acquired; earlier register effects are not rolled back.
|
||||
PostAcquireAllocation,
|
||||
Decode(c_int),
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct Region {
|
||||
offset: u64,
|
||||
vram_bytes: u64,
|
||||
size: u32,
|
||||
reserved: u32,
|
||||
}
|
||||
const _: () = assert!(size_of::<Region>() == 24);
|
||||
const _: () = assert!(core::mem::offset_of!(Region, size) == 16);
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_discovery_tmr_query(
|
||||
registers: *mut c_void,
|
||||
bytes: usize,
|
||||
asic: u32,
|
||||
context: *mut c_void,
|
||||
sleep_ms: unsafe extern "C" fn(*mut c_void, c_uint),
|
||||
out: &mut Region,
|
||||
) -> c_int;
|
||||
fn amdgpu_discovery_binary_validate(binary: *const u8, bytes: usize) -> c_int;
|
||||
}
|
||||
unsafe extern "C" fn sleep_ms(context: *mut c_void, milliseconds: c_uint) {
|
||||
// SAFETY: acquire lends this exact immutable Clock for the synchronous call.
|
||||
let clock = unsafe { &*context.cast::<Clock>() };
|
||||
clock.delay(u64::from(milliseconds) * 1000);
|
||||
}
|
||||
|
||||
/// Private immutable original bytes and the same actual device owner borrow.
|
||||
/// No mutable view is exposed: original in-place register-base conversions must
|
||||
/// use a separately owned working copy and retain these acquisition bytes.
|
||||
/// A snapshot is not a TMR reservation, BO, authenticated firmware or GPU READY.
|
||||
pub struct Snapshot<'owner> {
|
||||
words: Vec<u32>,
|
||||
region: Region,
|
||||
identity: Identity,
|
||||
_owner: PhantomData<&'owner ()>,
|
||||
}
|
||||
impl Snapshot<'_> {
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
// SAFETY: fully initialized private DWORD allocation; only immutable
|
||||
// bytes exposed, exact logical extent, no device DMA into this buffer.
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(self.words.as_ptr().cast(), self.region.size as usize)
|
||||
}
|
||||
}
|
||||
pub fn identity(&self) -> Identity {
|
||||
self.identity
|
||||
}
|
||||
pub fn vram_offset(&self) -> u64 {
|
||||
self.region.offset
|
||||
}
|
||||
pub fn vram_bytes(&self) -> u64 {
|
||||
self.region.vram_bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Query the original TMR and acquire its actual PF GPU-VRAM snapshot.
|
||||
/// All available register/service bounds are checked before first access;
|
||||
/// mailbox-dependent memory bounds are checked after query and before copying.
|
||||
/// Original void MM reads provide no transport acknowledgement. Only original
|
||||
/// signature/checksums/geometry qualify the private bytes, never hardware state.
|
||||
/// IFWI exhaustion remains nonfatal as in the original driver.
|
||||
///
|
||||
/// # Safety
|
||||
/// The original native owner has selected this discovery bootstrap path on the
|
||||
/// actual matched ASIC. Preserve its static-IP/optional-file policy; this API
|
||||
/// cannot bypass a preferred firmware source or admit another device family.
|
||||
/// Caller holds genuine D0/bridge/reset/removal/MM-index/IRQ exclusion, actual
|
||||
/// UC ordered MMIO semantics and allowed process/CPU context for the WHOLE
|
||||
/// query/copy. No concurrent driver/firmware/device mutation may affect source
|
||||
/// acquisition. The observed RCC extent and selected VRAM source must actually
|
||||
/// be accessible in this epoch. Actual original TMR/VRAM ownership is retained;
|
||||
/// this API creates no reservation and never substitutes host PA or DMA IOVA.
|
||||
/// The same owner cannot reset/rebind/retire while the returned borrow is used.
|
||||
/// `clock` is the mount's genuine calibrated elapsed-time clock, with its real
|
||||
/// wait hook/context. The existing delay busy-waits; it is not scheduler sleep.
|
||||
/// Unexpected access faults follow real platform retention/fail-stop policy;
|
||||
/// no error or Drop can undo earlier register/index effects.
|
||||
pub unsafe fn acquire<'owner>(
|
||||
bars: &'owner AttachedBars<'_>,
|
||||
clock: &Clock,
|
||||
) -> Result<Snapshot<'owner>, Error> {
|
||||
if clock.ticks_per_microsecond == 0 {
|
||||
return Err(Error::ClockUnavailable);
|
||||
}
|
||||
let window = bars.registers().map_err(Error::Window)?;
|
||||
// SAFETY: this same borrowed original owner and full acquisition contract.
|
||||
unsafe { acquire_window(&window, bars.identity(), clock) }
|
||||
}
|
||||
|
||||
unsafe fn query_storage<'owner>(
|
||||
window: &RegisterWindow<'owner>,
|
||||
identity: Identity,
|
||||
clock: &Clock,
|
||||
) -> Result<Snapshot<'owner>, Error> {
|
||||
if clock.ticks_per_microsecond == 0 {
|
||||
return Err(Error::ClockUnavailable);
|
||||
}
|
||||
// SAFETY: original owner contract above; borrowed mapping retained throughout.
|
||||
let registers = unsafe { window.native_base() }.map_err(Error::Window)?;
|
||||
let mut region = Region::default();
|
||||
// SAFETY: exact scalar ABI and synchronous Clock borrow; native preflight
|
||||
// precedes access. No borrowed pointer is retained by the original core.
|
||||
let status = unsafe {
|
||||
stela_amd_discovery_tmr_query(
|
||||
registers.as_ptr().cast(),
|
||||
window.bytes(),
|
||||
identity.asic_type,
|
||||
(clock as *const Clock).cast_mut().cast(),
|
||||
sleep_ms,
|
||||
&mut region,
|
||||
)
|
||||
};
|
||||
match status {
|
||||
0 => {}
|
||||
TMR_VF_OWNER_UNAVAILABLE => return Err(Error::VfOwnerUnavailable),
|
||||
TMR_SYSTEM_OWNER_UNAVAILABLE => return Err(Error::SystemFirmwareOwnerUnavailable),
|
||||
other => return Err(Error::Query(other)),
|
||||
}
|
||||
if region.reserved != 0
|
||||
|| region.size == 0
|
||||
|| !region.size.is_multiple_of(4)
|
||||
|| region.offset > region.vram_bytes
|
||||
|| u64::from(region.size) > region.vram_bytes - region.offset
|
||||
{
|
||||
return Err(Error::InvalidRegion);
|
||||
}
|
||||
let count = region.size as usize / size_of::<u32>();
|
||||
let mut words = Vec::new();
|
||||
words
|
||||
.try_reserve_exact(count)
|
||||
.map_err(|_| Error::PostQueryAllocation)?;
|
||||
words.resize(count, 0);
|
||||
Ok(Snapshot {
|
||||
words,
|
||||
region,
|
||||
identity,
|
||||
_owner: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn acquire_window<'owner>(
|
||||
window: &RegisterWindow<'owner>,
|
||||
identity: Identity,
|
||||
clock: &Clock,
|
||||
) -> Result<Snapshot<'owner>, Error> {
|
||||
// SAFETY: exact same genuine owner/query exclusion contract as acquire.
|
||||
let mut snapshot = unsafe { query_storage(window, identity, clock) }?;
|
||||
// SAFETY: actual bounded original VRAM region and exclusive private CPU RAM.
|
||||
unsafe {
|
||||
vram::read(
|
||||
window,
|
||||
snapshot.region.vram_bytes,
|
||||
snapshot.region.offset,
|
||||
&mut snapshot.words,
|
||||
)
|
||||
}
|
||||
.map_err(Error::Read)?;
|
||||
validate_snapshot(&snapshot)?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
fn validate_snapshot(snapshot: &Snapshot<'_>) -> Result<(), Error> {
|
||||
// SAFETY: complete actual same-allocation private source bytes, immutable
|
||||
// and fully initialized before the original bounded validator runs.
|
||||
let status = unsafe {
|
||||
amdgpu_discovery_binary_validate(
|
||||
snapshot.words.as_ptr().cast(),
|
||||
snapshot.region.size as usize,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Validation(status));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Binding {
|
||||
offset: u32,
|
||||
count: u32,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Shape {
|
||||
hw_ip_count: u32,
|
||||
instances: u32,
|
||||
}
|
||||
/// Original pre-harvest counts and masks, not final topology or Metal limits.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct IpCounts {
|
||||
pub xcc_mask: u16,
|
||||
pub vcn_mask: u16,
|
||||
pub jpeg_mask: u16,
|
||||
pub vcn_count: u8,
|
||||
pub vcn_config: [u8; 4],
|
||||
pub sdma_count: i32,
|
||||
pub sdma_mask: u32,
|
||||
pub vpe_count: u32,
|
||||
pub umc_count: i32,
|
||||
pub node_count: u32,
|
||||
}
|
||||
const _: () = assert!(size_of::<Binding>() == 8);
|
||||
const _: () = assert!(size_of::<Shape>() == 8);
|
||||
const _: () = assert!(size_of::<IpCounts>() == 32);
|
||||
const _: () = assert!(core::mem::offset_of!(IpCounts, sdma_count) == 12);
|
||||
const _: () = assert!(core::mem::offset_of!(IpCounts, node_count) == 28);
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_discovery_ip_shape() -> Shape;
|
||||
fn stela_amd_discovery_ip_decode(
|
||||
work: *mut u8,
|
||||
bytes: usize,
|
||||
versions: *mut u32,
|
||||
version_count: usize,
|
||||
bindings: *mut Binding,
|
||||
binding_count: usize,
|
||||
counts: &mut IpCounts,
|
||||
) -> c_int;
|
||||
}
|
||||
|
||||
/// Observed original IP/register facts. This retains the exact admitted source
|
||||
/// owner, immutable acquisition bytes and one private once-converted copy.
|
||||
/// No public constructor/conversion from Snapshot or raw bytes exists.
|
||||
/// Register offsets are facts, not permission to bypass original register
|
||||
/// routing, bounds, power/reset, firmware or device-context prerequisites.
|
||||
struct IpData<'owner> {
|
||||
snapshot: Snapshot<'owner>,
|
||||
work: Vec<u32>,
|
||||
versions: Vec<u32>,
|
||||
bindings: Vec<Binding>,
|
||||
shape: Shape,
|
||||
counts: IpCounts,
|
||||
}
|
||||
impl IpData<'_> {
|
||||
fn source_bytes(&self) -> &[u8] {
|
||||
self.snapshot.bytes()
|
||||
}
|
||||
fn identity(&self) -> Identity {
|
||||
self.snapshot.identity()
|
||||
}
|
||||
fn counts(&self) -> IpCounts {
|
||||
self.counts
|
||||
}
|
||||
fn slot(&self, hw_ip: u32, instance: u32) -> Option<usize> {
|
||||
if hw_ip >= self.shape.hw_ip_count || instance >= self.shape.instances {
|
||||
return None;
|
||||
}
|
||||
(hw_ip as usize)
|
||||
.checked_mul(self.shape.instances as usize)?
|
||||
.checked_add(instance as usize)
|
||||
}
|
||||
/// Original full version, including variant/subrevision. Zero remains an
|
||||
/// original value; WAFLC may provide a version without a register binding.
|
||||
fn version(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
self.versions.get(self.slot(hw_ip, instance)?).copied()
|
||||
}
|
||||
/// None is unbound/out of range; Some(0) is an original zero-segment binding.
|
||||
fn register_count(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
let binding = self.bindings.get(self.slot(hw_ip, instance)?)?;
|
||||
(binding.offset != u32::MAX).then_some(binding.count)
|
||||
}
|
||||
/// By-value unaligned-safe load from the private converted CPU allocation.
|
||||
/// Never form a Rust &[u32] over the original packed base array.
|
||||
fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option<u32> {
|
||||
let binding = self.bindings.get(self.slot(hw_ip, instance)?)?;
|
||||
if binding.offset == u32::MAX || segment >= binding.count {
|
||||
return None;
|
||||
}
|
||||
let offset = (binding.offset as usize).checked_add((segment as usize).checked_mul(4)?)?;
|
||||
let end = offset.checked_add(4)?;
|
||||
let bytes = self.work.len().checked_mul(size_of::<u32>())?;
|
||||
if end > bytes {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: checked complete initialized owned allocation, immutable CPU
|
||||
// bytes only. No aliasing or device pointer enters this view.
|
||||
let work = unsafe { core::slice::from_raw_parts(self.work.as_ptr().cast::<u8>(), bytes) };
|
||||
Some(u32::from_ne_bytes(work.get(offset..end)?.try_into().ok()?))
|
||||
}
|
||||
}
|
||||
fn storage<T: Clone>(count: usize, value: T) -> Result<Vec<T>, Error> {
|
||||
let mut result = Vec::new();
|
||||
result
|
||||
.try_reserve_exact(count)
|
||||
.map_err(|_| Error::PostAcquireAllocation)?;
|
||||
result.resize(count, value);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Acquire and decode only the original matched dynamic hardware route.
|
||||
/// Static, preferred-file and manual-attachment routes refuse before effects.
|
||||
/// This does not initialize NBIO/GMC or publish a working GPU/VM.
|
||||
///
|
||||
/// # Safety
|
||||
/// All genuine source/VRAM/reservation/context and full MM-index/D0/reset/IRQ
|
||||
/// exclusion requirements of [`acquire`] apply. This exact canonical owner and
|
||||
/// its real device/reset epoch remain valid through all returned facts. No
|
||||
/// allocation/Drop undoes query/index effects or releases original TMR ownership.
|
||||
pub unsafe fn acquire_dynamic_ip<'owner>(
|
||||
bars: &'owner AttachedBars<'_>,
|
||||
clock: &Clock,
|
||||
) -> Result<ObservedIp<'owner>, Error> {
|
||||
let owner = bars.dynamic_hardware().map_err(Error::Window)?;
|
||||
// SAFETY: token holds this exact private admitted window and caller supplies
|
||||
// the same genuine acquisition/reset/exclusion contract as acquire.
|
||||
let snapshot = unsafe { acquire_window(owner.window(), owner.identity(), clock) }?;
|
||||
let data = decode_ip(snapshot)?;
|
||||
Ok(ObservedIp {
|
||||
data,
|
||||
_owner: owner,
|
||||
})
|
||||
}
|
||||
fn decode_ip(snapshot: Snapshot<'_>) -> Result<IpData<'_>, Error> {
|
||||
let mut work = storage(snapshot.words.len(), 0u32)?;
|
||||
work.copy_from_slice(&snapshot.words);
|
||||
// SAFETY: original compiled storage shape, no device access or callback.
|
||||
let shape = unsafe { stela_amd_discovery_ip_shape() };
|
||||
let cells = (shape.hw_ip_count as usize)
|
||||
.checked_mul(shape.instances as usize)
|
||||
.filter(|count| *count > 0)
|
||||
.ok_or(Error::PostAcquireAllocation)?;
|
||||
let mut versions = storage(cells, 0u32)?;
|
||||
let mut bindings = storage(cells, Binding::default())?;
|
||||
let mut counts = IpCounts::default();
|
||||
// SAFETY: exclusive complete disjoint CPU allocations, checked scalar ABI,
|
||||
// original immutable bytes copied once. No raw pointer is retained by C.
|
||||
let status = unsafe {
|
||||
stela_amd_discovery_ip_decode(
|
||||
work.as_mut_ptr().cast(),
|
||||
snapshot.bytes().len(),
|
||||
versions.as_mut_ptr(),
|
||||
versions.len(),
|
||||
bindings.as_mut_ptr(),
|
||||
bindings.len(),
|
||||
&mut counts,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Decode(status));
|
||||
}
|
||||
Ok(IpData {
|
||||
snapshot,
|
||||
work,
|
||||
versions,
|
||||
bindings,
|
||||
shape,
|
||||
counts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Observed original hardware IP facts, retaining this privately admitted owner.
|
||||
/// The raw source/once-converted work ownership and getter semantics are unchanged.
|
||||
pub struct ObservedIp<'owner> {
|
||||
data: IpData<'owner>,
|
||||
_owner: DynamicHardware<'owner>,
|
||||
}
|
||||
impl ObservedIp<'_> {
|
||||
pub fn source_bytes(&self) -> &[u8] {
|
||||
self.data.source_bytes()
|
||||
}
|
||||
pub fn identity(&self) -> Identity {
|
||||
self.data.identity()
|
||||
}
|
||||
pub fn counts(&self) -> IpCounts {
|
||||
self.data.counts()
|
||||
}
|
||||
pub fn version(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
self.data.version(hw_ip, instance)
|
||||
}
|
||||
pub fn register_count(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
self.data.register_count(hw_ip, instance)
|
||||
}
|
||||
pub fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option<u32> {
|
||||
self.data.register_base(hw_ip, instance, segment)
|
||||
}
|
||||
}
|
||||
|
||||
/// Original outer cleanup required after a selected-file acquisition error.
|
||||
/// This is a pending service requirement, never an executed status/read result.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum FileFailureDiagnostics {
|
||||
/// Original option2 omits the version-register/RAS cleanup branch.
|
||||
OmittedByOriginalOption2,
|
||||
/// Original non-option2 checks real mmIP_DISCOVERY_VERSION and may query
|
||||
/// actual RAS boot status. That device service has not run in this adapter.
|
||||
DiscoveryVersionAndRasCheckRequired,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum FileSourceError {
|
||||
Provider(crate::firmware::Error),
|
||||
WrongImage,
|
||||
Policy(c_int),
|
||||
Region(Error),
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum FileError {
|
||||
Window(WindowError),
|
||||
IdentityEncoding,
|
||||
InvalidCatalogName,
|
||||
InvalidNativePolicy,
|
||||
/// Original query or zeroed storage failed before any provider request.
|
||||
Acquire(Error),
|
||||
/// File selection/read failed after query/allocation; no hardware fallback.
|
||||
Source {
|
||||
error: FileSourceError,
|
||||
pending: FileFailureDiagnostics,
|
||||
},
|
||||
/// Source already validated. Later native fact storage failed, with all
|
||||
/// earlier query effects retained and no published IP result.
|
||||
Ip(Error),
|
||||
}
|
||||
|
||||
// Fixed-width observed PCI labels only; no allocation or guessed GPU family.
|
||||
struct FileLabel<const N: usize> {
|
||||
bytes: [u8; N],
|
||||
used: usize,
|
||||
}
|
||||
impl<const N: usize> FileLabel<N> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
bytes: [0; N],
|
||||
used: 0,
|
||||
}
|
||||
}
|
||||
fn as_str(&self) -> &str {
|
||||
// SAFETY: Write only copies complete valid UTF-8 strings below.
|
||||
unsafe { core::str::from_utf8_unchecked(&self.bytes[..self.used]) }
|
||||
}
|
||||
}
|
||||
impl<const N: usize> core::fmt::Write for FileLabel<N> {
|
||||
fn write_str(&mut self, value: &str) -> core::fmt::Result {
|
||||
let end = self
|
||||
.used
|
||||
.checked_add(value.len())
|
||||
.filter(|end| *end <= N)
|
||||
.ok_or(core::fmt::Error)?;
|
||||
self.bytes[self.used..end].copy_from_slice(value.as_bytes());
|
||||
self.used = end;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_discovery_file_minimum() -> usize;
|
||||
fn stela_amd_discovery_file_validate(data: *const u8, bytes: usize, capacity: u32) -> c_int;
|
||||
}
|
||||
|
||||
/// Original exact preferred-file request, minted from this same live privately
|
||||
/// admitted BAR owner. No Image, Snapshot, path string, tuple or BDF constructor.
|
||||
/// A request is not firmware authentication, TMR reservation or GPU readiness.
|
||||
pub struct FileRequest<'owner> {
|
||||
owner: FileSource<'owner>,
|
||||
name: &'static str,
|
||||
hardware: FileLabel<16>,
|
||||
revision: FileLabel<40>,
|
||||
minimum: usize,
|
||||
}
|
||||
impl<'owner> FileRequest<'owner> {
|
||||
pub fn new(bars: &'owner AttachedBars<'_>) -> Result<Self, FileError> {
|
||||
use core::fmt::Write;
|
||||
let owner = bars.source_file().map_err(FileError::Window)?;
|
||||
let name = owner
|
||||
.filename()
|
||||
.to_str()
|
||||
.map_err(|_| FileError::InvalidCatalogName)?;
|
||||
let mut hardware = FileLabel::new();
|
||||
let (vendor, device) = owner.hardware_ids();
|
||||
write!(hardware, "pci-{vendor:04x}-{device:04x}")
|
||||
.map_err(|_| FileError::IdentityEncoding)?;
|
||||
let mut revision = FileLabel::new();
|
||||
let (pci_revision, subvendor, subdevice) = owner.revision_ids();
|
||||
write!(
|
||||
revision,
|
||||
"pci-{pci_revision:02x};subsys-{subvendor:04x}-{subdevice:04x}"
|
||||
)
|
||||
.map_err(|_| FileError::IdentityEncoding)?;
|
||||
// SAFETY: actual original compiled header span, no device effects.
|
||||
let minimum = unsafe { stela_amd_discovery_file_minimum() };
|
||||
if minimum == 0 {
|
||||
return Err(FileError::InvalidNativePolicy);
|
||||
}
|
||||
Ok(Self {
|
||||
owner,
|
||||
name,
|
||||
hardware,
|
||||
revision,
|
||||
minimum,
|
||||
})
|
||||
}
|
||||
pub fn name(&self) -> &str {
|
||||
self.name
|
||||
}
|
||||
/// Exact manifest equality keys from actual observed PCI fields; not a
|
||||
/// declaration that some other device/revision can use this firmware.
|
||||
pub fn target(&self) -> crate::firmware::Target<'_> {
|
||||
crate::firmware::Target {
|
||||
driver: "amd-amdgpu-ip-discovery",
|
||||
hardware: self.hardware.as_str(),
|
||||
revision: self.revision.as_str(),
|
||||
board: None,
|
||||
}
|
||||
}
|
||||
pub fn requirement(&self) -> crate::firmware::Requirement<'_> {
|
||||
crate::firmware::Requirement {
|
||||
name: self.name(),
|
||||
target: self.target(),
|
||||
minimum_bytes: self.minimum,
|
||||
}
|
||||
}
|
||||
fn source_error(&self, error: FileSourceError) -> FileError {
|
||||
FileError::Source {
|
||||
error,
|
||||
pending: if self.owner.discovery_option() == 2 {
|
||||
FileFailureDiagnostics::OmittedByOriginalOption2
|
||||
} else {
|
||||
FileFailureDiagnostics::DiscoveryVersionAndRasCheckRequired
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire the selected file in original order: real TMR query -> normal
|
||||
/// zeroed allocation -> exact provider request -> actual file bounds/checksum
|
||||
/// -> copy/region validation. No preferred-source fallback occurs.
|
||||
///
|
||||
/// # Safety
|
||||
/// All genuine source/VRAM/TMR ownership, calibrated Clock and full D0/reset,
|
||||
/// removal/MM-index/IRQ exclusion/context requirements of [`acquire`] hold
|
||||
/// for the whole synchronous query/load/copy. Retain the same genuine device
|
||||
/// owner/reset epoch through returned facts. A file
|
||||
/// cannot bypass query/VF/system-memory services. Original option2 requests
|
||||
/// TMR reservation but this adapter cannot create or assert that reservation.
|
||||
/// Earlier query/index effects are never rolled back on provider/OOM/error.
|
||||
/// A static inventory result does not run fixed-IP initialization or the
|
||||
/// original outer version-register/RAS diagnostic service after failures.
|
||||
pub unsafe fn acquire<'provider, P: crate::firmware::Provider + ?Sized>(
|
||||
self,
|
||||
provider: &'provider P,
|
||||
clock: &Clock,
|
||||
) -> Result<SelectedFile<'owner, 'provider>, FileError> {
|
||||
// SAFETY: same retained admitted window and complete original contract.
|
||||
let mut snapshot =
|
||||
unsafe { query_storage(self.owner.window(), self.owner.identity(), clock) }
|
||||
.map_err(FileError::Acquire)?;
|
||||
let requirement = self.requirement();
|
||||
let image = provider
|
||||
.load(requirement)
|
||||
.map_err(|error| self.source_error(FileSourceError::Provider(error)))?;
|
||||
if image.name() != requirement.name || image.target() != requirement.target {
|
||||
return Err(self.source_error(FileSourceError::WrongImage));
|
||||
}
|
||||
// SAFETY: actual immutable canonical image allocation and queried extent.
|
||||
let status = unsafe {
|
||||
stela_amd_discovery_file_validate(
|
||||
image.bytes().as_ptr(),
|
||||
image.bytes().len(),
|
||||
snapshot.region.size,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(self.source_error(FileSourceError::Policy(status)));
|
||||
}
|
||||
// SAFETY: complete initialized exclusive CPU Vec, no active aliases.
|
||||
// Original file policy already checked actual bytes fit real capacity.
|
||||
let destination = unsafe {
|
||||
core::slice::from_raw_parts_mut(
|
||||
snapshot.words.as_mut_ptr().cast::<u8>(),
|
||||
snapshot.region.size as usize,
|
||||
)
|
||||
};
|
||||
destination[..image.bytes().len()].copy_from_slice(image.bytes());
|
||||
validate_snapshot(&snapshot)
|
||||
.map_err(|error| self.source_error(FileSourceError::Region(error)))?;
|
||||
match self.owner.path() {
|
||||
super::pci::IpPath::Dynamic => {
|
||||
let data = decode_ip(snapshot).map_err(FileError::Ip)?;
|
||||
Ok(SelectedFile::Dynamic(FileIp {
|
||||
data,
|
||||
image,
|
||||
_owner: self.owner,
|
||||
}))
|
||||
}
|
||||
super::pci::IpPath::SocStatic => Ok(SelectedFile::Static(FileInventory {
|
||||
snapshot,
|
||||
image,
|
||||
_owner: self.owner,
|
||||
})),
|
||||
_ => Err(FileError::Window(WindowError::StaticInitializationRequired)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Actual privately selected path determines the result. Static inventory has
|
||||
/// no conversion into dynamic IP facts or permission to override fixed tables.
|
||||
pub enum SelectedFile<'owner, 'provider> {
|
||||
Dynamic(FileIp<'owner, 'provider>),
|
||||
Static(FileInventory<'owner, 'provider>),
|
||||
}
|
||||
/// Exact canonical Image and real acquired bytes for static optional inventory.
|
||||
/// This does not run static register/IP setup or sanitize missing inventory.
|
||||
pub struct FileInventory<'owner, 'provider> {
|
||||
snapshot: Snapshot<'owner>,
|
||||
image: crate::firmware::Image<'provider>,
|
||||
_owner: FileSource<'owner>,
|
||||
}
|
||||
impl<'provider> FileInventory<'_, 'provider> {
|
||||
pub fn image(&self) -> crate::firmware::Image<'provider> {
|
||||
self.image
|
||||
}
|
||||
/// Copied file plus original zero-filled queried-region tail. Exact original
|
||||
/// file bytes/hash/provenance remain separately available via image().
|
||||
pub fn acquired_bytes(&self) -> &[u8] {
|
||||
self.snapshot.bytes()
|
||||
}
|
||||
pub fn identity(&self) -> Identity {
|
||||
self.snapshot.identity()
|
||||
}
|
||||
pub fn vram_offset(&self) -> u64 {
|
||||
self.snapshot.vram_offset()
|
||||
}
|
||||
pub fn vram_bytes(&self) -> u64 {
|
||||
self.snapshot.vram_bytes()
|
||||
}
|
||||
}
|
||||
/// Dynamic facts decoded by the SAME original decoder after selected-file
|
||||
/// acquisition. Original Image/provider and actual device epoch remain borrowed.
|
||||
pub struct FileIp<'owner, 'provider> {
|
||||
data: IpData<'owner>,
|
||||
image: crate::firmware::Image<'provider>,
|
||||
_owner: FileSource<'owner>,
|
||||
}
|
||||
impl<'provider> FileIp<'_, 'provider> {
|
||||
pub fn image(&self) -> crate::firmware::Image<'provider> {
|
||||
self.image
|
||||
}
|
||||
pub fn acquired_bytes(&self) -> &[u8] {
|
||||
self.data.source_bytes()
|
||||
}
|
||||
pub fn identity(&self) -> Identity {
|
||||
self.data.identity()
|
||||
}
|
||||
pub fn counts(&self) -> IpCounts {
|
||||
self.data.counts()
|
||||
}
|
||||
pub fn version(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
self.data.version(hw_ip, instance)
|
||||
}
|
||||
pub fn register_count(&self, hw_ip: u32, instance: u32) -> Option<u32> {
|
||||
self.data.register_count(hw_ip, instance)
|
||||
}
|
||||
pub fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option<u32> {
|
||||
self.data.register_base(hw_ip, instance, segment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2015 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef AMD_CHIP_FLAGS_H
|
||||
#define AMD_CHIP_FLAGS_H
|
||||
|
||||
/*
|
||||
* Chip flags
|
||||
*/
|
||||
enum amd_chip_flags {
|
||||
AMD_ASIC_MASK = 0x0000ffffUL,
|
||||
AMD_FLAGS_MASK = 0xffff0000UL,
|
||||
AMD_IS_MOBILITY = 0x00010000UL,
|
||||
AMD_IS_APU = 0x00020000UL,
|
||||
AMD_IS_PX = 0x00040000UL,
|
||||
AMD_EXP_HW_SUPPORT = 0x00080000UL,
|
||||
};
|
||||
|
||||
enum amd_apu_flags {
|
||||
AMD_APU_IS_RAVEN = 0x00000001UL,
|
||||
AMD_APU_IS_RAVEN2 = 0x00000002UL,
|
||||
AMD_APU_IS_PICASSO = 0x00000004UL,
|
||||
AMD_APU_IS_RENOIR = 0x00000008UL,
|
||||
AMD_APU_IS_GREEN_SARDINE = 0x00000010UL,
|
||||
AMD_APU_IS_VANGOGH = 0x00000020UL,
|
||||
AMD_APU_IS_CYAN_SKILLFISH2 = 0x00000040UL,
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -31,27 +31,7 @@
|
||||
struct amdgpu_ip_block;
|
||||
|
||||
|
||||
/*
|
||||
* Chip flags
|
||||
*/
|
||||
enum amd_chip_flags {
|
||||
AMD_ASIC_MASK = 0x0000ffffUL,
|
||||
AMD_FLAGS_MASK = 0xffff0000UL,
|
||||
AMD_IS_MOBILITY = 0x00010000UL,
|
||||
AMD_IS_APU = 0x00020000UL,
|
||||
AMD_IS_PX = 0x00040000UL,
|
||||
AMD_EXP_HW_SUPPORT = 0x00080000UL,
|
||||
};
|
||||
|
||||
enum amd_apu_flags {
|
||||
AMD_APU_IS_RAVEN = 0x00000001UL,
|
||||
AMD_APU_IS_RAVEN2 = 0x00000002UL,
|
||||
AMD_APU_IS_PICASSO = 0x00000004UL,
|
||||
AMD_APU_IS_RENOIR = 0x00000008UL,
|
||||
AMD_APU_IS_GREEN_SARDINE = 0x00000010UL,
|
||||
AMD_APU_IS_VANGOGH = 0x00000020UL,
|
||||
AMD_APU_IS_CYAN_SKILLFISH2 = 0x00000040UL,
|
||||
};
|
||||
#include "amd_chip_flags.h"
|
||||
|
||||
/**
|
||||
* DOC: IP Blocks
|
||||
|
||||
@@ -24,6 +24,20 @@
|
||||
#ifndef _DISCOVERY_H_
|
||||
#define _DISCOVERY_H_
|
||||
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#include <linux/stddef.h>
|
||||
#else
|
||||
#include <stdint.h>
|
||||
/* Original public flex-array declarations, with no Linux service shim. */
|
||||
#include "../../common/linux/include/uapi/linux/stddef.h"
|
||||
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_LITTLE_ENDIAN__) || !defined(__ORDER_BIG_ENDIAN__)
|
||||
#error "Discovery format requires compiler byte-order definitions"
|
||||
#elif __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ && __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__
|
||||
#error "Discovery format requires an explicit native byte order"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define PSP_HEADER_SIZE 256
|
||||
#define BINARY_SIGNATURE 0x28211407
|
||||
#define DISCOVERY_TABLE_SIGNATURE 0x53445049
|
||||
@@ -110,7 +124,8 @@ typedef struct ip
|
||||
uint8_t major; /* HCID Major */
|
||||
uint8_t minor; /* HCID Minor */
|
||||
uint8_t revision; /* HCID Revision */
|
||||
#if defined(__BIG_ENDIAN)
|
||||
#if (defined(__KERNEL__) && defined(__BIG_ENDIAN)) || \
|
||||
(!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
|
||||
uint8_t reserved : 4; /* Placeholder field */
|
||||
uint8_t harvest : 4; /* Harvest */
|
||||
#else
|
||||
@@ -128,7 +143,8 @@ typedef struct ip_v3
|
||||
uint8_t major; /* Hardware ID.major version */
|
||||
uint8_t minor; /* Hardware ID.minor version */
|
||||
uint8_t revision; /* Hardware ID.revision version */
|
||||
#if defined(__BIG_ENDIAN)
|
||||
#if (defined(__KERNEL__) && defined(__BIG_ENDIAN)) || \
|
||||
(!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
|
||||
uint8_t variant : 4; /* HW variant */
|
||||
uint8_t sub_revision : 4; /* HCID Sub-Revision */
|
||||
#else
|
||||
@@ -145,17 +161,19 @@ typedef struct ip_v4 {
|
||||
uint8_t major; /* Hardware ID.major version */
|
||||
uint8_t minor; /* Hardware ID.minor version */
|
||||
uint8_t revision; /* Hardware ID.revision version */
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#if defined(LITTLEENDIAN_CPU) || \
|
||||
(!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
|
||||
uint8_t sub_revision : 4; /* HCID Sub-Revision */
|
||||
uint8_t variant : 4; /* HW variant */
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU) || \
|
||||
(!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
|
||||
uint8_t variant : 4; /* HW variant */
|
||||
uint8_t sub_revision : 4; /* HCID Sub-Revision */
|
||||
#endif
|
||||
union {
|
||||
DECLARE_FLEX_ARRAY(uint32_t, base_address); /* 32-bit Base Address list. Corresponds to the num_base_address field*/
|
||||
DECLARE_FLEX_ARRAY(uint64_t, base_address_64); /* 64-bit Base Address list. Corresponds to the num_base_address field*/
|
||||
} __packed;
|
||||
__DECLARE_FLEX_ARRAY(uint32_t, base_address); /* 32-bit Base Address list. Corresponds to the num_base_address field*/
|
||||
__DECLARE_FLEX_ARRAY(uint64_t, base_address_64); /* 64-bit Base Address list. Corresponds to the num_base_address field*/
|
||||
} __attribute__((__packed__));
|
||||
} ip_v4;
|
||||
|
||||
typedef struct die_header
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
//! Original AMDGPU BAR policy attached to the canonical native MMIO owner.
|
||||
//!
|
||||
//! No register access, doorbell write, firmware load or hardware activation is
|
||||
//! performed here. Original AMDGPU register routing and device lifecycle remain
|
||||
//! mandatory; this module only retains their real, bounded CPU windows.
|
||||
use super::pci::{Admission, IpPath, MatchedFunction, Source};
|
||||
use crate::bus::{
|
||||
mmio::owned::{
|
||||
Authority, CacheAttribute, Error as MmioError, Mapping, MappingView, PAGE_BYTES,
|
||||
PhysicalSpan, Protection, Resource, ResourceKind,
|
||||
},
|
||||
pci::{Address, ConfigSpace, Function},
|
||||
};
|
||||
use core::{ffi::c_int, marker::PhantomData, ptr::NonNull};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Error {
|
||||
InvalidOwner,
|
||||
AdmissionRequired,
|
||||
StaticInitializationRequired,
|
||||
FirmwareSourceRequired,
|
||||
PreferredFileRequired,
|
||||
InvalidRange,
|
||||
Policy(c_int),
|
||||
Mapping(MmioError),
|
||||
IndirectRegisterRequired,
|
||||
Retired,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Stage {
|
||||
Preflight,
|
||||
Registers,
|
||||
Doorbells,
|
||||
}
|
||||
|
||||
/// Failure ownership is truthful even when attachment fails after a real map.
|
||||
/// The canonical authority owns uncertain failed-map reservations internally.
|
||||
/// `rollback` describes the already-installed, unpublished register window.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct AttachError {
|
||||
pub stage: Stage,
|
||||
pub error: Error,
|
||||
pub rollback: Rollback,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Rollback {
|
||||
NotAttempted,
|
||||
Retired,
|
||||
/// Drop retained the real mapping/resource in canonical quarantine after
|
||||
/// this failed retirement. No resource or native table was freed here.
|
||||
Quarantined(MmioError),
|
||||
}
|
||||
|
||||
/// The actual resource owner, not a physical BAR tuple or a DMA allocation.
|
||||
pub struct RegisterBar {
|
||||
pub index: u8,
|
||||
pub resource: Resource,
|
||||
}
|
||||
|
||||
/// Actual original kernel doorbell reservation within BAR2. The resource's
|
||||
/// original backing must pin this allocation as well as the whole BAR through
|
||||
/// acknowledged retirement or permanent canonical quarantine, including Drop.
|
||||
/// `reserved_bytes` covers complete physical pages; `logical_dwords` is the
|
||||
/// original post-MES-allocation extent, not the entire BAR's capacity.
|
||||
pub struct KernelDoorbells {
|
||||
pub index: u8,
|
||||
pub resource: Resource,
|
||||
pub offset: usize,
|
||||
pub reserved_bytes: usize,
|
||||
pub logical_dwords: u32,
|
||||
pub max_assignment: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identity {
|
||||
pub address: Address,
|
||||
pub device: u16,
|
||||
/// Original pciidlist match's driver flags; never a Metal feature mask.
|
||||
pub original_flags: u32,
|
||||
pub asic_type: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Layout {
|
||||
register_bar: u32,
|
||||
kernel_doorbells: u32,
|
||||
kernel_doorbell_bytes: u64,
|
||||
}
|
||||
const _: () = assert!(size_of::<Layout>() == 16);
|
||||
const _: () = assert!(core::mem::offset_of!(Layout, kernel_doorbell_bytes) == 8);
|
||||
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_native_register_bar(asic_type: u32, bar: *mut u32) -> c_int;
|
||||
fn stela_amd_native_bar_layout(
|
||||
asic_type: u32,
|
||||
doorbell_bar_bytes: u64,
|
||||
max_assignment: u32,
|
||||
page_bytes: u64,
|
||||
layout: *mut Layout,
|
||||
) -> c_int;
|
||||
}
|
||||
|
||||
/// The lifetime also borrows the actual matched PCI function. ResourceBacking
|
||||
/// retains the real resource/reset epoch; caller's original owner retains its
|
||||
/// doorbell BO reservation and all C consumers through this borrow.
|
||||
pub struct AttachedBars<'a> {
|
||||
identity: Identity,
|
||||
admission: Option<Admission>,
|
||||
registers: Mapping,
|
||||
doorbells: Option<Mapping>,
|
||||
logical_doorbell_bytes: usize,
|
||||
active: bool,
|
||||
_function: PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
fn preflight(error: Error) -> AttachError {
|
||||
AttachError {
|
||||
stage: Stage::Preflight,
|
||||
error,
|
||||
rollback: Rollback::NotAttempted,
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_pages(resource: &Resource, offset: usize, bytes: usize) -> Result<(), Error> {
|
||||
let span = resource.physical_span();
|
||||
let offset = u64::try_from(offset).map_err(|_| Error::InvalidRange)?;
|
||||
let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidRange)?;
|
||||
let start = span
|
||||
.start()
|
||||
.checked_add(offset)
|
||||
.ok_or(Error::InvalidRange)?;
|
||||
let end = start.checked_add(bytes).ok_or(Error::InvalidRange)?;
|
||||
if bytes == 0
|
||||
|| !start.is_multiple_of(PAGE_BYTES)
|
||||
|| !bytes.is_multiple_of(PAGE_BYTES)
|
||||
|| start < span.start()
|
||||
|| end > span.end()
|
||||
{
|
||||
return Err(Error::InvalidRange);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn query_layout(asic_type: u32, doorbells: Option<&KernelDoorbells>) -> Result<Layout, Error> {
|
||||
if doorbells.is_some_and(|d| d.index != 2) {
|
||||
return Err(Error::InvalidOwner);
|
||||
}
|
||||
let mut layout = Layout::default();
|
||||
// SAFETY: private C ABI has independent layout assertions and writes only
|
||||
// initialized local outputs; original policies are allocation-free.
|
||||
let status = unsafe {
|
||||
match doorbells {
|
||||
None => stela_amd_native_register_bar(asic_type, &mut layout.register_bar),
|
||||
Some(d) => stela_amd_native_bar_layout(
|
||||
asic_type,
|
||||
d.resource.physical_span().bytes(),
|
||||
d.max_assignment,
|
||||
PAGE_BYTES,
|
||||
&mut layout,
|
||||
),
|
||||
}
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Policy(status));
|
||||
}
|
||||
Ok(layout)
|
||||
}
|
||||
|
||||
fn validate_doorbells(
|
||||
registers: PhysicalSpan,
|
||||
doorbells: &KernelDoorbells,
|
||||
layout: Layout,
|
||||
) -> Result<usize, Error> {
|
||||
let bytes = usize::try_from(layout.kernel_doorbell_bytes).map_err(|_| Error::InvalidRange)?;
|
||||
if doorbells.logical_dwords != layout.kernel_doorbells
|
||||
|| bytes == 0
|
||||
|| bytes > doorbells.reserved_bytes
|
||||
{
|
||||
return Err(Error::InvalidRange);
|
||||
}
|
||||
whole_pages(
|
||||
&doorbells.resource,
|
||||
doorbells.offset,
|
||||
doorbells.reserved_bytes,
|
||||
)?;
|
||||
let span = doorbells.resource.physical_span();
|
||||
if registers.start() < span.end() && span.start() < registers.end() {
|
||||
return Err(Error::InvalidOwner);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
impl<'a> AttachedBars<'a> {
|
||||
pub(super) fn source_file(&self) -> Result<FileSource<'_>, Error> {
|
||||
if !self.active {
|
||||
return Err(Error::Retired);
|
||||
}
|
||||
let admission = self.admission.ok_or(Error::AdmissionRequired)?;
|
||||
let Source::Firmware(filename) = admission.source() else {
|
||||
return Err(Error::PreferredFileRequired);
|
||||
};
|
||||
if !matches!(admission.path(), IpPath::Dynamic | IpPath::SocStatic) {
|
||||
return Err(Error::StaticInitializationRequired);
|
||||
}
|
||||
Ok(FileSource {
|
||||
window: self.registers()?,
|
||||
identity: self.identity,
|
||||
admission,
|
||||
filename,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn dynamic_hardware(&self) -> Result<DynamicHardware<'_>, Error> {
|
||||
if !self.active {
|
||||
return Err(Error::Retired);
|
||||
}
|
||||
let admission = self.admission.ok_or(Error::AdmissionRequired)?;
|
||||
if admission.path() != IpPath::Dynamic {
|
||||
return Err(Error::StaticInitializationRequired);
|
||||
}
|
||||
if admission.source() != Source::Hardware {
|
||||
return Err(Error::FirmwareSourceRequired);
|
||||
}
|
||||
Ok(DynamicHardware {
|
||||
window: self.registers()?,
|
||||
identity: self.identity,
|
||||
})
|
||||
}
|
||||
|
||||
/// Attach from the actual original normal PCI match. The private result is
|
||||
/// retained on this exact mapping owner; the legacy manual unsafe path
|
||||
/// cannot mint this admission. No firmware/static fallback or activation.
|
||||
///
|
||||
/// # Safety
|
||||
/// All actual resource/context/exclusion requirements of [`Self::attach`]
|
||||
/// hold. The matched function and resources are from this same genuine
|
||||
/// owner/reset epoch. Keep its original source/static plan; matching does
|
||||
/// not acquire the selected firmware or implement static IP initialization.
|
||||
pub unsafe fn attach_matched<C: ConfigSpace>(
|
||||
authority: &Authority,
|
||||
matched: &'a MatchedFunction<'_, C>,
|
||||
registers: RegisterBar,
|
||||
doorbells: Option<KernelDoorbells>,
|
||||
) -> Result<Self, AttachError> {
|
||||
let admission = matched.admission();
|
||||
// SAFETY: actual owner/resource contract above; ASIC/flags are private
|
||||
// outputs of original matching, not independently supplied labels.
|
||||
let mut bars = unsafe {
|
||||
Self::attach(
|
||||
authority,
|
||||
matched.function(),
|
||||
admission.flags(),
|
||||
admission.asic(),
|
||||
registers,
|
||||
doorbells,
|
||||
)
|
||||
}?;
|
||||
bars.admission = Some(admission);
|
||||
Ok(bars)
|
||||
}
|
||||
|
||||
/// Original initialization/source plan of an actual matched attachment.
|
||||
/// None means the older manual unsafe attachment has no such admission.
|
||||
/// A dynamic hardware plan still requires genuine acquisition/validation.
|
||||
pub fn original_plan(&self) -> Option<(IpPath, Source)> {
|
||||
self.admission
|
||||
.map(|admission| (admission.path(), admission.source()))
|
||||
}
|
||||
|
||||
/// Attach unpublished CPU windows for an actual original AMDGPU PCI match.
|
||||
/// The display-only diagnostic inventory is intentionally not consulted.
|
||||
///
|
||||
/// # Safety
|
||||
/// `function`, `original_flags` and `asic_type` must describe the same real
|
||||
/// original pciidlist match and original native device/reset epoch. Both
|
||||
/// resources must be that function's assigned BARs, with live exclusive
|
||||
/// reservations; no other driver or firmware may use them. `registers`
|
||||
/// must be the complete original register BAR. `None` bootstraps registers
|
||||
/// before original IP discovery/BO initialization; it never reports doors
|
||||
/// or an initialized device. A supplied `doorbells` must describe the
|
||||
/// actual original kernel BO reservation in BAR2, actual ASIC
|
||||
/// max_assignment and post-allocation logical extent, including paging/MES
|
||||
/// pages. The original owner must retain that suballocation and prevent
|
||||
/// rebinding/reset/removal or C access after teardown begins, until every
|
||||
/// borrowed window is released and retirement is acknowledged. No booleans
|
||||
/// supplied here establish firmware, queue, power or device readiness.
|
||||
/// Native process/deferred context and the canonical provider's rules apply.
|
||||
pub unsafe fn attach<C: ConfigSpace>(
|
||||
authority: &Authority,
|
||||
function: &'a Function<C>,
|
||||
original_flags: u32,
|
||||
asic_type: u32,
|
||||
registers: RegisterBar,
|
||||
doorbells: Option<KernelDoorbells>,
|
||||
) -> Result<Self, AttachError> {
|
||||
if function.vendor != 0x1002 || registers.resource.kind() != ResourceKind::Registers {
|
||||
return Err(preflight(Error::InvalidOwner));
|
||||
}
|
||||
let layout = query_layout(asic_type, doorbells.as_ref()).map_err(preflight)?;
|
||||
if u32::from(registers.index) != layout.register_bar {
|
||||
return Err(preflight(Error::InvalidOwner));
|
||||
}
|
||||
let register_bytes = usize::try_from(registers.resource.physical_span().bytes())
|
||||
.map_err(|_| preflight(Error::InvalidRange))?;
|
||||
whole_pages(®isters.resource, 0, register_bytes).map_err(preflight)?;
|
||||
let logical_doorbell_bytes = doorbells
|
||||
.as_ref()
|
||||
.map_or(Ok(0), |d| {
|
||||
validate_doorbells(registers.resource.physical_span(), d, layout)
|
||||
})
|
||||
.map_err(preflight)?;
|
||||
let mut registers = authority
|
||||
.map(
|
||||
registers.resource,
|
||||
0,
|
||||
register_bytes,
|
||||
CacheAttribute::Uncached,
|
||||
Protection::ReadWrite,
|
||||
)
|
||||
.map_err(|error| AttachError {
|
||||
stage: Stage::Registers,
|
||||
error: Error::Mapping(error),
|
||||
rollback: Rollback::NotAttempted,
|
||||
})?;
|
||||
let doorbell_mapping = match doorbells {
|
||||
None => None,
|
||||
Some(d) => match authority.map(
|
||||
d.resource,
|
||||
d.offset,
|
||||
d.reserved_bytes,
|
||||
CacheAttribute::Uncached,
|
||||
Protection::ReadWrite,
|
||||
) {
|
||||
Ok(mapping) => Some(mapping),
|
||||
Err(error) => {
|
||||
// SAFETY: no pointer/view was exposed and no CPU/device
|
||||
// access occurred through this new unpublished mapping.
|
||||
let rollback = match unsafe { registers.retire() } {
|
||||
Ok(()) => Rollback::Retired,
|
||||
Err(error) => Rollback::Quarantined(error),
|
||||
};
|
||||
// Failed retire is retained by canonical Drop quarantine.
|
||||
drop(registers);
|
||||
return Err(AttachError {
|
||||
stage: Stage::Doorbells,
|
||||
error: Error::Mapping(error),
|
||||
rollback,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
Ok(Self {
|
||||
identity: Identity {
|
||||
address: function.address,
|
||||
device: function.device,
|
||||
original_flags,
|
||||
asic_type,
|
||||
},
|
||||
admission: None,
|
||||
registers,
|
||||
doorbells: doorbell_mapping,
|
||||
logical_doorbell_bytes,
|
||||
active: true,
|
||||
_function: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn identity(&self) -> Identity {
|
||||
self.identity
|
||||
}
|
||||
|
||||
/// Retained views may be held by the original native C owner independently
|
||||
/// of this container; canonical retirement stays Busy until they drain.
|
||||
pub fn registers(&self) -> Result<RegisterWindow<'a>, Error> {
|
||||
if !self.active {
|
||||
return Err(Error::Retired);
|
||||
}
|
||||
let bytes = self.registers.bytes().map_err(Error::Mapping)?;
|
||||
Ok(RegisterWindow {
|
||||
view: self.registers.view(0..bytes).map_err(Error::Mapping)?,
|
||||
_owner: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn doorbells(&self) -> Result<Option<DoorbellWindow<'a>>, Error> {
|
||||
if !self.active {
|
||||
return Err(Error::Retired);
|
||||
}
|
||||
self.doorbells
|
||||
.as_ref()
|
||||
.map(|mapping| {
|
||||
Ok(DoorbellWindow {
|
||||
view: mapping
|
||||
.view(0..self.logical_doorbell_bytes)
|
||||
.map_err(Error::Mapping)?,
|
||||
_owner: PhantomData,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn register_physical_span(&self) -> Result<PhysicalSpan, Error> {
|
||||
self.registers.physical_span().map_err(Error::Mapping)
|
||||
}
|
||||
|
||||
/// Attach the real kernel reservation after original discovery/doorbell BO
|
||||
/// creation, reusing the existing register mapping. Failure preserves that
|
||||
/// published register owner; canonical failed-map quarantine still applies.
|
||||
///
|
||||
/// # Safety
|
||||
/// The reservation/backing, ASIC assignment and original owner must obey
|
||||
/// `attach`'s same-device/reset-epoch and lifetime requirements. The backing
|
||||
/// retains the actual BO suballocation even on permanent map quarantine.
|
||||
/// Original device initialization remains serialized by its actual owner.
|
||||
pub unsafe fn attach_kernel_doorbells(
|
||||
&mut self,
|
||||
authority: &Authority,
|
||||
doorbells: KernelDoorbells,
|
||||
) -> Result<(), AttachError> {
|
||||
if !self.active || self.doorbells.is_some() {
|
||||
return Err(preflight(Error::InvalidOwner));
|
||||
}
|
||||
let layout = query_layout(self.identity.asic_type, Some(&doorbells)).map_err(preflight)?;
|
||||
let span = self.register_physical_span().map_err(preflight)?;
|
||||
let bytes = validate_doorbells(span, &doorbells, layout).map_err(preflight)?;
|
||||
let mapping = authority
|
||||
.map(
|
||||
doorbells.resource,
|
||||
doorbells.offset,
|
||||
doorbells.reserved_bytes,
|
||||
CacheAttribute::Uncached,
|
||||
Protection::ReadWrite,
|
||||
)
|
||||
.map_err(|error| AttachError {
|
||||
stage: Stage::Doorbells,
|
||||
error: Error::Mapping(error),
|
||||
rollback: Rollback::NotAttempted,
|
||||
})?;
|
||||
self.doorbells = Some(mapping);
|
||||
self.logical_doorbell_bytes = bytes;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire only after real original consumers stop and posted accesses drain.
|
||||
/// An error disables new windows and retains the exact mappings for retry;
|
||||
/// Drop without acknowledged retirement uses canonical quarantine.
|
||||
///
|
||||
/// # Safety
|
||||
/// Every C/CPU/worker/IRQ consumer and original-owner access through all
|
||||
/// obtained raw pointers must be stopped/drained, with no future access.
|
||||
/// Caller proves device/reset exclusion, correct process/deferred context
|
||||
/// and all canonical retirement requirements. This does not stop hardware.
|
||||
pub unsafe fn retire(&mut self) -> Result<(), Error> {
|
||||
self.active = false;
|
||||
if let Some(mapping) = &mut self.doorbells {
|
||||
// SAFETY: the caller supplies the real shared consumer drain.
|
||||
unsafe { mapping.retire().map_err(Error::Mapping)? };
|
||||
self.doorbells = None;
|
||||
}
|
||||
// SAFETY: the same actual consumer drain and context proof apply.
|
||||
unsafe { self.registers.retire().map_err(Error::Mapping) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Private proof of original dynamic/hardware selection on this exact live
|
||||
/// mapping owner. No Clone or public constructor; public selection metadata and
|
||||
/// arbitrary snapshots cannot create it. The canonical lease/borrow pins epoch.
|
||||
pub(super) struct DynamicHardware<'owner> {
|
||||
window: RegisterWindow<'owner>,
|
||||
identity: Identity,
|
||||
}
|
||||
impl<'owner> DynamicHardware<'owner> {
|
||||
pub(super) fn window(&self) -> &RegisterWindow<'owner> {
|
||||
&self.window
|
||||
}
|
||||
pub(super) fn identity(&self) -> Identity {
|
||||
self.identity
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded register mapping only. Original RREG/WREG dispatch still owns
|
||||
/// direct versus indirect PCIe/KIQ/RLCG/XCC routing and power/reset rules.
|
||||
pub struct RegisterWindow<'a> {
|
||||
view: MappingView,
|
||||
_owner: PhantomData<&'a ()>,
|
||||
}
|
||||
impl RegisterWindow<'_> {
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.view.bytes()
|
||||
}
|
||||
|
||||
/// Private native C bootstrap may borrow this exact rmmio pointer/size.
|
||||
/// No Rust reference is formed, and no register is read or written.
|
||||
///
|
||||
/// # Safety
|
||||
/// The pointer must not escape this borrowed window's lifetime. All actual
|
||||
/// accesses must use original AMDGPU register routing/width/order/reset
|
||||
/// semantics. A pointer is not authority to bypass indirect/KIQ/XCC routes.
|
||||
pub unsafe fn native_base(&self) -> Result<NonNull<u8>, Error> {
|
||||
self.view.address(0, self.bytes()).map_err(Error::Mapping)
|
||||
}
|
||||
|
||||
/// A checked direct DWORD location. An out-of-window register requires
|
||||
/// original indirect dispatch, never a wrapped or widened MMIO access.
|
||||
pub fn direct_dword(&self, register: u32) -> Result<NonNull<u32>, Error> {
|
||||
let offset = usize::try_from(register)
|
||||
.ok()
|
||||
.and_then(|r| r.checked_mul(4))
|
||||
.filter(|offset| offset.checked_add(4).is_some_and(|end| end <= self.bytes()))
|
||||
.ok_or(Error::IndirectRegisterRequired)?;
|
||||
let address = self.view.address(offset, 4).map_err(Error::Mapping)?;
|
||||
if !(address.as_ptr() as usize).is_multiple_of(4) {
|
||||
return Err(Error::InvalidRange);
|
||||
}
|
||||
Ok(address.cast())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DoorbellWindow<'a> {
|
||||
view: MappingView,
|
||||
_owner: PhantomData<&'a ()>,
|
||||
}
|
||||
impl DoorbellWindow<'_> {
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.view.bytes()
|
||||
}
|
||||
|
||||
fn address(&self, index: u32, width: usize) -> Result<NonNull<u8>, Error> {
|
||||
let offset = usize::try_from(index)
|
||||
.ok()
|
||||
.and_then(|i| i.checked_mul(4))
|
||||
.ok_or(Error::InvalidRange)?;
|
||||
let pointer = self.view.address(offset, width).map_err(Error::Mapping)?;
|
||||
if !(pointer.as_ptr() as usize).is_multiple_of(width) {
|
||||
return Err(Error::InvalidRange);
|
||||
}
|
||||
Ok(pointer)
|
||||
}
|
||||
|
||||
/// Original doorbell index is measured in DWORDs. Pointer access remains
|
||||
/// unsafe and requires the original initialized ring/doorbell owner.
|
||||
pub fn dword(&self, index: u32) -> Result<NonNull<u32>, Error> {
|
||||
self.address(index, 4).map(NonNull::cast)
|
||||
}
|
||||
|
||||
/// Keep the original native atomic 64-bit transaction; never synthesize
|
||||
/// two DWORD doorbell writes. Both DWORDs and alignment are checked.
|
||||
pub fn qword(&self, index: u32) -> Result<NonNull<u64>, Error> {
|
||||
self.address(index, 8).map(NonNull::cast)
|
||||
}
|
||||
}
|
||||
|
||||
// Only actual selected Firmware admission on this same active owner can mint it.
|
||||
// A path tuple, copied Identity, bare Image or manual attachment cannot do so.
|
||||
pub(super) struct FileSource<'owner> {
|
||||
window: RegisterWindow<'owner>,
|
||||
identity: Identity,
|
||||
admission: Admission,
|
||||
filename: &'static core::ffi::CStr,
|
||||
}
|
||||
impl<'owner> FileSource<'owner> {
|
||||
pub(super) fn window(&self) -> &RegisterWindow<'owner> {
|
||||
&self.window
|
||||
}
|
||||
pub(super) fn identity(&self) -> Identity {
|
||||
self.identity
|
||||
}
|
||||
pub(super) fn filename(&self) -> &'static core::ffi::CStr {
|
||||
self.filename
|
||||
}
|
||||
pub(super) fn path(&self) -> IpPath {
|
||||
self.admission.path()
|
||||
}
|
||||
pub(super) fn discovery_option(&self) -> i32 {
|
||||
self.admission.discovery_option()
|
||||
}
|
||||
pub(super) fn hardware_ids(&self) -> (u16, u16) {
|
||||
self.admission.firmware_hardware()
|
||||
}
|
||||
pub(super) fn revision_ids(&self) -> (u8, u16, u16) {
|
||||
self.admission.firmware_revision()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Original AMDGPU PCI matching and phase-specific discovery source selection.
|
||||
//! This binds identity/policy to an actual borrowed PCI function; it neither
|
||||
//! reserves resources nor establishes initialization, topology or GPU readiness.
|
||||
use crate::bus::pci::{Address, ConfigSpace, Function};
|
||||
use core::ffi::{CStr, c_char, c_int};
|
||||
|
||||
/// Actual native build/user/platform policy corresponding to the original probe.
|
||||
/// These are configuration inputs, not hardware readiness/capability booleans.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Policy {
|
||||
pub si_built: bool,
|
||||
pub cik_built: bool,
|
||||
pub radeon_built: bool,
|
||||
pub si_support: i32,
|
||||
pub cik_support: i32,
|
||||
pub experimental: i32,
|
||||
pub discovery: i32,
|
||||
pub force_asic: i32,
|
||||
pub memory_encrypted: bool,
|
||||
pub firmware_drivers_only: bool,
|
||||
pub modeset: i32,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Error {
|
||||
Absent,
|
||||
UnsupportedHeader,
|
||||
IdentityChanged,
|
||||
Native(c_int),
|
||||
InvalidNativeResult,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IpPath {
|
||||
SiStatic,
|
||||
CikStatic,
|
||||
ViStatic,
|
||||
/// Original per-ASIC versions/bases; optional discovery is inventory only.
|
||||
SocStatic,
|
||||
/// Original discovery consumer is required; source selection is independent.
|
||||
Dynamic,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Source {
|
||||
NotUsed,
|
||||
Hardware,
|
||||
/// Exact original preferred source; no fallback to hardware on failure.
|
||||
Firmware(&'static CStr),
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
struct ConfigIdentity {
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
subvendor: u32,
|
||||
subdevice: u32,
|
||||
class_code: u32,
|
||||
revision: u32,
|
||||
}
|
||||
#[repr(C)]
|
||||
struct NativePolicy {
|
||||
si_built: u32,
|
||||
cik_built: u32,
|
||||
radeon_built: u32,
|
||||
si_support: i32,
|
||||
cik_support: i32,
|
||||
experimental: i32,
|
||||
discovery: i32,
|
||||
force_asic: i32,
|
||||
memory_encrypted: u32,
|
||||
firmware_drivers_only: u32,
|
||||
modeset: i32,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct NativeMatch {
|
||||
row: u32,
|
||||
original_flags: u32,
|
||||
asic_type: u32,
|
||||
initial_apu_flags: u32,
|
||||
ip_path: u32,
|
||||
discovery_source: u32,
|
||||
filename: *const c_char,
|
||||
}
|
||||
const _: () = assert!(size_of::<ConfigIdentity>() == 24);
|
||||
const _: () = assert!(size_of::<NativePolicy>() == 44);
|
||||
const _: () = assert!(size_of::<NativeMatch>() == 32);
|
||||
const _: () = assert!(core::mem::offset_of!(NativeMatch, filename) == 24);
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_pci_match(
|
||||
identity: &ConfigIdentity,
|
||||
policy: &NativePolicy,
|
||||
out: &mut NativeMatch,
|
||||
) -> c_int;
|
||||
}
|
||||
|
||||
/// Private original result. Only actual config matching may construct this.
|
||||
/// Kept with the real borrowed resource/reset owner by matched attachment.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Admission {
|
||||
config: ConfigIdentity,
|
||||
row: u32,
|
||||
original_flags: u32,
|
||||
asic_type: u32,
|
||||
initial_apu_flags: u32,
|
||||
path: IpPath,
|
||||
source: Source,
|
||||
discovery_option: i32,
|
||||
}
|
||||
impl Admission {
|
||||
pub(super) fn flags(self) -> u32 {
|
||||
self.original_flags
|
||||
}
|
||||
pub(super) fn asic(self) -> u32 {
|
||||
self.asic_type
|
||||
}
|
||||
pub(super) fn path(self) -> IpPath {
|
||||
self.path
|
||||
}
|
||||
pub(super) fn source(self) -> Source {
|
||||
self.source
|
||||
}
|
||||
pub(super) fn discovery_option(self) -> i32 {
|
||||
self.discovery_option
|
||||
}
|
||||
pub(super) fn firmware_hardware(self) -> (u16, u16) {
|
||||
(self.config.vendor as u16, self.config.device as u16)
|
||||
}
|
||||
pub(super) fn firmware_revision(self) -> (u8, u16, u16) {
|
||||
(
|
||||
self.config.revision as u8,
|
||||
self.config.subvendor as u16,
|
||||
self.config.subdevice as u16,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The original normal-table match and policy result for this exact function.
|
||||
/// Borrowing prevents mutation/rebinding of its Function while this is retained.
|
||||
/// Actual platform/resource exclusion remains an unsafe native-owner duty.
|
||||
pub struct MatchedFunction<'function, C> {
|
||||
function: &'function Function<C>,
|
||||
admission: Admission,
|
||||
}
|
||||
impl<C: ConfigSpace> MatchedFunction<'_, C> {
|
||||
pub fn address(&self) -> Address {
|
||||
self.function.address
|
||||
}
|
||||
pub fn revision(&self) -> u8 {
|
||||
self.admission.config.revision as u8
|
||||
}
|
||||
pub fn subsystem_ids(&self) -> (u16, u16) {
|
||||
(
|
||||
self.admission.config.subvendor as u16,
|
||||
self.admission.config.subdevice as u16,
|
||||
)
|
||||
}
|
||||
pub fn matched_row(&self) -> u32 {
|
||||
self.admission.row
|
||||
}
|
||||
pub fn original_flags(&self) -> u32 {
|
||||
self.admission.original_flags
|
||||
}
|
||||
pub fn asic_type(&self) -> u32 {
|
||||
self.admission.asic_type
|
||||
}
|
||||
/// Only flags established at original initial-APU stage. Modern wildcard
|
||||
/// matches may be APUs; final classification follows genuine IP discovery.
|
||||
pub fn initial_apu_flags(&self) -> u32 {
|
||||
self.admission.initial_apu_flags
|
||||
}
|
||||
pub fn ip_path(&self) -> IpPath {
|
||||
self.admission.path
|
||||
}
|
||||
pub fn source(&self) -> Source {
|
||||
self.admission.source
|
||||
}
|
||||
pub(super) fn function(&self) -> &Function<C> {
|
||||
self.function
|
||||
}
|
||||
pub(super) fn admission(&self) -> Admission {
|
||||
self.admission
|
||||
}
|
||||
}
|
||||
|
||||
/// Read actual config and apply original normal-table probe/source decisions.
|
||||
/// No config writes, allocation, hardware activation or firmware acquisition.
|
||||
/// Linux dynamic IDs/driver_override and forced-ASIC debug paths do not produce
|
||||
/// this result. Preferred files and static implementations remain explicit.
|
||||
///
|
||||
/// # Safety
|
||||
/// `function` is this native owner's genuine, accessible PCI function in the
|
||||
/// retained device/reset epoch, with native config/reset/removal exclusion.
|
||||
/// `policy` is the actual native build/user/platform policy at this probe stage;
|
||||
/// memory-encryption/firmware-driver arbitration cannot be guessed to admit a
|
||||
/// device. Existing native resources/firmware/PCI enable ownership is separate.
|
||||
/// Keep the real owner/epoch stable through all returned dependent objects.
|
||||
/// This API cannot turn a model ConfigSpace into actual hardware evidence.
|
||||
pub unsafe fn identify<C: ConfigSpace>(
|
||||
function: &mut Function<C>,
|
||||
policy: Policy,
|
||||
) -> Result<MatchedFunction<'_, C>, Error> {
|
||||
let labels = (function.vendor, function.device, function.class);
|
||||
let config = function.config();
|
||||
let ids = config.read32(0);
|
||||
if ids as u16 == u16::MAX {
|
||||
return Err(Error::Absent);
|
||||
}
|
||||
if config.read8(0x0e) & 0x7f != 0 {
|
||||
return Err(Error::UnsupportedHeader);
|
||||
}
|
||||
let class_revision = config.read32(8);
|
||||
let subsystem = config.read32(0x2c);
|
||||
let observed = ConfigIdentity {
|
||||
vendor: u32::from(ids as u16),
|
||||
device: ids >> 16,
|
||||
subvendor: u32::from(subsystem as u16),
|
||||
subdevice: subsystem >> 16,
|
||||
class_code: class_revision >> 8,
|
||||
revision: class_revision & 0xff,
|
||||
};
|
||||
let actual_class = [
|
||||
(class_revision >> 24) as u8,
|
||||
(class_revision >> 16) as u8,
|
||||
(class_revision >> 8) as u8,
|
||||
];
|
||||
if labels != (ids as u16, (ids >> 16) as u16, actual_class) {
|
||||
return Err(Error::IdentityChanged);
|
||||
}
|
||||
let native_policy = NativePolicy {
|
||||
si_built: u32::from(policy.si_built),
|
||||
cik_built: u32::from(policy.cik_built),
|
||||
radeon_built: u32::from(policy.radeon_built),
|
||||
si_support: policy.si_support,
|
||||
cik_support: policy.cik_support,
|
||||
experimental: policy.experimental,
|
||||
discovery: policy.discovery,
|
||||
force_asic: policy.force_asic,
|
||||
memory_encrypted: u32::from(policy.memory_encrypted),
|
||||
firmware_drivers_only: u32::from(policy.firmware_drivers_only),
|
||||
modeset: policy.modeset,
|
||||
};
|
||||
let mut matched = NativeMatch::default();
|
||||
// SAFETY: exact independently asserted scalar ABI; no borrowed input retained.
|
||||
let status = unsafe { stela_amd_pci_match(&observed, &native_policy, &mut matched) };
|
||||
if status != 0 {
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
let path = match matched.ip_path {
|
||||
0 => IpPath::SiStatic,
|
||||
1 => IpPath::CikStatic,
|
||||
2 => IpPath::ViStatic,
|
||||
3 => IpPath::SocStatic,
|
||||
4 => IpPath::Dynamic,
|
||||
_ => return Err(Error::InvalidNativeResult),
|
||||
};
|
||||
let source = match matched.discovery_source {
|
||||
0 if matched.filename.is_null() => Source::NotUsed,
|
||||
1 if matched.filename.is_null() => Source::Hardware,
|
||||
2 if !matched.filename.is_null() => {
|
||||
// SAFETY: successful original C selector returns only its immutable
|
||||
// static nul-terminated filename literal, linked for process lifetime.
|
||||
Source::Firmware(unsafe { CStr::from_ptr(matched.filename) })
|
||||
}
|
||||
_ => return Err(Error::InvalidNativeResult),
|
||||
};
|
||||
Ok(MatchedFunction {
|
||||
function,
|
||||
admission: Admission {
|
||||
config: observed,
|
||||
row: matched.row,
|
||||
original_flags: matched.original_flags,
|
||||
asic_type: matched.asic_type,
|
||||
initial_apu_flags: matched.initial_apu_flags,
|
||||
path,
|
||||
source,
|
||||
discovery_option: policy.discovery,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -46,3 +46,307 @@ $(OUT_DIR)/vm_cpu.o: $(SOURCE)/vm_cpu.c $(VM_HEADERS) | $(OUT_DIR)
|
||||
$(OUT_DIR)/vm_cpu_uefi.obj: $(SOURCE)/vm_cpu.c $(VM_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows $(COMMON) $(CFLAGS) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Original BAR policy only: no PCI/MMIO access or native provider activation.
|
||||
BAR_INCLUDE := -I$(SOURCE)/../../common/linux/include
|
||||
BAR_HEADERS := $(SOURCE)/native_bar.h $(SOURCE)/../../common/linux/include/drm/amd_asic_type.h
|
||||
BAR_INPUTS := $(SOURCE)/native_bar.c $(SOURCE)/../tests/native_bar_test.c
|
||||
.PHONY: bar-test bar-sanitize bar-native bar-uefi
|
||||
bar-test: $(OUT_DIR)/native_bar_test
|
||||
"$<"
|
||||
bar-sanitize: $(OUT_DIR)/native_bar_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 "$<"
|
||||
bar-native: $(OUT_DIR)/native_bar.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
bar-uefi: $(OUT_DIR)/native_bar_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
$(OUT_DIR)/native_bar_test: $(BAR_INPUTS) $(BAR_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) $(BAR_INPUTS) -o "$@"
|
||||
$(OUT_DIR)/native_bar_sanitize: $(BAR_INPUTS) $(BAR_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -O1 -fsanitize=address,undefined $(BAR_INPUTS) -o "$@"
|
||||
$(OUT_DIR)/native_bar.o: $(SOURCE)/native_bar.c $(BAR_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -ffreestanding -fno-stack-protector \
|
||||
-mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/native_bar_uefi.obj: $(SOURCE)/native_bar.c $(BAR_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Same original MM-index loop; CPU-only traces and actual bounded native entry.
|
||||
VRAM_MM_HEADERS := $(SOURCE)/vram_mm.h $(SOURCE)/../amdgpu/amdgpu_mm_access_core.h \
|
||||
$(SOURCE)/../include/asic_reg/bif/bif_4_1_d.h
|
||||
VRAM_MM_TEST := $(SOURCE)/../tests/vram_mm.c
|
||||
.PHONY: vram-mm-test vram-mm-sanitize vram-mm-native vram-mm-uefi
|
||||
vram-mm-test: $(OUT_DIR)/vram_mm_test
|
||||
"$<"
|
||||
vram-mm-sanitize: $(OUT_DIR)/vram_mm_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<"
|
||||
vram-mm-native: $(OUT_DIR)/vram_mm.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
vram-mm-uefi: $(OUT_DIR)/vram_mm_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
$(OUT_DIR)/vram-mm-wrapper.inc: $(SOURCE)/../amdgpu/amdgpu_device.c | $(OUT_DIR)
|
||||
sed -n '/^static uint32_t amdgpu_mm_access_read32(/,/^size_t amdgpu_device_aper_access(/{ /^size_t amdgpu_device_aper_access(/d; p; }' "$<" > "$@"
|
||||
test -s "$@"
|
||||
$(OUT_DIR)/vram-mm-instrumented.c: $(SOURCE)/vram_mm.c | $(OUT_DIR)
|
||||
printf '%s\n' '#include "vram_mm_test_io.h"' > "$@"
|
||||
sed -e 's/^stela_amd_vram_mm_read(/stela_amd_vram_mm_test_read(/' \
|
||||
-e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_test_io_read(pointer);/' \
|
||||
-e 's/\*pointer = value;/stela_amd_test_io_write(pointer, value);/' "$<" >> "$@"
|
||||
$(OUT_DIR)/vram_mm_test: $(SOURCE)/vram_mm.c $(VRAM_MM_TEST) $(VRAM_MM_HEADERS) \
|
||||
$(SOURCE)/../tests/vram_mm_reference.h $(SOURCE)/../tests/vram_mm_test_io.h \
|
||||
$(OUT_DIR)/vram-mm-wrapper.inc $(OUT_DIR)/vram-mm-instrumented.c
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \
|
||||
$(SOURCE)/vram_mm.c $(OUT_DIR)/vram-mm-instrumented.c $(VRAM_MM_TEST) -o "$@"
|
||||
$(OUT_DIR)/vram_mm_sanitize: $(SOURCE)/vram_mm.c $(VRAM_MM_TEST) $(VRAM_MM_HEADERS) \
|
||||
$(SOURCE)/../tests/vram_mm_reference.h $(SOURCE)/../tests/vram_mm_test_io.h \
|
||||
$(OUT_DIR)/vram-mm-wrapper.inc $(OUT_DIR)/vram-mm-instrumented.c
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests -O1 -fno-omit-frame-pointer \
|
||||
-fsanitize=address,undefined $(SOURCE)/vram_mm.c $(OUT_DIR)/vram-mm-instrumented.c $(VRAM_MM_TEST) -o "$@"
|
||||
$(OUT_DIR)/vram_mm.o: $(SOURCE)/vram_mm.c $(VRAM_MM_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \
|
||||
-mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/vram_mm_uefi.obj: $(SOURCE)/vram_mm.c $(VRAM_MM_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Actual original TMR query, with CPU-only test I/O instrumentation.
|
||||
TMR_HEADERS := $(SOURCE)/discovery_tmr.h $(SOURCE)/vram_mm.h \
|
||||
$(SOURCE)/../include/asic_reg/bif/bif_4_1_d.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_discovery_tmr_core.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_discovery_tmr_limits.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_virt_bootstrap_core.h \
|
||||
$(SOURCE)/discovery_binary.h $(SOURCE)/../include/discovery.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_ip_limits.h \
|
||||
$(SOURCE)/../../common/linux/include/uapi/linux/stddef.h \
|
||||
$(SOURCE)/../../common/linux/include/drm/amd_asic_type.h
|
||||
.PHONY: tmr-test tmr-sanitize tmr-native tmr-uefi
|
||||
tmr-test: $(OUT_DIR)/discovery_tmr_test
|
||||
"$<"
|
||||
tmr-sanitize: $(OUT_DIR)/discovery_tmr_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<"
|
||||
tmr-native: $(OUT_DIR)/discovery_tmr.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test "$$(wc -l < "$<.undefined" | tr -d ' ')" = 1
|
||||
rg 'stela_amd_vram_mm_read' "$<.undefined"
|
||||
tmr-uefi: $(OUT_DIR)/discovery_tmr_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test "$$(wc -l < "$<.undefined" | tr -d ' ')" = 1
|
||||
rg 'stela_amd_vram_mm_read' "$<.undefined"
|
||||
$(OUT_DIR)/discovery-tmr-wrapper.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
sed -n '/^static uint32_t amdgpu_discovery_tmr_read32(/,/^static int amdgpu_discovery_read_binary_from_sysmem/{ /^static int amdgpu_discovery_read_binary_from_sysmem/d; p; }' "$<" > "$@"
|
||||
test -s "$@"
|
||||
$(OUT_DIR)/discovery-tmr-instrumented.c: $(SOURCE)/discovery_tmr.c | $(OUT_DIR)
|
||||
printf '%s\n' '#include "discovery_tmr_test_io.h"' > "$@"
|
||||
sed -e 's/^int stela_amd_discovery_tmr_query(/int stela_amd_discovery_tmr_test_query(/' \
|
||||
-e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_tmr_test_read(pointer);/' "$<" >> "$@"
|
||||
$(OUT_DIR)/tmr-vram-instrumented.c: $(SOURCE)/vram_mm.c | $(OUT_DIR)
|
||||
printf '%s\n' '#include "discovery_tmr_test_io.h"' > "$@"
|
||||
sed -e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_tmr_test_read(pointer);/' \
|
||||
-e 's/\*pointer = value;/stela_amd_tmr_test_write(pointer, value);/' "$<" >> "$@"
|
||||
TMR_TEST_INPUTS = $(SOURCE)/../tests/discovery_tmr.c \
|
||||
$(OUT_DIR)/discovery-tmr-instrumented.c $(OUT_DIR)/tmr-vram-instrumented.c
|
||||
TMR_TEST_HEADERS := $(TMR_HEADERS) $(SOURCE)/../tests/discovery_tmr_reference.h \
|
||||
$(SOURCE)/../tests/discovery_tmr_virt_reference.h \
|
||||
$(SOURCE)/../tests/discovery_tmr_test_io.h
|
||||
$(OUT_DIR)/discovery_tmr_test: $(TMR_TEST_INPUTS) $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \
|
||||
$(TMR_TEST_INPUTS) -o "$@"
|
||||
$(OUT_DIR)/discovery_tmr_sanitize: $(TMR_TEST_INPUTS) $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \
|
||||
-O1 -fno-omit-frame-pointer -fsanitize=address,undefined $(TMR_TEST_INPUTS) -o "$@"
|
||||
$(OUT_DIR)/discovery_tmr.o: $(SOURCE)/discovery_tmr.c $(TMR_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \
|
||||
-mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/discovery_tmr_uefi.obj: $(SOURCE)/discovery_tmr.c $(TMR_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Test-only same-process canonical RAM fixture objects; never linked in a driver.
|
||||
.PHONY: tmr-ram-model
|
||||
tmr-ram-model: $(OUT_DIR)/tmr-model.o $(OUT_DIR)/tmr-query-model.o \
|
||||
$(OUT_DIR)/tmr-vram-model.o $(OUT_DIR)/tmr-fixture.o $(OUT_DIR)/tmr-binary.o
|
||||
$(OUT_DIR)/tmr-model.o: $(SOURCE)/../tests/discovery_tmr.c $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc
|
||||
$(CC) $(COMMON) $(CFLAGS) -DSTELA_TMR_RUST_MODEL -I$(OUT_DIR) -c "$<" -o "$@"
|
||||
$(OUT_DIR)/tmr-query-model.o: $(OUT_DIR)/discovery-tmr-instrumented.c $(TMR_HEADERS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(SOURCE) -I$(SOURCE)/../tests \
|
||||
-Dstela_amd_discovery_tmr_test_query=stela_amd_discovery_tmr_query -c "$<" -o "$@"
|
||||
$(OUT_DIR)/tmr-vram-model.o: $(OUT_DIR)/tmr-vram-instrumented.c $(VRAM_MM_HEADERS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(SOURCE) -I$(SOURCE)/../tests -c "$<" -o "$@"
|
||||
$(OUT_DIR)/tmr-fixture.o: $(SOURCE)/../tests/discovery_tmr_fixture.c \
|
||||
$(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h $(TMR_HEADERS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@"
|
||||
$(OUT_DIR)/tmr-binary.o: $(SOURCE)/discovery_binary.c $(TMR_HEADERS) $(SOURCE)/../include/soc15_hw_ip.h | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@"
|
||||
|
||||
# Immutable discovery snapshots only; optional external files are CPU fixtures.
|
||||
DISCOVERY_INPUTS ?=
|
||||
DISCOVERY_HEADERS := $(SOURCE)/discovery_binary.h $(SOURCE)/../include/discovery.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_ip_limits.h $(SOURCE)/../include/soc15_hw_ip.h \
|
||||
$(SOURCE)/../../common/linux/include/uapi/linux/stddef.h
|
||||
DISCOVERY_SOURCES := $(SOURCE)/discovery_binary.c $(SOURCE)/../tests/discovery_binary_test.c
|
||||
DISCOVERY_TEST_HEADERS := $(DISCOVERY_HEADERS) $(SOURCE)/../tests/discovery_reference.h
|
||||
.PHONY: discovery-test discovery-sanitize discovery-native discovery-uefi
|
||||
discovery-test: $(OUT_DIR)/discovery_binary_test
|
||||
"$<" $(DISCOVERY_INPUTS)
|
||||
discovery-sanitize: $(OUT_DIR)/discovery_binary_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 "$<" $(DISCOVERY_INPUTS)
|
||||
discovery-native: $(OUT_DIR)/discovery_binary.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
discovery-uefi: $(OUT_DIR)/discovery_binary_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
$(OUT_DIR)/discovery_binary_test: $(DISCOVERY_SOURCES) $(DISCOVERY_TEST_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -Wno-unused-function -fwrapv $(DISCOVERY_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_binary_sanitize: $(DISCOVERY_SOURCES) $(DISCOVERY_TEST_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -Wno-unused-function -fwrapv -O1 -fno-omit-frame-pointer \
|
||||
-fsanitize=address,undefined $(DISCOVERY_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_binary.o: $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \
|
||||
-mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/discovery_binary_uefi.obj: $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Compile the actual retained live-read function, not a copied replacement.
|
||||
# Only acquisition/OS context is a bounded CPU model in the test fixture.
|
||||
.PHONY: discovery-refresh-test discovery-refresh-sanitize
|
||||
discovery-refresh-test: $(OUT_DIR)/discovery_refresh_test
|
||||
"$<"
|
||||
discovery-refresh-sanitize: $(OUT_DIR)/discovery_refresh_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 "$<"
|
||||
$(OUT_DIR)/discovery-refresh.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
sed -n '/^static int amdgpu_discovery_refresh_nps_info(/,/^int amdgpu_discovery_get_nps_info(/{ /^int amdgpu_discovery_get_nps_info(/d; p; }' "$<" > "$@"
|
||||
test -s "$@"
|
||||
$(OUT_DIR)/discovery_refresh_test: $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) $(OUT_DIR)/discovery-refresh.inc
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c -o "$@"
|
||||
$(OUT_DIR)/discovery_refresh_sanitize: $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) $(OUT_DIR)/discovery-refresh.inc
|
||||
$(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -O1 -fsanitize=address,undefined $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c -o "$@"
|
||||
|
||||
# Original PCI normal-table admission and source policy; no config/MMIO effects.
|
||||
PCI_HEADERS := $(SOURCE)/pci_match.h $(SOURCE)/../amdgpu/amdgpu_pci_match_core.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_apu_flags_core.h $(SOURCE)/../amdgpu/amdgpu_discovery_source_core.h \
|
||||
$(SOURCE)/../include/amd_chip_flags.h \
|
||||
$(SOURCE)/../../common/linux/include/drm/amd_asic_type.h \
|
||||
$(SOURCE)/../../common/linux/include/linux/device-id/pci.h \
|
||||
$(SOURCE)/../../common/linux/include/linux/pci_ids.h
|
||||
# Original table shorthand/ARRAY_SIZE conventions, as in the Linux consumer.
|
||||
PCI_FLAGS := -Wno-missing-field-initializers -Wno-sign-compare
|
||||
.PHONY: pci-test pci-sanitize pci-native pci-uefi
|
||||
pci-test: $(OUT_DIR)/pci_match_test
|
||||
"$<"
|
||||
pci-sanitize: $(OUT_DIR)/pci_match_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<"
|
||||
pci-native: $(OUT_DIR)/pci_match.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
pci-uefi: $(OUT_DIR)/pci_match_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test ! -s "$<.undefined"
|
||||
$(OUT_DIR)/pci-linux-wrappers.inc: $(SOURCE)/../amdgpu/amdgpu_drv.c $(SOURCE)/../amdgpu/amdgpu_device.c $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
sed -n '/^static unsigned long amdgpu_fix_asic_type(/,/^static int amdgpu_pci_probe(/{ /^static int amdgpu_pci_probe(/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_drv.c" > "$@"
|
||||
sed -n '/^static int amdgpu_device_init_apu_flags(/,/^\/\*\*/{ /^\/\*\*/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_device.c" >> "$@"
|
||||
sed -n '/^static const char \*amdgpu_discovery_get_fw_name(/,/^static int amdgpu_discovery_get_table_info(/{ /^static int amdgpu_discovery_get_table_info(/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_discovery.c" >> "$@"
|
||||
test -s "$@"
|
||||
$(OUT_DIR)/pci_match_test: $(SOURCE)/../tests/pci_match.c $(SOURCE)/../tests/pci_reference.h $(SOURCE)/pci_match.c $(PCI_HEADERS) $(OUT_DIR)/pci-linux-wrappers.inc $(OUT_DIR)/pci-linux-paths.inc | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -I$(OUT_DIR) "$<" -o "$@"
|
||||
$(OUT_DIR)/pci_match_sanitize: $(SOURCE)/../tests/pci_match.c $(SOURCE)/../tests/pci_reference.h $(SOURCE)/pci_match.c $(PCI_HEADERS) $(OUT_DIR)/pci-linux-wrappers.inc $(OUT_DIR)/pci-linux-paths.inc | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -I$(OUT_DIR) -O1 -fno-omit-frame-pointer -fsanitize=address,undefined "$<" -o "$@"
|
||||
$(OUT_DIR)/pci_match.o: $(SOURCE)/pci_match.c $(PCI_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -ffreestanding -fno-stack-protector \
|
||||
-mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/pci_match_uefi.obj: $(SOURCE)/pci_match.c $(PCI_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) $(PCI_FLAGS) -ffreestanding \
|
||||
-fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/pci-linux-paths.inc: $(SOURCE)/../amdgpu/amdgpu_device.c $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
printf '%s\n' 'static int linux_initial_path(struct amdgpu_device *adev) {' 'int r;' > "$@"
|
||||
sed -n '/switch (amdgpu_initial_ip_path(/,/Check for IP version/{ /Check for IP version/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_device.c" >> "$@"
|
||||
printf '%s\n' 'return 0;' '}' 'static int linux_discovery_path(struct amdgpu_device *adev) {' 'int r;' >> "$@"
|
||||
sed -n '/switch (amdgpu_discovery_static_asic(/,/amdgpu_discovery_init_soc_config(adev)/{ /amdgpu_discovery_init_soc_config(adev)/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_discovery.c" >> "$@"
|
||||
printf '%s\n' 'return 0;' '}' >> "$@"
|
||||
|
||||
IP_HEADERS := $(SOURCE)/discovery_ip.h $(SOURCE)/discovery_binary.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_discovery_ip_core.h $(SOURCE)/../amdgpu/amdgpu_ip_types.h \
|
||||
$(SOURCE)/../amdgpu/amdgpu_ip_instance_limits.h $(SOURCE)/../amdgpu/amdgpu_ip_limits.h \
|
||||
$(SOURCE)/../include/discovery.h $(SOURCE)/../include/soc15_hw_ip.h
|
||||
.PHONY: ip-test ip-sanitize ip-native ip-uefi
|
||||
ip-test: $(OUT_DIR)/discovery_ip_test
|
||||
"$<" $(IP_INPUTS)
|
||||
ip-sanitize: $(OUT_DIR)/discovery_ip_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" $(IP_INPUTS)
|
||||
ip-native: $(OUT_DIR)/discovery_ip.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test $$(wc -l <"$<.undefined") -eq 2
|
||||
rg 'amdgpu_discovery_binary_(table|validate)' "$<.undefined"
|
||||
ip-uefi: $(OUT_DIR)/discovery_ip_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test $$(wc -l <"$<.undefined") -eq 2
|
||||
rg 'amdgpu_discovery_binary_(table|validate)' "$<.undefined"
|
||||
$(OUT_DIR)/discovery-ip-linux.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
sed -n '/^static void amdgpu_discovery_ip_debug(/,/^static uint32_t amdgpu_discovery_tmr_read32(/{ /^static uint32_t amdgpu_discovery_tmr_read32(/d; p; }' "$<" > "$@"
|
||||
sed -n '/^static int amdgpu_discovery_validate_ip(/,/^static void amdgpu_discovery_read_harvest_bit_per_ip(/{ /^static void amdgpu_discovery_read_harvest_bit_per_ip(/d; p; }' "$<" >> "$@"
|
||||
sed -n '/^static int amdgpu_discovery_reg_base_init(/,/^static void amdgpu_discovery_harvest_ip(/{ /^static void amdgpu_discovery_harvest_ip(/d; p; }' "$<" >> "$@"
|
||||
IP_TEST_SOURCES := $(SOURCE)/discovery_ip.c $(SOURCE)/discovery_binary.c \
|
||||
$(SOURCE)/../tests/discovery_ip.c $(SOURCE)/../tests/discovery_ip_fixture.c
|
||||
IP_TEST_DEPS := $(IP_HEADERS) $(SOURCE)/../tests/discovery_ip_reference.h \
|
||||
$(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h \
|
||||
$(OUT_DIR)/discovery-ip-linux.inc
|
||||
$(OUT_DIR)/discovery_ip_test: $(IP_TEST_SOURCES) $(IP_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -Wno-sign-compare -I$(OUT_DIR) $(IP_TEST_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_ip_sanitize: $(IP_TEST_SOURCES) $(IP_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -O1 -fwrapv -fno-omit-frame-pointer -fsanitize=address,undefined -Wno-sign-compare -I$(OUT_DIR) $(IP_TEST_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_ip.o: $(SOURCE)/discovery_ip.c $(IP_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/discovery_ip_uefi.obj: $(SOURCE)/discovery_ip.c $(IP_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -fwrapv -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
# Test-only independent frozen consumer for the canonical owned-source harness.
|
||||
# Never linked into the production driver archive or used as a provider.
|
||||
.PHONY: ip-ram-model
|
||||
ip-ram-model: $(OUT_DIR)/ip-oracle.o $(OUT_DIR)/ip-fixture.o
|
||||
$(OUT_DIR)/ip-oracle.o: $(IP_TEST_SOURCES) $(IP_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -Wno-sign-compare -DSTELA_IP_RUST_MODEL \
|
||||
-Dmain=stela_amd_ip_test_main -I$(OUT_DIR) -c "$(SOURCE)/../tests/discovery_ip.c" -o "$@"
|
||||
$(OUT_DIR)/ip-fixture.o: $(SOURCE)/../tests/discovery_ip_fixture.c $(DISCOVERY_TEST_HEADERS) \
|
||||
$(SOURCE)/../tests/discovery_binary_test.c | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@"
|
||||
|
||||
FILE_HEADERS := $(SOURCE)/discovery_file.h $(SOURCE)/../amdgpu/amdgpu_discovery_file_core.h $(DISCOVERY_HEADERS)
|
||||
FILE_SOURCES := $(SOURCE)/discovery_file.c $(SOURCE)/discovery_binary.c \
|
||||
$(SOURCE)/../tests/discovery_file.c $(SOURCE)/../tests/discovery_ip_fixture.c
|
||||
FILE_TEST_DEPS := $(FILE_HEADERS) $(SOURCE)/../tests/discovery_file_reference.h \
|
||||
$(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h \
|
||||
$(OUT_DIR)/discovery-file-linux.inc
|
||||
.PHONY: file-test file-sanitize file-native file-uefi
|
||||
file-test: $(OUT_DIR)/discovery_file_test
|
||||
"$<" $(FILE_INPUTS)
|
||||
file-sanitize: $(OUT_DIR)/discovery_file_sanitize
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" $(FILE_INPUTS)
|
||||
file-native: $(OUT_DIR)/discovery_file.o
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test $$(wc -l <"$<.undefined") -eq 1
|
||||
rg 'amdgpu_discovery_binary_validate' "$<.undefined"
|
||||
file-uefi: $(OUT_DIR)/discovery_file_uefi.obj
|
||||
$(NM) -u "$<" >"$<.undefined"
|
||||
test $$(wc -l <"$<.undefined") -eq 1
|
||||
rg 'amdgpu_discovery_binary_validate' "$<.undefined"
|
||||
$(OUT_DIR)/discovery-file-linux.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR)
|
||||
sed -n '/^static int amdgpu_discovery_read_binary_from_file(/,/^static inline bool amdgpu_discovery_verify_checksum(/{ /^static inline bool amdgpu_discovery_verify_checksum(/d; p; }' "$<" > "$@"
|
||||
$(OUT_DIR)/discovery_file_test: $(FILE_SOURCES) $(FILE_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -I$(OUT_DIR) $(FILE_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_file_sanitize: $(FILE_SOURCES) $(FILE_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -O1 -fno-omit-frame-pointer -fsanitize=address,undefined -I$(OUT_DIR) $(FILE_SOURCES) -o "$@"
|
||||
$(OUT_DIR)/discovery_file.o: $(SOURCE)/discovery_file.c $(FILE_HEADERS) | $(OUT_DIR)
|
||||
$(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
$(OUT_DIR)/discovery_file_uefi.obj: $(SOURCE)/discovery_file.c $(FILE_HEADERS) | $(OUT_DIR)
|
||||
$(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@"
|
||||
|
||||
.PHONY: file-ram-model
|
||||
file-ram-model: $(OUT_DIR)/file-oracle.o
|
||||
$(OUT_DIR)/file-oracle.o: $(FILE_SOURCES) $(FILE_TEST_DEPS)
|
||||
$(CC) $(COMMON) $(CFLAGS) -fwrapv -Dmain=stela_amd_file_test_main \
|
||||
-I$(OUT_DIR) -c "$(SOURCE)/../tests/discovery_file.c" -o "$@"
|
||||
@@ -0,0 +1,419 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "air_compile.h"
|
||||
#include "amd/common/ac_binary.h"
|
||||
#include "amd/common/nir/ac_nir.h"
|
||||
#include "amd/compiler/aco_interface.h"
|
||||
#include "util/ralloc.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_TEXT 4096u /* Same bounded reflection strings as library assembly. */
|
||||
#define MAX_CODE (64u * 1024u * 1024u)
|
||||
|
||||
struct stela_amd_air_compilation {
|
||||
struct stela_amd_compute_binary binary;
|
||||
struct stela_amd_air_provenance provenance;
|
||||
nir_shader_compiler_options nir_options;
|
||||
struct ac_shader_args args;
|
||||
struct ac_shader_config config;
|
||||
struct stela_amd_air_binding bindings[STELA_AMD_AIR_MAX_BUFFERS];
|
||||
uint32_t binding_count;
|
||||
void *metadata;
|
||||
uint8_t *code;
|
||||
bool type_reference, captured;
|
||||
enum stela_amd_air_status capture_status;
|
||||
};
|
||||
|
||||
static enum stela_amd_air_status
|
||||
report(struct stela_amd_air_error *error, enum stela_amd_air_status status,
|
||||
const char *detail)
|
||||
{
|
||||
if (error) {
|
||||
error->status = status;
|
||||
snprintf(error->detail, sizeof(error->detail), "%s", detail);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
void
|
||||
stela_amd_air_destroy(struct stela_amd_air_compilation **slot)
|
||||
{
|
||||
if (!slot || !*slot)
|
||||
return;
|
||||
struct stela_amd_air_compilation *owner = *slot;
|
||||
*slot = NULL;
|
||||
ralloc_free((void *)owner->binary.shader);
|
||||
if (owner->type_reference)
|
||||
glsl_type_singleton_decref();
|
||||
free(owner->code);
|
||||
free(owner->metadata);
|
||||
free(owner);
|
||||
}
|
||||
|
||||
static bool
|
||||
text_valid(const char *text, size_t length)
|
||||
{
|
||||
return length <= MAX_TEXT && (!length || (text && !memchr(text, 0, length)));
|
||||
}
|
||||
|
||||
static char *
|
||||
copy_text(char **cursor, const void *text, size_t length)
|
||||
{
|
||||
if (!text)
|
||||
return NULL;
|
||||
char *result = *cursor;
|
||||
if (length)
|
||||
memcpy(result, text, length);
|
||||
result[length] = 0;
|
||||
*cursor += length + 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
static enum stela_amd_air_status
|
||||
copy_provenance(struct stela_amd_air_compilation *owner,
|
||||
const struct stela_metal_library_manifest *manifest,
|
||||
const struct stela_metal_function_record *record, uint32_t selected,
|
||||
struct stela_amd_air_error *error)
|
||||
{
|
||||
if (!text_valid((const char *)record->name, record->name_bytes) || !record->name_bytes ||
|
||||
!text_valid((const char *)manifest->target, manifest->target_bytes) || !manifest->target_bytes ||
|
||||
record->argument_count > AIR_MAX_ARGUMENTS ||
|
||||
(record->argument_count && !record->arguments))
|
||||
return report(error, STELA_AMD_AIR_INVALID, "Unrepresentable selected entry metadata");
|
||||
size_t bytes = record->argument_count * sizeof(struct stela_air_argument_info) +
|
||||
(size_t)record->name_bytes + (size_t)manifest->target_bytes + 2;
|
||||
for (unsigned i = 0; i < record->argument_count; i++) {
|
||||
const struct stela_air_argument_info *arg = &record->arguments[i];
|
||||
if (!text_valid(arg->name, arg->name_bytes) || !text_valid(arg->type_name, arg->type_name_bytes))
|
||||
return report(error, STELA_AMD_AIR_INVALID, "Unrepresentable argument strings");
|
||||
bytes += arg->name_bytes + arg->type_name_bytes + 2;
|
||||
}
|
||||
/* All additions are bounded by 128 arguments and 4096 bytes/string. */
|
||||
owner->metadata = malloc(bytes);
|
||||
if (!owner->metadata)
|
||||
return report(error, STELA_AMD_AIR_ALLOCATION, "Selected metadata allocation failed");
|
||||
struct stela_air_argument_info *args = owner->metadata;
|
||||
char *cursor = (char *)(args + record->argument_count);
|
||||
struct stela_amd_air_provenance *p = &owner->provenance;
|
||||
p->input = manifest->input;
|
||||
p->entry = record->entry;
|
||||
p->selected_entry = selected;
|
||||
p->entry_flags = record->flags;
|
||||
p->library_flags = manifest->flags;
|
||||
p->compiler_profile = manifest->compiler_profile;
|
||||
p->request_language = manifest->request_language;
|
||||
p->request_fast_math = manifest->request_fast_math;
|
||||
p->build = manifest->build;
|
||||
p->air_offset = record->air_offset;
|
||||
p->air_bytes = record->air_bytes;
|
||||
memcpy(p->air_sha256, record->air_sha256, 32);
|
||||
memcpy(p->source_sha256, manifest->source_sha256, 32);
|
||||
p->name = copy_text(&cursor, record->name, (size_t)record->name_bytes);
|
||||
p->target = copy_text(&cursor, manifest->target, (size_t)manifest->target_bytes);
|
||||
p->argument_count = record->argument_count;
|
||||
p->arguments = args;
|
||||
for (unsigned i = 0; i < record->argument_count; i++) {
|
||||
args[i] = record->arguments[i];
|
||||
args[i].name = copy_text(&cursor, args[i].name, args[i].name_bytes);
|
||||
args[i].type_name = copy_text(&cursor, args[i].type_name, args[i].type_name_bytes);
|
||||
}
|
||||
return STELA_AMD_AIR_OK;
|
||||
}
|
||||
|
||||
static enum stela_amd_air_status
|
||||
prepare_args(struct stela_amd_air_compilation *owner, const struct radeon_info *info,
|
||||
struct stela_amd_air_error *error)
|
||||
{
|
||||
for (unsigned i = 0; i < owner->provenance.argument_count; i++) {
|
||||
const struct stela_air_argument_info *arg = &owner->provenance.arguments[i];
|
||||
if (arg->kind == 2)
|
||||
continue; /* Existing AIR frontend validates/lower the actual builtin. */
|
||||
if (arg->kind == 1 && arg->buffer.address_space == 3 && arg->plain_buffer_type) continue;
|
||||
if (arg->kind != 1 || arg->buffer.address_space != 1 || !arg->plain_buffer_type)
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "Resource requires an unsupported binding specialization");
|
||||
if (owner->binding_count == STELA_AMD_AIR_MAX_BUFFERS)
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "More than eight AS1 address pairs");
|
||||
struct stela_amd_air_binding *binding = &owner->bindings[owner->binding_count++];
|
||||
binding->buffer = arg->buffer;
|
||||
ac_add_arg(&owner->args, AC_ARG_SGPR, 2, AC_ARG_CONST_ADDR, &binding->argument);
|
||||
}
|
||||
for (unsigned axis = 0; axis < 3; axis++) {
|
||||
if (info->gfx_level >= GFX12)
|
||||
owner->args.workgroup_ids[axis].used = true;
|
||||
else
|
||||
ac_add_arg(&owner->args, AC_ARG_SGPR, 1, AC_ARG_VALUE, &owner->args.workgroup_ids[axis]);
|
||||
}
|
||||
if (info->gfx_level < GFX11)
|
||||
ac_add_arg(&owner->args, AC_ARG_SGPR, 1, AC_ARG_VALUE, &owner->args.scratch_offset);
|
||||
if (info->compiler_info.local_invocation_ids_packed) {
|
||||
ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_ids_packed);
|
||||
} else {
|
||||
ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_x);
|
||||
ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_y);
|
||||
ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_z);
|
||||
}
|
||||
if (owner->args.num_sgprs_used > info->compiler_info.max_sgpr_alloc ||
|
||||
owner->args.num_vgprs_used > info->compiler_info.max_vgpr_alloc)
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "Argument layout exceeds actual device register limits");
|
||||
return STELA_AMD_AIR_OK;
|
||||
}
|
||||
|
||||
static nir_def *
|
||||
bind_buffer(nir_builder *b, const struct stela_air_buffer *buffer, void *data)
|
||||
{
|
||||
struct stela_amd_air_compilation *owner = data;
|
||||
for (unsigned i = 0; i < owner->binding_count; i++) {
|
||||
const struct stela_amd_air_binding *binding = &owner->bindings[i];
|
||||
if (binding->buffer.argument == buffer->argument &&
|
||||
binding->buffer.index == buffer->index &&
|
||||
binding->buffer.address_space == buffer->address_space &&
|
||||
binding->buffer.access == buffer->access &&
|
||||
binding->buffer.type_size == buffer->type_size &&
|
||||
binding->buffer.type_alignment == buffer->type_alignment)
|
||||
return nir_pack_64_2x32(b, ac_nir_load_arg(b, &owner->args, binding->argument));
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool
|
||||
compiler_facts_valid(const struct radeon_info *info, unsigned wave)
|
||||
{
|
||||
const struct ac_compiler_info *c = &info->compiler_info;
|
||||
unsigned scale = wave == 32 ? 2 : 1;
|
||||
/* Original ACO init_program stores these in uint16_t and doubles the
|
||||
* physical VGPR count/allocation grain for wave32. Grains are NOT generally
|
||||
* powers of two (e.g. SGPR108, VGPR12). Check before those conversions and
|
||||
* the allocator's original division/alignment helpers. These are necessary
|
||||
* representation checks, not authentication of caller-created device info. */
|
||||
return c->max_waves_per_simd && c->max_waves_per_simd <= UINT16_MAX &&
|
||||
c->num_simd_per_compute_unit &&
|
||||
c->num_physical_sgprs_per_simd && c->num_physical_sgprs_per_simd <= UINT16_MAX &&
|
||||
c->num_physical_wave64_vgprs_per_simd && c->num_physical_wave64_vgprs_per_simd <= UINT16_MAX / scale &&
|
||||
c->min_sgpr_alloc && c->min_sgpr_alloc <= c->max_sgpr_alloc &&
|
||||
c->max_sgpr_alloc <= c->num_physical_sgprs_per_simd &&
|
||||
c->sgpr_alloc_granularity && c->sgpr_alloc_granularity <= c->max_sgpr_alloc &&
|
||||
c->min_wave64_vgpr_alloc && c->min_wave64_vgpr_alloc <= c->max_vgpr_alloc &&
|
||||
c->max_vgpr_alloc <= c->num_physical_wave64_vgprs_per_simd && c->max_vgpr_alloc <= UINT16_MAX &&
|
||||
c->wave64_vgpr_alloc_granularity && c->wave64_vgpr_alloc_granularity <= UINT16_MAX / scale &&
|
||||
c->wave64_vgpr_encode_granularity && c->wave64_vgpr_encode_granularity <= c->max_vgpr_alloc &&
|
||||
c->lds_size_per_workgroup && c->lds_size_per_workgroup <= (info->gfx_level >= GFX7 ? 65536u : 32768u);
|
||||
}
|
||||
|
||||
static void
|
||||
capture(void **private, const struct ac_shader_config *config,
|
||||
const char *ir, unsigned ir_bytes, const char *assembly, unsigned assembly_bytes,
|
||||
struct amd_stats *stats, uint32_t executable_bytes, const uint32_t *code,
|
||||
uint32_t code_dw, const struct aco_symbol *symbols, unsigned symbol_count,
|
||||
const struct ac_shader_debug_info *debug, unsigned debug_count)
|
||||
{
|
||||
(void)ir; (void)ir_bytes; (void)assembly; (void)assembly_bytes; (void)stats;
|
||||
(void)symbols; (void)debug; (void)debug_count;
|
||||
struct stela_amd_air_compilation *owner = *private;
|
||||
if (owner->captured || !config || !code || !code_dw || !executable_bytes ||
|
||||
code_dw > UINT32_MAX / 4 || executable_bytes > code_dw * 4 || executable_bytes % 4) {
|
||||
owner->capture_status = STELA_AMD_AIR_BACKEND;
|
||||
return;
|
||||
}
|
||||
owner->captured = true;
|
||||
if (symbol_count) {
|
||||
owner->capture_status = STELA_AMD_AIR_UNSUPPORTED;
|
||||
return;
|
||||
}
|
||||
if (code_dw * 4 > owner->provenance.options.max_code_bytes) {
|
||||
owner->capture_status = STELA_AMD_AIR_LIMIT;
|
||||
return;
|
||||
}
|
||||
owner->code = malloc((size_t)code_dw * 4);
|
||||
if (!owner->code) {
|
||||
owner->capture_status = STELA_AMD_AIR_ALLOCATION;
|
||||
return;
|
||||
}
|
||||
memcpy(owner->code, code, (size_t)code_dw * 4);
|
||||
owner->config = *config;
|
||||
owner->binary.executable_bytes = executable_bytes;
|
||||
owner->binary.code_bytes = code_dw * 4;
|
||||
}
|
||||
|
||||
static bool bind_threadgroup(const struct stela_air_buffer *buffer,
|
||||
struct stela_air_threadgroup_view *view, void *data)
|
||||
{
|
||||
const struct stela_amd_air_compilation *owner = data;
|
||||
const struct stela_metal_threadgroup_specialization *shared = &owner->provenance.threadgroup;
|
||||
for (unsigned i = 0; i < shared->count; i++) {
|
||||
const struct stela_metal_threadgroup_binding *binding = &shared->bindings[i];
|
||||
const struct stela_air_buffer *b = &binding->buffer;
|
||||
if (b->argument == buffer->argument && b->index == buffer->index &&
|
||||
b->address_space == buffer->address_space && b->access == buffer->access &&
|
||||
b->type_size == buffer->type_size && b->type_alignment == buffer->type_alignment) {
|
||||
*view = (struct stela_air_threadgroup_view){.size = binding->bytes,
|
||||
.alignment = binding->alignment, .available_access = STELA_AIR_READ_WRITE};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
enum stela_amd_air_status
|
||||
stela_amd_air_compile(const struct radeon_info *info, const struct stela_metal_assembly *library,
|
||||
uint32_t selected, const struct stela_amd_air_options *options,
|
||||
struct stela_amd_air_compilation **output, struct stela_amd_air_error *error)
|
||||
{
|
||||
return stela_amd_air_compile_specialized(info, library, selected, options, NULL, output, error);
|
||||
}
|
||||
enum stela_amd_air_status
|
||||
stela_amd_air_compile_specialized(const struct radeon_info *info, const struct stela_metal_assembly *library,
|
||||
uint32_t selected, const struct stela_amd_air_options *options,
|
||||
const struct stela_metal_threadgroup_request *request,
|
||||
struct stela_amd_air_compilation **output, struct stela_amd_air_error *error)
|
||||
{
|
||||
if (error)
|
||||
memset(error, 0, sizeof(*error));
|
||||
if (!info || !library || !options || !output || *output ||
|
||||
options->size != sizeof(*options) || options->abi != STELA_AMD_AIR_ABI)
|
||||
return report(error, STELA_AMD_AIR_INVALID, "Invalid local compiler ownership/ABI");
|
||||
if (!options->max_instructions || !options->max_code_bytes || options->max_code_bytes > MAX_CODE)
|
||||
return report(error, STELA_AMD_AIR_LIMIT, "Explicit nonzero compiler/code budgets required");
|
||||
if ((options->wave_size != 32 && options->wave_size != 64) ||
|
||||
(options->fp_profile != STELA_AIR_FP_IEEE_DEFAULT &&
|
||||
options->fp_profile != STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41))
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "Unsupported wave/FP profile");
|
||||
if (info->family < CHIP_TAHITI || info->family >= CHIP_LAST ||
|
||||
ac_get_gfx_level(info->family) != info->gfx_level || !aco_is_gpu_supported(info) ||
|
||||
(options->wave_size == 32 && info->gfx_level < GFX10))
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "Target requires a different retained backend");
|
||||
struct stela_amd_raw_buffer_facts facts;
|
||||
if (stela_amd_query_raw_buffer_facts(info, &facts) != STELA_AMD_BUFFER_OK ||
|
||||
!compiler_facts_valid(info, options->wave_size))
|
||||
return report(error, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE, "Actual initialized device/compiler facts required");
|
||||
const struct stela_metal_library_manifest *manifest = stela_metal_assembly_manifest(library);
|
||||
if (!manifest || selected >= manifest->entry_count)
|
||||
return report(error, STELA_AMD_AIR_INVALID, "Selected entry outside canonical library");
|
||||
const struct stela_metal_function_record *record = &manifest->entries[selected];
|
||||
struct stela_metal_input_view original = {.size = sizeof(original), .abi = STELA_METAL_INPUT_ABI};
|
||||
if (stela_metal_assembly_original(library, &original, NULL) != STELA_METAL_ASSEMBLY_OK ||
|
||||
record->air_offset > original.length || record->air_bytes > original.length - record->air_offset ||
|
||||
!record->air_bytes || record->air_bytes > AIR_MAX_BITCODE_BYTES)
|
||||
return report(error, STELA_AMD_AIR_INVALID, "Invalid retained raw AIR span");
|
||||
struct stela_metal_threadgroup_specialization threadgroup;
|
||||
enum stela_metal_threadgroup_status shared_status = stela_metal_threadgroup_normalize(
|
||||
record->arguments, record->argument_count, request, info->compiler_info.lds_size_per_workgroup, &threadgroup);
|
||||
if (shared_status != STELA_METAL_THREADGROUP_OK)
|
||||
return report(error, shared_status == STELA_METAL_THREADGROUP_INVALID ? STELA_AMD_AIR_INVALID :
|
||||
shared_status == STELA_METAL_THREADGROUP_LIMIT ? STELA_AMD_AIR_LIMIT : STELA_AMD_AIR_UNSUPPORTED,
|
||||
"Resource requires a supported threadgroup binding specialization");
|
||||
struct stela_amd_air_compilation *owner = calloc(1, sizeof(*owner));
|
||||
if (!owner)
|
||||
return report(error, STELA_AMD_AIR_ALLOCATION, "Compilation owner allocation failed");
|
||||
owner->provenance.options = *options; owner->provenance.threadgroup = threadgroup;
|
||||
owner->provenance.compiler_info = info->compiler_info;
|
||||
owner->provenance.pci_id = info->pci_id;
|
||||
owner->provenance.pci_rev_id = info->pci_rev_id;
|
||||
owner->provenance.has_graphics = info->has_graphics;
|
||||
ac_nir_set_options(&info->compiler_info, false, &owner->nir_options);
|
||||
uint64_t threads = 1;
|
||||
for (unsigned axis = 0; axis < 3; axis++) {
|
||||
unsigned count = options->workgroup_size[axis];
|
||||
if (!count || count > owner->nir_options.max_workgroup_invocations ||
|
||||
threads > owner->nir_options.max_workgroup_invocations / count) {
|
||||
stela_amd_air_destroy(&owner);
|
||||
return report(error, STELA_AMD_AIR_UNSUPPORTED, "Invalid/unsupported workgroup specialization");
|
||||
}
|
||||
threads *= count;
|
||||
}
|
||||
enum stela_amd_air_status status = copy_provenance(owner, manifest, record, selected, error);
|
||||
if (status == STELA_AMD_AIR_OK)
|
||||
status = prepare_args(owner, info, error);
|
||||
if (status != STELA_AMD_AIR_OK) {
|
||||
stela_amd_air_destroy(&owner);
|
||||
return status;
|
||||
}
|
||||
glsl_type_singleton_init_or_ref();
|
||||
owner->type_reference = true;
|
||||
struct stela_air_options air = {
|
||||
.workgroup_size = {options->workgroup_size[0], options->workgroup_size[1], options->workgroup_size[2]},
|
||||
.max_instructions = options->max_instructions, .bind_buffer = bind_buffer,
|
||||
.binding_data = owner, .fp_profile = options->fp_profile,
|
||||
.bind_threadgroup = threadgroup.count ? bind_threadgroup : NULL,
|
||||
.max_threadgroup_bytes = info->compiler_info.lds_size_per_workgroup,
|
||||
};
|
||||
struct stela_air_error air_error;
|
||||
nir_shader *shader = stela_air_to_nir(original.bytes + record->air_offset,
|
||||
(size_t)record->air_bytes, owner->provenance.name, &owner->nir_options, &air, &air_error);
|
||||
if (!shader) {
|
||||
if (error)
|
||||
error->air = air_error;
|
||||
stela_amd_air_destroy(&owner);
|
||||
return report(error, STELA_AMD_AIR_FRONTEND, "Shared AIR frontend refused selected body/policy");
|
||||
}
|
||||
owner->binary = (struct stela_amd_compute_binary) {
|
||||
.shader = shader, .args = &owner->args, .config = &owner->config,
|
||||
.family = info->family, .gfx_level = info->gfx_level, .wave_size = options->wave_size,
|
||||
};
|
||||
const ac_nir_lower_intrinsics_to_args_options arg_options = {
|
||||
.gfx_level = info->gfx_level, .hw_stage = AC_HW_COMPUTE_SHADER,
|
||||
.wave_size = options->wave_size, .workgroup_size = (unsigned)threads,
|
||||
};
|
||||
ac_nir_lower_intrinsics_to_args(shader, &owner->args, &arg_options);
|
||||
ac_nir_lower_global_access(shader, info->gfx_level);
|
||||
nir_lower_int64(shader);
|
||||
bool progress;
|
||||
do {
|
||||
progress = nir_opt_constant_folding(shader);
|
||||
progress |= nir_opt_copy_prop(shader);
|
||||
progress |= nir_opt_algebraic(shader);
|
||||
progress |= nir_opt_dce(shader);
|
||||
} while (progress);
|
||||
nir_lower_alu_width(shader, ac_nir_opt_vectorize_cb, &owner->binary.gfx_level);
|
||||
nir_lower_load_const_to_scalar(shader);
|
||||
nir_opt_copy_prop(shader);
|
||||
nir_opt_dce(shader);
|
||||
nir_shader_gather_info(shader, nir_shader_get_entrypoint(shader));
|
||||
nir_validate_shader(shader, "owned AIR to AMD compute ABI");
|
||||
const struct aco_compiler_options aco_options = {
|
||||
.compiler_info = &info->compiler_info, .family = info->family, .gfx_level = info->gfx_level,
|
||||
};
|
||||
const struct aco_shader_info aco_info = {
|
||||
.hw_stage = AC_HW_COMPUTE_SHADER,
|
||||
.lds_size = shader->info.shared_size,
|
||||
.wave_size = (uint8_t)options->wave_size,
|
||||
.workgroup_size = (unsigned)threads,
|
||||
};
|
||||
void *private = owner;
|
||||
aco_compile_shader(&aco_options, &aco_info, 1, &shader, &owner->args, capture, &private);
|
||||
owner->provenance.aco_codegen_flags = aco_get_codegen_flags();
|
||||
status = owner->capture_status;
|
||||
if (status == STELA_AMD_AIR_OK && (!owner->captured || !owner->code || !owner->config.num_vgprs))
|
||||
status = STELA_AMD_AIR_BACKEND;
|
||||
if (status != STELA_AMD_AIR_OK) {
|
||||
stela_amd_air_destroy(&owner);
|
||||
return report(error, status, "Vendor output unavailable, unresolved, over budget or allocation failed");
|
||||
}
|
||||
*output = owner;
|
||||
return report(error, STELA_AMD_AIR_OK, "");
|
||||
}
|
||||
|
||||
const struct stela_amd_compute_binary *
|
||||
stela_amd_air_binary(const struct stela_amd_air_compilation *owner)
|
||||
{
|
||||
return owner ? &owner->binary : NULL;
|
||||
}
|
||||
|
||||
const uint8_t *
|
||||
stela_amd_air_code(const struct stela_amd_air_compilation *owner)
|
||||
{
|
||||
return owner ? owner->code : NULL;
|
||||
}
|
||||
|
||||
const struct stela_amd_air_binding *
|
||||
stela_amd_air_bindings(const struct stela_amd_air_compilation *owner, uint32_t *count)
|
||||
{
|
||||
if (count)
|
||||
*count = owner ? owner->binding_count : 0;
|
||||
return owner ? owner->bindings : NULL;
|
||||
}
|
||||
|
||||
const struct stela_amd_air_provenance *
|
||||
stela_amd_air_provenance(const struct stela_amd_air_compilation *owner)
|
||||
{
|
||||
return owner ? &owner->provenance : NULL;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_AIR_COMPILE_H
|
||||
#define STELA_AMD_AIR_COMPILE_H
|
||||
|
||||
#include "compute.h"
|
||||
#include "../../metal/compiler/library_assembly.h"
|
||||
#include "stela/air_to_nir.h"
|
||||
#include "../../metal/compiler/threadgroup.h"
|
||||
#include "amd/common/ac_gpu_info.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define STELA_AMD_AIR_ABI 1u
|
||||
#define STELA_AMD_AIR_MAX_BUFFERS 8u
|
||||
|
||||
enum stela_amd_air_status {
|
||||
STELA_AMD_AIR_OK,
|
||||
STELA_AMD_AIR_INVALID,
|
||||
STELA_AMD_AIR_UNSUPPORTED,
|
||||
STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE,
|
||||
STELA_AMD_AIR_LIMIT,
|
||||
STELA_AMD_AIR_ALLOCATION,
|
||||
STELA_AMD_AIR_FRONTEND,
|
||||
STELA_AMD_AIR_BACKEND,
|
||||
};
|
||||
|
||||
struct stela_amd_air_options {
|
||||
uint32_t size, abi;
|
||||
uint32_t wave_size, workgroup_size[3], max_instructions, max_code_bytes;
|
||||
enum stela_air_fp_profile fp_profile;
|
||||
};
|
||||
|
||||
struct stela_amd_air_error {
|
||||
enum stela_amd_air_status status;
|
||||
struct stela_air_error air;
|
||||
char detail[256];
|
||||
};
|
||||
|
||||
/* Ordered as the actual user SGPR pairs consumed by compute.c. Metadata keeps
|
||||
* Metal index, LLVM argument ordinal, required access and reflected alignment;
|
||||
* neither a buffer VA nor a caller-created permission boolean is compiled in.
|
||||
* At dispatch, the real resource owner must supply matching views/rights,
|
||||
* lifetime, VM, residency and cache ordering through completion. */
|
||||
struct stela_amd_air_binding {
|
||||
struct stela_air_buffer buffer;
|
||||
struct ac_arg argument;
|
||||
};
|
||||
|
||||
/* Immutable same-process facts, not an IPC/cache wire format. All strings and
|
||||
* argument reflection below are copied from the selected canonical assembly.
|
||||
* Input/module/raw offsets and hashes retain their original distinct scopes.
|
||||
* Zero archive source/build fields remain absent; an FP policy NEVER fabricates
|
||||
* source compiler provenance. The compiler/input owner must independently
|
||||
* qualify the nondefault AIR FP profile, as required by air_to_nir.h. */
|
||||
struct stela_amd_air_provenance {
|
||||
struct stela_metal_input_info input;
|
||||
struct stela_metal_input_entry entry;
|
||||
uint32_t selected_entry, entry_flags, library_flags, compiler_profile;
|
||||
uint32_t request_language, request_fast_math, argument_count;
|
||||
uint64_t air_offset, air_bytes;
|
||||
uint8_t air_sha256[32], source_sha256[32];
|
||||
struct stela_msl_build_identity build;
|
||||
const char *name, *target;
|
||||
const struct stela_air_argument_info *arguments;
|
||||
struct stela_amd_air_options options;
|
||||
struct ac_compiler_info compiler_info;
|
||||
uint32_t pci_id, pci_rev_id;
|
||||
bool has_graphics;
|
||||
uint64_t aco_codegen_flags;
|
||||
struct stela_metal_threadgroup_specialization threadgroup;
|
||||
};
|
||||
|
||||
struct stela_amd_air_compilation;
|
||||
|
||||
/* Normal hosted compiler process only. info MUST be the actual initialized
|
||||
* device/compiler facts from the matching retained Mesa build, not a family
|
||||
* guessed from an Apple CPU or a test topology. This routine validates facts it
|
||||
* consumes but cannot authenticate a caller-created radeon_info. Input owner,
|
||||
* options and info are borrowed through this synchronous call only. No LLVM,
|
||||
* assembly, options or device pointer survives success.
|
||||
*
|
||||
* Only ordinary AS1 buffer arguments (up to the existing eight address pairs),
|
||||
* current shared frontend bodies and ACO-supported targets are admitted. Dynamic
|
||||
* AS3 arguments require compile_specialized with exact requested byte lengths.
|
||||
* Qualified static shared storage uses original NIR/ACO lowering
|
||||
* if admitted by the canonical library owner. No function-constant overrides,
|
||||
* descriptor/sampler/image ABI or compiler fallback is invented.
|
||||
*
|
||||
* Output MUST point to an empty sole-owning slot; every failure preserves it.
|
||||
* Error is optional complete writable storage. All input/output/error storage
|
||||
* must be valid, disjoint, and serialized against destruction/mutation. This
|
||||
* wrapper reports its own allocation failures, not recovery from fatal/OOM
|
||||
* inside LLVM/Mesa/ACO; the normal compiler-process owner supplies cancellation,
|
||||
* watchdog and crash isolation. No global fault handler is installed.
|
||||
*/
|
||||
/* Exact dispatch-size specialization; existing compile() delegates with NULL.
|
||||
* Request arrays are borrowed only during the call and copied into provenance.
|
||||
* Backend shared totals include these rows plus static layout, never expose
|
||||
* them as Metal staticThreadgroupMemoryLength or add dynamic bytes twice.
|
||||
* stela_metal_threadgroup_matches checks values only, not resource ownership. */
|
||||
enum stela_amd_air_status stela_amd_air_compile_specialized(
|
||||
const struct radeon_info *info, const struct stela_metal_assembly *library,
|
||||
uint32_t selected_entry, const struct stela_amd_air_options *options,
|
||||
const struct stela_metal_threadgroup_request *threadgroup,
|
||||
struct stela_amd_air_compilation **output, struct stela_amd_air_error *error);
|
||||
|
||||
enum stela_amd_air_status stela_amd_air_compile(
|
||||
const struct radeon_info *info, const struct stela_metal_assembly *library,
|
||||
uint32_t selected_entry, const struct stela_amd_air_options *options,
|
||||
struct stela_amd_air_compilation **output, struct stela_amd_air_error *error);
|
||||
|
||||
/* Borrowed immutable views last until the unique owner is destroyed. The code
|
||||
* view covers complete code/data; binary.executable_bytes excludes trailing
|
||||
* constants. Stable NIR/options/args/config backing makes binary usable by the
|
||||
* existing stela_amd_build_compute_pipeline, once the real code/resource owner
|
||||
* supplies the SAME initialized device/compiler facts and published allocation
|
||||
* views. That owner retains device identity/epoch: these C pointers are not a
|
||||
* replacement for its authenticated session or lifetime. Scratch/LDS
|
||||
* requirements are actual compiler results, NOT resource readiness or a Metal
|
||||
* pipeline state. No upload, relocation, allocation, submission or GPU access
|
||||
* occurs here. Symbols currently refuse, rather than escaping unresolved. */
|
||||
const struct stela_amd_compute_binary *stela_amd_air_binary(
|
||||
const struct stela_amd_air_compilation *owner);
|
||||
const uint8_t *stela_amd_air_code(const struct stela_amd_air_compilation *owner);
|
||||
const struct stela_amd_air_binding *stela_amd_air_bindings(
|
||||
const struct stela_amd_air_compilation *owner, uint32_t *count);
|
||||
const struct stela_amd_air_provenance *stela_amd_air_provenance(
|
||||
const struct stela_amd_air_compilation *owner);
|
||||
void stela_amd_air_destroy(struct stela_amd_air_compilation **owner);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -92,7 +92,7 @@ stela_amd_build_compute_pipeline(const struct radeon_info *info,
|
||||
struct stela_amd_compute_pipeline *pipeline)
|
||||
{
|
||||
if (!info || !binary || !binary->shader || !binary->args || !binary->config ||
|
||||
!code || !pipeline || !bindings || !binding_count || binding_count > 8)
|
||||
!code || !pipeline || (binding_count && !bindings) || binding_count > 8)
|
||||
return STELA_AMD_COMPUTE_INVALID;
|
||||
struct stela_amd_raw_buffer_facts facts;
|
||||
enum stela_amd_compute_status status =
|
||||
|
||||
@@ -54,7 +54,9 @@ struct stela_amd_compute_binding {
|
||||
* code is its real, published code allocation/view with sufficient retained
|
||||
* prefetch padding and 256-byte program alignment. No allocation, upload,
|
||||
* shader replacement, cache flush, device initialization or submission occurs.
|
||||
* Missing scratch/descriptor/sampler owners remain explicit refusals.
|
||||
* Zero buffer bindings are valid when the actual argument layout requires no
|
||||
* user address pairs; bindings may then be NULL. Missing required bindings or
|
||||
* scratch/descriptor/sampler owners remain explicit refusals.
|
||||
* Output is unchanged on every error.
|
||||
*/
|
||||
enum stela_amd_compute_status
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "discovery_binary.h"
|
||||
#include "../amdgpu/amdgpu_ip_limits.h"
|
||||
#include "../include/soc15_hw_ip.h"
|
||||
|
||||
_Static_assert(sizeof(struct binary_header) == 60, "original fixed directory ABI");
|
||||
_Static_assert(sizeof(struct binary_header_v2) == 16, "original variable directory ABI");
|
||||
_Static_assert(sizeof(struct ip_discovery_header) == 80, "original die directory ABI");
|
||||
_Static_assert(offsetof(struct ip_v4, base_address) == 8, "original IP32 prefix ABI");
|
||||
_Static_assert(offsetof(struct ip_v4, base_address_64) == 8, "original IP64 prefix ABI");
|
||||
|
||||
/* Original function body; const qualification only tightens the shared API.
|
||||
* Preserve its signed loop exactly; validated callers bound size to u16. */
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wsign-compare"
|
||||
uint16_t amdgpu_discovery_calculate_checksum(const uint8_t *data, uint32_t size)
|
||||
{
|
||||
uint16_t checksum = 0;
|
||||
int i;
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
checksum += data[i];
|
||||
|
||||
return checksum;
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
static uint16_t read16(const void *pointer)
|
||||
{
|
||||
const uint8_t *p = pointer;
|
||||
return (uint16_t)p[0] | (uint16_t)p[1] << 8;
|
||||
}
|
||||
|
||||
static uint32_t read32(const void *pointer)
|
||||
{
|
||||
const uint8_t *p = pointer;
|
||||
return (uint32_t)p[0] | (uint32_t)p[1] << 8 |
|
||||
(uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;
|
||||
}
|
||||
|
||||
#define FIELD16(p, type, field) read16((p) + offsetof(struct type, field))
|
||||
#define FIELD32(p, type, field) read32((p) + offsetof(struct type, field))
|
||||
|
||||
static int fits(size_t bytes, size_t offset, size_t count)
|
||||
{
|
||||
return offset <= bytes && count <= bytes - offset;
|
||||
}
|
||||
|
||||
/* Share directory geometry with bounded live refresh, without pretending a
|
||||
* stack prefix contains the variable directory's trailing entries. */
|
||||
enum amdgpu_discovery_binary_status
|
||||
amdgpu_discovery_binary_directory(const uint8_t *binary, size_t prefix_bytes,
|
||||
size_t available_bytes, uint16_t id,
|
||||
struct amdgpu_discovery_directory *output)
|
||||
{
|
||||
if (!binary || !output)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
if (!fits(prefix_bytes, 0, offsetof(struct binary_header, table_list)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
size_t size = FIELD16(binary, binary_header, binary_size);
|
||||
if (size > available_bytes)
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
size_t offset, count;
|
||||
switch (FIELD16(binary, binary_header, version_major)) {
|
||||
case 0:
|
||||
case 1:
|
||||
offset = offsetof(struct binary_header, table_list);
|
||||
count = TOTAL_TABLES;
|
||||
break;
|
||||
case 2:
|
||||
if (!fits(prefix_bytes, 0, sizeof(struct binary_header_v2)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
offset = offsetof(struct binary_header_v2, table_list);
|
||||
count = FIELD16(binary, binary_header_v2, num_tables);
|
||||
break;
|
||||
default:
|
||||
return AMDGPU_DISCOVERY_BINARY_VERSION;
|
||||
}
|
||||
if (id >= count || !fits(size, offset, count * sizeof(struct table_info)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
*output = (struct amdgpu_discovery_directory){
|
||||
size, offset + count * sizeof(struct table_info), offset + id * sizeof(struct table_info)
|
||||
};
|
||||
return AMDGPU_DISCOVERY_BINARY_OK;
|
||||
}
|
||||
|
||||
const struct table_info *
|
||||
amdgpu_discovery_binary_table(const uint8_t *binary, size_t bytes, uint16_t id)
|
||||
{
|
||||
struct amdgpu_discovery_directory directory;
|
||||
if (amdgpu_discovery_binary_directory(binary, bytes, bytes, id, &directory))
|
||||
return NULL;
|
||||
return (const struct table_info *)(binary + directory.entry_offset);
|
||||
}
|
||||
|
||||
struct span {
|
||||
size_t offset, bytes;
|
||||
};
|
||||
|
||||
static int disjoint(struct span a, struct span b)
|
||||
{
|
||||
return a.offset + a.bytes <= b.offset || b.offset + b.bytes <= a.offset;
|
||||
}
|
||||
|
||||
static enum amdgpu_discovery_binary_status
|
||||
ip_spans(const uint8_t *binary, struct span table, unsigned *umc_count)
|
||||
{
|
||||
const uint8_t *header = binary + table.offset;
|
||||
unsigned dies = FIELD16(header, ip_discovery_header, num_dies);
|
||||
const struct ip_discovery_header *original = (const void *)header;
|
||||
int wide = original->base_addr_64_bit;
|
||||
if (dies > sizeof(original->die_info) / sizeof(original->die_info[0]) ||
|
||||
(wide && FIELD16(header, ip_discovery_header, version) < 4))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
struct span previous[sizeof(original->die_info) / sizeof(original->die_info[0])];
|
||||
for (unsigned i = 0; i < dies; i++) {
|
||||
const uint8_t *entry = header + offsetof(struct ip_discovery_header, die_info) +
|
||||
i * sizeof(struct die_info);
|
||||
size_t die = FIELD16(entry, die_info, die_offset);
|
||||
if (die < table.offset + sizeof(struct ip_discovery_header) ||
|
||||
!fits(table.offset + table.bytes, die, sizeof(struct die_header)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
const uint8_t *dhdr = binary + die;
|
||||
if (FIELD16(dhdr, die_header, die_id) != i)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
unsigned ips = FIELD16(dhdr, die_header, num_ips);
|
||||
size_t position = die + sizeof(struct die_header);
|
||||
for (unsigned j = 0; j < ips; j++) {
|
||||
if (!fits(table.offset + table.bytes, position,
|
||||
offsetof(struct ip_v4, base_address)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
const struct ip_v4 *ip = (const void *)(binary + position);
|
||||
size_t bytes = offsetof(struct ip_v4, base_address) +
|
||||
ip->num_base_address * (wide ? sizeof(uint64_t) : sizeof(uint32_t));
|
||||
if (!fits(table.offset + table.bytes, position, bytes))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
unsigned id = read16(&ip->hw_id);
|
||||
/* Original validate_ip skips unknown/out-of-array IPs. Preserve that
|
||||
* policy, but validate every entry's stride before the next walk. */
|
||||
if (ip->instance_number < HWIP_MAX_INSTANCE && id < HW_ID_MAX) {
|
||||
if ((id == GC_HWID || id == VCN_HWID || id == SDMA0_HWID ||
|
||||
id == SDMA1_HWID || id == SDMA2_HWID || id == SDMA3_HWID) &&
|
||||
ip->instance_number >= 32)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
if (id == UMC_HWID)
|
||||
(*umc_count)++;
|
||||
}
|
||||
position += bytes;
|
||||
}
|
||||
previous[i] = (struct span){die, position - die};
|
||||
for (unsigned k = 0; k < i; k++) {
|
||||
if (!disjoint(previous[i], previous[k]))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
}
|
||||
}
|
||||
/* Original harvest mask computes (1ULL << node_inst_num) - 1. */
|
||||
return *umc_count < 64 ? AMDGPU_DISCOVERY_BINARY_OK : AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
}
|
||||
|
||||
static enum amdgpu_discovery_binary_status
|
||||
consumer_span(const uint8_t *data, size_t size, unsigned id)
|
||||
{
|
||||
size_t minimum = 0;
|
||||
if (id == GC) {
|
||||
if (!fits(size, 0, sizeof(struct gpu_info_header)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
unsigned major = FIELD16(data, gpu_info_header, version_major);
|
||||
unsigned minor = FIELD16(data, gpu_info_header, version_minor);
|
||||
if (major == 1) {
|
||||
minimum = minor >= 3 ? sizeof(struct gc_info_v1_3) :
|
||||
minor == 2 ? sizeof(struct gc_info_v1_2) :
|
||||
minor == 1 ? sizeof(struct gc_info_v1_1) : sizeof(struct gc_info_v1_0);
|
||||
if (!fits(size, 0, minimum))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
if (!FIELD32(data, gc_info_v1_0, gc_num_sa_per_se))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
} else if (major == 2) {
|
||||
minimum = minor == 1 ? sizeof(struct gc_info_v2_1) : sizeof(struct gc_info_v2_0);
|
||||
if (!fits(size, 0, minimum))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
if (!FIELD32(data, gc_info_v2_0, gc_num_sh_per_se))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
}
|
||||
} else if (id == MALL_INFO) {
|
||||
unsigned major = FIELD16(data, mall_info_header, version_major);
|
||||
minimum = major == 1 ? sizeof(struct mall_info_v1_0) :
|
||||
major == 2 ? sizeof(struct mall_info_v2_0) : sizeof(struct mall_info_header);
|
||||
} else if (id == VCN_INFO) {
|
||||
minimum = FIELD16(data, vcn_info_header, version_major) == 1 ?
|
||||
sizeof(struct vcn_info_v1_0) : sizeof(struct vcn_info_header);
|
||||
}
|
||||
return fits(size, 0, minimum) ? AMDGPU_DISCOVERY_BINARY_OK : AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
}
|
||||
|
||||
enum amdgpu_discovery_binary_status
|
||||
amdgpu_discovery_binary_validate(const uint8_t *binary, size_t bytes)
|
||||
{
|
||||
if (!binary)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
if (!fits(bytes, 0, offsetof(struct binary_header, table_list)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
if (FIELD32(binary, binary_header, binary_signature) != BINARY_SIGNATURE)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
unsigned version = FIELD16(binary, binary_header, version_major);
|
||||
if (version > 2)
|
||||
return AMDGPU_DISCOVERY_BINARY_VERSION;
|
||||
size_t size = FIELD16(binary, binary_header, binary_size);
|
||||
size_t checksum_start = offsetof(struct binary_header, binary_checksum) + sizeof(uint16_t);
|
||||
if (size < checksum_start || size > bytes)
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
if (amdgpu_discovery_calculate_checksum(binary + checksum_start, size - checksum_start) !=
|
||||
FIELD16(binary, binary_header, binary_checksum))
|
||||
return AMDGPU_DISCOVERY_BINARY_CHECKSUM;
|
||||
if (!amdgpu_discovery_binary_table(binary, size, MALL_INFO))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
size_t directory = version == 2 ? offsetof(struct binary_header_v2, table_list) +
|
||||
FIELD16(binary, binary_header_v2, num_tables) * sizeof(struct table_info) :
|
||||
sizeof(struct binary_header);
|
||||
struct span tables[TOTAL_TABLES] = {{0}};
|
||||
unsigned umc_count = 0;
|
||||
for (unsigned id = IP_DISCOVERY; id < TOTAL_TABLES; id++) {
|
||||
const struct table_info *info = amdgpu_discovery_binary_table(binary, size, id);
|
||||
if (!info) /* Optional NPS may be absent from a v2 counted directory. */
|
||||
continue;
|
||||
size_t offset = read16(&info->offset);
|
||||
if (!offset) {
|
||||
if (id == IP_DISCOVERY)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
continue;
|
||||
}
|
||||
if (offset < directory || !fits(size, offset, sizeof(struct gpu_info_header)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
const uint8_t *data = binary + offset;
|
||||
size_t length;
|
||||
uint32_t expected, actual;
|
||||
int checksum = 1;
|
||||
switch (id) {
|
||||
case IP_DISCOVERY:
|
||||
actual = FIELD32(data, ip_discovery_header, signature);
|
||||
expected = DISCOVERY_TABLE_SIGNATURE;
|
||||
length = FIELD16(data, ip_discovery_header, size);
|
||||
break;
|
||||
case GC:
|
||||
actual = FIELD32(data, gpu_info_header, table_id);
|
||||
expected = GC_TABLE_ID;
|
||||
length = FIELD32(data, gpu_info_header, size);
|
||||
break;
|
||||
case HARVEST_INFO:
|
||||
actual = FIELD32(data, harvest_info_header, signature);
|
||||
expected = HARVEST_TABLE_SIGNATURE;
|
||||
length = sizeof(struct harvest_table);
|
||||
break;
|
||||
case VCN_INFO:
|
||||
actual = FIELD32(data, vcn_info_header, table_id);
|
||||
expected = VCN_INFO_TABLE_ID;
|
||||
length = FIELD32(data, vcn_info_header, size_bytes);
|
||||
break;
|
||||
case MALL_INFO:
|
||||
/* Original policy deliberately does not check MALL integrity. */
|
||||
actual = expected = 0;
|
||||
length = FIELD32(data, mall_info_header, size_bytes);
|
||||
checksum = 0;
|
||||
break;
|
||||
default: /* Original NPS integrity check is lazy and nonfatal. */
|
||||
actual = FIELD32(data, nps_info_header, table_id);
|
||||
expected = actual;
|
||||
length = actual == NPS_INFO_TABLE_ID ? FIELD32(data, nps_info_header, size_bytes) :
|
||||
sizeof(struct nps_info_header);
|
||||
checksum = 0;
|
||||
break;
|
||||
}
|
||||
if (!fits(size, offset, length) || length < sizeof(struct gpu_info_header))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
if (checksum && (actual != expected))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
if (checksum && amdgpu_discovery_calculate_checksum(data, length) != read16(&info->checksum))
|
||||
return AMDGPU_DISCOVERY_BINARY_CHECKSUM;
|
||||
if (id == IP_DISCOVERY) {
|
||||
if (length < sizeof(struct ip_discovery_header))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
enum amdgpu_discovery_binary_status status = ip_spans(binary, (struct span){offset, length},
|
||||
&umc_count);
|
||||
if (status)
|
||||
return status;
|
||||
} else if (id == NPS_INFO && actual == NPS_INFO_TABLE_ID &&
|
||||
amdgpu_discovery_calculate_checksum(data, length) == read16(&info->checksum) &&
|
||||
FIELD16(data, nps_info_header, version_major) == 1) {
|
||||
if (length < offsetof(struct nps_info_v1_0, instance_info) ||
|
||||
FIELD32(data, nps_info_v1_0, count) > NPS_INFO_TABLE_MAX_NUM_INSTANCES ||
|
||||
!fits(length, offsetof(struct nps_info_v1_0, instance_info),
|
||||
FIELD32(data, nps_info_v1_0, count) * sizeof(struct nps_instance_info_v1_0)))
|
||||
return AMDGPU_DISCOVERY_BINARY_BOUNDS;
|
||||
} else {
|
||||
enum amdgpu_discovery_binary_status status = consumer_span(data, length, id);
|
||||
if (status)
|
||||
return status;
|
||||
if (id == MALL_INFO && FIELD16(data, mall_info_header, version_major) == 1 && umc_count > 32)
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
}
|
||||
tables[id] = (struct span){offset, length};
|
||||
for (unsigned previous = 0; previous < id; previous++) {
|
||||
if (tables[previous].bytes && !disjoint(tables[id], tables[previous]))
|
||||
return AMDGPU_DISCOVERY_BINARY_INVALID;
|
||||
}
|
||||
}
|
||||
return AMDGPU_DISCOVERY_BINARY_OK;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef STELA_AMD_DISCOVERY_BINARY_H
|
||||
#define STELA_AMD_DISCOVERY_BINARY_H
|
||||
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#include <linux/stddef.h>
|
||||
#else
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
#include "../include/discovery.h"
|
||||
|
||||
enum amdgpu_discovery_binary_status {
|
||||
AMDGPU_DISCOVERY_BINARY_OK,
|
||||
AMDGPU_DISCOVERY_BINARY_INVALID,
|
||||
AMDGPU_DISCOVERY_BINARY_BOUNDS,
|
||||
AMDGPU_DISCOVERY_BINARY_VERSION,
|
||||
AMDGPU_DISCOVERY_BINARY_CHECKSUM,
|
||||
};
|
||||
|
||||
/* Original additive checksum algorithm. Every byte must be readable; size is
|
||||
* bounded by INT_MAX. The full validator establishes its own stronger u16 span.
|
||||
*/
|
||||
uint16_t amdgpu_discovery_calculate_checksum(const uint8_t *data, uint32_t size);
|
||||
|
||||
/* Directory geometry from the original fixed/v2-counted header. A bounded
|
||||
* prefix is sufficient; available_bytes is the actual acquired region size.
|
||||
* This neither reads an entry nor validates a table/checksum. Failure leaves
|
||||
* the output unchanged. Live acquisition must retain its real reset owner. */
|
||||
struct amdgpu_discovery_directory {
|
||||
size_t binary_bytes, directory_bytes, entry_offset;
|
||||
};
|
||||
enum amdgpu_discovery_binary_status
|
||||
amdgpu_discovery_binary_directory(const uint8_t *prefix, size_t prefix_bytes,
|
||||
size_t available_bytes, uint16_t id,
|
||||
struct amdgpu_discovery_directory *output);
|
||||
|
||||
/* Checked original directory selection only, not full binary validation.
|
||||
* The returned original format pointer borrows the actual snapshot's lifetime;
|
||||
* NULL means malformed directory, missing table or unsupported binary version.
|
||||
*/
|
||||
const struct table_info *
|
||||
amdgpu_discovery_binary_table(const uint8_t *binary, size_t bytes, uint16_t id);
|
||||
|
||||
/* Validate a real readable immutable acquisition snapshot before original
|
||||
* driver consumers run. No allocation, register/memory acquisition, device
|
||||
* mutation, capability inference or hardware activation occurs here.
|
||||
*
|
||||
* Caller owns the actual TMR/firmware snapshot and excludes concurrent mutation
|
||||
* throughout validation and handoff. Original reg-base initialization then
|
||||
* intentionally mutates its private copy (endian/address conversion and VCN
|
||||
* revision masking); the preflight does not authorize revalidation of that
|
||||
* modified copy or concurrent untrusted access. Actual firmware/TMR ownership,
|
||||
* device binding, VRAM/ACPI acquisition and original consumer lifecycle remain
|
||||
* required. Optional NPS integrity policy remains lazy in the original caller.
|
||||
*/
|
||||
enum amdgpu_discovery_binary_status
|
||||
amdgpu_discovery_binary_validate(const uint8_t *binary, size_t bytes);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,12 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "discovery_file.h"
|
||||
#include "../amdgpu/amdgpu_discovery_file_core.h"
|
||||
int stela_amd_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity)
|
||||
{
|
||||
return amdgpu_discovery_file_validate(data, bytes, capacity);
|
||||
}
|
||||
size_t stela_amd_discovery_file_minimum(void)
|
||||
{
|
||||
return offsetof(struct binary_header, binary_size) +
|
||||
sizeof(((struct binary_header *)0)->binary_size);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_DISCOVERY_FILE_H
|
||||
#define STELA_AMD_DISCOVERY_FILE_H
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
/* Same status values as original shared bounded-file policy. Actual immutable
|
||||
* readable file allocation only; capacity is the real queried TMR extent.
|
||||
* No acquisition/admission/copy/allocator; no pointer retained or bytes changed. */
|
||||
size_t stela_amd_discovery_file_minimum(void);
|
||||
int stela_amd_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity);
|
||||
#endif
|
||||
@@ -0,0 +1,82 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "discovery_ip.h"
|
||||
#include "discovery_binary.h"
|
||||
#include "../amdgpu/amdgpu_discovery_ip_core.h"
|
||||
|
||||
_Static_assert(sizeof(int) == sizeof(int32_t), "original int fields");
|
||||
_Static_assert(sizeof(struct stela_amd_ip_binding) == 8, "IP binding ABI");
|
||||
_Static_assert(sizeof(struct stela_amd_ip_counts) == 32, "IP counts ABI");
|
||||
_Static_assert(offsetof(struct stela_amd_ip_counts, sdma_count) == 12, "IP int ABI");
|
||||
_Static_assert(offsetof(struct stela_amd_ip_counts, node_count) == 28, "IP node ABI");
|
||||
_Static_assert(AMDGPU_MAX_VCN_INSTANCES == 4, "explicit VCN configuration ABI");
|
||||
|
||||
struct stela_amd_ip_shape stela_amd_discovery_ip_shape(void)
|
||||
{
|
||||
return (struct stela_amd_ip_shape){MAX_HWIP, HWIP_MAX_INSTANCE};
|
||||
}
|
||||
struct binding_context { uintptr_t base; struct stela_amd_ip_binding *bindings; };
|
||||
static void bind(void *context, unsigned hw_ip, unsigned instance, uint32_t *base, unsigned count)
|
||||
{
|
||||
struct binding_context *c = context;
|
||||
/* Validated original geometry and private callback guarantee same allocation.
|
||||
* Convert pointer representation only; never dereference packed u32*. */
|
||||
c->bindings[hw_ip * HWIP_MAX_INSTANCE + instance] =
|
||||
(struct stela_amd_ip_binding){(uint32_t)((uintptr_t)base - c->base), count};
|
||||
}
|
||||
static int range(const void *pointer, size_t bytes, uintptr_t *start, uintptr_t *end)
|
||||
{
|
||||
*start = (uintptr_t)pointer;
|
||||
if (!pointer || bytes > UINTPTR_MAX - *start)
|
||||
return 0;
|
||||
*end = *start + bytes;
|
||||
return 1;
|
||||
}
|
||||
int stela_amd_discovery_ip_decode(uint8_t *work, size_t bytes,
|
||||
uint32_t *versions, size_t version_count,
|
||||
struct stela_amd_ip_binding *bindings, size_t binding_count,
|
||||
struct stela_amd_ip_counts *counts)
|
||||
{
|
||||
const size_t cells = MAX_HWIP * HWIP_MAX_INSTANCE;
|
||||
uintptr_t start[4], end[4];
|
||||
if (version_count < cells || binding_count < cells ||
|
||||
(uintptr_t)versions % _Alignof(uint32_t) ||
|
||||
(uintptr_t)bindings % _Alignof(struct stela_amd_ip_binding) ||
|
||||
(uintptr_t)counts % _Alignof(struct stela_amd_ip_counts) ||
|
||||
!range(work, bytes, &start[0], &end[0]) ||
|
||||
!range(versions, cells * sizeof(*versions), &start[1], &end[1]) ||
|
||||
!range(bindings, cells * sizeof(*bindings), &start[2], &end[2]) ||
|
||||
!range(counts, sizeof(*counts), &start[3], &end[3]))
|
||||
return -EINVAL;
|
||||
for (unsigned i = 0; i < 4; i++)
|
||||
for (unsigned j = i + 1; j < 4; j++)
|
||||
if (start[i] < end[j] && start[j] < end[i])
|
||||
return -EINVAL;
|
||||
int status = amdgpu_discovery_binary_validate(work, bytes);
|
||||
if (status)
|
||||
return -EINVAL;
|
||||
const struct table_info *info = amdgpu_discovery_binary_table(work, bytes, IP_DISCOVERY);
|
||||
if (!info)
|
||||
return -EINVAL;
|
||||
struct ip_discovery_header *ihdr = (void *)(work + le16_to_cpu(info->offset));
|
||||
/* All bounds/errors complete before the first output/working-copy write. */
|
||||
*counts = (struct stela_amd_ip_counts){0};
|
||||
for (size_t i = 0; i < cells; i++) {
|
||||
versions[i] = 0;
|
||||
bindings[i] = (struct stela_amd_ip_binding){UINT32_MAX, 0};
|
||||
}
|
||||
struct binding_context context = {(uintptr_t)work, bindings};
|
||||
struct amdgpu_discovery_ip_targets targets = {
|
||||
.xcc_mask=&counts->xcc_mask, .sdma_mask=&counts->sdma_mask,
|
||||
.vcn_mask=&counts->vcn_mask, .jpeg_mask=&counts->jpeg_mask,
|
||||
.vcn_count=&counts->vcn_count, .sdma_count=&counts->sdma_count,
|
||||
.vpe_count=&counts->vpe_count, .umc_count=&counts->umc_count,
|
||||
.node_count=&counts->node_count,
|
||||
.ip_versions=(uint32_t (*)[HWIP_MAX_INSTANCE])versions,
|
||||
};
|
||||
for (unsigned i = 0; i < AMDGPU_MAX_VCN_INSTANCES; i++)
|
||||
targets.vcn_config[i] = &counts->vcn_config[i];
|
||||
const struct amdgpu_discovery_ip_ops ops = {.context=&context, .bind=bind};
|
||||
/* Validated die IDs/geometry make the original walk's only failure
|
||||
* unreachable; no success/failure hardware hook or allocator exists. */
|
||||
return amdgpu_discovery_ip_walk(work, ihdr, &targets, &ops);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_DISCOVERY_IP_H
|
||||
#define STELA_AMD_DISCOVERY_IP_H
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
struct stela_amd_ip_binding { uint32_t offset, count; };
|
||||
struct stela_amd_ip_counts {
|
||||
uint16_t xcc_mask, vcn_mask, jpeg_mask;
|
||||
uint8_t vcn_count, vcn_config[4];
|
||||
int32_t sdma_count;
|
||||
uint32_t sdma_mask, vpe_count;
|
||||
int32_t umc_count;
|
||||
uint32_t node_count;
|
||||
};
|
||||
struct stela_amd_ip_shape { uint32_t hw_ip_count, instances; };
|
||||
struct stela_amd_ip_shape stela_amd_discovery_ip_shape(void);
|
||||
/* One validated fresh private copy, run once. Not an acquisition/admission API.
|
||||
* No pointer retained. All arrays are real disjoint CPU allocations. Error
|
||||
* leaves work/output bytes untouched. Counts correspond to the original fresh
|
||||
* zeroed device, before harvest/final topology. No device services performed. */
|
||||
int stela_amd_discovery_ip_decode(uint8_t *work, size_t bytes,
|
||||
uint32_t *versions, size_t version_count,
|
||||
struct stela_amd_ip_binding *bindings, size_t binding_count,
|
||||
struct stela_amd_ip_counts *counts);
|
||||
#endif
|
||||
@@ -0,0 +1,93 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "discovery_tmr.h"
|
||||
#include "discovery_binary.h"
|
||||
#include "vram_mm.h"
|
||||
#include "../include/asic_reg/bif/bif_4_1_d.h"
|
||||
#include "../amdgpu/amdgpu_discovery_tmr_core.h"
|
||||
#include "../amdgpu/amdgpu_virt_bootstrap_core.h"
|
||||
#include <stdatomic.h>
|
||||
_Static_assert(sizeof(struct stela_amd_discovery_tmr) == 24, "TMR ABI");
|
||||
_Static_assert(offsetof(struct stela_amd_discovery_tmr, size) == 16, "TMR size ABI");
|
||||
struct native_tmr {
|
||||
void *registers;
|
||||
size_t bytes;
|
||||
uint64_t vram_bytes;
|
||||
void *sleep_context;
|
||||
void (*sleep_ms)(void *, unsigned);
|
||||
};
|
||||
static uint32_t read32(void *context, uint32_t reg)
|
||||
{
|
||||
struct native_tmr *native = context;
|
||||
volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)native->registers + reg * 4u);
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
uint32_t value = *pointer;
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
if (reg == mmRCC_CONFIG_MEMSIZE)
|
||||
native->vram_bytes = (uint64_t)value << 20;
|
||||
return value;
|
||||
}
|
||||
static void sleep_ms(void *context, unsigned milliseconds)
|
||||
{
|
||||
struct native_tmr *native = context;
|
||||
native->sleep_ms(native->sleep_context, milliseconds);
|
||||
}
|
||||
static int read_vram(void *context, uint64_t offset, uint32_t *data, size_t size)
|
||||
{
|
||||
struct native_tmr *native = context;
|
||||
return stela_amd_vram_mm_read(native->registers, native->bytes,
|
||||
native->vram_bytes, offset, data, size) == STELA_AMD_VRAM_MM_OK
|
||||
? STELA_AMD_TMR_OK : STELA_AMD_TMR_BOUNDS;
|
||||
}
|
||||
static int acpi_tmr(void *context, uint64_t *offset, uint64_t *size)
|
||||
{
|
||||
(void)context; (void)offset; (void)size;
|
||||
/* Explicit missing actual ACPI/firmware owner, not a fabricated reply. */
|
||||
return STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;
|
||||
}
|
||||
static bool direct_register(size_t bytes, uint32_t reg)
|
||||
{
|
||||
return reg < bytes / sizeof(uint32_t);
|
||||
}
|
||||
int stela_amd_discovery_tmr_query(void *registers, size_t register_bytes,
|
||||
uint32_t asic_type, void *sleep_context,
|
||||
void (*sleep)(void *, unsigned), struct stela_amd_discovery_tmr *out)
|
||||
{
|
||||
uintptr_t base = (uintptr_t)registers, destination = (uintptr_t)out;
|
||||
if (!registers || base % sizeof(uint32_t) || !out || destination % _Alignof(struct stela_amd_discovery_tmr) ||
|
||||
!sleep || asic_type >= CHIP_LAST)
|
||||
return STELA_AMD_TMR_INVALID;
|
||||
if (register_bytes > PTRDIFF_MAX || register_bytes > UINTPTR_MAX - base ||
|
||||
sizeof(*out) > UINTPTR_MAX - destination ||
|
||||
(destination < base + register_bytes && base < destination + sizeof(*out)))
|
||||
return STELA_AMD_TMR_BOUNDS;
|
||||
uint32_t identifier = 0;
|
||||
bool has_identifier = amdgpu_virt_bootstrap_iov_register(asic_type, &identifier);
|
||||
const uint32_t required[] = {mmMP0_SMN_C2PMSG_33, mmRCC_CONFIG_MEMSIZE,
|
||||
mmDRIVER_SCRATCH_0, mmDRIVER_SCRATCH_1, mmDRIVER_SCRATCH_2,
|
||||
mmMM_INDEX, mmMM_DATA, mmMM_INDEX_HI};
|
||||
for (unsigned i = 0; i < sizeof(required) / sizeof(required[0]); ++i)
|
||||
if (!direct_register(register_bytes, required[i]))
|
||||
return STELA_AMD_TMR_BOUNDS;
|
||||
if (has_identifier && !direct_register(register_bytes, identifier))
|
||||
return STELA_AMD_TMR_BOUNDS;
|
||||
struct native_tmr native = {registers, register_bytes, 0, sleep_context, sleep};
|
||||
/* This is the original selector's actual hardware observation, not a guessed
|
||||
* role from flags or a caller boolean. VF protocols remain original owners. */
|
||||
if (has_identifier && (read32(&native, identifier) & 1))
|
||||
return STELA_AMD_TMR_VF_OWNER_UNAVAILABLE;
|
||||
static const struct amdgpu_discovery_tmr_ops ops = {read32, sleep_ms, read_vram, acpi_tmr};
|
||||
struct amdgpu_discovery_tmr_state state = {0};
|
||||
int status = amdgpu_discovery_tmr_query_core(&ops, &native, false, false, 0, 0, &state);
|
||||
if (status)
|
||||
return status;
|
||||
if (state.is_sysmem)
|
||||
return STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;
|
||||
if (!state.size || state.size % sizeof(uint32_t) || state.offset % sizeof(uint32_t) ||
|
||||
state.offset > native.vram_bytes || state.size > native.vram_bytes - state.offset)
|
||||
return STELA_AMD_TMR_BOUNDS;
|
||||
const struct stela_amd_discovery_tmr result = {
|
||||
.offset = state.offset, .vram_bytes = native.vram_bytes, .size = state.size,
|
||||
};
|
||||
*out = result;
|
||||
return STELA_AMD_TMR_OK;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_DISCOVERY_TMR_H
|
||||
#define STELA_AMD_DISCOVERY_TMR_H
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
struct stela_amd_discovery_tmr {
|
||||
uint64_t offset, vram_bytes;
|
||||
uint32_t size, reserved;
|
||||
};
|
||||
enum stela_amd_discovery_tmr_status {
|
||||
STELA_AMD_TMR_OK = 0,
|
||||
STELA_AMD_TMR_INVALID = 1,
|
||||
STELA_AMD_TMR_BOUNDS = 2,
|
||||
STELA_AMD_TMR_VF_OWNER_UNAVAILABLE = 3,
|
||||
STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE = 4,
|
||||
};
|
||||
/* Borrow the same actual canonical UC register mapping, matched original ASIC,
|
||||
* D0/reset/removal/MM-index/IRQ exclusion and process context as vram_mm.h.
|
||||
* The original discovery caller must have selected this bootstrap path; no
|
||||
* SI/CIK/VI admission or preferred-file policy is inferred here. sleep_ms is
|
||||
* mandatory real elapsed-time service, not an immediate/success callback.
|
||||
* Actual direct register/owner/service bounds are checked before first I/O.
|
||||
* Output unchanged on every error. Negative values are original errno status.
|
||||
* A successful region is GPU VRAM, never a system physical/DMA/IOVA address.
|
||||
* It is not a reservation, BO, firmware integrity or readiness proof.
|
||||
* Real system-memory/VF owners are unavailable here and explicitly refused.
|
||||
* After original reads/index writes there is no rollback; returned void reads
|
||||
* carry no transport ACK. No pointer is retained. Output is exclusive CPU RAM,
|
||||
* distinct from the register span, and all callbacks retain the same owner.
|
||||
*/
|
||||
int stela_amd_discovery_tmr_query(void *registers, size_t register_bytes,
|
||||
uint32_t asic_type, void *sleep_context,
|
||||
void (*sleep_ms)(void *, unsigned), struct stela_amd_discovery_tmr *out);
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "native_bar.h"
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
|
||||
_Static_assert(sizeof(struct stela_amd_bar_layout) == 16, "BAR layout ABI");
|
||||
_Static_assert(offsetof(struct stela_amd_bar_layout, kernel_doorbell_bytes) == 8, "BAR bytes ABI");
|
||||
|
||||
enum stela_amd_bar_status
|
||||
stela_amd_native_register_bar(uint32_t asic_type, uint32_t *bar)
|
||||
{
|
||||
if (!bar || asic_type >= CHIP_LAST)
|
||||
return STELA_AMD_BAR_INVALID;
|
||||
*bar = amdgpu_native_register_bar((enum amd_asic_type)asic_type);
|
||||
return STELA_AMD_BAR_OK;
|
||||
}
|
||||
|
||||
enum stela_amd_bar_status
|
||||
stela_amd_native_bar_layout(uint32_t asic_type, uint64_t doorbell_bar_bytes,
|
||||
uint32_t max_assignment, uint64_t page_bytes,
|
||||
struct stela_amd_bar_layout *layout)
|
||||
{
|
||||
if (!layout || asic_type >= CHIP_LAST || page_bytes < 4096 ||
|
||||
page_bytes > UINT32_MAX || (page_bytes & (page_bytes - 1)))
|
||||
return STELA_AMD_BAR_INVALID;
|
||||
const enum amd_asic_type asic = asic_type;
|
||||
struct stela_amd_bar_layout result = {.register_bar = amdgpu_native_register_bar(asic)};
|
||||
if (asic < CHIP_BONAIRE) {
|
||||
if (doorbell_bar_bytes || max_assignment)
|
||||
return STELA_AMD_BAR_INVALID;
|
||||
} else {
|
||||
if (doorbell_bar_bytes < 4 || doorbell_bar_bytes / 4 > UINT32_MAX ||
|
||||
max_assignment == UINT32_MAX ||
|
||||
(asic >= CHIP_VEGA10 && max_assignment + 1 > UINT32_MAX - 0x400))
|
||||
return STELA_AMD_BAR_UNREPRESENTABLE;
|
||||
const uint32_t count = amdgpu_native_kernel_doorbell_count(asic, doorbell_bar_bytes,
|
||||
max_assignment);
|
||||
const uint64_t bytes = amdgpu_native_kernel_doorbell_bytes(count, page_bytes);
|
||||
/* The original kernel allocator's temporary size is int. Keep that
|
||||
* producer's representable domain, and never acquire outside the BAR. */
|
||||
if (!count || bytes > INT_MAX || bytes > doorbell_bar_bytes)
|
||||
return STELA_AMD_BAR_UNREPRESENTABLE;
|
||||
result.kernel_doorbell_bytes = bytes;
|
||||
result.kernel_doorbells = bytes / 4;
|
||||
}
|
||||
*layout = result;
|
||||
return STELA_AMD_BAR_OK;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2008, 2022 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
#ifndef STELA_AMD_NATIVE_BAR_H
|
||||
#define STELA_AMD_NATIVE_BAR_H
|
||||
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
#include <drm/amd_asic_type.h>
|
||||
|
||||
/* Pure policies shared with original amdgpu_device/doorbell consumers.
|
||||
* Callers retain original ASIC classification and actual doorbell assignment.
|
||||
* Native entry preflights arithmetic before using the original expressions.
|
||||
*/
|
||||
static inline unsigned
|
||||
amdgpu_native_register_bar(enum amd_asic_type asic_type)
|
||||
{
|
||||
return asic_type >= CHIP_BONAIRE ? 5 : 2;
|
||||
}
|
||||
|
||||
static inline uint32_t
|
||||
amdgpu_native_kernel_doorbell_count(enum amd_asic_type asic_type,
|
||||
uint64_t bar_bytes, uint32_t max_assignment)
|
||||
{
|
||||
uint32_t count = (uint32_t)(bar_bytes / sizeof(uint32_t));
|
||||
count = count < max_assignment + 1 ? count : max_assignment + 1;
|
||||
if (!count)
|
||||
return 0;
|
||||
/*
|
||||
* For Vega, reserve and map two pages on doorbell BAR since SDMA
|
||||
* paging queue doorbell use the second page. The
|
||||
* AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the
|
||||
* doorbells are in the first page. So with paging queue enabled,
|
||||
* the max num_kernel_doorbells should + 1 page (0x400 in dword)
|
||||
*/
|
||||
if (asic_type >= CHIP_VEGA10)
|
||||
count += 0x400;
|
||||
return count;
|
||||
}
|
||||
|
||||
static inline uint64_t
|
||||
amdgpu_native_kernel_doorbell_storage_bytes(uint32_t count, uint64_t page_bytes)
|
||||
{
|
||||
return ((uint64_t)count * sizeof(uint32_t) + page_bytes - 1) & ~(page_bytes - 1);
|
||||
}
|
||||
|
||||
static inline uint64_t
|
||||
amdgpu_native_kernel_doorbell_bytes(uint32_t count, uint64_t page_bytes)
|
||||
{
|
||||
uint64_t size = amdgpu_native_kernel_doorbell_storage_bytes(count, page_bytes);
|
||||
/* Original extra page for MES kernel usages (ring test). */
|
||||
size += page_bytes;
|
||||
return size;
|
||||
}
|
||||
|
||||
#ifndef __KERNEL__
|
||||
enum stela_amd_bar_status {
|
||||
STELA_AMD_BAR_OK,
|
||||
STELA_AMD_BAR_INVALID,
|
||||
STELA_AMD_BAR_UNREPRESENTABLE,
|
||||
};
|
||||
|
||||
struct stela_amd_bar_layout {
|
||||
uint32_t register_bar;
|
||||
uint32_t kernel_doorbells; /* Actual original post-allocation DWORD extent. */
|
||||
uint64_t kernel_doorbell_bytes;
|
||||
};
|
||||
|
||||
/* Facts come from the original matched PCI function/ASIC and initialized
|
||||
* doorbell-index owner; never Mesa family or display inventory inference.
|
||||
* SI passes zero doorbell facts. CIK+ supplies its actual BAR and assignment.
|
||||
* Output is unchanged on error. This query reserves/maps/writes nothing.
|
||||
*/
|
||||
enum stela_amd_bar_status
|
||||
stela_amd_native_register_bar(uint32_t asic_type, uint32_t *bar);
|
||||
|
||||
enum stela_amd_bar_status
|
||||
stela_amd_native_bar_layout(uint32_t asic_type, uint64_t doorbell_bar_bytes,
|
||||
uint32_t max_assignment, uint64_t page_bytes,
|
||||
struct stela_amd_bar_layout *layout);
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,106 @@
|
||||
/* SPDX-License-Identifier: GPL-2.0-only */
|
||||
#include "pci_match.h"
|
||||
#include "../amdgpu/amdgpu_pci_match_core.h"
|
||||
#include "../amdgpu/amdgpu_apu_flags_core.h"
|
||||
#include "../amdgpu/amdgpu_discovery_source_core.h"
|
||||
#include <stddef.h>
|
||||
|
||||
_Static_assert(sizeof(struct stela_amd_pci_identity) == 24, "PCI identity ABI");
|
||||
_Static_assert(sizeof(struct stela_amd_pci_policy) == 44, "PCI policy ABI");
|
||||
_Static_assert(sizeof(struct stela_amd_pci_match) == 32, "PCI match ABI");
|
||||
_Static_assert(offsetof(struct stela_amd_pci_match, filename) == 24, "PCI filename ABI");
|
||||
|
||||
/* Exact Linux 8d3ae592 drivers/pci/pci.h:pci_match_one_device predicate,
|
||||
* binding only original dev fields to this synchronous scalar query. */
|
||||
static const struct pci_device_id *
|
||||
match_one(const struct pci_device_id *id, const struct stela_amd_pci_identity *dev)
|
||||
{
|
||||
if ((id->vendor == (uint32_t)PCI_ANY_ID || id->vendor == dev->vendor) &&
|
||||
(id->device == (uint32_t)PCI_ANY_ID || id->device == dev->device) &&
|
||||
(id->subvendor == (uint32_t)PCI_ANY_ID || id->subvendor == dev->subvendor) &&
|
||||
(id->subdevice == (uint32_t)PCI_ANY_ID || id->subdevice == dev->subdevice) &&
|
||||
!((id->class ^ dev->class_code) & id->class_mask))
|
||||
return id;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
stela_amd_pci_match(const struct stela_amd_pci_identity *identity,
|
||||
const struct stela_amd_pci_policy *policy,
|
||||
struct stela_amd_pci_match *out)
|
||||
{
|
||||
if (!identity || !policy || !out || identity->vendor > UINT16_MAX ||
|
||||
identity->device > UINT16_MAX || identity->subvendor > UINT16_MAX ||
|
||||
identity->subdevice > UINT16_MAX || identity->class_code > 0xffffff ||
|
||||
identity->revision > UINT8_MAX || policy->si_built > 1 ||
|
||||
policy->cik_built > 1 || policy->radeon_built > 1 ||
|
||||
policy->memory_encrypted > 1 || policy->firmware_drivers_only > 1)
|
||||
return STELA_AMD_PCI_INVALID;
|
||||
|
||||
const struct pci_device_id *id = pciidlist;
|
||||
/* Original pci_match_id first-match/sentinel algorithm. */
|
||||
while (id->vendor || id->subvendor || id->class_mask) {
|
||||
/* Original pci_match_device normal static-table route also skips
|
||||
* override_only rows; dynamic IDs and driver_override are not this API. */
|
||||
if (match_one(id, identity) && !id->override_only)
|
||||
break;
|
||||
id++;
|
||||
}
|
||||
if (!(id->vendor || id->subvendor || id->class_mask))
|
||||
return STELA_AMD_PCI_NO_MATCH;
|
||||
|
||||
if ((identity->class_code >> 8) == PCI_CLASS_DISPLAY_VGA ||
|
||||
(identity->class_code >> 8) == PCI_CLASS_DISPLAY_OTHER) {
|
||||
if (policy->firmware_drivers_only && policy->modeset == -1)
|
||||
return STELA_AMD_PCI_FIRMWARE_ONLY;
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(amdgpu_unsupported_pciidlist) /
|
||||
sizeof(amdgpu_unsupported_pciidlist[0]); i++)
|
||||
if (amdgpu_unsupported_pciidlist[i] == identity->device)
|
||||
return STELA_AMD_PCI_UNSUPPORTED_ID;
|
||||
if (id->driver_data > UINT32_MAX)
|
||||
return STELA_AMD_PCI_INVALID;
|
||||
unsigned long flags = id->driver_data;
|
||||
if (!amdgpu_pci_experimental_allowed(flags, policy->experimental))
|
||||
return STELA_AMD_PCI_EXPERIMENTAL_DISABLED;
|
||||
flags = amdgpu_pci_fix_asic_type(identity->device, identity->revision, flags);
|
||||
if (policy->memory_encrypted && (flags & AMD_ASIC_MASK) == CHIP_RAVEN)
|
||||
return STELA_AMD_PCI_RAVEN_ENCRYPTION;
|
||||
const enum amd_asic_type asic = flags & AMD_ASIC_MASK;
|
||||
struct amdgpu_pci_support_policy support;
|
||||
if (amdgpu_pci_support_policy(asic, policy->si_built, policy->cik_built,
|
||||
policy->si_support, policy->cik_support, &support) &&
|
||||
!amdgpu_pci_support_allowed(&support, policy->radeon_built))
|
||||
return STELA_AMD_PCI_SUPPORT_DISABLED;
|
||||
/* Original nonnegative in-range override is a separate debug path, not a
|
||||
* native physical ASIC assertion. Invalid values are ignored originally. */
|
||||
if (policy->force_asic >= 0 && policy->force_asic < CHIP_LAST)
|
||||
return STELA_AMD_PCI_OVERRIDE_UNAVAILABLE;
|
||||
|
||||
struct stela_amd_pci_match result = {
|
||||
.row = (uint32_t)(id - pciidlist), .original_flags = flags, .asic_type = asic,
|
||||
.initial_apu_flags = amdgpu_initial_apu_flags(flags, asic, identity->device, 0),
|
||||
.discovery_source = STELA_AMD_DISCOVERY_NOT_USED,
|
||||
};
|
||||
switch (amdgpu_initial_ip_path(asic)) {
|
||||
case AMDGPU_INITIAL_IP_SI: result.ip_path = STELA_AMD_IP_SI_STATIC; break;
|
||||
case AMDGPU_INITIAL_IP_CIK: result.ip_path = STELA_AMD_IP_CIK_STATIC; break;
|
||||
case AMDGPU_INITIAL_IP_VI: result.ip_path = STELA_AMD_IP_VI_STATIC; break;
|
||||
case AMDGPU_INITIAL_IP_DISCOVERY:
|
||||
result.ip_path = amdgpu_discovery_static_asic(asic) != CHIP_LAST &&
|
||||
!(asic == CHIP_CYAN_SKILLFISH &&
|
||||
amdgpu_discovery_cyan_skillfish2(result.initial_apu_flags))
|
||||
? STELA_AMD_IP_SOC_STATIC : STELA_AMD_IP_DYNAMIC;
|
||||
/* Original static CyanSkillfish never calls discovery_init, including
|
||||
* option2. Other SOC-static arms acquire optional inventory only. */
|
||||
if (asic == CHIP_CYAN_SKILLFISH && result.ip_path == STELA_AMD_IP_SOC_STATIC)
|
||||
break;
|
||||
result.filename = amdgpu_discovery_fw_name(asic, result.initial_apu_flags,
|
||||
policy->discovery);
|
||||
result.discovery_source = result.filename ? STELA_AMD_DISCOVERY_FILE
|
||||
: STELA_AMD_DISCOVERY_HARDWARE;
|
||||
break;
|
||||
}
|
||||
*out = result;
|
||||
return STELA_AMD_PCI_OK;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_PCI_MATCH_H
|
||||
#define STELA_AMD_PCI_MATCH_H
|
||||
#include <stdint.h>
|
||||
|
||||
/* Actual type-0 configuration values; class is base/subclass/prog-if (24 bits).
|
||||
* Header kind is checked by the Rust config owner before subsystem-ID reads.
|
||||
* This is a scalar query ABI, not an alternate PCI/device/resource owner. */
|
||||
struct stela_amd_pci_identity {
|
||||
uint32_t vendor, device, subvendor, subdevice, class_code, revision;
|
||||
};
|
||||
struct stela_amd_pci_policy {
|
||||
uint32_t si_built, cik_built, radeon_built;
|
||||
int32_t si_support, cik_support, experimental, discovery, force_asic;
|
||||
/* Actual original platform policy, not readiness/capability assertions. */
|
||||
uint32_t memory_encrypted, firmware_drivers_only;
|
||||
int32_t modeset;
|
||||
};
|
||||
enum stela_amd_pci_status {
|
||||
STELA_AMD_PCI_OK,
|
||||
STELA_AMD_PCI_INVALID,
|
||||
STELA_AMD_PCI_NO_MATCH,
|
||||
STELA_AMD_PCI_UNSUPPORTED_ID,
|
||||
STELA_AMD_PCI_EXPERIMENTAL_DISABLED,
|
||||
STELA_AMD_PCI_RAVEN_ENCRYPTION,
|
||||
STELA_AMD_PCI_SUPPORT_DISABLED,
|
||||
STELA_AMD_PCI_FIRMWARE_ONLY,
|
||||
STELA_AMD_PCI_OVERRIDE_UNAVAILABLE,
|
||||
};
|
||||
enum stela_amd_ip_path {
|
||||
STELA_AMD_IP_SI_STATIC,
|
||||
STELA_AMD_IP_CIK_STATIC,
|
||||
STELA_AMD_IP_VI_STATIC,
|
||||
STELA_AMD_IP_SOC_STATIC,
|
||||
STELA_AMD_IP_DYNAMIC,
|
||||
};
|
||||
enum stela_amd_discovery_source {
|
||||
STELA_AMD_DISCOVERY_NOT_USED,
|
||||
STELA_AMD_DISCOVERY_HARDWARE,
|
||||
STELA_AMD_DISCOVERY_FILE,
|
||||
};
|
||||
struct stela_amd_pci_match {
|
||||
uint32_t row, original_flags, asic_type, initial_apu_flags;
|
||||
uint32_t ip_path, discovery_source;
|
||||
/* C static original filename; NULL for hardware/not-used. */
|
||||
const char *filename;
|
||||
};
|
||||
|
||||
/* No allocation, config/MMIO access, publication or resource reservation.
|
||||
* Genuine PCI/config and platform/build options are owner prerequisites.
|
||||
* Normal retained table only: Linux dynamic IDs/driver_override and forced
|
||||
* ASIC debug emulation do not establish this route. Output unchanged on error.
|
||||
* A selected file is required by the dynamic path (optional inventory for the
|
||||
* original static path); this result never authorizes substituting hardware.
|
||||
*/
|
||||
int stela_amd_pci_match(const struct stela_amd_pci_identity *identity,
|
||||
const struct stela_amd_pci_policy *policy,
|
||||
struct stela_amd_pci_match *out);
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include "vram_mm.h"
|
||||
#include "../include/asic_reg/bif/bif_4_1_d.h"
|
||||
#include "../amdgpu/amdgpu_mm_access_core.h"
|
||||
#include <stdatomic.h>
|
||||
|
||||
static uint32_t read32(void *context, uint32_t reg)
|
||||
{
|
||||
volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)context + reg * 4u);
|
||||
/* Original x86 readl/writel carry a compiler memory clobber. Keep CPU
|
||||
* buffer accesses ordered too; volatile alone only orders device accesses.
|
||||
* UC/device ordering is still the real x86 platform owner's obligation. */
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
uint32_t value = *pointer;
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
return value;
|
||||
}
|
||||
static void write32(void *context, uint32_t reg, uint32_t value)
|
||||
{
|
||||
volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)context + reg * 4u);
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
*pointer = value;
|
||||
atomic_signal_fence(memory_order_seq_cst);
|
||||
}
|
||||
|
||||
enum stela_amd_vram_mm_status
|
||||
stela_amd_vram_mm_read(void *registers, size_t register_bytes,
|
||||
uint64_t vram_bytes, uint64_t position,
|
||||
uint32_t *data, size_t size)
|
||||
{
|
||||
uintptr_t base = (uintptr_t)registers, destination = (uintptr_t)data;
|
||||
/* Every pointer addition and the original signed loff_t increment is bounded
|
||||
* before entering the common loop. Actual allocation/lifetime and native
|
||||
* owner/ordering proofs are the mandatory caller contract, not these ints. */
|
||||
if (!registers || base % sizeof(uint32_t) || position % sizeof(uint32_t) ||
|
||||
size % sizeof(uint32_t) || (size && (!data || destination % sizeof(uint32_t))))
|
||||
return STELA_AMD_VRAM_MM_INVALID;
|
||||
if (register_bytes / sizeof(uint32_t) <= mmMM_INDEX ||
|
||||
register_bytes / sizeof(uint32_t) <= mmMM_DATA ||
|
||||
register_bytes / sizeof(uint32_t) <= mmMM_INDEX_HI ||
|
||||
register_bytes > (size_t)PTRDIFF_MAX || register_bytes > UINTPTR_MAX - base ||
|
||||
size > (size_t)PTRDIFF_MAX || (size && size > UINTPTR_MAX - destination) ||
|
||||
vram_bytes > INT64_MAX || position > vram_bytes || size > vram_bytes - position ||
|
||||
/* Original hi=~0 sentinel cannot initialize a first all-ones HI value.
|
||||
* Do not guess prior hardware state or change the retained algorithm. */
|
||||
(size && (position >> 31) == UINT32_MAX))
|
||||
return STELA_AMD_VRAM_MM_BOUNDS;
|
||||
if (size && destination < base + register_bytes && base < destination + size)
|
||||
return STELA_AMD_VRAM_MM_INVALID;
|
||||
static const struct amdgpu_mm_access_ops ops = {read32, write32};
|
||||
amdgpu_mm_access_core(&ops, registers, (int64_t)position, data, size, false);
|
||||
return STELA_AMD_VRAM_MM_OK;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AMD_VRAM_MM_H
|
||||
#define STELA_AMD_VRAM_MM_H
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
enum stela_amd_vram_mm_status {
|
||||
STELA_AMD_VRAM_MM_OK,
|
||||
STELA_AMD_VRAM_MM_INVALID,
|
||||
STELA_AMD_VRAM_MM_BOUNDS,
|
||||
};
|
||||
|
||||
/* Native x86-64 synchronous original NO_KIQ MM_INDEX/MM_DATA read only. OK means
|
||||
* numeric preflight accepted and the original void transaction loop returned;
|
||||
* it is NOT a transport acknowledgement or proof that VRAM bytes are valid.
|
||||
* Discovery must still check its original signature/checksums and ownership.
|
||||
*
|
||||
* registers is the actual retained canonical UC register mapping of this same
|
||||
* AMD device, not physical/guest memory. data is exclusive live CPU RAM for the
|
||||
* complete indicated size; neither span may overlap. Both are DWORD aligned.
|
||||
* The owner retains genuine D0/bridge/reset/removal and MM-index/IRQ exclusion,
|
||||
* required native CPU/process context and ordered MMIO32 access semantics for
|
||||
* the entire call. No new lock, mapping, allocator, provider or guard is made.
|
||||
* vram_bytes is the actual accessible VRAM extent, not a host DMA/IOVA extent.
|
||||
* Only these three original direct registers are accessed; other registers
|
||||
* still require original PCIe/KIQ/RLCG/XCC dispatch. No pointer is retained.
|
||||
*
|
||||
* The first HI value must not equal the original all-ones cache sentinel. This
|
||||
* is an original-loop representation restriction, not a guessed GPU capacity.
|
||||
* All numeric errors leave registers/data untouched. An empty read performs no
|
||||
* MMIO, but still validates the window and position. After index writes there
|
||||
* is no rollback or failure-cleanup capability. Unexpected access faults must
|
||||
* follow the real platform's fail-stop/owner-retention policy. No hardware
|
||||
* status is invented for the original void transport. Callers serialize all
|
||||
* borrowed window accesses and destruction; no Rust references alias MMIO.
|
||||
*/
|
||||
enum stela_amd_vram_mm_status
|
||||
stela_amd_vram_mm_read(void *registers, size_t register_bytes,
|
||||
uint64_t vram_bytes, uint64_t position,
|
||||
uint32_t *data, size_t size);
|
||||
#endif
|
||||
@@ -0,0 +1,731 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Hosted ownership/ABI and retained compiler tests only. Target/VM facts and
|
||||
* upload addresses are CPU models; no initialized physical GPU is claimed. */
|
||||
#include "../stela/air_compile.h"
|
||||
#include "amd/common/ac_binary.h"
|
||||
#include "amd/common/ac_shader_util.h"
|
||||
#include "amd/common/sid.h"
|
||||
#include "amd/compiler/aco_interface.h"
|
||||
#include "stela/air_test_fixture.h"
|
||||
#include "util/mesa-blake3.h"
|
||||
#include "util/ralloc.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef NDEBUG
|
||||
#error "Owned compilation tests require active assertions"
|
||||
#endif
|
||||
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #x); abort(); } } while (0)
|
||||
|
||||
/* Test-object-only renaming of the new owner's direct libc allocations. Mesa,
|
||||
* LLVM, Rust and Foundation retain their original allocators. */
|
||||
static unsigned allocations, fail_allocation, live_allocations;
|
||||
void *stela_amd_air_test_malloc(size_t size);
|
||||
void *stela_amd_air_test_calloc(size_t count, size_t size);
|
||||
void stela_amd_air_test_free(void *pointer);
|
||||
void *stela_amd_air_test_malloc(size_t size)
|
||||
{
|
||||
if (++allocations == fail_allocation)
|
||||
return NULL;
|
||||
void *p = malloc(size);
|
||||
if (p) live_allocations++;
|
||||
return p;
|
||||
}
|
||||
void *stela_amd_air_test_calloc(size_t count, size_t size)
|
||||
{
|
||||
if (++allocations == fail_allocation)
|
||||
return NULL;
|
||||
void *p = calloc(count, size);
|
||||
if (p) live_allocations++;
|
||||
return p;
|
||||
}
|
||||
void stela_amd_air_test_free(void *pointer)
|
||||
{
|
||||
if (pointer) { CHECK(live_allocations); live_allocations--; }
|
||||
free(pointer);
|
||||
}
|
||||
|
||||
struct bytes { uint8_t *data; size_t size; };
|
||||
static void append(struct bytes *bytes, const void *data, size_t size)
|
||||
{
|
||||
CHECK(size <= SIZE_MAX - bytes->size);
|
||||
bytes->data = realloc(bytes->data, bytes->size + size);
|
||||
CHECK(bytes->data);
|
||||
memcpy(bytes->data + bytes->size, data, size);
|
||||
bytes->size += size;
|
||||
}
|
||||
static void little(void *data, uint64_t value, unsigned bytes)
|
||||
{
|
||||
for (unsigned i = 0; i < bytes; i++) ((uint8_t *)data)[i] = (uint8_t)(value >> (8 * i));
|
||||
}
|
||||
static void tag(struct bytes *bytes, const char name[4], const void *data, size_t size)
|
||||
{
|
||||
CHECK(size <= UINT16_MAX);
|
||||
uint8_t length[2]; little(length, size, 2);
|
||||
append(bytes, name, 4); append(bytes, length, 2); append(bytes, data, size);
|
||||
}
|
||||
static void digest(const void *bytes, size_t size, uint8_t output[32])
|
||||
{
|
||||
CHECK(size <= AIR_MAX_BITCODE_BYTES);
|
||||
CC_SHA256(bytes, (CC_LONG)size, output);
|
||||
}
|
||||
/* Own one-entry framing fixture, never a second parser. The production Rust
|
||||
* parser and shared inspector independently validate all original extents. */
|
||||
static struct bytes archive(const void *air, size_t size, const char *name,
|
||||
unsigned air_minor, unsigned major, unsigned minor,
|
||||
unsigned os_major, unsigned os_minor)
|
||||
{
|
||||
struct bytes record = {0}; uint8_t prefix[4] = {0}, kind = 2, hash[32];
|
||||
append(&record, prefix, 4); tag(&record, "NAME", name, strlen(name) + 1);
|
||||
tag(&record, "TYPE", &kind, 1); digest(air, size, hash); tag(&record, "HASH", hash, 32);
|
||||
uint8_t length[8], offsets[24] = {0}, versions[8]; little(length, size, 8);
|
||||
tag(&record, "MDSZ", length, 8); tag(&record, "OFFT", offsets, 24);
|
||||
little(versions, 2, 2); little(versions + 2, air_minor, 2);
|
||||
little(versions + 4, major, 2); little(versions + 6, minor, 2);
|
||||
tag(&record, "VERS", versions, 8); append(&record, "ENDT", 4); little(record.data, record.size, 4);
|
||||
uint8_t header[88] = {0}; memcpy(header, "MTLB", 4);
|
||||
little(header + 4, 0x8001, 2); little(header + 6, 2, 2); little(header + 8, 9, 2);
|
||||
header[11] = 0x81; little(header + 12, os_major, 2); little(header + 14, os_minor, 2);
|
||||
size_t start = 92 + record.size;
|
||||
little(header + 16, start + size, 8); little(header + 24, 88, 8); little(header + 32, record.size, 8);
|
||||
little(header + 40, start, 8); little(header + 56, start, 8);
|
||||
little(header + 72, start, 8); little(header + 80, size, 8);
|
||||
struct bytes result = {0}; append(&result, header, sizeof(header));
|
||||
little(prefix, 1, 4); append(&result, prefix, 4); append(&result, record.data, record.size);
|
||||
append(&result, air, size); free(record.data); return result;
|
||||
}
|
||||
static struct stela_metal_assembly *assemble(const struct bytes *bytes)
|
||||
{
|
||||
struct stela_metal_assembly_options options = stela_metal_assembly_default_options();
|
||||
struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL;
|
||||
enum stela_metal_assembly_status status = stela_metal_assemble_archive(
|
||||
&options, bytes->data, bytes->size, &library, &error);
|
||||
if (status) fprintf(stderr, "assembly refused: %u %s\n", status, error.detail);
|
||||
CHECK(status == STELA_METAL_ASSEMBLY_OK && library);
|
||||
return library;
|
||||
}
|
||||
static struct stela_metal_assembly *fixture(LLVMMemoryBufferRef air)
|
||||
{
|
||||
struct bytes bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 8, 4, 0, 26, 7);
|
||||
struct stela_metal_assembly *library = assemble(&bytes); free(bytes.data); return library;
|
||||
}
|
||||
static struct stela_metal_assembly *two_entries(LLVMMemoryBufferRef air)
|
||||
{
|
||||
size_t size = LLVMGetBufferSize(air);
|
||||
struct bytes a = archive(LLVMGetBufferStart(air), size, "kernel", 8, 4, 0, 26, 7);
|
||||
struct bytes b = archive(LLVMGetBufferStart(air), size, "other", 8, 4, 0, 26, 7);
|
||||
size_t a_record = a.size - 92 - size, b_record = b.size - 92 - size;
|
||||
size_t start = 92 + a_record + b_record;
|
||||
uint8_t header[88], count[4]; memcpy(header, a.data, sizeof(header));
|
||||
little(header + 16, start + size, 8); little(header + 32, a_record + b_record, 8);
|
||||
little(header + 40, start, 8); little(header + 56, start, 8); little(header + 72, start, 8);
|
||||
little(count, 2, 4);
|
||||
struct bytes bytes = {0}; append(&bytes, header, sizeof(header)); append(&bytes, count, 4);
|
||||
append(&bytes, a.data + 92, a_record); append(&bytes, b.data + 92, b_record);
|
||||
append(&bytes, LLVMGetBufferStart(air), size);
|
||||
struct stela_metal_assembly *library = assemble(&bytes);
|
||||
free(a.data); free(b.data); free(bytes.data); return library;
|
||||
}
|
||||
static struct radeon_info model(enum radeon_family family, bool graphics)
|
||||
{
|
||||
struct radeon_info info = {
|
||||
.family = family, .gfx_level = ac_get_gfx_level(family), .has_graphics = graphics,
|
||||
.num_cu = 8, .num_se = 2, .max_se = 2, .spi_cu_en = UINT32_MAX,
|
||||
.max_good_cu_per_sa = 4, .max_sa_per_se = 1,
|
||||
.virtual_address_max = UINT64_C(0x800000000000), .virtual_address_alignment = 4096,
|
||||
.tcc_cache_line_size = 128,
|
||||
};
|
||||
ac_fill_compiler_info(&info, NULL, false);
|
||||
info.instr_prefetch_distance = info.gfx_level >= GFX11 ? 4 : 0;
|
||||
return info;
|
||||
}
|
||||
static struct stela_amd_air_options options(unsigned wave)
|
||||
{
|
||||
return (struct stela_amd_air_options) {
|
||||
.size = sizeof(struct stela_amd_air_options), .abi = STELA_AMD_AIR_ABI,
|
||||
.wave_size = wave, .workgroup_size = {32, 1, 1}, .max_instructions = 4096,
|
||||
.max_code_bytes = 1024u * 1024u,
|
||||
};
|
||||
}
|
||||
static struct stela_amd_air_compilation *compile(const struct radeon_info *info,
|
||||
struct stela_metal_assembly *library, const struct stela_amd_air_options *opts,
|
||||
enum stela_amd_air_status expected)
|
||||
{
|
||||
struct stela_amd_air_compilation *result = NULL; struct stela_amd_air_error error;
|
||||
#ifdef STELA_AMD_AIR_ALLOC_TEST
|
||||
unsigned baseline = live_allocations;
|
||||
#endif
|
||||
enum stela_amd_air_status status = stela_amd_air_compile(info, library, 0, opts, &result, &error);
|
||||
if (status != expected) fprintf(stderr, "compile %s: %u expected %u: %s (AIR %u %s)\n",
|
||||
ac_get_family_name(info->family), status, expected, error.detail, error.air.kind, error.air.detail);
|
||||
CHECK(status == expected && error.status == status && (result != NULL) == (status == STELA_AMD_AIR_OK));
|
||||
#ifdef STELA_AMD_AIR_ALLOC_TEST
|
||||
if (status != STELA_AMD_AIR_OK) CHECK(live_allocations == baseline);
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
static void destroy(struct stela_amd_air_compilation **owner)
|
||||
{
|
||||
stela_amd_air_destroy(owner); CHECK(!*owner);
|
||||
stela_amd_air_destroy(owner); stela_amd_air_destroy(NULL);
|
||||
}
|
||||
struct reference {const struct stela_amd_air_compilation *owner; unsigned count;};
|
||||
static void reference_binary(void **private, const struct ac_shader_config *config,
|
||||
const char *ir, unsigned ir_size, const char *assembly, unsigned assembly_size,
|
||||
struct amd_stats *stats, uint32_t exec_size, const uint32_t *code, uint32_t code_dw,
|
||||
const struct aco_symbol *symbols, unsigned symbol_count,
|
||||
const struct ac_shader_debug_info *debug, unsigned debug_count)
|
||||
{
|
||||
(void)ir; (void)ir_size; (void)assembly; (void)assembly_size; (void)stats;
|
||||
(void)symbols; (void)debug; (void)debug_count;
|
||||
struct reference *ref = *private;
|
||||
const struct stela_amd_compute_binary *binary = stela_amd_air_binary(ref->owner);
|
||||
CHECK(!ref->count++ && !symbol_count && exec_size == binary->executable_bytes && code_dw * 4 == binary->code_bytes &&
|
||||
!memcmp(code, stela_amd_air_code(ref->owner), binary->code_bytes) &&
|
||||
!memcmp(config, binary->config, sizeof(*config)));
|
||||
}
|
||||
static uint32_t
|
||||
register_word(const uint32_t *words, unsigned count, unsigned reg)
|
||||
{
|
||||
for (unsigned cursor = 0; cursor < count;) {
|
||||
const unsigned header = words[cursor], length = ((header >> 16) & 0x3fff) + 2;
|
||||
CHECK(header >> 30 == 3 && length <= count - cursor &&
|
||||
((header >> 8) & 255) == PKT3_SET_SH_REG && length >= 3);
|
||||
const unsigned start = 0xb000 + 4 * words[cursor + 1];
|
||||
for (unsigned i = 2; i < length; i++) {
|
||||
if (start + 4 * (i - 2) == reg)
|
||||
return words[cursor + i];
|
||||
}
|
||||
cursor += length;
|
||||
}
|
||||
CHECK(false);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void validate_result(const struct radeon_info *info, struct stela_amd_air_compilation *owner,
|
||||
const char *label)
|
||||
{
|
||||
const struct stela_amd_compute_binary *binary = stela_amd_air_binary(owner);
|
||||
const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner);
|
||||
uint32_t count; const struct stela_amd_air_binding *bindings = stela_amd_air_bindings(owner, &count);
|
||||
CHECK(binary && p && bindings && stela_amd_air_code(owner));
|
||||
CHECK(binary->code_bytes >= binary->executable_bytes && binary->executable_bytes > 0 &&
|
||||
binary->shader->options && binary->config->num_vgprs && binary->args->return_count == 0);
|
||||
CHECK(binary->family == info->family && binary->gfx_level == info->gfx_level);
|
||||
CHECK(!memcmp(&p->compiler_info, &info->compiler_info, sizeof(p->compiler_info)));
|
||||
CHECK(p->pci_id == info->pci_id && p->pci_rev_id == info->pci_rev_id && p->has_graphics == info->has_graphics);
|
||||
CHECK(binary->shader->options->max_workgroup_invocations >= 32 && p->name && p->target);
|
||||
nir_validate_shader((nir_shader *)binary->shader, "retained owned compile result");
|
||||
/* Original backend callback is an independent byte/config oracle for the
|
||||
* owner's copied result. Compile a real NIR clone through unchanged ACO;
|
||||
* inspection below also happens after its temporary vectors are destroyed. */
|
||||
nir_shader *copy = nir_shader_clone(NULL, binary->shader);
|
||||
CHECK(copy);
|
||||
const struct aco_compiler_options opts = {.compiler_info = &info->compiler_info,
|
||||
.family = info->family, .gfx_level = info->gfx_level};
|
||||
const struct aco_shader_info shader_info = {.hw_stage = AC_HW_COMPUTE_SHADER,
|
||||
.lds_size = binary->shader->info.shared_size,
|
||||
.wave_size = (uint8_t)binary->wave_size, .workgroup_size =
|
||||
binary->shader->info.workgroup_size[0] * binary->shader->info.workgroup_size[1] * binary->shader->info.workgroup_size[2]};
|
||||
struct reference ref = {.owner = owner}; void *private = &ref;
|
||||
aco_compile_shader(&opts, &shader_info, 1, ©, binary->args, reference_binary, &private);
|
||||
CHECK(ref.count == 1); ralloc_free(copy);
|
||||
struct stela_amd_compute_binding runtime[STELA_AMD_AIR_MAX_BUFFERS] = {0};
|
||||
bool seen[AC_MAX_ARGS] = {false};
|
||||
nir_foreach_function_impl(impl, (nir_shader *)binary->shader) {
|
||||
nir_foreach_block(block, impl) {
|
||||
nir_foreach_instr(instr, block) {
|
||||
if (instr->type != nir_instr_type_intrinsic) continue;
|
||||
nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
|
||||
if (intr->intrinsic == nir_intrinsic_load_scalar_arg_amd && nir_intrinsic_base(intr) < AC_MAX_ARGS)
|
||||
seen[nir_intrinsic_base(intr)] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
struct ac_arg arg = bindings[i].argument;
|
||||
CHECK(arg.used && arg.arg_index < binary->args->arg_count &&
|
||||
binary->args->args[arg.arg_index].file == AC_ARG_SGPR &&
|
||||
binary->args->args[arg.arg_index].offset == 2 * i && binary->args->args[arg.arg_index].size == 2);
|
||||
runtime[i] = (struct stela_amd_compute_binding) {.argument = arg,
|
||||
.view = {.allocation_va = UINT64_C(0x100000) + (uint64_t)i * 4096,
|
||||
.allocation_bytes = 4096, .range = 4096, .required_alignment = bindings[i].buffer.type_alignment}};
|
||||
CHECK(bindings[i].buffer.address_space == 1 && bindings[i].buffer.type_alignment);
|
||||
bool used = false;
|
||||
for (unsigned a = 0; a < p->argument_count; a++)
|
||||
if (p->arguments[a].buffer.argument == bindings[i].buffer.argument) used = p->arguments[a].used;
|
||||
if (used) CHECK(seen[arg.arg_index]);
|
||||
}
|
||||
const unsigned padded = ac_align_shader_binary_for_prefetch(info->gfx_level,
|
||||
info->instr_prefetch_distance, binary->code_bytes);
|
||||
struct stela_amd_buffer_view code = {.allocation_va = UINT64_C(0x400000),
|
||||
.allocation_bytes = padded, .range = padded, .required_alignment = 256};
|
||||
struct stela_amd_compute_pipeline pipeline;
|
||||
enum stela_amd_compute_status status = stela_amd_build_compute_pipeline(info, binary, &code, runtime, count, &pipeline);
|
||||
if (binary->config->scratch_bytes_per_wave)
|
||||
CHECK(status == STELA_AMD_COMPUTE_RESOURCE_OWNER_UNAVAILABLE);
|
||||
else if (count)
|
||||
CHECK(status == STELA_AMD_COMPUTE_OK && pipeline.user_sgpr_count == 2 * count);
|
||||
else {
|
||||
CHECK(status == STELA_AMD_COMPUTE_OK && !pipeline.user_sgpr_count &&
|
||||
!G_00B84C_USER_SGPR(pipeline.rsrc2));
|
||||
struct stela_amd_compute_pipeline null_bindings;
|
||||
CHECK(stela_amd_build_compute_pipeline(info, binary, &code, NULL, 0, &null_bindings) == STELA_AMD_COMPUTE_OK &&
|
||||
!memcmp(&pipeline, &null_bindings, sizeof(pipeline)));
|
||||
uint32_t words[256], written;
|
||||
CHECK(stela_amd_compute_pipeline(info, &pipeline, words, ARRAY_SIZE(words), &written) == STELA_AMD_COMMAND_OK && written);
|
||||
bool resource_word = false;
|
||||
for (unsigned cursor = 0; cursor < written;) {
|
||||
const uint32_t header = words[cursor], length = ((header >> 16) & 0x3fff) + 2;
|
||||
CHECK(header >> 30 == 3 && length <= written - cursor && length >= 3 &&
|
||||
((header >> 8) & 255) == PKT3_SET_SH_REG);
|
||||
const uint32_t start = 0xb000 + words[cursor + 1] * 4;
|
||||
for (unsigned i = 2; i < length; i++) {
|
||||
const uint32_t reg = start + (i - 2) * 4;
|
||||
CHECK(reg < R_00B900_COMPUTE_USER_DATA_0 || reg >= R_00B900_COMPUTE_USER_DATA_0 + 4 * STELA_AMD_COMPUTE_USER_SGPRS);
|
||||
if (reg == R_00B84C_COMPUTE_PGM_RSRC2) {
|
||||
CHECK(words[cursor + i] == pipeline.rsrc2 && !G_00B84C_USER_SGPR(words[cursor + i]));
|
||||
resource_word = true;
|
||||
}
|
||||
}
|
||||
cursor += length;
|
||||
}
|
||||
CHECK(resource_word);
|
||||
const struct stela_amd_compute_pipeline preserved = pipeline;
|
||||
CHECK(stela_amd_build_compute_pipeline(info, binary, &code, NULL, 1, &pipeline) == STELA_AMD_COMPUTE_INVALID &&
|
||||
!memcmp(&pipeline, &preserved, sizeof(pipeline)));
|
||||
struct ac_shader_config scratch = *binary->config; scratch.scratch_bytes_per_wave = 1024;
|
||||
struct stela_amd_compute_binary unowned = *binary; unowned.config = &scratch;
|
||||
CHECK(stela_amd_build_compute_pipeline(info, &unowned, &code, NULL, 0, &pipeline) == STELA_AMD_COMPUTE_RESOURCE_OWNER_UNAVAILABLE &&
|
||||
!memcmp(&pipeline, &preserved, sizeof(pipeline)));
|
||||
}
|
||||
CHECK(binary->config->lds_size == binary->shader->info.shared_size);
|
||||
if (status == STELA_AMD_COMPUTE_OK) {
|
||||
CHECK(G_00B84C_LDS_SIZE(pipeline.rsrc2) == ac_shader_encode_lds_size(
|
||||
binary->shader->info.shared_size, info->gfx_level, MESA_SHADER_COMPUTE));
|
||||
uint32_t words[256], written;
|
||||
CHECK(stela_amd_compute_pipeline(info, &pipeline, words, ARRAY_SIZE(words), &written) == STELA_AMD_COMMAND_OK);
|
||||
CHECK(register_word(words, written, R_00B84C_COMPUTE_PGM_RSRC2) == pipeline.rsrc2);
|
||||
const struct stela_amd_compute_pipeline preserved = pipeline;
|
||||
struct ac_shader_config incompatible = *binary->config;
|
||||
incompatible.lds_size = binary->shader->info.shared_size ? 0 : 1;
|
||||
struct stela_amd_compute_binary wrong_lds = *binary; wrong_lds.config = &incompatible;
|
||||
CHECK(stela_amd_build_compute_pipeline(info, &wrong_lds, &code, runtime, count, &pipeline) == STELA_AMD_COMPUTE_UNSUPPORTED &&
|
||||
!memcmp(&pipeline, &preserved, sizeof(pipeline)));
|
||||
}
|
||||
blake3_hash hash; char code_hash[BLAKE3_HEX_LEN];
|
||||
_mesa_blake3_compute(stela_amd_air_code(owner), binary->code_bytes, hash); _mesa_blake3_format(code_hash, hash);
|
||||
printf("owned-air-aco input=%s target=%s.wave%u buffers=%u code_bytes=%u executable_bytes=%u code_blake3=%s "
|
||||
"sgprs=%u vgprs=%u lds=%u scratch=%u float_mode=%u\n", label, ac_get_family_name(info->family),
|
||||
binary->wave_size, count, binary->code_bytes, binary->executable_bytes, code_hash, binary->config->num_sgprs,
|
||||
binary->config->num_vgprs, binary->config->lds_size, binary->config->scratch_bytes_per_wave, binary->config->float_mode);
|
||||
}
|
||||
|
||||
static void text_append(char *text, size_t capacity, const char *format, ...)
|
||||
{
|
||||
size_t length = strlen(text); CHECK(length < capacity);
|
||||
va_list args; va_start(args, format); int bytes = vsnprintf(text + length, capacity - length, format, args);
|
||||
va_end(args); CHECK(bytes >= 0 && (size_t)bytes < capacity - length);
|
||||
}
|
||||
static LLVMMemoryBufferRef multibuffer(unsigned count)
|
||||
{
|
||||
CHECK(count <= 9);
|
||||
char prefix[4096] = "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n"
|
||||
"target triple = \"air64_v28-apple-macosx26.7.0\"\ndefine void @kernel(i32 %tid";
|
||||
char body[8192] = "%index = zext i32 %tid to i64\n", metadata[16384] = "}\n"
|
||||
"!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n"
|
||||
"!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n"
|
||||
"!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5";
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
text_append(prefix, sizeof(prefix), ", ptr addrspace(1) %%b%u", i);
|
||||
text_append(body, sizeof(body), "%%p%u = getelementptr i32, ptr addrspace(1) %%b%u, i64 %%index\n"
|
||||
"%%v%u = load i32, ptr addrspace(1) %%p%u, align 4\n"
|
||||
"%%x%u = add i32 %%v%u, %u\nstore i32 %%x%u, ptr addrspace(1) %%p%u, align 4\n",
|
||||
i, i, i, i, i, i, i + 1, i, i);
|
||||
text_append(metadata, sizeof(metadata), ",!%u", i + 6);
|
||||
}
|
||||
text_append(prefix, sizeof(prefix), ") {\n"); text_append(body, sizeof(body), "ret void\n");
|
||||
text_append(metadata, sizeof(metadata), "}\n!5 = !{i32 0, !\"air.thread_position_in_grid\","
|
||||
" !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n");
|
||||
for (unsigned i = 0; i < count; i++)
|
||||
text_append(metadata, sizeof(metadata), "!%u = !{i32 %u, !\"air.buffer\", !\"air.location_index\", i32 %u, i32 1,"
|
||||
" !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4,"
|
||||
" !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"buffer%u\"}\n",
|
||||
i + 6, i + 1, (i * 7 + 3) % 31, i);
|
||||
return stela_air_test_custom_bitcode(prefix, body, metadata, "");
|
||||
}
|
||||
|
||||
static void failures(struct stela_metal_assembly *library, const struct radeon_info *info)
|
||||
{
|
||||
struct stela_amd_air_options valid = options(64), bad;
|
||||
const struct {unsigned field, value; enum stela_amd_air_status status;} cases[] = {
|
||||
{0, 0, STELA_AMD_AIR_INVALID}, {1, 0, STELA_AMD_AIR_INVALID},
|
||||
{2, 0, STELA_AMD_AIR_UNSUPPORTED}, {3, 0, STELA_AMD_AIR_UNSUPPORTED},
|
||||
{4, UINT32_MAX, STELA_AMD_AIR_UNSUPPORTED}, {5, 0, STELA_AMD_AIR_LIMIT},
|
||||
{6, 0, STELA_AMD_AIR_LIMIT}, {6, UINT32_MAX, STELA_AMD_AIR_LIMIT},
|
||||
};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(cases); i++) {
|
||||
bad = valid;
|
||||
switch (cases[i].field) {
|
||||
case 0: bad.size = cases[i].value; break; case 1: bad.abi = cases[i].value; break;
|
||||
case 2: bad.wave_size = cases[i].value; break; case 3: bad.workgroup_size[0] = cases[i].value; break;
|
||||
case 4: bad.workgroup_size[2] = cases[i].value; break; case 5: bad.max_instructions = cases[i].value; break;
|
||||
case 6: bad.max_code_bytes = cases[i].value; break;
|
||||
}
|
||||
CHECK(!compile(info, library, &bad, cases[i].status));
|
||||
}
|
||||
bad = valid; bad.fp_profile = (enum stela_air_fp_profile)99;
|
||||
CHECK(!compile(info, library, &bad, STELA_AMD_AIR_UNSUPPORTED));
|
||||
bad = valid; bad.max_code_bytes = 4;
|
||||
CHECK(!compile(info, library, &bad, STELA_AMD_AIR_LIMIT));
|
||||
bad = valid; bad.max_instructions = 1;
|
||||
CHECK(!compile(info, library, &bad, STELA_AMD_AIR_FRONTEND));
|
||||
struct radeon_info missing = *info; missing.virtual_address_max = 0;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
missing = *info; missing.compiler_info.max_sgpr_alloc = 1;
|
||||
missing.compiler_info.min_sgpr_alloc = missing.compiler_info.sgpr_alloc_granularity = 1;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_UNSUPPORTED));
|
||||
missing = *info; missing.compiler_info.num_physical_sgprs_per_simd = 0;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
missing = *info; missing.compiler_info.num_physical_wave64_vgprs_per_simd = UINT32_MAX;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
missing = *info; missing.compiler_info.wave64_vgpr_alloc_granularity = 0;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
missing = *info; missing.compiler_info.lds_size_per_workgroup = UINT32_MAX;
|
||||
CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
missing = *info; missing.compiler_info.num_physical_wave64_vgprs_per_simd = UINT16_MAX / 2 + 1;
|
||||
bad = valid; bad.wave_size = 32;
|
||||
CHECK(!compile(&missing, library, &bad, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE));
|
||||
struct radeon_info cdna = model(CHIP_MI100, false);
|
||||
CHECK(!compile(&cdna, library, &valid, STELA_AMD_AIR_UNSUPPORTED));
|
||||
struct radeon_info gfx121 = model(CHIP_GFX1210, true);
|
||||
CHECK(!compile(&gfx121, library, &valid, STELA_AMD_AIR_UNSUPPORTED));
|
||||
struct stela_amd_air_error error; struct stela_amd_air_compilation *owner = NULL;
|
||||
CHECK(stela_amd_air_compile(info, library, UINT32_MAX, &valid, &owner, &error) == STELA_AMD_AIR_INVALID && !owner);
|
||||
owner = compile(info, library, &valid, STELA_AMD_AIR_OK);
|
||||
struct stela_amd_air_compilation *same = owner;
|
||||
CHECK(stela_amd_air_compile(info, library, 0, &valid, &owner, &error) == STELA_AMD_AIR_INVALID && owner == same);
|
||||
destroy(&owner);
|
||||
}
|
||||
static void targets(struct stela_metal_assembly *library, enum stela_air_fp_profile profile, const char *label)
|
||||
{
|
||||
const enum radeon_family families[] = {CHIP_TAHITI, CHIP_BONAIRE, CHIP_CARRIZO, CHIP_RAVEN,
|
||||
CHIP_NAVI10, CHIP_REMBRANDT, CHIP_NAVI31, CHIP_STRIX1, CHIP_GFX1170, CHIP_GFX1201};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(families); i++) {
|
||||
struct radeon_info info = model(families[i], true);
|
||||
for (unsigned wave = info.gfx_level < GFX10 ? 64 : 32; wave <= 64; wave *= 2) {
|
||||
struct stela_amd_air_options opts = options(wave); opts.fp_profile = profile;
|
||||
struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK);
|
||||
validate_result(&info, owner, label); destroy(&owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
static void original_tests(void)
|
||||
{
|
||||
LLVMMemoryBufferRef air = stela_air_test_bitcode(stela_air_test_store_body, "");
|
||||
struct stela_metal_assembly *library = fixture(air);
|
||||
LLVMDisposeMemoryBuffer(air);
|
||||
targets(library, STELA_AIR_FP_IEEE_DEFAULT, "original-integer");
|
||||
struct radeon_info info = model(CHIP_NAVI31, true);
|
||||
failures(library, &info);
|
||||
struct stela_amd_air_options three_d = options(32);
|
||||
three_d.workgroup_size[0] = 4; three_d.workgroup_size[1] = 2; three_d.workgroup_size[2] = 3;
|
||||
struct stela_amd_air_compilation *specialized = compile(&info, library, &three_d, STELA_AMD_AIR_OK);
|
||||
const struct stela_amd_air_provenance *specialization = stela_amd_air_provenance(specialized);
|
||||
CHECK(!memcmp(&specialization->options, &three_d, sizeof(three_d)));
|
||||
for (unsigned axis = 0; axis < 3; axis++)
|
||||
CHECK(stela_amd_air_binary(specialized)->shader->info.workgroup_size[axis] == three_d.workgroup_size[axis]);
|
||||
validate_result(&info, specialized, "3d-workgroup"); destroy(&specialized);
|
||||
struct stela_amd_air_options opts = options(64);
|
||||
struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK);
|
||||
const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(library);
|
||||
const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner);
|
||||
CHECK(!memcmp(&p->input, &m->input, sizeof(p->input)) &&
|
||||
!memcmp(&p->entry, &m->entries[0].entry, sizeof(p->entry)) &&
|
||||
!memcmp(p->air_sha256, m->entries[0].air_sha256, 32) &&
|
||||
p->air_offset == m->entries[0].air_offset && p->air_bytes == m->entries[0].air_bytes &&
|
||||
p->arguments[1].name != m->entries[0].arguments[1].name &&
|
||||
!strcmp(p->arguments[1].name, m->entries[0].arguments[1].name));
|
||||
stela_metal_assembly_destroy(&library);
|
||||
CHECK(!strcmp(p->name, "kernel") && !strcmp(p->target, "air64_v28-apple-macosx26.7.0") &&
|
||||
!strcmp(p->arguments[1].type_name, "uint"));
|
||||
/* Hold one shader/options/type reference across creation/destruction of a
|
||||
* distinct owner: no borrowed assembly or prematurely released type state. */
|
||||
air = multibuffer(8); library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
struct stela_amd_air_compilation *second = compile(&info, library, &opts, STELA_AMD_AIR_OK);
|
||||
uint32_t count; const struct stela_amd_air_binding *bindings = stela_amd_air_bindings(second, &count);
|
||||
CHECK(count == 8);
|
||||
for (unsigned i = 0; i < count; i++) CHECK(bindings[i].buffer.index == (i * 7 + 3) % 31 && bindings[i].buffer.argument == i + 1);
|
||||
validate_result(&info, second, "eight-buffer"); destroy(&second);
|
||||
validate_result(&info, owner, "after-other-owner-destroy"); destroy(&owner);
|
||||
stela_metal_assembly_destroy(&library);
|
||||
const char *selected_metadata = "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n"
|
||||
"!air.kernel = !{!2,!7}\n!0 = !{i32 2, i32 8, i32 0}\n"
|
||||
"!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!2 = !{ptr @kernel, !3, !4}\n"
|
||||
"!3 = !{}\n!4 = !{!5,!6}\n!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\"}\n"
|
||||
"!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 13, i32 1, !\"air.write\","
|
||||
" !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4,"
|
||||
" !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"result\"}\n!7 = !{ptr @other, !3, !4}\n";
|
||||
air = stela_air_test_custom_bitcode(stela_air_test_prefix,
|
||||
"store i32 11, ptr addrspace(1) %out, align 4\nret void\n", selected_metadata,
|
||||
"define void @other(i32 %tid, ptr addrspace(1) %out) {\nstore i32 99, ptr addrspace(1) %out, align 4\nret void\n}\n");
|
||||
library = two_entries(air); LLVMDisposeMemoryBuffer(air);
|
||||
struct stela_amd_air_error selected_error;
|
||||
CHECK(stela_amd_air_compile(&info, library, 1, &opts, &owner, &selected_error) == STELA_AMD_AIR_OK && owner);
|
||||
stela_metal_assembly_destroy(&library);
|
||||
p = stela_amd_air_provenance(owner);
|
||||
CHECK(p->selected_entry == 1 && !strcmp(p->name, "other") && p->input.entry_count == 2 &&
|
||||
p->arguments[1].buffer.index == 13 && p->arguments[1].buffer.access == STELA_AIR_WRITE &&
|
||||
!p->arguments[0].name && p->arguments[0].name_bytes == 0);
|
||||
unsigned selected_stores = 0;
|
||||
nir_foreach_function_impl(impl, (nir_shader *)stela_amd_air_binary(owner)->shader) {
|
||||
nir_foreach_block(block, impl) {
|
||||
nir_foreach_instr(instr, block) {
|
||||
if (instr->type != nir_instr_type_intrinsic) continue;
|
||||
nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
|
||||
if (intr->intrinsic == nir_intrinsic_store_global_amd || intr->intrinsic == nir_intrinsic_store_global) {
|
||||
CHECK(nir_src_is_const(intr->src[0]) && nir_src_as_uint(intr->src[0]) == 99); selected_stores++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK(selected_stores == 1); validate_result(&info, owner, "selected-second-entry"); destroy(&owner);
|
||||
air = multibuffer(9); library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_UNSUPPORTED)); stela_metal_assembly_destroy(&library);
|
||||
air = stela_air_test_bitcode("call void @unsupported()\nret void\n", "declare void @unsupported()\n");
|
||||
library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_FRONTEND)); stela_metal_assembly_destroy(&library);
|
||||
/* Original LLVM fixture with complete AS3 argument reflection and no module
|
||||
* globals: distinguish this leaf's dispatch-specialization refusal from the
|
||||
* canonical library owner's separate incomplete-global reflection refusal. */
|
||||
air = stela_air_test_custom_bitcode(
|
||||
"target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n"
|
||||
"target triple = \"air64_v29-apple-macosx27.2.0\"\n"
|
||||
"define void @kernel(i32 %tid, ptr addrspace(3) %scratch) {\n",
|
||||
"store i32 %tid, ptr addrspace(3) %scratch, align 4\nret void\n",
|
||||
"}\n!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n"
|
||||
"!0 = !{i32 2, i32 9, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 1, i32 0}\n"
|
||||
"!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5,!6}\n"
|
||||
"!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n"
|
||||
"!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 7, i32 1, !\"air.read_write\","
|
||||
" !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4,"
|
||||
" !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"scratch\"}\n", "");
|
||||
struct bytes shared_bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 9, 4, 1, 27, 2);
|
||||
library = assemble(&shared_bytes); free(shared_bytes.data); LLVMDisposeMemoryBuffer(air);
|
||||
CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_UNSUPPORTED)); stela_metal_assembly_destroy(&library);
|
||||
for (unsigned n = 0; n <= 8; n++) {
|
||||
air = multibuffer(n); library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
targets(library, STELA_AIR_FP_IEEE_DEFAULT, "generic-buffer-indices");
|
||||
stela_metal_assembly_destroy(&library);
|
||||
}
|
||||
#ifdef STELA_AMD_AIR_ALLOC_TEST
|
||||
air = stela_air_test_bitcode(stela_air_test_store_body, ""); library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
allocations = 0; owner = compile(&info, library, &opts, STELA_AMD_AIR_OK);
|
||||
unsigned total = allocations; CHECK(total == 3); destroy(&owner);
|
||||
for (unsigned fail = 1; fail <= total; fail++) {
|
||||
allocations = 0; fail_allocation = fail;
|
||||
CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_ALLOCATION) && !live_allocations);
|
||||
}
|
||||
fail_allocation = 0; owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); destroy(&owner);
|
||||
stela_metal_assembly_destroy(&library);
|
||||
#endif
|
||||
CHECK(!stela_amd_air_binary(NULL) && !stela_amd_air_code(NULL) && !stela_amd_air_provenance(NULL));
|
||||
count = UINT32_MAX; CHECK(!stela_amd_air_bindings(NULL, &count) && !count);
|
||||
puts("owned AMD AIR compiler lifetime, multi-buffer, producer and failure tests passed");
|
||||
}
|
||||
|
||||
static struct bytes read_file(const char *path)
|
||||
{
|
||||
FILE *f = fopen(path, "rb"); CHECK(f && !fseek(f, 0, SEEK_END)); long size = ftell(f);
|
||||
CHECK(size > 0 && size <= AIR_MAX_BITCODE_BYTES && !fseek(f, 0, SEEK_SET));
|
||||
struct bytes b = {.data = malloc((size_t)size), .size = (size_t)size}; CHECK(b.data);
|
||||
CHECK(fread(b.data, 1, b.size, f) == b.size && fgetc(f) == EOF && !ferror(f) && !fclose(f)); return b;
|
||||
}
|
||||
struct input_facts {const char *name; unsigned air_minor, major, minor, os_major, os_minor; bool found;};
|
||||
static bool facts(const struct stela_air_inspection *inspection, const struct stela_air_entry *entry, void *data)
|
||||
{
|
||||
struct input_facts *f = data;
|
||||
if (strlen(f->name) != entry->name_bytes || memcmp(f->name, entry->name, entry->name_bytes)) return true;
|
||||
f->found = true; f->air_minor = inspection->air_minor; f->major = inspection->language_major; f->minor = inspection->language_minor;
|
||||
CHECK(sscanf(inspection->target, "air64_v%*u-apple-macosx%u.%u.", &f->os_major, &f->os_minor) == 2);
|
||||
return true;
|
||||
}
|
||||
static void real_input(int argc, char **argv)
|
||||
{
|
||||
CHECK(argc == 4 || argc == 5); /* --input RAW_AIR ENTRY [qualified FP profile number] */
|
||||
struct bytes air = read_file(argv[2]); struct input_facts f = {.name = argv[3]}; struct stela_air_error error;
|
||||
CHECK(stela_air_inspect(air.data, air.size, 256, facts, &f, &error) && f.found);
|
||||
struct bytes bytes = archive(air.data, air.size, f.name, f.air_minor, f.major, f.minor, f.os_major, f.os_minor);
|
||||
struct stela_metal_assembly *library = assemble(&bytes); free(air.data); free(bytes.data);
|
||||
enum stela_air_fp_profile profile = argc == 5 ? (enum stela_air_fp_profile)strtoul(argv[4], NULL, 10) : STELA_AIR_FP_IEEE_DEFAULT;
|
||||
targets(library, profile, "unchanged-original-file"); stela_metal_assembly_destroy(&library);
|
||||
}
|
||||
static void source_input(int argc, char **argv)
|
||||
{
|
||||
CHECK(argc == 5); /* --source ORIGINAL_MSL ORIGINAL_ADAPTER_AIR INDEPENDENT_RECEIPT_IDENTITY_208_BYTES */
|
||||
struct bytes source = read_file(argv[2]), air = read_file(argv[3]), identity = read_file(argv[4]); CHECK(identity.size == 208);
|
||||
struct stela_msl_output compiled = {.air = air.data, .air_bytes = air.size};
|
||||
memcpy(compiled.source_sha256, identity.data, 32); memcpy(compiled.air_sha256, identity.data + 32, 32);
|
||||
memcpy(&compiled.build, identity.data + 64, sizeof(compiled.build));
|
||||
struct stela_msl_apple_config config = stela_msl_apple_default_config();
|
||||
struct stela_msl_request request = {.source = source.data, .source_bytes = source.size, .language_version = 0x40001,
|
||||
.fast_math = true, .target_triple = "air64_v29-apple-macosx27.2.0"};
|
||||
struct stela_metal_assembly_options assembly_options = stela_metal_assembly_default_options();
|
||||
struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL;
|
||||
CHECK(stela_metal_assemble_source(&assembly_options, &config, &request, &compiled, &library, &error) == STELA_METAL_ASSEMBLY_OK);
|
||||
struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options opts = options(32);
|
||||
opts.fp_profile = STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41;
|
||||
struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK);
|
||||
free(air.data); free(source.data); stela_metal_assembly_destroy(&library);
|
||||
const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner);
|
||||
CHECK(p->library_flags == STELA_METAL_LIBRARY_SOURCE_COMPILED && p->compiler_profile == config.profile &&
|
||||
p->request_language == 0x40001 && p->request_fast_math == 1 &&
|
||||
!memcmp(p->source_sha256, identity.data, 32) && !memcmp(p->input.original_sha256, identity.data + 32, 32) &&
|
||||
!memcmp(&p->build, identity.data + 64, sizeof(p->build)));
|
||||
free(identity.data); validate_result(&info, owner, "original-source-owner"); destroy(&owner);
|
||||
}
|
||||
static void requested_threadgroups(int argc,char **argv,struct stela_metal_threadgroup_request_row *rows)
|
||||
{
|
||||
CHECK(argc>=6&&argc-5<=(int)AIR_MAX_ARGUMENTS);
|
||||
for(int i=5;i<argc;i++) {
|
||||
char *end;errno=0;CHECK(argv[i][0]>='0'&&argv[i][0]<='9');
|
||||
unsigned long long index=strtoull(argv[i],&end,10);CHECK(!errno&&index<=UINT32_MAX&&*end==':');
|
||||
const char *start=end+1;CHECK(*start>='0'&&*start<='9');errno=0;
|
||||
unsigned long long bytes=strtoull(start,&end,10);CHECK(!errno&&!*end);
|
||||
rows[i-5]=(struct stela_metal_threadgroup_request_row){.index=(uint32_t)index,.bytes=(uint64_t)bytes};
|
||||
}
|
||||
}
|
||||
static void threadgroup_input(int argc,char **argv)
|
||||
{
|
||||
struct stela_metal_threadgroup_request_row rows[AIR_MAX_ARGUMENTS]={0};requested_threadgroups(argc,argv,rows);
|
||||
char *end;errno=0;unsigned long workgroup=strtoul(argv[4],&end,10);CHECK(!errno&&!*end&&workgroup&&workgroup<=1024);
|
||||
struct stela_metal_threadgroup_request request={.size=sizeof(request),.abi=STELA_METAL_THREADGROUP_ABI,
|
||||
.count=(uint32_t)(argc-5),.rows=rows};
|
||||
struct bytes air=read_file(argv[2]);struct input_facts f={.name=argv[3]};struct stela_air_error air_error;
|
||||
CHECK(stela_air_inspect(air.data,air.size,256,facts,&f,&air_error)&&f.found);
|
||||
struct bytes bytes=archive(air.data,air.size,f.name,f.air_minor,f.major,f.minor,f.os_major,f.os_minor);
|
||||
struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data);
|
||||
const enum radeon_family families[]={CHIP_TAHITI,CHIP_BONAIRE,CHIP_CARRIZO,CHIP_RAVEN,
|
||||
CHIP_NAVI10,CHIP_REMBRANDT,CHIP_NAVI31,CHIP_STRIX1,CHIP_GFX1170,CHIP_GFX1201};
|
||||
for(unsigned i=0;i<ARRAY_SIZE(families);i++) {
|
||||
struct radeon_info info=model(families[i],true);
|
||||
for(unsigned wave=info.gfx_level<GFX10?64:32;wave<=64;wave*=2) {
|
||||
struct stela_amd_air_options opts=options(wave);opts.workgroup_size[0]=(uint32_t)workgroup;
|
||||
struct stela_amd_air_compilation *owner=NULL;struct stela_amd_air_error error;
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&request,&owner,&error)==STELA_AMD_AIR_OK&&owner);
|
||||
const struct stela_amd_air_provenance *p=stela_amd_air_provenance(owner);
|
||||
if(i==0) {
|
||||
struct stela_metal_threadgroup_request bad_request=request;
|
||||
struct stela_amd_air_compilation *failed=NULL;
|
||||
bad_request.size--;
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&bad_request,&failed,&error)==STELA_AMD_AIR_INVALID&&!failed);
|
||||
bad_request=request;bad_request.count=0;
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&bad_request,&failed,&error)==STELA_AMD_AIR_UNSUPPORTED&&!failed);
|
||||
bad_request=request;
|
||||
struct stela_metal_threadgroup_request_row bad_rows[AIR_MAX_ARGUMENTS];memcpy(bad_rows,rows,sizeof(rows));
|
||||
bad_request.rows=bad_rows;bad_rows[0].bytes=0;
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&bad_request,&failed,&error)==STELA_AMD_AIR_UNSUPPORTED&&!failed);
|
||||
bad_rows[0].bytes=UINT64_C(0x100000000);
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&bad_request,&failed,&error)==STELA_AMD_AIR_LIMIT&&!failed);
|
||||
#ifdef STELA_AMD_AIR_ALLOC_TEST
|
||||
unsigned baseline=live_allocations;
|
||||
bad_request=request;
|
||||
for(unsigned fail=1;fail<=(3);fail++) {
|
||||
allocations=0;fail_allocation=fail;
|
||||
CHECK(stela_amd_air_compile_specialized(&info,library,0,&opts,&bad_request,&failed,&error)==STELA_AMD_AIR_ALLOCATION&&!failed&&live_allocations==baseline);
|
||||
}
|
||||
fail_allocation=0;
|
||||
#endif
|
||||
}
|
||||
CHECK(p->threadgroup.count==request.count&&stela_metal_threadgroup_matches(&p->threadgroup,&request));
|
||||
struct stela_metal_threadgroup_request_row saved[AIR_MAX_ARGUMENTS];memcpy(saved,rows,sizeof(rows));
|
||||
rows[0].bytes+=16;CHECK(!stela_metal_threadgroup_matches(&p->threadgroup,&request));
|
||||
memset(rows,0,sizeof(rows));
|
||||
CHECK(p->threadgroup.bindings[0].bytes&&p->threadgroup.bindings[0].alignment>=16);
|
||||
memcpy(rows,saved,sizeof(rows));CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request));
|
||||
validate_result(&info,owner,"dispatch-threadgroup-specialization");
|
||||
printf("owned-threadgroup-aco target=%s.wave%u count=%u total_shared=%u",ac_get_family_name(info.family),wave,
|
||||
p->threadgroup.count,stela_amd_air_binary(owner)->shader->info.shared_size);
|
||||
for(unsigned r=0;r<p->threadgroup.count;r++)printf(" row=%u:%u:%llu:%u",p->threadgroup.bindings[r].buffer.argument,
|
||||
p->threadgroup.bindings[r].buffer.index,(unsigned long long)p->threadgroup.bindings[r].bytes,p->threadgroup.bindings[r].alignment);
|
||||
puts("");
|
||||
CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request));destroy(&owner);
|
||||
}
|
||||
}
|
||||
stela_metal_assembly_destroy(&library);
|
||||
}
|
||||
static void shared_refusal(int argc, char **argv)
|
||||
{
|
||||
CHECK(argc == 4);
|
||||
struct bytes air = read_file(argv[2]); struct input_facts f = {.name = argv[3]}; struct stela_air_error air_error;
|
||||
CHECK(stela_air_inspect(air.data, air.size, 256, facts, &f, &air_error) && f.found);
|
||||
struct bytes bytes = archive(air.data, air.size, f.name, f.air_minor, f.major, f.minor, f.os_major, f.os_minor);
|
||||
struct stela_metal_assembly_options opts = stela_metal_assembly_default_options();
|
||||
struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL;
|
||||
enum stela_metal_assembly_status status = stela_metal_assemble_archive(&opts, bytes.data, bytes.size, &library, &error);
|
||||
if (status == STELA_METAL_ASSEMBLY_OK) {
|
||||
struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options compile_options = options(32);
|
||||
CHECK(!compile(&info, library, &compile_options, STELA_AMD_AIR_UNSUPPORTED));
|
||||
puts("shared input explicitly refused: dynamic AS3 dispatch specialization unavailable");
|
||||
} else {
|
||||
CHECK(status == STELA_METAL_ASSEMBLY_REFLECTION && !library);
|
||||
puts("shared input explicitly refused: canonical reflection incomplete");
|
||||
}
|
||||
stela_metal_assembly_destroy(&library); free(bytes.data); free(air.data);
|
||||
}
|
||||
#ifdef STELA_AMD_AIR_CAPTURE_TEST
|
||||
/* Deliberately invalid borrowed backend-output records, confined to this
|
||||
* separately linked rejection test. No successful fake binary is published. */
|
||||
static unsigned bad_capture;
|
||||
void stela_amd_air_bad_backend(const struct aco_compiler_options *options,
|
||||
const struct aco_shader_info *info, unsigned count, nir_shader *const *shaders,
|
||||
const struct ac_shader_args *args, aco_callback *callback, void **private);
|
||||
void stela_amd_air_bad_backend(const struct aco_compiler_options *options,
|
||||
const struct aco_shader_info *info, unsigned count, nir_shader *const *shaders,
|
||||
const struct ac_shader_args *args, aco_callback *callback, void **private)
|
||||
{
|
||||
(void)options; (void)info; (void)count; (void)shaders; (void)args;
|
||||
struct ac_shader_config config = {.num_vgprs = 8, .num_sgprs = 8};
|
||||
const uint32_t invalid_test_bytes[2] = {0, 0};
|
||||
callback(private, bad_capture == 0 ? NULL : &config, NULL, 0, NULL, 0, NULL,
|
||||
bad_capture == 2 ? 0 : bad_capture == 4 ? 12 : bad_capture == 5 ? 3 : 4,
|
||||
bad_capture == 1 ? NULL : invalid_test_bytes,
|
||||
bad_capture == 3 ? UINT32_MAX : 2, NULL, bad_capture == 6 ? 1 : 0, NULL, 0);
|
||||
if (bad_capture == 7) callback(private, &config, NULL, 0, NULL, 0, NULL, 4,
|
||||
invalid_test_bytes, 2, NULL, 0, NULL, 0);
|
||||
}
|
||||
static void invalid_capture_tests(void)
|
||||
{
|
||||
LLVMMemoryBufferRef air = stela_air_test_bitcode(stela_air_test_store_body, "");
|
||||
struct stela_metal_assembly *library = fixture(air); LLVMDisposeMemoryBuffer(air);
|
||||
struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options opts = options(32);
|
||||
for (bad_capture = 0; bad_capture < 8; bad_capture++) {
|
||||
CHECK(!compile(&info, library, &opts,
|
||||
bad_capture == 6 ? STELA_AMD_AIR_UNSUPPORTED : STELA_AMD_AIR_BACKEND));
|
||||
}
|
||||
stela_metal_assembly_destroy(&library);
|
||||
puts("invalid borrowed backend-output records refused atomically; no fake code published");
|
||||
}
|
||||
#endif
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
#ifdef STELA_AMD_AIR_CAPTURE_TEST
|
||||
(void)argc; (void)argv; invalid_capture_tests();
|
||||
#else
|
||||
if (argc == 1) original_tests();
|
||||
else if (!strcmp(argv[1], "--input")) real_input(argc, argv);
|
||||
else if (!strcmp(argv[1], "--source")) source_input(argc, argv);
|
||||
else if(!strcmp(argv[1],"--threadgroup"))threadgroup_input(argc,argv);
|
||||
else if (!strcmp(argv[1], "--shared-refusal")) shared_refusal(argc, argv);
|
||||
else CHECK(false);
|
||||
#endif
|
||||
#ifdef STELA_AMD_AIR_ALLOC_TEST
|
||||
CHECK(!live_allocations);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
@@ -333,6 +333,11 @@ test_compiled_target(enum radeon_family family, unsigned wave, bool llvm_backend
|
||||
assert(register_word(words, written, R_00B900_COMPUTE_USER_DATA_0) == result.user_sgprs[0]);
|
||||
|
||||
const struct stela_amd_compute_pipeline preserved = result;
|
||||
/* A zero-binding pipeline cannot discard the real shader's address ABI. */
|
||||
assert(stela_amd_build_compute_pipeline(&info, &binary, &code, NULL, 0, &result) != STELA_AMD_COMPUTE_OK);
|
||||
assert(!memcmp(&result, &preserved, sizeof(result)));
|
||||
assert(stela_amd_build_compute_pipeline(&info, &binary, &code, NULL, 1, &result) == STELA_AMD_COMPUTE_INVALID);
|
||||
assert(!memcmp(&result, &preserved, sizeof(result)));
|
||||
struct stela_amd_compute_binary wrong_target = binary;
|
||||
wrong_target.family = CHIP_UNKNOWN;
|
||||
assert(stela_amd_build_compute_pipeline(&info, &wrong_target, &code, &binding, 1, &result) ==
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Child of the single-authority canonical test, with bounded generated C
|
||||
//! leaf-I/O instrumentation. No physical GPU or production provider is used.
|
||||
use super::native_mmio;
|
||||
use super::*;
|
||||
#[path = "../discovery.rs"]
|
||||
mod discovery;
|
||||
#[path = "../vram.rs"]
|
||||
mod vram;
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_tmr_fixture(size: &mut usize) -> *const u8;
|
||||
fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize);
|
||||
fn stela_amd_tmr_model_accesses() -> u32;
|
||||
fn stela_amd_tmr_model_delay();
|
||||
fn stela_amd_tmr_model_vf();
|
||||
fn stela_amd_tmr_model_system();
|
||||
fn stela_amd_tmr_model_corrupt();
|
||||
fn stela_amd_tmr_model_end();
|
||||
}
|
||||
pub(super) fn acquire_snapshot(authority: &Authority, pci: &Function<Config>) {
|
||||
let (resource, drops) = resource(0x1200_0000, 0x60000, ResourceKind::Registers);
|
||||
// SAFETY: isolated canonical RAM-only model, no physical state asserted.
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach(
|
||||
authority,
|
||||
pci,
|
||||
asic(2),
|
||||
asic(2),
|
||||
RegisterBar { index: 5, resource },
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let window = bars.registers().unwrap();
|
||||
let clock = stela_drivers::Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
};
|
||||
let mut bytes = 0;
|
||||
// SAFETY: actual immutable static CPU fixture, existing bounded generator.
|
||||
let source = unsafe { stela_amd_tmr_fixture(&mut bytes) };
|
||||
let begin = || unsafe {
|
||||
stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, bytes)
|
||||
};
|
||||
begin();
|
||||
// Exercise the actual C-to-Rust elapsed-time callback once. This CPU
|
||||
// model does not qualify calibration, scheduler sleep or physical timing.
|
||||
unsafe { stela_amd_tmr_model_delay() };
|
||||
// SAFETY: production acquisition runs only the instrumented CPU fixture path;
|
||||
// actual original algorithms execute with canonical model ownership/lifetime.
|
||||
let snapshot = unsafe { discovery::acquire(&bars, &clock) }.unwrap();
|
||||
assert_eq!(snapshot.bytes(), unsafe {
|
||||
core::slice::from_raw_parts(source, bytes)
|
||||
});
|
||||
assert_eq!(snapshot.identity(), bars.identity());
|
||||
assert_eq!(snapshot.vram_bytes(), 64 << 20);
|
||||
assert_eq!(snapshot.vram_offset(), (64 << 20) - 65536);
|
||||
assert!(unsafe { stela_amd_tmr_model_accesses() } > bytes as u32 / 4);
|
||||
drop(snapshot);
|
||||
begin();
|
||||
unsafe { stela_amd_tmr_model_corrupt() };
|
||||
assert!(matches!(
|
||||
unsafe { discovery::acquire(&bars, &clock) },
|
||||
Err(discovery::Error::Validation(_))
|
||||
));
|
||||
begin();
|
||||
allocation_failure::arm();
|
||||
// SAFETY: same controlled CPU fixture; only snapshot Vec allocation fails.
|
||||
let failed = unsafe { discovery::acquire(&bars, &clock) };
|
||||
let consumed = allocation_failure::disarm();
|
||||
assert!(consumed);
|
||||
assert!(matches!(failed, Err(discovery::Error::PostQueryAllocation)));
|
||||
assert!(unsafe { stela_amd_tmr_model_accesses() } > 0);
|
||||
begin();
|
||||
// SAFETY: zero clock is rejected before the actual query sees any register.
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
discovery::acquire(
|
||||
&bars,
|
||||
&stela_drivers::Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(discovery::Error::ClockUnavailable)
|
||||
));
|
||||
assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0);
|
||||
unsafe { stela_amd_tmr_model_vf() };
|
||||
assert!(matches!(
|
||||
unsafe { discovery::acquire(&bars, &clock) },
|
||||
Err(discovery::Error::VfOwnerUnavailable)
|
||||
));
|
||||
begin();
|
||||
unsafe { stela_amd_tmr_model_system() };
|
||||
assert!(matches!(
|
||||
unsafe { discovery::acquire(&bars, &clock) },
|
||||
Err(discovery::Error::SystemFirmwareOwnerUnavailable)
|
||||
));
|
||||
unsafe { stela_amd_tmr_model_end() };
|
||||
drop(window);
|
||||
// SAFETY: all CPU-only fixture accesses/views have ended before retirement.
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 1);
|
||||
println!(
|
||||
"AMD TMR Rust/C: full retained validated snapshot equality, actual identity/extent, pre-I/O clock refusal, missing VF/sysmem owners; generated leaf-I/O RAM model only"
|
||||
);
|
||||
}
|
||||
|
||||
// Test-only System wrapper: arm exactly the current test thread's next
|
||||
// allocation. It does not replace any production allocator/service.
|
||||
mod allocation_failure {
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
thread_local! { static ARMED: Cell<bool> = const { Cell::new(false) }; }
|
||||
thread_local! { static CONSUMED: Cell<bool> = const { Cell::new(false) }; }
|
||||
struct FaultAllocator;
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: FaultAllocator = FaultAllocator;
|
||||
// SAFETY: exact System delegation except the explicit valid null OOM
|
||||
// response; TLS access is allocation-free and bounded to this test thread.
|
||||
unsafe impl GlobalAlloc for FaultAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
if ARMED.try_with(|v| v.replace(false)).unwrap_or(false) {
|
||||
let _ = CONSUMED.try_with(|v| v.set(true));
|
||||
core::ptr::null_mut()
|
||||
} else {
|
||||
// SAFETY: unchanged allocator request supplied by Rust.
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
// SAFETY: exact System allocation and original layout from Rust.
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
}
|
||||
pub fn arm() {
|
||||
CONSUMED.with(|v| v.set(false));
|
||||
ARMED.with(|v| v.set(true));
|
||||
}
|
||||
pub fn disarm() -> bool {
|
||||
ARMED.with(|v| v.set(false));
|
||||
CONSUMED.with(Cell::get)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* CPU-only original-driver metadata fixtures; no device or acquisition hooks. */
|
||||
#include "../stela/discovery_binary.h"
|
||||
#include "../amdgpu/amdgpu_ip_limits.h"
|
||||
#include "../include/soc15_hw_ip.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static void reference_log(void *device, const char *format, ...)
|
||||
{
|
||||
(void)device;
|
||||
(void)format;
|
||||
}
|
||||
|
||||
/* Original Linux donors intentionally retain signed comparisons. Their native
|
||||
* tests use Linux's signed-overflow policy (-fwrapv), not a rewritten policy. */
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wsign-compare"
|
||||
#include "discovery_reference.h"
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
struct fixture {
|
||||
uint8_t binary[8192];
|
||||
size_t size, directory, offset[TOTAL_TABLES], length[TOTAL_TABLES];
|
||||
unsigned version, dies, wide;
|
||||
};
|
||||
static unsigned comparisons, mutations, accepted_mutations, official;
|
||||
static void put16(void *p, uint16_t value)
|
||||
{
|
||||
uint8_t *bytes = p;
|
||||
bytes[0] = value;
|
||||
bytes[1] = value >> 8;
|
||||
}
|
||||
static void put32(void *p, uint32_t value)
|
||||
{
|
||||
uint8_t *bytes = p;
|
||||
for (unsigned i = 0; i < 4; i++)
|
||||
bytes[i] = value >> (i * 8);
|
||||
}
|
||||
static void put64(void *p, uint64_t value)
|
||||
{
|
||||
put32(p, value);
|
||||
put32((uint8_t *)p + 4, value >> 32);
|
||||
}
|
||||
static struct table_info *directory_entry(struct fixture *f, unsigned id)
|
||||
{
|
||||
return (void *)(f->binary + f->directory + id * sizeof(struct table_info));
|
||||
}
|
||||
static void checksums(struct fixture *f)
|
||||
{
|
||||
for (unsigned i = 0; i < TOTAL_TABLES; i++) {
|
||||
if (f->length[i]) {
|
||||
struct table_info *entry = directory_entry(f, i);
|
||||
put16(&entry->checksum, donor_checksum(f->binary + f->offset[i], f->length[i]));
|
||||
}
|
||||
}
|
||||
struct binary_header *h = (void *)f->binary;
|
||||
size_t start = offsetof(struct binary_header, binary_checksum) + sizeof(h->binary_checksum);
|
||||
put16(&h->binary_checksum, donor_checksum(f->binary + start, f->size - start));
|
||||
}
|
||||
static void declare_table(struct fixture *f, unsigned id, size_t bytes)
|
||||
{
|
||||
f->size = (f->size + 3) & ~(size_t)3;
|
||||
assert(f->size + bytes <= sizeof(f->binary));
|
||||
f->offset[id] = f->size;
|
||||
f->length[id] = bytes;
|
||||
struct table_info *entry = directory_entry(f, id);
|
||||
put16(&entry->offset, f->size);
|
||||
put16(&entry->size, bytes);
|
||||
f->size += bytes;
|
||||
}
|
||||
static size_t gfx_bytes(unsigned major, unsigned minor)
|
||||
{
|
||||
if (major == 1)
|
||||
return minor >= 3 ? sizeof(struct gc_info_v1_3) :
|
||||
minor == 2 ? sizeof(struct gc_info_v1_2) :
|
||||
minor == 1 ? sizeof(struct gc_info_v1_1) : sizeof(struct gc_info_v1_0);
|
||||
return minor == 1 ? sizeof(struct gc_info_v2_1) : sizeof(struct gc_info_v2_0);
|
||||
}
|
||||
static struct fixture make_fixture(unsigned version, unsigned ip_version, unsigned wide,
|
||||
unsigned gc_major, unsigned gc_minor, unsigned variant)
|
||||
{
|
||||
struct fixture f = {.version = version, .dies = 2, .wide = wide};
|
||||
f.directory = version == 2 ? offsetof(struct binary_header_v2, table_list) :
|
||||
offsetof(struct binary_header, table_list);
|
||||
f.size = f.directory + TOTAL_TABLES * sizeof(struct table_info);
|
||||
struct binary_header *header = (void *)f.binary;
|
||||
put32(&header->binary_signature, BINARY_SIGNATURE);
|
||||
put16(&header->version_major, version);
|
||||
if (version == 2)
|
||||
put16(&((struct binary_header_v2 *)header)->num_tables, TOTAL_TABLES);
|
||||
struct { unsigned hwid, instance, bases, revision; } ips[] = {
|
||||
{GC_HWID, 0, 4, 3}, {SDMA0_HWID, 0, 3, 1}, {SDMA1_HWID, 3, 2, 1},
|
||||
{VCN_HWID, 0, 2, 0x42}, {VCN_HWID, 1, 1, 0x82},
|
||||
{UMC_HWID, 0, 1, 1}, {UMC_HWID, 3, 2, 1}, {DMU_HWID, 0, 1, 1},
|
||||
{WAFLC_HWID, 0, 2, 5}, {HW_ID_MAX + 1, 1, 3, 1}, {GC_HWID, 255, 0, 1},
|
||||
};
|
||||
size_t ip_bytes = 0;
|
||||
for (unsigned i = 0; i < sizeof(ips) / sizeof(ips[0]); i++)
|
||||
ip_bytes += offsetof(struct ip_v4, base_address) + ips[i].bases * (wide ? 8 : 4);
|
||||
declare_table(&f, IP_DISCOVERY, sizeof(struct ip_discovery_header) +
|
||||
f.dies * (sizeof(struct die_header) + ip_bytes));
|
||||
struct ip_discovery_header *ip_header = (void *)(f.binary + f.offset[IP_DISCOVERY]);
|
||||
put32(&ip_header->signature, DISCOVERY_TABLE_SIGNATURE);
|
||||
put16(&ip_header->version, ip_version);
|
||||
put16(&ip_header->size, f.length[IP_DISCOVERY]);
|
||||
put16(&ip_header->num_dies, f.dies);
|
||||
ip_header->base_addr_64_bit = wide;
|
||||
size_t at = f.offset[IP_DISCOVERY] + sizeof(*ip_header);
|
||||
for (unsigned d = 0; d < f.dies; d++) {
|
||||
put16(&ip_header->die_info[d].die_id, d);
|
||||
put16(&ip_header->die_info[d].die_offset, at);
|
||||
struct die_header *die = (void *)(f.binary + at);
|
||||
put16(&die->die_id, d);
|
||||
put16(&die->num_ips, sizeof(ips) / sizeof(ips[0]));
|
||||
at += sizeof(*die);
|
||||
for (unsigned i = 0; i < sizeof(ips) / sizeof(ips[0]); i++) {
|
||||
struct ip_v4 *ip = (void *)(f.binary + at);
|
||||
put16(&ip->hw_id, ips[i].hwid);
|
||||
ip->instance_number = ips[i].instance;
|
||||
ip->num_base_address = ips[i].bases;
|
||||
ip->major = i == 0 ? 9 : 4;
|
||||
ip->minor = d;
|
||||
ip->revision = ips[i].revision;
|
||||
ip->variant = ip_version >= 3 ? 2 : 0;
|
||||
ip->sub_revision = ip_version >= 3 ? 3 : 1; /* Original harvest nibble. */
|
||||
for (unsigned k = 0; k < ips[i].bases; k++) {
|
||||
uint64_t address = 0xc0000100u + d * 0x4000 + i * 0x100 + k * 0x10;
|
||||
if (wide)
|
||||
put64(&ip->base_address_64[k], UINT64_C(0xabcde00000000) | address);
|
||||
else
|
||||
put32(&ip->base_address[k], address);
|
||||
}
|
||||
at += offsetof(struct ip_v4, base_address) + ips[i].bases * (wide ? 8 : 4);
|
||||
}
|
||||
}
|
||||
declare_table(&f, GC, gfx_bytes(gc_major, gc_minor));
|
||||
struct gpu_info_header *gc = (void *)(f.binary + f.offset[GC]);
|
||||
put32(&gc->table_id, GC_TABLE_ID);
|
||||
put16(&gc->version_major, gc_major);
|
||||
put16(&gc->version_minor, gc_minor);
|
||||
put32(&gc->size, f.length[GC]);
|
||||
for (size_t i = sizeof(*gc); i < f.length[GC]; i += 4)
|
||||
put32((uint8_t *)gc + i, 4 + i / 4);
|
||||
declare_table(&f, HARVEST_INFO, sizeof(struct harvest_table));
|
||||
struct harvest_table *harvest = (void *)(f.binary + f.offset[HARVEST_INFO]);
|
||||
put32(&harvest->header.signature, HARVEST_TABLE_SIGNATURE);
|
||||
put16(&harvest->list[0].hw_id, VCN_HWID);
|
||||
harvest->list[0].number_instance = 1;
|
||||
put16(&harvest->list[1].hw_id, UMC_HWID);
|
||||
harvest->list[1].number_instance = 3;
|
||||
declare_table(&f, VCN_INFO, sizeof(struct vcn_info_v1_0));
|
||||
struct vcn_info_v1_0 *vcn = (void *)(f.binary + f.offset[VCN_INFO]);
|
||||
put32(&vcn->header.table_id, VCN_INFO_TABLE_ID);
|
||||
put16(&vcn->header.version_major, 1);
|
||||
put32(&vcn->header.size_bytes, f.length[VCN_INFO]);
|
||||
put32(&vcn->num_of_instances, 4);
|
||||
for (unsigned i = 0; i < VCN_INFO_TABLE_MAX_NUM_INSTANCES; i++)
|
||||
put32(&vcn->instance_info[i].fuse_data.all_bits, i + 1);
|
||||
declare_table(&f, MALL_INFO, sizeof(struct mall_info_v1_0));
|
||||
struct mall_info_v1_0 *mall = (void *)(f.binary + f.offset[MALL_INFO]);
|
||||
put32(&mall->header.table_id, MALL_INFO_TABLE_ID);
|
||||
put16(&mall->header.version_major, 1 + (variant & 1));
|
||||
put32(&mall->header.size_bytes, f.length[MALL_INFO]);
|
||||
put32(&mall->mall_size_per_m, 1024);
|
||||
put32(&mall->m_s_present, 1);
|
||||
put32(&mall->m_half_use, 2);
|
||||
declare_table(&f, NPS_INFO, sizeof(struct nps_info_v1_0));
|
||||
struct nps_info_v1_0 *nps = (void *)(f.binary + f.offset[NPS_INFO]);
|
||||
put32(&nps->header.table_id, NPS_INFO_TABLE_ID);
|
||||
put16(&nps->header.version_major, 1);
|
||||
put32(&nps->header.size_bytes, f.length[NPS_INFO]);
|
||||
put32(&nps->count, 2);
|
||||
put64(&nps->instance_info[0].base_address, 0x1000);
|
||||
put64(&nps->instance_info[0].limit_address, 0x1fff);
|
||||
put64(&nps->instance_info[1].base_address, 0x4000);
|
||||
put64(&nps->instance_info[1].limit_address, 0x8fff);
|
||||
put16(&header->binary_size, f.size);
|
||||
checksums(&f);
|
||||
return f;
|
||||
}
|
||||
|
||||
static void normalize(struct amdgpu_device *device)
|
||||
{
|
||||
for (unsigned ip = 0; ip < MAX_HWIP; ip++) {
|
||||
for (unsigned i = 0; i < HWIP_MAX_INSTANCE; i++) {
|
||||
if (device->reg_offset[ip][i]) {
|
||||
size_t offset = (uint8_t *)device->reg_offset[ip][i] - device->discovery.bin;
|
||||
device->reg_offset[ip][i] = (void *)(uintptr_t)(offset + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
device->discovery.bin = NULL;
|
||||
}
|
||||
static void compare_original(const uint8_t *binary, size_t bytes)
|
||||
{
|
||||
uint8_t *left = malloc(bytes), *right = malloc(bytes);
|
||||
assert(left && right);
|
||||
memcpy(left, binary, bytes);
|
||||
memcpy(right, binary, bytes);
|
||||
struct amdgpu_device old, next;
|
||||
memset(&old, 0, sizeof(old));
|
||||
memset(&next, 0, sizeof(next));
|
||||
old.discovery.bin = left;
|
||||
next.discovery.bin = right;
|
||||
old.discovery.size = next.discovery.size = bytes;
|
||||
checked = 0;
|
||||
assert(!reference_validation(&old));
|
||||
checked = 1;
|
||||
assert(!reference_validation(&next));
|
||||
checked = 0;
|
||||
assert(!amdgpu_discovery_reg_base_init(&old));
|
||||
checked = 1;
|
||||
assert(!amdgpu_discovery_reg_base_init(&next));
|
||||
checked = 0;
|
||||
int gfx = amdgpu_discovery_get_gfx_info(&old);
|
||||
int mall = amdgpu_discovery_get_mall_info(&old);
|
||||
int vcn = amdgpu_discovery_get_vcn_info(&old);
|
||||
checked = 1;
|
||||
assert(gfx == amdgpu_discovery_get_gfx_info(&next));
|
||||
assert(mall == amdgpu_discovery_get_mall_info(&next));
|
||||
assert(vcn == amdgpu_discovery_get_vcn_info(&next));
|
||||
unsigned left_count = 0, right_count = 0, left_umc = 0, right_umc = 0;
|
||||
checked = 0;
|
||||
amdgpu_discovery_read_from_harvest_table(&old, &left_count, &left_umc);
|
||||
checked = 1;
|
||||
amdgpu_discovery_read_from_harvest_table(&next, &right_count, &right_umc);
|
||||
assert(left_count == right_count && left_umc == right_umc);
|
||||
struct amdgpu_gmc_memrange old_ranges[NPS_INFO_TABLE_MAX_NUM_INSTANCES];
|
||||
struct amdgpu_gmc_memrange next_ranges[NPS_INFO_TABLE_MAX_NUM_INSTANCES];
|
||||
memset(old_ranges, 0x5a, sizeof(old_ranges));
|
||||
memset(next_ranges, 0x5a, sizeof(next_ranges));
|
||||
uint32_t old_type = UINT32_MAX, next_type = UINT32_MAX;
|
||||
int old_count = NPS_INFO_TABLE_MAX_NUM_INSTANCES, next_count = old_count;
|
||||
checked = 0;
|
||||
int nps = amdgpu_discovery_get_nps_info(&old, &old_type, old_ranges, &old_count, false);
|
||||
checked = 1;
|
||||
assert(nps == amdgpu_discovery_get_nps_info(&next, &next_type, next_ranges, &next_count, false));
|
||||
assert(old_type == next_type && old_count == next_count);
|
||||
assert(!memcmp(old_ranges, next_ranges, sizeof(old_ranges)));
|
||||
assert(!memcmp(left, right, bytes));
|
||||
normalize(&old);
|
||||
normalize(&next);
|
||||
assert(!memcmp(&old, &next, sizeof(old)));
|
||||
free(left);
|
||||
free(right);
|
||||
comparisons++;
|
||||
}
|
||||
static void harvest_lookup(void)
|
||||
{
|
||||
for (unsigned version = 0; version <= 2; version++) {
|
||||
struct fixture f = make_fixture(version, 2, 0, 1, 0, 0);
|
||||
uint8_t old_bytes[sizeof(f.binary)], next_bytes[sizeof(f.binary)];
|
||||
memcpy(old_bytes, f.binary, sizeof(old_bytes));
|
||||
memcpy(next_bytes, f.binary, sizeof(next_bytes));
|
||||
struct amdgpu_device old, next;
|
||||
memset(&old, 0, sizeof(old));
|
||||
memset(&next, 0, sizeof(next));
|
||||
old.discovery.bin = old_bytes;
|
||||
next.discovery.bin = next_bytes;
|
||||
old.discovery.size = next.discovery.size = f.size;
|
||||
checked = 0;
|
||||
assert(!amdgpu_discovery_reg_base_init(&old));
|
||||
checked = 1;
|
||||
assert(!amdgpu_discovery_reg_base_init(&next));
|
||||
uint32_t count = 0;
|
||||
checked_harvest(&next, &count);
|
||||
assert(count == 4);
|
||||
assert(next.vcn.harvest_config == 3 && next.vcn.inst_mask == 0);
|
||||
assert(next.jpeg.inst_mask == 0 && next.harvest_ip_mask == AMD_HARVEST_IP_DMU_MASK);
|
||||
if (version < 2) {
|
||||
uint32_t old_count = 0;
|
||||
checked = 0;
|
||||
amdgpu_discovery_read_harvest_bit_per_ip(&old, &old_count);
|
||||
assert(old_count == count);
|
||||
normalize(&old);
|
||||
normalize(&next);
|
||||
assert(!memcmp(&old, &next, sizeof(old)));
|
||||
} else {
|
||||
/* Explicit corrected behavior: the old fixed directory would choose
|
||||
* offset6 (num_tables), not this valid v2 IP offset64. Never execute
|
||||
* that unsafe old walk as a successful native result. */
|
||||
const struct binary_header *fixed = (const void *)f.binary;
|
||||
assert(fixed->table_list[IP_DISCOVERY].offset == TOTAL_TABLES);
|
||||
assert(fixed->table_list[IP_DISCOVERY].offset != f.offset[IP_DISCOVERY]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void boundary_layouts(void)
|
||||
{
|
||||
struct fixture f = make_fixture(2, 4, 1, 2, 1, 1);
|
||||
struct ip_discovery_header *ip = (void *)(f.binary + f.offset[IP_DISCOVERY]);
|
||||
put16(&ip->num_dies, 16);
|
||||
size_t at = f.offset[IP_DISCOVERY] + sizeof(*ip);
|
||||
for (unsigned i = 0; i < 16; i++) {
|
||||
put16(&ip->die_info[i].die_id, i);
|
||||
put16(&ip->die_info[i].die_offset, at);
|
||||
struct die_header *die = (void *)(f.binary + at);
|
||||
put16(&die->die_id, i);
|
||||
put16(&die->num_ips, 0);
|
||||
at += sizeof(*die);
|
||||
}
|
||||
checksums(&f);
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
compare_original(f.binary, f.size);
|
||||
put16(&ip->num_dies, 0);
|
||||
checksums(&f);
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
compare_original(f.binary, f.size);
|
||||
put16(&ip->num_dies, 1);
|
||||
struct die_header *die = (void *)(f.binary + ip->die_info[0].die_offset);
|
||||
put16(&die->num_ips, 63);
|
||||
at = ip->die_info[0].die_offset + sizeof(*die);
|
||||
for (unsigned i = 0; i < 64; i++) {
|
||||
struct ip_v4 *entry = (void *)(f.binary + at);
|
||||
memset(entry, 0, offsetof(struct ip_v4, base_address));
|
||||
put16(&entry->hw_id, UMC_HWID);
|
||||
entry->instance_number = i % HWIP_MAX_INSTANCE;
|
||||
at += offsetof(struct ip_v4, base_address);
|
||||
}
|
||||
checksums(&f);
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
compare_original(f.binary, f.size);
|
||||
put16(&die->num_ips, 64);
|
||||
checksums(&f);
|
||||
assert(amdgpu_discovery_binary_validate(f.binary, f.size) == AMDGPU_DISCOVERY_BINARY_INVALID);
|
||||
mutations++;
|
||||
/* Five real v2 directory entries are sufficient for original initialization;
|
||||
* optional NPS directory access is now bounded instead of indexing past it. */
|
||||
f = make_fixture(2, 4, 0, 1, 0, 0);
|
||||
put16(&((struct binary_header_v2 *)f.binary)->num_tables, 5);
|
||||
checksums(&f);
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
assert(!amdgpu_discovery_binary_table(f.binary, f.size, NPS_INFO));
|
||||
}
|
||||
|
||||
static void refused(struct fixture *f)
|
||||
{
|
||||
uint8_t saved[sizeof(f->binary)];
|
||||
memcpy(saved, f->binary, sizeof(saved));
|
||||
assert(amdgpu_discovery_binary_validate(f->binary, f->size) != AMDGPU_DISCOVERY_BINARY_OK);
|
||||
assert(!memcmp(saved, f->binary, sizeof(saved)));
|
||||
mutations++;
|
||||
}
|
||||
static void malformed(void)
|
||||
{
|
||||
const struct fixture good = make_fixture(2, 4, 1, 1, 3, 0);
|
||||
struct fixture f;
|
||||
for (size_t bytes = 0; bytes < good.size; bytes++) {
|
||||
uint8_t *shortened = malloc(bytes ? bytes : 1);
|
||||
assert(shortened);
|
||||
memcpy(shortened, good.binary, bytes);
|
||||
assert(amdgpu_discovery_binary_validate(shortened, bytes));
|
||||
free(shortened);
|
||||
mutations++;
|
||||
}
|
||||
for (unsigned which = 0; which < 22; which++) {
|
||||
f = good;
|
||||
struct binary_header *header = (void *)f.binary;
|
||||
struct ip_discovery_header *ip = (void *)(f.binary + f.offset[IP_DISCOVERY]);
|
||||
struct die_header *die = (void *)(f.binary + ip->die_info[0].die_offset);
|
||||
struct ip_v4 *first = (void *)((uint8_t *)die + sizeof(*die));
|
||||
switch (which) {
|
||||
case 0: put16(&header->binary_size, 9); break;
|
||||
case 1: put16(&header->binary_size, UINT16_MAX); break;
|
||||
case 2: put16(&header->version_major, 3); break;
|
||||
case 3: put16(&((struct binary_header_v2 *)header)->num_tables, 4); break;
|
||||
case 4: put16(&((struct binary_header_v2 *)header)->num_tables, UINT16_MAX); break;
|
||||
case 5: put16(&directory_entry(&f, IP_DISCOVERY)->offset, 0); break;
|
||||
case 6: put16(&directory_entry(&f, IP_DISCOVERY)->offset, f.size - 1); break;
|
||||
case 7: put16(&ip->size, 79); break;
|
||||
case 8: put16(&ip->size, UINT16_MAX); break;
|
||||
case 9: put16(&ip->num_dies, 17); break;
|
||||
case 10: put16(&ip->die_info[0].die_offset, 1); break;
|
||||
case 11: put16(&ip->die_info[0].die_offset, f.size - 1); break;
|
||||
case 12: put16(&die->die_id, 3); break;
|
||||
case 13: put16(&die->num_ips, UINT16_MAX); break;
|
||||
case 14: first->num_base_address = 255; break;
|
||||
case 15: first->instance_number = 32; break;
|
||||
case 16: put16(&ip->version, 2); break;
|
||||
case 17: put32(f.binary + f.offset[GC] + offsetof(struct gc_info_v1_0, gc_num_sa_per_se), 0); break;
|
||||
case 18: put32(f.binary + f.offset[GC] + offsetof(struct gpu_info_header, size), UINT32_MAX); break;
|
||||
case 19: put32(f.binary + f.offset[VCN_INFO] + offsetof(struct vcn_info_header, size_bytes), 12); break;
|
||||
case 20: put32(f.binary + f.offset[NPS_INFO] + offsetof(struct nps_info_v1_0, count), 13); break;
|
||||
case 21: put16(&directory_entry(&f, GC)->offset, f.offset[IP_DISCOVERY]); break;
|
||||
}
|
||||
checksums(&f); /* Uses only builder-owned original spans, never mutated offsets. */
|
||||
refused(&f);
|
||||
}
|
||||
assert(amdgpu_discovery_binary_validate(NULL, 0) == AMDGPU_DISCOVERY_BINARY_INVALID);
|
||||
/* Optional integrity failures retain original nonfatal/lazy policy. */
|
||||
f = good;
|
||||
put16(&directory_entry(&f, NPS_INFO)->checksum, 0);
|
||||
size_t start = offsetof(struct binary_header, binary_checksum) + 2;
|
||||
put16(f.binary + offsetof(struct binary_header, binary_checksum),
|
||||
donor_checksum(f.binary + start, f.size - start));
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
compare_original(f.binary, f.size);
|
||||
/* Deterministic field/byte mutation with repaired original checksums. */
|
||||
for (unsigned i = 0; i < 4096; i++) {
|
||||
f = good;
|
||||
size_t at = (i * 127u + 37u) % f.size;
|
||||
f.binary[at] ^= 1u << (i % 8);
|
||||
checksums(&f);
|
||||
uint8_t saved[sizeof(f.binary)];
|
||||
memcpy(saved, f.binary, sizeof(saved));
|
||||
enum amdgpu_discovery_binary_status result = amdgpu_discovery_binary_validate(f.binary, f.size);
|
||||
assert(!memcmp(saved, f.binary, sizeof(saved)));
|
||||
if (!result) {
|
||||
compare_original(f.binary, f.size);
|
||||
accepted_mutations++;
|
||||
}
|
||||
mutations++;
|
||||
}
|
||||
}
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
for (unsigned binary = 0; binary <= 2; binary++) {
|
||||
for (unsigned layout = 1; layout <= 5; layout++) {
|
||||
for (unsigned gfx = 0; gfx < 8; gfx++) {
|
||||
for (unsigned variant = 0; variant < 2; variant++) {
|
||||
struct fixture f = make_fixture(binary, layout == 5 ? 4 : layout, layout == 5,
|
||||
gfx < 5 ? 1 : 2, gfx < 5 ? gfx : gfx - 5, variant);
|
||||
assert(!amdgpu_discovery_binary_validate(f.binary, f.size));
|
||||
compare_original(f.binary, f.size);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
harvest_lookup();
|
||||
boundary_layouts();
|
||||
malformed();
|
||||
for (int i = 1; i < argc; i++) {
|
||||
FILE *file = fopen(argv[i], "rb");
|
||||
assert(file);
|
||||
uint8_t bytes[UINT16_MAX + 1];
|
||||
size_t count = fread(bytes, 1, sizeof(bytes), file);
|
||||
assert(!ferror(file) && feof(file) && count < sizeof(bytes));
|
||||
assert(!fclose(file));
|
||||
assert(!amdgpu_discovery_binary_validate(bytes, count));
|
||||
compare_original(bytes, count);
|
||||
official++;
|
||||
}
|
||||
printf("AMD discovery: %u original consumer comparisons (%u external inputs), %u mutations/truncations (%u accepted); no hardware\n",
|
||||
comparisons, official, mutations, accepted_mutations);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Actual whole Linux file wrapper vs frozen guarded original. CPU only. */
|
||||
#include "../stela/discovery_file.h"
|
||||
#include "../amdgpu/amdgpu_discovery_file_core.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
typedef uint8_t u8;
|
||||
struct firmware { size_t size; const uint8_t *data; };
|
||||
struct amdgpu_device { void *dev; unsigned ddev; struct { uint32_t size; } discovery; };
|
||||
static struct firmware image;
|
||||
static int request_status, amdgpu_discovery;
|
||||
static char trace[8192];static size_t used;
|
||||
static unsigned comparisons;
|
||||
static void event(const char *format,...)
|
||||
{
|
||||
va_list a;va_start(a,format);int n=vsnprintf(trace+used,sizeof(trace)-used,format,a);va_end(a);
|
||||
assert(n>=0&&(size_t)n<sizeof(trace)-used);used+=(size_t)n;
|
||||
}
|
||||
static void log_error(void *device,const char *format,...)
|
||||
{
|
||||
(void)device;event("E:");va_list a;va_start(a,format);int n=vsnprintf(trace+used,sizeof(trace)-used,format,a);va_end(a);
|
||||
assert(n>=0&&(size_t)n<sizeof(trace)-used);used+=(size_t)n;
|
||||
}
|
||||
static void log_info(void *device,const char *format,...)
|
||||
{
|
||||
(void)device;event("I:");va_list a;va_start(a,format);int n=vsnprintf(trace+used,sizeof(trace)-used,format,a);va_end(a);
|
||||
assert(n>=0&&(size_t)n<sizeof(trace)-used);used+=(size_t)n;
|
||||
}
|
||||
#define dev_err(...) log_error(__VA_ARGS__)
|
||||
#define drm_info(...) log_info(__VA_ARGS__)
|
||||
static int firmware_request_nowarn(const struct firmware **out,const char *name,void *device)
|
||||
{
|
||||
(void)device;event("request:%s;",name);if(request_status)return request_status;*out=ℑreturn 0;
|
||||
}
|
||||
static void release_firmware(const struct firmware *firmware)
|
||||
{assert(firmware==&image);event("release;");}
|
||||
static void *copy_bytes(void *destination,const void *source,size_t bytes)
|
||||
{event("copy:%zu;",bytes);return memcpy(destination,source,bytes);}
|
||||
#undef memcpy
|
||||
#define memcpy copy_bytes
|
||||
#include "discovery_file_reference.h"
|
||||
#include "discovery-file-linux.inc"
|
||||
#undef memcpy
|
||||
size_t stela_amd_ip_fixture(uint8_t *,size_t,unsigned,unsigned,unsigned);
|
||||
static void compare(const uint8_t *data,size_t bytes,uint32_t capacity,int status,int option)
|
||||
{
|
||||
size_t allocation=capacity?capacity:1;uint8_t *a=malloc(allocation),*b=malloc(allocation);assert(a&&b);
|
||||
memset(a,0,allocation);memset(b,0,allocation);image=(struct firmware){bytes,data};
|
||||
request_status=status;amdgpu_discovery=option;
|
||||
struct amdgpu_device adev={.discovery={capacity}};
|
||||
used=0;trace[0]=0;int expected=original_read_file(&adev,a,"amdgpu/ip_discovery.bin");
|
||||
char saved[sizeof(trace)];memcpy(saved,trace,used+1);size_t saved_used=used;
|
||||
used=0;trace[0]=0;int actual=amdgpu_discovery_read_binary_from_file(&adev,b,"amdgpu/ip_discovery.bin");
|
||||
assert(expected==actual&&used==saved_used&&!memcmp(saved,trace,used+1));
|
||||
assert(!memcmp(a,b,allocation));
|
||||
if(expected)for(size_t i=0;i<allocation;i++)assert(a[i]==0);
|
||||
else {assert(bytes<=capacity&&!memcmp(a,data,bytes));for(size_t i=bytes;i<allocation;i++)assert(a[i]==0);}
|
||||
free(a);free(b);comparisons++;
|
||||
}
|
||||
static void exercise(const uint8_t *data,size_t bytes)
|
||||
{
|
||||
const uint32_t minimum=offsetof(struct binary_header,binary_size)+sizeof(((struct binary_header*)0)->binary_size);
|
||||
const uint32_t capacities[]={0,1,minimum-1,minimum,minimum+1,(uint32_t)bytes-1,(uint32_t)bytes,(uint32_t)bytes+1,65536};
|
||||
for(unsigned i=0;i<sizeof(capacities)/sizeof(*capacities);i++)
|
||||
for(int option=-1;option<=3;option++)for(int request=0;request<3;request++)
|
||||
compare(data,bytes,capacities[i],request==0?0:request==1?-ENOENT:-EIO,option);
|
||||
for(size_t cut=0;cut<bytes;cut++)compare(data,cut,(uint32_t)bytes,0,2);
|
||||
uint8_t *copy=malloc(bytes);assert(copy);memcpy(copy,data,bytes);
|
||||
for(size_t i=0;i<bytes;i+=17){copy[i]^=0xa5;compare(copy,bytes,(uint32_t)bytes,0,2);copy[i]^=0xa5;}
|
||||
free(copy);
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
uint8_t data[65536];
|
||||
for(unsigned version=0;version<=2;version++)for(unsigned wide=0;wide<2;wide++){
|
||||
size_t bytes=stela_amd_ip_fixture(data,sizeof(data),version,4,wide);exercise(data,bytes);
|
||||
}
|
||||
for(int n=1;n<argc;n++){
|
||||
FILE *f=fopen(argv[n],"rb");assert(f);size_t bytes=fread(data,1,sizeof(data),f);assert(bytes&&bytes<sizeof(data)&&feof(f));fclose(f);
|
||||
exercise(data,bytes);
|
||||
}
|
||||
assert(stela_amd_discovery_file_minimum()==offsetof(struct binary_header,binary_size)+sizeof(((struct binary_header*)0)->binary_size));
|
||||
assert(stela_amd_discovery_file_validate(NULL,0,0)==AMDGPU_DISCOVERY_FILE_TOO_SMALL);
|
||||
assert(stela_amd_discovery_file_validate(NULL,20,0)==AMDGPU_DISCOVERY_FILE_TOO_LARGE);
|
||||
assert(stela_amd_discovery_file_validate(NULL,20,20)==AMDGPU_DISCOVERY_FILE_INVALID);
|
||||
printf("AMD selected-file: %u whole original/current request/log/copy/release comparisons; actual extent/zero-tail/error atomicity; CPU only\n",comparisons);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Test-only original packed-header query, no parallel Rust wire format. */
|
||||
size_t stela_amd_file_fixture_declared(const uint8_t *source,size_t bytes)
|
||||
{
|
||||
assert(!amdgpu_discovery_binary_validate(source,bytes));
|
||||
const struct binary_header *header=(const void*)source;
|
||||
return header->binary_size;
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Separate generated same-authority CPU harness, using actual production Rust,
|
||||
//! canonical Catalog/Image and existing original MM leaf-I/O instrumentation.
|
||||
use super::*;
|
||||
use crate::{discovery, dynamic_ip_tests::allocation_failure, firmware, pci};
|
||||
use firmware::{Catalog, Provider};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cell::Cell;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_file_fixture_declared(source: *const u8, bytes: usize) -> usize;
|
||||
fn stela_amd_tmr_fixture(bytes: &mut usize) -> *const u8;
|
||||
fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize);
|
||||
fn stela_amd_tmr_model_accesses() -> u32;
|
||||
fn stela_amd_tmr_model_vf();
|
||||
fn stela_amd_tmr_model_system();
|
||||
fn stela_amd_tmr_model_end();
|
||||
fn stela_amd_ip_oracle(
|
||||
source: *const u8,
|
||||
bytes: usize,
|
||||
counts: &mut discovery::IpCounts,
|
||||
hwips: &mut u32,
|
||||
instances: &mut u32,
|
||||
);
|
||||
fn stela_amd_ip_oracle_fact(hwip: u32, instance: u32, segment: u32, kind: u32) -> u64;
|
||||
}
|
||||
struct FileConfig(u16);
|
||||
impl ConfigSpace for FileConfig {
|
||||
fn read32(&self, offset: u16) -> u32 {
|
||||
match offset {
|
||||
0 => (u32::from(self.0) << 16) | 0x1002,
|
||||
8 => 0x1200_0045,
|
||||
12 => 0,
|
||||
44 => 0x5678_abcd,
|
||||
_ => panic!("unexpected config read"),
|
||||
}
|
||||
}
|
||||
fn write32(&mut self, _: u16, _: u32) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
fn write16(&mut self, _: u16, _: u16) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
fn write8(&mut self, _: u16, _: u8) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
}
|
||||
fn policy(discovery: i32) -> pci::Policy {
|
||||
pci::Policy {
|
||||
si_built: true,
|
||||
cik_built: true,
|
||||
radeon_built: false,
|
||||
si_support: -1,
|
||||
cik_support: -1,
|
||||
experimental: 0,
|
||||
discovery,
|
||||
force_asic: -1,
|
||||
memory_encrypted: false,
|
||||
firmware_drivers_only: false,
|
||||
modeset: -1,
|
||||
}
|
||||
}
|
||||
fn file_function(device: u16) -> Function<FileConfig> {
|
||||
Function::new(
|
||||
Address {
|
||||
segment: 4,
|
||||
bus: 0x81,
|
||||
device: 3,
|
||||
function: 0,
|
||||
},
|
||||
FileConfig(device),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn make_catalog(request: &discovery::FileRequest<'_>, bytes: &[u8], member: &str) -> Catalog {
|
||||
Catalog::from_handoff(vec![firmware::Resource {
|
||||
name: request.name(),
|
||||
target: request.target(),
|
||||
provenance: firmware::Provenance {
|
||||
source: "original CPU fixture",
|
||||
revision: "immutable-input",
|
||||
member,
|
||||
license: "test-only",
|
||||
},
|
||||
expected_length: bytes.len(),
|
||||
expected_sha256: Sha256::digest(bytes).into(),
|
||||
bytes: bytes.to_vec(),
|
||||
}])
|
||||
.unwrap()
|
||||
}
|
||||
struct ObservedProvider<'a> {
|
||||
catalog: &'a Catalog,
|
||||
calls: Cell<u32>,
|
||||
alternate: Option<firmware::Requirement<'a>>,
|
||||
}
|
||||
impl Provider for ObservedProvider<'_> {
|
||||
fn load(
|
||||
&self,
|
||||
requirement: firmware::Requirement<'_>,
|
||||
) -> Result<firmware::Image<'_>, firmware::Error> {
|
||||
assert!(
|
||||
unsafe { stela_amd_tmr_model_accesses() } > 0,
|
||||
"provider before original TMR query"
|
||||
);
|
||||
self.calls.set(self.calls.get() + 1);
|
||||
self.catalog.load(self.alternate.unwrap_or(requirement))
|
||||
}
|
||||
}
|
||||
fn make_provider(catalog: &Catalog) -> ObservedProvider<'_> {
|
||||
ObservedProvider {
|
||||
catalog,
|
||||
calls: Cell::new(0),
|
||||
alternate: None,
|
||||
}
|
||||
}
|
||||
fn facts(ip: &discovery::FileIp<'_, '_>, bytes: &[u8]) {
|
||||
assert_eq!(&ip.acquired_bytes()[..bytes.len()], bytes);
|
||||
assert!(ip.acquired_bytes()[bytes.len()..].iter().all(|&v| v == 0));
|
||||
let mut expected = discovery::IpCounts::default();
|
||||
let (mut hwips, mut instances) = (0, 0);
|
||||
unsafe {
|
||||
stela_amd_ip_oracle(
|
||||
ip.acquired_bytes().as_ptr(),
|
||||
ip.acquired_bytes().len(),
|
||||
&mut expected,
|
||||
&mut hwips,
|
||||
&mut instances,
|
||||
)
|
||||
};
|
||||
assert_eq!(ip.counts(), expected);
|
||||
for hwip in 0..hwips {
|
||||
for instance in 0..instances {
|
||||
assert_eq!(
|
||||
ip.version(hwip, instance),
|
||||
Some(unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 0) } as u32)
|
||||
);
|
||||
let count = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 1) };
|
||||
if count == u64::MAX {
|
||||
assert_eq!(ip.register_count(hwip, instance), None);
|
||||
} else {
|
||||
assert_eq!(ip.register_count(hwip, instance), Some(count as u32));
|
||||
for segment in 0..count as u32 {
|
||||
assert_eq!(
|
||||
ip.register_base(hwip, instance, segment),
|
||||
Some(
|
||||
unsafe { stela_amd_ip_oracle_fact(hwip, instance, segment, 2) } as u32
|
||||
)
|
||||
);
|
||||
}
|
||||
assert_eq!(ip.register_base(hwip, instance, count as u32), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn selected_files(authority: &Authority) {
|
||||
let mut function = file_function(0xffff);
|
||||
// SAFETY: actual public Function observes immutable synthetic config only.
|
||||
let matched = unsafe { pci::identify(&mut function, policy(2)) }.unwrap();
|
||||
assert_eq!(matched.ip_path(), pci::IpPath::Dynamic);
|
||||
let (resource, drops) = super::resource(0x1400_0000, 0x60000, ResourceKind::Registers);
|
||||
// SAFETY: canonical RAM-only owner, no genuine hardware activation claim.
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach_matched(
|
||||
authority,
|
||||
&matched,
|
||||
RegisterBar { index: 5, resource },
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let window = bars.registers().unwrap();
|
||||
let clock = Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
};
|
||||
let mut size = 0;
|
||||
let source = unsafe { stela_amd_tmr_fixture(&mut size) };
|
||||
let source_bytes = unsafe { core::slice::from_raw_parts(source, size) };
|
||||
let begin = || unsafe {
|
||||
stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size)
|
||||
};
|
||||
allocation_failure::arm(0);
|
||||
let no_allocation = discovery::FileRequest::new(&bars).unwrap();
|
||||
drop(no_allocation);
|
||||
assert!(!allocation_failure::disarm());
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
assert_eq!(request.name(), "amdgpu/ip_discovery.bin");
|
||||
assert_eq!(
|
||||
request.target(),
|
||||
firmware::Target {
|
||||
driver: "amd-amdgpu-ip-discovery",
|
||||
hardware: "pci-1002-ffff",
|
||||
revision: "pci-45;subsys-abcd-5678",
|
||||
board: None
|
||||
}
|
||||
);
|
||||
let catalog = make_catalog(&request, source_bytes, "fixtures/ip-discovery.bin");
|
||||
let provider = make_provider(&catalog);
|
||||
begin();
|
||||
// SAFETY: only the bounded generated C RAM leaf handles original MM I/O.
|
||||
let discovery::SelectedFile::Dynamic(ip) =
|
||||
unsafe { request.acquire(&provider, &clock) }.unwrap()
|
||||
else {
|
||||
panic!("dynamic admission became static")
|
||||
};
|
||||
assert_eq!(provider.calls.get(), 1);
|
||||
assert_eq!(ip.identity(), bars.identity());
|
||||
assert_eq!(ip.image().bytes(), source_bytes);
|
||||
assert_eq!(
|
||||
ip.image().sha256(),
|
||||
<[u8; 32]>::from(Sha256::digest(source_bytes))
|
||||
);
|
||||
assert_eq!(ip.image().provenance().member, "fixtures/ip-discovery.bin");
|
||||
facts(&ip, source_bytes);
|
||||
drop(ip);
|
||||
// Fresh immutable real inputs exercise original file policy/decoder unchanged.
|
||||
let mut real_inputs = 0;
|
||||
if let Ok(paths) = std::env::var("STELA_AMD_DISCOVERY_INPUTS") {
|
||||
for path in paths.lines() {
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
let member = std::path::Path::new(path)
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
let catalog = make_catalog(&request, &bytes, member);
|
||||
let provider = make_provider(&catalog);
|
||||
begin();
|
||||
let discovery::SelectedFile::Dynamic(ip) =
|
||||
unsafe { request.acquire(&provider, &clock) }.unwrap()
|
||||
else {
|
||||
panic!("static")
|
||||
};
|
||||
facts(&ip, &bytes);
|
||||
assert_eq!(ip.image().bytes(), bytes);
|
||||
assert_eq!(ip.image().provenance().member, member);
|
||||
real_inputs += 1;
|
||||
}
|
||||
}
|
||||
// Each actual native Vec OOM point: query-storage precedes provider load;
|
||||
// the three IP allocations follow validated image acquisition.
|
||||
for allocation in 0..4 {
|
||||
begin();
|
||||
provider.calls.set(0);
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
allocation_failure::arm(allocation);
|
||||
let error = unsafe { request.acquire(&provider, &clock) }.err().unwrap();
|
||||
assert!(allocation_failure::disarm());
|
||||
assert!(unsafe { stela_amd_tmr_model_accesses() } > 0);
|
||||
assert!(matches!(
|
||||
(allocation, error),
|
||||
(
|
||||
0,
|
||||
discovery::FileError::Acquire(discovery::Error::PostQueryAllocation)
|
||||
) | (
|
||||
1..=3,
|
||||
discovery::FileError::Ip(discovery::Error::PostAcquireAllocation)
|
||||
)
|
||||
));
|
||||
assert_eq!(provider.calls.get(), u32::from(allocation != 0));
|
||||
}
|
||||
begin();
|
||||
provider.calls.set(0);
|
||||
let error = unsafe {
|
||||
discovery::FileRequest::new(&bars).unwrap().acquire(
|
||||
&provider,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
error,
|
||||
discovery::FileError::Acquire(discovery::Error::ClockUnavailable)
|
||||
));
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0);
|
||||
for system in [false, true] {
|
||||
begin();
|
||||
provider.calls.set(0);
|
||||
unsafe {
|
||||
if system {
|
||||
stela_amd_tmr_model_system()
|
||||
} else {
|
||||
stela_amd_tmr_model_vf()
|
||||
}
|
||||
};
|
||||
let error = unsafe {
|
||||
discovery::FileRequest::new(&bars)
|
||||
.unwrap()
|
||||
.acquire(&provider, &clock)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
error,
|
||||
discovery::FileError::Acquire(
|
||||
discovery::Error::VfOwnerUnavailable
|
||||
| discovery::Error::SystemFirmwareOwnerUnavailable
|
||||
)
|
||||
));
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
}
|
||||
let empty = Catalog::from_handoff(vec![]).unwrap();
|
||||
let missing = make_provider(&empty);
|
||||
for fail_diagnostic_name in [false, true] {
|
||||
begin();
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
if fail_diagnostic_name {
|
||||
allocation_failure::arm(1);
|
||||
}
|
||||
let error = unsafe { request.acquire(&missing, &clock) }.err().unwrap();
|
||||
if fail_diagnostic_name {
|
||||
assert!(allocation_failure::disarm());
|
||||
}
|
||||
let discovery::FileError::Source {
|
||||
error: discovery::FileSourceError::Provider(error),
|
||||
pending: discovery::FileFailureDiagnostics::OmittedByOriginalOption2,
|
||||
} = error
|
||||
else {
|
||||
panic!("wrong source failure")
|
||||
};
|
||||
assert_eq!(error.kind, firmware::ErrorKind::Missing);
|
||||
if fail_diagnostic_name {
|
||||
assert!(error.name.as_str().is_none());
|
||||
}
|
||||
}
|
||||
// A real canonical image returned for the wrong request is still refused.
|
||||
let mut alternate = make_provider(&catalog);
|
||||
alternate.alternate = Some(firmware::Requirement {
|
||||
name: "amdgpu/ip_discovery.bin",
|
||||
target: firmware::Target {
|
||||
driver: "amd-amdgpu-ip-discovery",
|
||||
hardware: "pci-1002-ffff",
|
||||
revision: "pci-45;subsys-abcd-5678",
|
||||
board: None,
|
||||
},
|
||||
minimum_bytes: 1,
|
||||
});
|
||||
// The alternate uses identical image here; verify it is accepted first.
|
||||
begin();
|
||||
drop(
|
||||
unsafe {
|
||||
discovery::FileRequest::new(&bars)
|
||||
.unwrap()
|
||||
.acquire(&alternate, &clock)
|
||||
}
|
||||
.unwrap(),
|
||||
);
|
||||
let other = Catalog::from_handoff(vec![firmware::Resource {
|
||||
name: "other.bin",
|
||||
target: firmware::Target {
|
||||
driver: "other",
|
||||
hardware: "other",
|
||||
revision: "other",
|
||||
board: None,
|
||||
},
|
||||
provenance: firmware::Provenance {
|
||||
source: "fixture",
|
||||
revision: "1",
|
||||
member: "other.bin",
|
||||
license: "test",
|
||||
},
|
||||
expected_length: source_bytes.len(),
|
||||
expected_sha256: Sha256::digest(source_bytes).into(),
|
||||
bytes: source_bytes.to_vec(),
|
||||
}])
|
||||
.unwrap();
|
||||
let mut wrong = make_provider(&other);
|
||||
wrong.alternate = Some(firmware::Requirement {
|
||||
name: "other.bin",
|
||||
target: firmware::Target {
|
||||
driver: "other",
|
||||
hardware: "other",
|
||||
revision: "other",
|
||||
board: None,
|
||||
},
|
||||
minimum_bytes: 1,
|
||||
});
|
||||
begin();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
discovery::FileRequest::new(&bars)
|
||||
.unwrap()
|
||||
.acquire(&wrong, &clock)
|
||||
},
|
||||
Err(discovery::FileError::Source {
|
||||
error: discovery::FileSourceError::WrongImage,
|
||||
..
|
||||
})
|
||||
));
|
||||
let other_target = firmware::Target {
|
||||
driver: "amd-amdgpu-ip-discovery",
|
||||
hardware: "pci-1002-ffff",
|
||||
revision: "pci-46;subsys-abcd-5678",
|
||||
board: None,
|
||||
};
|
||||
let other_same_name = Catalog::from_handoff(vec![firmware::Resource {
|
||||
name: "amdgpu/ip_discovery.bin",
|
||||
target: other_target,
|
||||
provenance: firmware::Provenance {
|
||||
source: "fixture",
|
||||
revision: "1",
|
||||
member: "same-name.bin",
|
||||
license: "test",
|
||||
},
|
||||
expected_length: source_bytes.len(),
|
||||
expected_sha256: Sha256::digest(source_bytes).into(),
|
||||
bytes: source_bytes.to_vec(),
|
||||
}])
|
||||
.unwrap();
|
||||
let mut wrong_target = make_provider(&other_same_name);
|
||||
wrong_target.alternate = Some(firmware::Requirement {
|
||||
name: "amdgpu/ip_discovery.bin",
|
||||
target: other_target,
|
||||
minimum_bytes: 1,
|
||||
});
|
||||
begin();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
discovery::FileRequest::new(&bars)
|
||||
.unwrap()
|
||||
.acquire(&wrong_target, &clock)
|
||||
},
|
||||
Err(discovery::FileError::Source {
|
||||
error: discovery::FileSourceError::WrongImage,
|
||||
..
|
||||
})
|
||||
));
|
||||
// A valid manifest cannot hide invalid actual bytes or a too-large source.
|
||||
let mut oversized = source_bytes.to_vec();
|
||||
oversized.extend_from_slice(&[0; 4]);
|
||||
let mut corrupt = source_bytes.to_vec();
|
||||
corrupt[0] ^= 1;
|
||||
for bytes in [&oversized[..], &corrupt[..]] {
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
let bad = make_catalog(&request, bytes, "bad.bin");
|
||||
let bad = make_provider(&bad);
|
||||
begin();
|
||||
assert!(matches!(
|
||||
unsafe { request.acquire(&bad, &clock) },
|
||||
Err(discovery::FileError::Source {
|
||||
error: discovery::FileSourceError::Policy(_),
|
||||
pending: discovery::FileFailureDiagnostics::OmittedByOriginalOption2
|
||||
})
|
||||
));
|
||||
}
|
||||
let mut short = source_bytes.to_vec();
|
||||
// Original binary_size field comes from the actual retained packed header;
|
||||
// fixture helper exposes it without copying a Rust wire-format definition.
|
||||
let declared = unsafe { stela_amd_file_fixture_declared(source, size) };
|
||||
assert!(declared > 16 && declared <= short.len());
|
||||
short.truncate(declared - 1);
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
let short_catalog = make_catalog(&request, &short, "short.bin");
|
||||
let short_provider = make_provider(&short_catalog);
|
||||
begin();
|
||||
assert!(matches!(
|
||||
unsafe { request.acquire(&short_provider, &clock) },
|
||||
Err(discovery::FileError::Source {
|
||||
error: discovery::FileSourceError::Policy(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
unsafe { stela_amd_tmr_model_end() };
|
||||
drop(window);
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 1);
|
||||
// Legacy static selected-file inventory never becomes dynamic facts. Missing
|
||||
// optional inventory reports its still-pending original version/RAS check.
|
||||
for option in [-1, 2] {
|
||||
let mut function = file_function(0x6860);
|
||||
let matched = unsafe { pci::identify(&mut function, policy(option)) }.unwrap();
|
||||
assert_eq!(matched.ip_path(), pci::IpPath::SocStatic);
|
||||
let (resource, drops) = super::resource(0x1500_0000, 0x60000, ResourceKind::Registers);
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach_matched(
|
||||
authority,
|
||||
&matched,
|
||||
RegisterBar { index: 5, resource },
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let window = bars.registers().unwrap();
|
||||
let request = discovery::FileRequest::new(&bars).unwrap();
|
||||
assert_eq!(
|
||||
request.name(),
|
||||
if option == 2 {
|
||||
"amdgpu/ip_discovery.bin"
|
||||
} else {
|
||||
"amdgpu/vega10_ip_discovery.bin"
|
||||
}
|
||||
);
|
||||
let good = make_catalog(&request, source_bytes, "static.bin");
|
||||
let good = make_provider(&good);
|
||||
unsafe {
|
||||
stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size)
|
||||
};
|
||||
let discovery::SelectedFile::Static(inventory) =
|
||||
unsafe { request.acquire(&good, &clock) }.unwrap()
|
||||
else {
|
||||
panic!("static inventory became dynamic")
|
||||
};
|
||||
assert_eq!(inventory.acquired_bytes(), source_bytes);
|
||||
assert_eq!(inventory.image().provenance().member, "static.bin");
|
||||
assert_eq!(inventory.identity(), bars.identity());
|
||||
drop(inventory);
|
||||
unsafe {
|
||||
stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size)
|
||||
};
|
||||
let error = unsafe {
|
||||
discovery::FileRequest::new(&bars)
|
||||
.unwrap()
|
||||
.acquire(&missing, &clock)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
let discovery::FileError::Source { pending, .. } = error else {
|
||||
panic!("wrong static failure")
|
||||
};
|
||||
assert_eq!(
|
||||
pending,
|
||||
if option == 2 {
|
||||
discovery::FileFailureDiagnostics::OmittedByOriginalOption2
|
||||
} else {
|
||||
discovery::FileFailureDiagnostics::DiscoveryVersionAndRasCheckRequired
|
||||
}
|
||||
);
|
||||
unsafe { stela_amd_tmr_model_end() };
|
||||
drop(window);
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
println!(
|
||||
"AMD selected-file Rust/C: actual admitted source/provider owners, query-before-load, retained image/provenance, same original facts, static inventory isolation, four Vec OOMs + provider diagnostic OOM, missing owners, pending original failure diagnostics; {real_inputs} unchanged real inputs; CPU only"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
/* Frozen a239 guarded original file consumer, test only. */
|
||||
#define amdgpu_discovery_read_binary_from_file original_read_file
|
||||
static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev,
|
||||
uint8_t *binary,
|
||||
const char *fw_name)
|
||||
{
|
||||
const struct firmware *fw;
|
||||
int r;
|
||||
|
||||
r = firmware_request_nowarn(&fw, fw_name, adev->dev);
|
||||
if (r) {
|
||||
if (amdgpu_discovery == 2)
|
||||
dev_err(adev->dev, "can't load firmware \"%s\"\n", fw_name);
|
||||
else
|
||||
drm_info(&adev->ddev, "Optional firmware \"%s\" was not found\n", fw_name);
|
||||
return r;
|
||||
}
|
||||
|
||||
if (fw->size > adev->discovery.size) {
|
||||
dev_err(adev->dev,
|
||||
"ip discovery firmware \"%s\" too large (%zu > %u)\n",
|
||||
fw_name, fw->size, adev->discovery.size);
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
/* Ensure the firmware is at least large enough to contain the
|
||||
* binary header fields.
|
||||
*/
|
||||
if (fw->size < offsetof(struct binary_header, binary_size) +
|
||||
sizeof(((struct binary_header *)0)->binary_size)) {
|
||||
dev_err(adev->dev,
|
||||
"ip discovery firmware \"%s\" too small (%zu)\n",
|
||||
fw_name, fw->size);
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
/* A short file must not borrow zero-filled TMR padding as firmware data. */
|
||||
if (amdgpu_discovery_binary_validate(fw->data, fw->size) !=
|
||||
AMDGPU_DISCOVERY_BINARY_OK) {
|
||||
release_firmware(fw);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
memcpy((u8 *)binary, (u8 *)fw->data, fw->size);
|
||||
release_firmware(fw);
|
||||
|
||||
return 0;
|
||||
}
|
||||
#undef amdgpu_discovery_read_binary_from_file
|
||||
@@ -0,0 +1,249 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Actual shared/current Linux consumer and independent frozen original oracle. */
|
||||
#include "../stela/discovery_ip.h"
|
||||
#include "../stela/discovery_binary.h"
|
||||
#include "../amdgpu/amdgpu_discovery_ip_core.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <limits.h>
|
||||
|
||||
struct va_format { const char *fmt; va_list *va; };
|
||||
struct amdgpu_device {
|
||||
void *dev;
|
||||
struct { uint8_t *bin; size_t size; } discovery;
|
||||
struct { uint16_t xcc_mask; } gfx;
|
||||
struct { int num_instances; uint32_t sdma_mask; } sdma;
|
||||
struct { uint8_t num_vcn_inst; struct {uint8_t vcn_config;} inst[AMDGPU_MAX_VCN_INSTANCES]; uint16_t inst_mask; } vcn;
|
||||
struct {uint16_t inst_mask;} jpeg;
|
||||
struct {uint32_t num_instances;} vpe;
|
||||
struct {int num_umc;} gmc;
|
||||
struct {uint32_t node_inst_num;} umc;
|
||||
uint32_t *reg_offset[MAX_HWIP][HWIP_MAX_INSTANCE];
|
||||
uint32_t ip_versions[MAX_HWIP][HWIP_MAX_INSTANCE];
|
||||
};
|
||||
static const char *hw_id_names[HW_ID_MAX];
|
||||
static char logs[2][262144];static size_t log_at[2];static unsigned current;
|
||||
static void log_message(const char *format, va_list args)
|
||||
{
|
||||
if (!strcmp(format,"%pV")) {
|
||||
struct va_format *vaf=va_arg(args,struct va_format *);
|
||||
log_at[current]+=(size_t)vsnprintf(logs[current]+log_at[current],sizeof(logs[current])-log_at[current],vaf->fmt,*vaf->va);
|
||||
} else log_at[current]+=(size_t)vsnprintf(logs[current]+log_at[current],sizeof(logs[current])-log_at[current],format,args);
|
||||
assert(log_at[current]<sizeof(logs[current]));
|
||||
}
|
||||
static void log_debug(const char *format,...) {va_list a;va_start(a,format);log_message(format,a);va_end(a);}
|
||||
static void log_error(void *device,const char *format,...) {(void)device;va_list a;va_start(a,format);log_message(format,a);va_end(a);}
|
||||
#define DRM_DEBUG(...) log_debug(__VA_ARGS__)
|
||||
#define DRM_ERROR(...) log_debug(__VA_ARGS__)
|
||||
#define dev_err(...) log_error(__VA_ARGS__)
|
||||
static int acquisition_error, table_error, acquisitions[2], lookups[2];
|
||||
static int amdgpu_discovery_init(struct amdgpu_device *a) {(void)a;acquisitions[current]++;return acquisition_error;}
|
||||
static int amdgpu_discovery_get_table_info(struct amdgpu_device *a,struct table_info **out,uint16_t id)
|
||||
{lookups[current]++;if(table_error)return table_error;*out=(void*)amdgpu_discovery_binary_table(a->discovery.bin,a->discovery.size,id);return *out?0:-EINVAL;}
|
||||
#include "discovery_ip_reference.h"
|
||||
#include "discovery-ip-linux.inc"
|
||||
|
||||
size_t stela_amd_ip_fixture(uint8_t *,size_t,unsigned,unsigned,unsigned);
|
||||
static unsigned comparisons, native_cases, malformed;
|
||||
static void seed(struct amdgpu_device *a,unsigned seed)
|
||||
{
|
||||
a->gfx.xcc_mask=0xf1f1;a->vcn.inst_mask=0xfffa;a->jpeg.inst_mask=0xf0ff;a->sdma.sdma_mask=0xff00ff00;
|
||||
a->vcn.num_vcn_inst=seed%5;a->sdma.num_instances=(int)seed-1;
|
||||
a->vpe.num_instances=seed%3;a->gmc.num_umc=seed;a->umc.node_inst_num=seed;
|
||||
for(unsigned i=0;i<AMDGPU_MAX_VCN_INSTANCES;i++)a->vcn.inst[i].vcn_config=(uint8_t)(seed+i);
|
||||
a->ip_versions[XGMI_HWIP][0]=seed&1?0x09040100:0;
|
||||
if(seed==8){a->vcn.num_vcn_inst=255;a->sdma.num_instances=INT_MAX;
|
||||
a->vpe.num_instances=UINT32_MAX;a->gmc.num_umc=INT_MAX;a->umc.node_inst_num=UINT32_MAX;}
|
||||
}
|
||||
static void compare(const uint8_t *binary,size_t bytes,unsigned state)
|
||||
{
|
||||
uint8_t *left=malloc(bytes),*right=malloc(bytes);assert(left&&right);
|
||||
memcpy(left,binary,bytes);memcpy(right,binary,bytes);
|
||||
struct amdgpu_device a={0},b={0};seed(&a,state);b=a;
|
||||
a.discovery.bin=left;b.discovery.bin=right;a.discovery.size=b.discovery.size=bytes;
|
||||
memset(logs,0,sizeof(logs));memset(log_at,0,sizeof(log_at));memset(acquisitions,0,sizeof(acquisitions));memset(lookups,0,sizeof(lookups));
|
||||
current=0;int expected=ip_donor_amdgpu_discovery_reg_base_init(&a);
|
||||
current=1;int status=amdgpu_discovery_reg_base_init(&b);
|
||||
assert(expected==status && acquisitions[0]==acquisitions[1]&&lookups[0]==lookups[1]);
|
||||
assert(!memcmp(left,right,bytes));assert(log_at[0]==log_at[1]&&!memcmp(logs[0],logs[1],log_at[0]));
|
||||
for(unsigned ip=0;ip<MAX_HWIP;ip++)for(unsigned i=0;i<HWIP_MAX_INSTANCE;i++){
|
||||
if(a.reg_offset[ip][i]){assert(b.reg_offset[ip][i]);assert((uintptr_t)a.reg_offset[ip][i]-(uintptr_t)left==(uintptr_t)b.reg_offset[ip][i]-(uintptr_t)right);}
|
||||
else assert(!b.reg_offset[ip][i]);
|
||||
a.reg_offset[ip][i]=b.reg_offset[ip][i]=NULL;
|
||||
}
|
||||
a.discovery.bin=b.discovery.bin=NULL;assert(!memcmp(&a,&b,sizeof(a)));
|
||||
free(left);free(right);comparisons++;
|
||||
}
|
||||
static unsigned count_for(const uint8_t *binary,size_t bytes,uint32_t offset)
|
||||
{
|
||||
const struct table_info *t=amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY);
|
||||
const struct ip_discovery_header *h=(const void*)(binary+t->offset);
|
||||
for(unsigned d=0;d<h->num_dies;d++){
|
||||
size_t pos=h->die_info[d].die_offset;const struct die_header *die=(const void*)(binary+pos);pos+=sizeof(*die);
|
||||
for(unsigned n=0;n<die->num_ips;n++){
|
||||
const struct ip_v4 *ip=(const void*)(binary+pos);
|
||||
if(pos+offsetof(struct ip_v4,base_address)==offset)return ip->num_base_address;
|
||||
pos+=sizeof(*ip)+ip->num_base_address*(h->base_addr_64_bit?8:4);
|
||||
}
|
||||
}
|
||||
assert(0);return 0;
|
||||
}
|
||||
static void native(const uint8_t *binary,size_t bytes)
|
||||
{
|
||||
struct stela_amd_ip_shape shape=stela_amd_discovery_ip_shape();size_t cells=shape.hw_ip_count*shape.instances;
|
||||
assert(shape.hw_ip_count==MAX_HWIP&&shape.instances==HWIP_MAX_INSTANCE);
|
||||
uint8_t *work=malloc(bytes+1),*raw=malloc(bytes);uint32_t *versions=malloc(cells*4);
|
||||
struct stela_amd_ip_binding *bindings=malloc(cells*sizeof(*bindings));assert(work&&raw&&versions&&bindings);
|
||||
memcpy(work+1,binary,bytes);memcpy(raw,binary,bytes); // Entire allocation deliberately unaligned.
|
||||
struct stela_amd_ip_counts counts;
|
||||
int result=stela_amd_discovery_ip_decode(work+1,bytes,versions,cells,bindings,cells,&counts);assert(!result);
|
||||
struct amdgpu_device a={0};a.discovery.bin=raw;a.discovery.size=bytes;
|
||||
current=0;log_at[0]=0;assert(!ip_donor_amdgpu_discovery_reg_base_init(&a));
|
||||
assert(!memcmp(work+1,raw,bytes));assert(!memcmp(versions,a.ip_versions,cells*4));
|
||||
assert(counts.xcc_mask==a.gfx.xcc_mask&&counts.vcn_mask==a.vcn.inst_mask&&counts.jpeg_mask==a.jpeg.inst_mask);
|
||||
assert(counts.vcn_count==a.vcn.num_vcn_inst&&counts.sdma_count==a.sdma.num_instances&&counts.sdma_mask==a.sdma.sdma_mask);
|
||||
assert(counts.vpe_count==a.vpe.num_instances&&counts.umc_count==a.gmc.num_umc&&counts.node_count==a.umc.node_inst_num);
|
||||
for(unsigned i=0;i<AMDGPU_MAX_VCN_INSTANCES;i++)assert(counts.vcn_config[i]==a.vcn.inst[i].vcn_config);
|
||||
for(unsigned ip=0;ip<MAX_HWIP;ip++)for(unsigned i=0;i<HWIP_MAX_INSTANCE;i++){
|
||||
struct stela_amd_ip_binding *b=&bindings[ip*HWIP_MAX_INSTANCE+i];
|
||||
if(a.reg_offset[ip][i]){assert(b->offset==(uintptr_t)a.reg_offset[ip][i]-(uintptr_t)raw);assert(b->count==count_for(binary,bytes,b->offset));}
|
||||
else assert(b->offset==UINT32_MAX&&b->count==0);
|
||||
}
|
||||
free(work);free(raw);free(versions);free(bindings);native_cases++;
|
||||
}
|
||||
static void checksum(uint8_t *binary,size_t bytes)
|
||||
{
|
||||
struct binary_header *h=(void*)binary;
|
||||
for(unsigned i=0;i<TOTAL_TABLES;i++){
|
||||
struct table_info *t=(void*)amdgpu_discovery_binary_table(binary,bytes,i);
|
||||
if(t&&t->size)t->checksum=amdgpu_discovery_calculate_checksum(binary+t->offset,t->size);
|
||||
}
|
||||
size_t start=offsetof(struct binary_header,binary_checksum)+2;
|
||||
h->binary_checksum=amdgpu_discovery_calculate_checksum(binary+start,h->binary_size-start);
|
||||
}
|
||||
static struct ip_v4 *record(uint8_t *binary,size_t bytes,unsigned die,unsigned index)
|
||||
{
|
||||
const struct table_info *t=amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY);
|
||||
struct ip_discovery_header *h=(void*)(binary+t->offset);
|
||||
size_t pos=h->die_info[die].die_offset+sizeof(struct die_header);
|
||||
for(unsigned i=0;i<index;i++){struct ip_v4 *ip=(void*)(binary+pos);pos+=sizeof(*ip)+ip->num_base_address*(h->base_addr_64_bit?8:4);}
|
||||
return (void*)(binary+pos);
|
||||
}
|
||||
static void atomic_refusal(uint8_t *binary,size_t bytes,unsigned kind)
|
||||
{
|
||||
struct stela_amd_ip_shape shape=stela_amd_discovery_ip_shape();size_t cells=shape.hw_ip_count*shape.instances;
|
||||
uint8_t *raw=malloc(bytes?bytes:1);memcpy(raw,binary,bytes);
|
||||
uint32_t *versions=malloc(cells*4);struct stela_amd_ip_binding *bindings=malloc(cells*sizeof(*bindings));
|
||||
struct stela_amd_ip_counts counts,before;
|
||||
memset(versions,0xa5,cells*4);memset(bindings,0xa5,cells*sizeof(*bindings));memset(&counts,0xa5,sizeof(counts));before=counts;
|
||||
uint32_t *vp=versions;struct stela_amd_ip_binding *bp=bindings;struct stela_amd_ip_counts *cp=&counts;
|
||||
size_t vc=cells,bc=cells;
|
||||
switch(kind){case 1:vc--;break;case 2:bc--;break;case 3:vp=NULL;break;case 4:bp=NULL;break;case 5:cp=NULL;break;
|
||||
case 6:vp=(void*)((uint8_t*)versions+1);break;case 7:bp=(void*)((uint8_t*)bindings+1);break;case 8:cp=(void*)((uint8_t*)&counts+1);break;
|
||||
case 9:vp=(void*)binary;break;case 10:cp=(void*)bindings;break;case 11:bp=(void*)versions;break;}
|
||||
assert(stela_amd_discovery_ip_decode(binary,bytes,vp,vc,bp,bc,cp));
|
||||
assert(!memcmp(binary,raw,bytes)&&!memcmp(&counts,&before,sizeof(counts)));
|
||||
for(size_t i=0;i<cells*4;i++)assert(((uint8_t*)versions)[i]==0xa5);
|
||||
for(size_t i=0;i<cells*sizeof(*bindings);i++)assert(((uint8_t*)bindings)[i]==0xa5);
|
||||
free(raw);free(versions);free(bindings);malformed++;
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
for(unsigned i=0;i<HW_ID_MAX;i++)hw_id_names[i]="original-name";
|
||||
const unsigned instances[]={0,47,48,255}, ids[]={0,299,300,65535};
|
||||
struct amdgpu_device dummy={0};
|
||||
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<4;j++) {
|
||||
log_at[0]=log_at[1]=0;current=0;
|
||||
int expected=ip_donor_amdgpu_discovery_validate_ip(&dummy,instances[i],ids[j]);
|
||||
current=1;assert(amdgpu_discovery_validate_ip(&dummy,instances[i],ids[j])==expected);
|
||||
assert(log_at[0]==log_at[1]&&!memcmp(logs[0],logs[1],log_at[0]));
|
||||
}
|
||||
uint8_t binary[65536],original[65536];
|
||||
for(unsigned directory=0;directory<=2;directory++)for(unsigned wide=0;wide<2;wide++)for(unsigned ver=wide?4:1;ver<=4;ver++){
|
||||
size_t bytes=stela_amd_ip_fixture(binary,sizeof(binary),directory,ver,wide);
|
||||
assert(!amdgpu_discovery_binary_validate(binary,bytes));
|
||||
for(unsigned s=0;s<9;s++)compare(binary,bytes,s);
|
||||
native(binary,bytes);
|
||||
for(unsigned k=1;k<=11;k++)atomic_refusal(binary,bytes,k);
|
||||
memcpy(original,binary,bytes);
|
||||
for(size_t n=0;n<bytes;n++)atomic_refusal(binary,n,0);
|
||||
for(size_t at=0;at<bytes;at+=7){binary[at]^=1;if(amdgpu_discovery_binary_validate(binary,bytes))atomic_refusal(binary,bytes,0);else{compare(binary,bytes,0);native(binary,bytes);}binary[at]^=1;}
|
||||
/* Actual version bits above signed-int positive domain; no major<128 gate. */
|
||||
const struct table_info *t=amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY);
|
||||
struct ip_discovery_header *h=(void*)(binary+t->offset);
|
||||
struct ip_v4 *ip=(void*)(binary+h->die_info[0].die_offset+sizeof(struct die_header));
|
||||
ip->major=255;ip->minor=254;ip->revision=253;checksum(binary,bytes);compare(binary,bytes,0);native(binary,bytes);
|
||||
memcpy(binary,original,bytes);
|
||||
for(unsigned variant=0;variant<5;variant++) {
|
||||
memcpy(binary,original,bytes);
|
||||
for(unsigned d=0;d<2;d++) {
|
||||
if(variant==0){record(binary,bytes,d,0)->instance_number=31;record(binary,bytes,d,3)->instance_number=31;record(binary,bytes,d,2)->instance_number=31;}
|
||||
if(variant==1){record(binary,bytes,d,2)->hw_id=NBIF_HWID;record(binary,bytes,d,2)->instance_number=0;record(binary,bytes,d,10)->hw_id=NBIF_HWID;record(binary,bytes,d,10)->instance_number=0;}
|
||||
if(variant==2){struct ip_v4 *x=record(binary,bytes,d,9);x->hw_id=XGMI_HWID;x->instance_number=0;x->major=x->minor=x->revision=x->variant=x->sub_revision=0;}
|
||||
if(variant==3)record(binary,bytes,d,7)->hw_id=VPE_HWID;
|
||||
if(variant==4)record(binary,bytes,d,7)->hw_id=AUDIO_AZ_HWID;
|
||||
}
|
||||
if(variant==2){struct ip_v4 *w=record(binary,bytes,0,8);w->major=w->minor=w->revision=0;}
|
||||
checksum(binary,bytes);assert(!amdgpu_discovery_binary_validate(binary,bytes));
|
||||
for(unsigned seed=0;seed<9;seed++)compare(binary,bytes,seed);native(binary,bytes);
|
||||
}
|
||||
memcpy(binary,original,bytes);
|
||||
/* Preserve original partial first-die effects and global DRM error route. */
|
||||
struct ip_discovery_header *ph=(void*)(binary+amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY)->offset);
|
||||
((struct die_header*)(binary+ph->die_info[1].die_offset))->die_id=5;checksum(binary,bytes);
|
||||
compare(binary,bytes,0);atomic_refusal(binary,bytes,0);
|
||||
memcpy(binary,original,bytes);
|
||||
/* Original outer failures/partial masks remain in Linux caller. */
|
||||
acquisition_error=-EIO;compare(binary,bytes,0);acquisition_error=0;
|
||||
table_error=-EINVAL;compare(binary,bytes,3);table_error=0;
|
||||
}
|
||||
for(int n=1;n<argc;n++){
|
||||
FILE *f=fopen(argv[n],"rb");assert(f);size_t bytes=fread(binary,1,sizeof(binary),f);assert(bytes&&bytes<sizeof(binary)&&feof(f));fclose(f);
|
||||
assert(!amdgpu_discovery_binary_validate(binary,bytes));for(unsigned s=0;s<8;s++)compare(binary,bytes,s);native(binary,bytes);
|
||||
}
|
||||
printf("AMD IP: %u whole original/current consumers, %u native packed copies, %u atomic malformed/storage refusals; CPU only\n",comparisons,native_cases,malformed);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef STELA_IP_RUST_MODEL
|
||||
/* Frozen original consumer oracle, CPU fixture only. The production native
|
||||
* adapter is not used to derive these expected values. */
|
||||
static struct amdgpu_device rust_oracle;
|
||||
static uint8_t rust_oracle_work[65536];
|
||||
void stela_amd_ip_oracle(const uint8_t *source, size_t bytes,
|
||||
struct stela_amd_ip_counts *counts,
|
||||
uint32_t *hwips, uint32_t *instances)
|
||||
{
|
||||
assert(bytes <= sizeof(rust_oracle_work));
|
||||
assert(!amdgpu_discovery_binary_validate(source,bytes));
|
||||
memcpy(rust_oracle_work,source,bytes);memset(&rust_oracle,0,sizeof(rust_oracle));
|
||||
rust_oracle.discovery.bin=rust_oracle_work;rust_oracle.discovery.size=bytes;
|
||||
for(unsigned i=0;i<HW_ID_MAX;i++)hw_id_names[i]="original-name";
|
||||
current=0;log_at[0]=0;acquisition_error=table_error=0;
|
||||
assert(!ip_donor_amdgpu_discovery_reg_base_init(&rust_oracle));
|
||||
memset(counts,0,sizeof(*counts));
|
||||
counts->xcc_mask=rust_oracle.gfx.xcc_mask;counts->vcn_mask=rust_oracle.vcn.inst_mask;
|
||||
counts->jpeg_mask=rust_oracle.jpeg.inst_mask;counts->vcn_count=rust_oracle.vcn.num_vcn_inst;
|
||||
for(unsigned i=0;i<AMDGPU_MAX_VCN_INSTANCES;i++)counts->vcn_config[i]=rust_oracle.vcn.inst[i].vcn_config;
|
||||
counts->sdma_count=rust_oracle.sdma.num_instances;counts->sdma_mask=rust_oracle.sdma.sdma_mask;
|
||||
counts->vpe_count=rust_oracle.vpe.num_instances;counts->umc_count=rust_oracle.gmc.num_umc;
|
||||
counts->node_count=rust_oracle.umc.node_inst_num;
|
||||
*hwips=MAX_HWIP;*instances=HWIP_MAX_INSTANCE;
|
||||
}
|
||||
uint64_t stela_amd_ip_oracle_fact(unsigned hwip,unsigned instance,unsigned segment,unsigned kind)
|
||||
{
|
||||
assert(hwip<MAX_HWIP&&instance<HWIP_MAX_INSTANCE);
|
||||
if(kind==0)return rust_oracle.ip_versions[hwip][instance];
|
||||
const uint32_t *base=rust_oracle.reg_offset[hwip][instance];
|
||||
if(!base)return UINT64_MAX;
|
||||
uint32_t offset=(uint32_t)((uintptr_t)base-(uintptr_t)rust_oracle_work);
|
||||
unsigned count=count_for(rust_oracle_work,rust_oracle.discovery.size,offset);
|
||||
if(kind==1)return count;
|
||||
if(segment>=count)return UINT64_MAX;
|
||||
uint32_t value;memcpy(&value,(const uint8_t*)base+segment*4,4);return value;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Child of the canonical single-authority test in a separate generated CPU
|
||||
//! harness. Only the existing original C MM leaf is instrumented, never a
|
||||
//! production provider. No physical PCI/GPU services are exercised.
|
||||
use super::*;
|
||||
use crate::{discovery, pci};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_tmr_fixture(bytes: &mut usize) -> *const u8;
|
||||
fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize);
|
||||
fn stela_amd_tmr_model_accesses() -> u32;
|
||||
fn stela_amd_tmr_model_end();
|
||||
fn stela_amd_ip_oracle(
|
||||
source: *const u8,
|
||||
bytes: usize,
|
||||
counts: &mut discovery::IpCounts,
|
||||
hwips: &mut u32,
|
||||
instances: &mut u32,
|
||||
);
|
||||
fn stela_amd_ip_oracle_fact(hwip: u32, instance: u32, segment: u32, kind: u32) -> u64;
|
||||
}
|
||||
struct FixtureConfig;
|
||||
impl ConfigSpace for FixtureConfig {
|
||||
fn read32(&self, offset: u16) -> u32 {
|
||||
match offset {
|
||||
0 => 0xffff_1002,
|
||||
8 => 0x1200_0045,
|
||||
12 => 0,
|
||||
44 => 0x5678_abcd,
|
||||
_ => panic!("unexpected config read"),
|
||||
}
|
||||
}
|
||||
fn write32(&mut self, _: u16, _: u32) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
fn write16(&mut self, _: u16, _: u16) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
fn write8(&mut self, _: u16, _: u8) {
|
||||
panic!("no config writes")
|
||||
}
|
||||
}
|
||||
pub(super) fn acquire_observed(authority: &Authority) {
|
||||
let mut function = Function::new(
|
||||
Address {
|
||||
segment: 4,
|
||||
bus: 0x81,
|
||||
device: 2,
|
||||
function: 0,
|
||||
},
|
||||
FixtureConfig,
|
||||
)
|
||||
.unwrap();
|
||||
let policy = pci::Policy {
|
||||
si_built: true,
|
||||
cik_built: true,
|
||||
radeon_built: false,
|
||||
si_support: -1,
|
||||
cik_support: -1,
|
||||
experimental: 0,
|
||||
discovery: -1,
|
||||
force_asic: -1,
|
||||
memory_encrypted: false,
|
||||
firmware_drivers_only: false,
|
||||
modeset: -1,
|
||||
};
|
||||
// SAFETY: actual public Function observes only immutable synthetic config.
|
||||
let matched = unsafe { pci::identify(&mut function, policy) }.unwrap();
|
||||
assert_eq!(matched.ip_path(), pci::IpPath::Dynamic);
|
||||
assert_eq!(matched.source(), pci::Source::Hardware);
|
||||
let (resource, drops) = resource(0x1300_0000, 0x60000, ResourceKind::Registers);
|
||||
// SAFETY: exact canonical RAM model resource, no physical admission claim.
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach_matched(
|
||||
authority,
|
||||
&matched,
|
||||
RegisterBar { index: 5, resource },
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let window = bars.registers().unwrap();
|
||||
let clock = Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
};
|
||||
let mut bytes = 0;
|
||||
// SAFETY: original-format immutable static CPU fixture, no firmware payload.
|
||||
let source = unsafe { stela_amd_tmr_fixture(&mut bytes) };
|
||||
let begin = || unsafe {
|
||||
stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, bytes)
|
||||
};
|
||||
begin();
|
||||
// SAFETY: instrumented original MM query/copy runs only the bounded RAM
|
||||
// fixture. The real production admission and ownership APIs are unchanged.
|
||||
let observed = unsafe { discovery::acquire_dynamic_ip(&bars, &clock) }.unwrap();
|
||||
assert_eq!(observed.source_bytes(), unsafe {
|
||||
core::slice::from_raw_parts(source, bytes)
|
||||
});
|
||||
assert_eq!(observed.identity(), bars.identity());
|
||||
let mut counts = discovery::IpCounts::default();
|
||||
let (mut hwips, mut instances) = (0, 0);
|
||||
// SAFETY: exact checked C/Rust ABI; independent frozen original consumer
|
||||
// owns its distinct work copy and returns only scalar expected values.
|
||||
unsafe { stela_amd_ip_oracle(source, bytes, &mut counts, &mut hwips, &mut instances) };
|
||||
assert_eq!(observed.counts(), counts);
|
||||
let mut bound = 0;
|
||||
for hwip in 0..hwips {
|
||||
for instance in 0..instances {
|
||||
let version = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 0) };
|
||||
assert_eq!(observed.version(hwip, instance), Some(version as u32));
|
||||
let count = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 1) };
|
||||
if count == u64::MAX {
|
||||
assert_eq!(observed.register_count(hwip, instance), None);
|
||||
} else {
|
||||
bound += 1;
|
||||
assert_eq!(observed.register_count(hwip, instance), Some(count as u32));
|
||||
for segment in 0..count as u32 {
|
||||
let expected = unsafe { stela_amd_ip_oracle_fact(hwip, instance, segment, 2) };
|
||||
assert_eq!(
|
||||
observed.register_base(hwip, instance, segment),
|
||||
Some(expected as u32)
|
||||
);
|
||||
}
|
||||
assert_eq!(observed.register_base(hwip, instance, count as u32), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(bound > 0);
|
||||
assert_eq!(observed.version(hwips, 0), None);
|
||||
assert_eq!(observed.version(0, instances), None);
|
||||
assert_eq!(observed.register_base(u32::MAX, u32::MAX, u32::MAX), None);
|
||||
assert!(unsafe { stela_amd_tmr_model_accesses() } > bytes as u32 / 4);
|
||||
drop(observed);
|
||||
// Each of four fallible production allocations is independently refused.
|
||||
// Query/index effects remain real in this model, never falsely rolled back.
|
||||
for allocation in 0..4 {
|
||||
begin();
|
||||
allocation_failure::arm(allocation);
|
||||
let failed = unsafe { discovery::acquire_dynamic_ip(&bars, &clock) };
|
||||
let consumed = allocation_failure::disarm();
|
||||
assert!(consumed);
|
||||
assert!(matches!(
|
||||
(allocation, failed),
|
||||
(0, Err(discovery::Error::PostQueryAllocation))
|
||||
| (1..=3, Err(discovery::Error::PostAcquireAllocation))
|
||||
));
|
||||
assert!(unsafe { stela_amd_tmr_model_accesses() } > 0);
|
||||
}
|
||||
begin();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
discovery::acquire_dynamic_ip(
|
||||
&bars,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(discovery::Error::ClockUnavailable)
|
||||
));
|
||||
assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0);
|
||||
unsafe { stela_amd_tmr_model_end() };
|
||||
drop(window);
|
||||
// SAFETY: all model consumers drained; failed unpublished copies dropped.
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 1);
|
||||
println!(
|
||||
"AMD dynamic IP Rust/C: same admitted source owner; immutable raw bytes; every original version/binding/base/count; four allocation failures; CPU leaf-I/O model only"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) mod allocation_failure {
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
thread_local! { static REMAINING: Cell<Option<usize>> = const { Cell::new(None) }; }
|
||||
thread_local! { static CONSUMED: Cell<bool> = const { Cell::new(false) }; }
|
||||
struct FaultAllocator;
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: FaultAllocator = FaultAllocator;
|
||||
// SAFETY: exact System delegation except one explicit valid null response;
|
||||
// TLS is allocation-free and limited to this single harness thread.
|
||||
unsafe impl GlobalAlloc for FaultAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
let fail = REMAINING
|
||||
.try_with(|value| match value.get() {
|
||||
Some(0) => {
|
||||
value.set(None);
|
||||
true
|
||||
}
|
||||
Some(n) => {
|
||||
value.set(Some(n - 1));
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if fail {
|
||||
let _ = CONSUMED.try_with(|v| v.set(true));
|
||||
core::ptr::null_mut()
|
||||
} else {
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
// SAFETY: unmodified System allocation/layout from Rust.
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
}
|
||||
pub fn arm(before: usize) {
|
||||
CONSUMED.with(|v| v.set(false));
|
||||
REMAINING.with(|v| v.set(Some(before)));
|
||||
}
|
||||
pub fn disarm() -> bool {
|
||||
REMAINING.with(|v| v.set(None));
|
||||
CONSUMED.with(Cell::get)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Original existing CPU fixture generation, never a production firmware source. */
|
||||
#define main stela_amd_ip_existing_fixture_main
|
||||
#include "discovery_binary_test.c"
|
||||
#undef main
|
||||
size_t stela_amd_ip_fixture(uint8_t *out, size_t capacity, unsigned version,
|
||||
unsigned ip_version, unsigned wide)
|
||||
{
|
||||
struct fixture f = make_fixture(version, ip_version, wide, 1, 3, 0);
|
||||
assert(capacity >= f.size);
|
||||
memcpy(out, f.binary, f.size);
|
||||
return f.size;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
/* Frozen original consumer, exact92d3 body identical to Linux8d3ae592.
|
||||
* Test-only real-field prototype, not a production device. */
|
||||
#define hw_id_map ip_donor_hw_id_map
|
||||
#define amdgpu_discovery_validate_ip ip_donor_amdgpu_discovery_validate_ip
|
||||
#define amdgpu_discovery_reg_base_init ip_donor_amdgpu_discovery_reg_base_init
|
||||
static int hw_id_map[MAX_HWIP] = {
|
||||
[GC_HWIP] = GC_HWID,
|
||||
[HDP_HWIP] = HDP_HWID,
|
||||
[SDMA0_HWIP] = SDMA0_HWID,
|
||||
[SDMA1_HWIP] = SDMA1_HWID,
|
||||
[SDMA2_HWIP] = SDMA2_HWID,
|
||||
[SDMA3_HWIP] = SDMA3_HWID,
|
||||
[LSDMA_HWIP] = LSDMA_HWID,
|
||||
[MMHUB_HWIP] = MMHUB_HWID,
|
||||
[ATHUB_HWIP] = ATHUB_HWID,
|
||||
[NBIO_HWIP] = NBIF_HWID,
|
||||
[MP0_HWIP] = MP0_HWID,
|
||||
[MP1_HWIP] = MP1_HWID,
|
||||
[UVD_HWIP] = UVD_HWID,
|
||||
[VCE_HWIP] = VCE_HWID,
|
||||
[DF_HWIP] = DF_HWID,
|
||||
[DCE_HWIP] = DMU_HWID,
|
||||
[OSSSYS_HWIP] = OSSSYS_HWID,
|
||||
[SMUIO_HWIP] = SMUIO_HWID,
|
||||
[PWR_HWIP] = PWR_HWID,
|
||||
[NBIF_HWIP] = NBIF_HWID,
|
||||
[THM_HWIP] = THM_HWID,
|
||||
[CLK_HWIP] = CLKA_HWID,
|
||||
[UMC_HWIP] = UMC_HWID,
|
||||
[XGMI_HWIP] = XGMI_HWID,
|
||||
[DCI_HWIP] = DCI_HWID,
|
||||
[PCIE_HWIP] = PCIE_HWID,
|
||||
[VPE_HWIP] = VPE_HWID,
|
||||
[ISP_HWIP] = ISP_HWID,
|
||||
[ATU_HWIP] = ATU_HWID,
|
||||
};
|
||||
|
||||
static int amdgpu_discovery_validate_ip(struct amdgpu_device *adev,
|
||||
uint8_t instance, uint16_t hw_id)
|
||||
{
|
||||
if (instance >= HWIP_MAX_INSTANCE) {
|
||||
dev_err(adev->dev,
|
||||
"Unexpected instance_number (%d) from ip discovery blob\n",
|
||||
instance);
|
||||
return -EINVAL;
|
||||
}
|
||||
if (hw_id >= HW_ID_MAX) {
|
||||
dev_err(adev->dev,
|
||||
"Unexpected hw_id (%d) from ip discovery blob\n",
|
||||
hw_id);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev)
|
||||
{
|
||||
uint8_t num_base_address, subrev, variant;
|
||||
struct table_info *info;
|
||||
struct ip_discovery_header *ihdr;
|
||||
struct die_header *dhdr;
|
||||
uint8_t *discovery_bin;
|
||||
struct ip_v4 *ip;
|
||||
uint16_t die_offset;
|
||||
uint16_t ip_offset;
|
||||
uint16_t num_dies;
|
||||
uint32_t wafl_ver;
|
||||
uint16_t num_ips;
|
||||
uint16_t hw_id;
|
||||
uint8_t inst;
|
||||
int hw_ip;
|
||||
int i, j, k;
|
||||
int r;
|
||||
|
||||
r = amdgpu_discovery_init(adev);
|
||||
if (r)
|
||||
return r;
|
||||
discovery_bin = adev->discovery.bin;
|
||||
wafl_ver = 0;
|
||||
adev->gfx.xcc_mask = 0;
|
||||
adev->sdma.sdma_mask = 0;
|
||||
adev->vcn.inst_mask = 0;
|
||||
adev->jpeg.inst_mask = 0;
|
||||
r = amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY);
|
||||
if (r)
|
||||
return r;
|
||||
ihdr = (struct ip_discovery_header
|
||||
*)(discovery_bin +
|
||||
le16_to_cpu(info->offset));
|
||||
num_dies = le16_to_cpu(ihdr->num_dies);
|
||||
|
||||
DRM_DEBUG("number of dies: %d\n", num_dies);
|
||||
|
||||
for (i = 0; i < num_dies; i++) {
|
||||
die_offset = le16_to_cpu(ihdr->die_info[i].die_offset);
|
||||
dhdr = (struct die_header *)(discovery_bin + die_offset);
|
||||
num_ips = le16_to_cpu(dhdr->num_ips);
|
||||
ip_offset = die_offset + sizeof(*dhdr);
|
||||
|
||||
if (le16_to_cpu(dhdr->die_id) != i) {
|
||||
DRM_ERROR("invalid die id %d, expected %d\n",
|
||||
le16_to_cpu(dhdr->die_id), i);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
DRM_DEBUG("number of hardware IPs on die%d: %d\n",
|
||||
le16_to_cpu(dhdr->die_id), num_ips);
|
||||
|
||||
for (j = 0; j < num_ips; j++) {
|
||||
ip = (struct ip_v4 *)(discovery_bin + ip_offset);
|
||||
|
||||
inst = ip->instance_number;
|
||||
hw_id = le16_to_cpu(ip->hw_id);
|
||||
if (amdgpu_discovery_validate_ip(adev, inst, hw_id))
|
||||
goto next_ip;
|
||||
|
||||
num_base_address = ip->num_base_address;
|
||||
|
||||
DRM_DEBUG("%s(%d) #%d v%d.%d.%d:\n",
|
||||
hw_id_names[le16_to_cpu(ip->hw_id)],
|
||||
le16_to_cpu(ip->hw_id),
|
||||
ip->instance_number,
|
||||
ip->major, ip->minor,
|
||||
ip->revision);
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VCN_HWID) {
|
||||
/* Bit [5:0]: original revision value
|
||||
* Bit [7:6]: en/decode capability:
|
||||
* 0b00 : VCN function normally
|
||||
* 0b10 : encode is disabled
|
||||
* 0b01 : decode is disabled
|
||||
*/
|
||||
if (adev->vcn.num_vcn_inst <
|
||||
AMDGPU_MAX_VCN_INSTANCES) {
|
||||
adev->vcn.inst[adev->vcn.num_vcn_inst].vcn_config =
|
||||
ip->revision & 0xc0;
|
||||
adev->vcn.num_vcn_inst++;
|
||||
adev->vcn.inst_mask |=
|
||||
(1U << ip->instance_number);
|
||||
adev->jpeg.inst_mask |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
dev_err(adev->dev, "Too many VCN instances: %d vs %d\n",
|
||||
adev->vcn.num_vcn_inst + 1,
|
||||
AMDGPU_MAX_VCN_INSTANCES);
|
||||
}
|
||||
ip->revision &= ~0xc0;
|
||||
}
|
||||
if (le16_to_cpu(ip->hw_id) == SDMA0_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA1_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA2_HWID ||
|
||||
le16_to_cpu(ip->hw_id) == SDMA3_HWID) {
|
||||
if (adev->sdma.num_instances <
|
||||
AMDGPU_MAX_SDMA_INSTANCES) {
|
||||
adev->sdma.num_instances++;
|
||||
adev->sdma.sdma_mask |=
|
||||
(1U << ip->instance_number);
|
||||
} else {
|
||||
dev_err(adev->dev, "Too many SDMA instances: %d vs %d\n",
|
||||
adev->sdma.num_instances + 1,
|
||||
AMDGPU_MAX_SDMA_INSTANCES);
|
||||
}
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == VPE_HWID) {
|
||||
if (adev->vpe.num_instances < AMDGPU_MAX_VPE_INSTANCES)
|
||||
adev->vpe.num_instances++;
|
||||
else
|
||||
dev_err(adev->dev, "Too many VPE instances: %d vs %d\n",
|
||||
adev->vpe.num_instances + 1,
|
||||
AMDGPU_MAX_VPE_INSTANCES);
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == UMC_HWID) {
|
||||
adev->gmc.num_umc++;
|
||||
adev->umc.node_inst_num++;
|
||||
}
|
||||
|
||||
if (le16_to_cpu(ip->hw_id) == GC_HWID)
|
||||
adev->gfx.xcc_mask |=
|
||||
(1U << ip->instance_number);
|
||||
|
||||
if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID)
|
||||
wafl_ver = IP_VERSION_FULL(ip->major, ip->minor,
|
||||
ip->revision, 0, 0);
|
||||
|
||||
for (k = 0; k < num_base_address; k++) {
|
||||
/*
|
||||
* convert the endianness of base addresses in place,
|
||||
* so that we don't need to convert them when accessing adev->reg_offset.
|
||||
*/
|
||||
if (ihdr->base_addr_64_bit)
|
||||
/* Truncate the 64bit base address from ip discovery
|
||||
* and only store lower 32bit ip base in reg_offset[].
|
||||
* Bits > 32 follows ASIC specific format, thus just
|
||||
* discard them and handle it within specific ASIC.
|
||||
* By this way reg_offset[] and related helpers can
|
||||
* stay unchanged.
|
||||
* The base address is in dwords, thus clear the
|
||||
* highest 2 bits to store.
|
||||
*/
|
||||
ip->base_address[k] =
|
||||
lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF;
|
||||
else
|
||||
ip->base_address[k] = le32_to_cpu(ip->base_address[k]);
|
||||
DRM_DEBUG("\t0x%08x\n", ip->base_address[k]);
|
||||
}
|
||||
|
||||
for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) {
|
||||
if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) &&
|
||||
hw_id_map[hw_ip] != 0) {
|
||||
DRM_DEBUG("set register base offset for %s\n",
|
||||
hw_id_names[le16_to_cpu(ip->hw_id)]);
|
||||
adev->reg_offset[hw_ip][ip->instance_number] =
|
||||
ip->base_address;
|
||||
/* Instance support is somewhat inconsistent.
|
||||
* SDMA is a good example. Sienna cichlid has 4 total
|
||||
* SDMA instances, each enumerated separately (HWIDs
|
||||
* 42, 43, 68, 69). Arcturus has 8 total SDMA instances,
|
||||
* but they are enumerated as multiple instances of the
|
||||
* same HWIDs (4x HWID 42, 4x HWID 43). UMC is another
|
||||
* example. On most chips there are multiple instances
|
||||
* with the same HWID.
|
||||
*/
|
||||
|
||||
if (ihdr->version < 3) {
|
||||
subrev = 0;
|
||||
variant = 0;
|
||||
} else {
|
||||
subrev = ip->sub_revision;
|
||||
variant = ip->variant;
|
||||
}
|
||||
|
||||
adev->ip_versions[hw_ip]
|
||||
[ip->instance_number] =
|
||||
IP_VERSION_FULL(ip->major,
|
||||
ip->minor,
|
||||
ip->revision,
|
||||
variant,
|
||||
subrev);
|
||||
}
|
||||
}
|
||||
|
||||
next_ip:
|
||||
if (ihdr->base_addr_64_bit)
|
||||
ip_offset += struct_size(ip, base_address_64, ip->num_base_address);
|
||||
else
|
||||
ip_offset += struct_size(ip, base_address, ip->num_base_address);
|
||||
}
|
||||
}
|
||||
|
||||
if (wafl_ver && !adev->ip_versions[XGMI_HWIP][0])
|
||||
adev->ip_versions[XGMI_HWIP][0] = wafl_ver;
|
||||
|
||||
return 0;
|
||||
}
|
||||
#undef hw_id_map
|
||||
#undef amdgpu_discovery_validate_ip
|
||||
#undef amdgpu_discovery_reg_base_init
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,218 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Actual retained refresh function compiled against a bounded CPU acquisition
|
||||
* model. This is not a production amdgpu_device, MMIO or reset provider. */
|
||||
#ifdef NDEBUG
|
||||
#error "discovery refresh checks require active assertions"
|
||||
#endif
|
||||
#include "../stela/discovery_binary.h"
|
||||
#include <assert.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef uint64_t u64;
|
||||
typedef uint32_t u32;
|
||||
typedef uint16_t u16;
|
||||
typedef uint8_t u8;
|
||||
typedef int64_t loff_t;
|
||||
#define U32_MAX UINT32_MAX
|
||||
#define __aligned(bytes) __attribute__((__aligned__(bytes)))
|
||||
#define ALIGN(value, bytes) (((value) + (bytes) - 1) & ~((bytes) - 1))
|
||||
#define mmRCC_CONFIG_MEMSIZE 0
|
||||
#define DISCOVERY_TMR_OFFSET (64u * 1024u)
|
||||
#define le16_to_cpu(x) (x)
|
||||
#define le32_to_cpu(x) (x)
|
||||
#define RREG32(reg) ((void)(reg), adev->memory_mib)
|
||||
union nps_info { struct nps_info_v1_0 v1; };
|
||||
struct amdgpu_device {
|
||||
struct { uint8_t *bin; uint64_t offset; size_t size; bool reserve_tmr; } discovery;
|
||||
uint8_t vram[1024];
|
||||
uint64_t region;
|
||||
uint32_t memory_mib;
|
||||
bool skip, mm_fallback;
|
||||
unsigned reads, omit_read, change_read;
|
||||
};
|
||||
static bool amdgpu_device_skip_hw_access(struct amdgpu_device *adev) { return adev->skip; }
|
||||
static void amdgpu_device_vram_access(struct amdgpu_device *adev, loff_t pos,
|
||||
void *bytes, size_t size, bool write)
|
||||
{
|
||||
assert(!write && pos >= 0 && (uint64_t)pos >= adev->region);
|
||||
uint64_t offset = (uint64_t)pos - adev->region;
|
||||
assert(offset <= adev->discovery.size && size <= adev->discovery.size - offset);
|
||||
assert(offset <= sizeof(adev->vram) && size <= sizeof(adev->vram) - offset);
|
||||
unsigned read = ++adev->reads;
|
||||
assert(read <= 6);
|
||||
if (adev->mm_fallback && ((pos & 3) || (size & 3))) return;
|
||||
if (adev->mm_fallback) assert(!((uintptr_t)bytes & 3));
|
||||
if (read == adev->change_read) adev->vram[0] ^= 1;
|
||||
if (read != adev->omit_read) memcpy(bytes, adev->vram + offset, size);
|
||||
}
|
||||
static bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev,
|
||||
uint8_t *data, uint32_t bytes,
|
||||
uint16_t expected)
|
||||
{
|
||||
(void)adev;
|
||||
assert(bytes <= sizeof(union nps_info));
|
||||
return amdgpu_discovery_calculate_checksum(data, bytes) == expected;
|
||||
}
|
||||
/* Generated from amdgpu_discovery.c by the Make dependency, without replacing
|
||||
* its function body or importing Linux allocation/IO implementations. */
|
||||
#include "discovery-refresh.inc"
|
||||
|
||||
static unsigned accepted, refused, mutation_accept, mutation_refuse, transfer_cases;
|
||||
static void put16(void *pointer, uint16_t value) { memcpy(pointer, &value, sizeof(value)); }
|
||||
static void put32(void *pointer, uint32_t value) { memcpy(pointer, &value, sizeof(value)); }
|
||||
static size_t directory_offset(unsigned version)
|
||||
{
|
||||
return version == 2 ? offsetof(struct binary_header_v2, table_list) :
|
||||
offsetof(struct binary_header, table_list);
|
||||
}
|
||||
static struct table_info *entry(struct amdgpu_device *device, unsigned version)
|
||||
{
|
||||
return (void *)(device->vram + directory_offset(version) + NPS_INFO * sizeof(struct table_info));
|
||||
}
|
||||
static struct nps_info_v1_0 *nps(struct amdgpu_device *device)
|
||||
{
|
||||
return (void *)(device->vram + 128);
|
||||
}
|
||||
static void checksum(struct amdgpu_device *device, unsigned version)
|
||||
{
|
||||
put16(&entry(device,version)->checksum,
|
||||
amdgpu_discovery_calculate_checksum((uint8_t *)nps(device),nps(device)->header.size_bytes));
|
||||
}
|
||||
static struct amdgpu_device fixture(unsigned version, unsigned count, bool dynamic)
|
||||
{
|
||||
struct amdgpu_device device = {0};
|
||||
device.memory_mib = 4;
|
||||
device.region = dynamic ? 0x240000 : (4u << 20) - DISCOVERY_TMR_OFFSET;
|
||||
device.discovery.offset = device.region;
|
||||
device.discovery.size = sizeof(device.vram);
|
||||
device.discovery.reserve_tmr = true;
|
||||
/* Only non-NULL initialization evidence; never dereferenced by refresh. */
|
||||
device.discovery.bin = (uint8_t *)(uintptr_t)1;
|
||||
struct binary_header_v2 *h = (void *)device.vram;
|
||||
put32(&h->binary_signature,BINARY_SIGNATURE);
|
||||
put16(&h->version_major,version);
|
||||
put16(&h->binary_size,sizeof(device.vram));
|
||||
if (version == 2) put16(&h->num_tables,TOTAL_TABLES);
|
||||
put16(&entry(&device,version)->offset,128);
|
||||
put16(&entry(&device,version)->size,sizeof(struct nps_info_v1_0));
|
||||
struct nps_info_v1_0 *data = nps(&device);
|
||||
data->header.table_id = NPS_INFO_TABLE_ID;
|
||||
data->header.version_major = 1;
|
||||
data->header.size_bytes = (uint32_t)(offsetof(struct nps_info_v1_0,instance_info) +
|
||||
count * sizeof(struct nps_instance_info_v1_0));
|
||||
data->nps_type = 3;
|
||||
data->count = count;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
data->instance_info[i].base_address = (uint64_t)i << 24;
|
||||
data->instance_info[i].limit_address = ((uint64_t)i + 1) << 24;
|
||||
}
|
||||
checksum(&device,version);
|
||||
return device;
|
||||
}
|
||||
static void reject(struct amdgpu_device *device)
|
||||
{
|
||||
union nps_info output, before;
|
||||
memset(&output,0xa5,sizeof(output)); before = output;
|
||||
assert(amdgpu_discovery_refresh_nps_info(device,&output) < 0);
|
||||
assert(!memcmp(&output,&before,sizeof(output)));
|
||||
refused++;
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
for (unsigned version = 1; version <= 2; version++) {
|
||||
for (unsigned count = 0; count <= NPS_INFO_TABLE_MAX_NUM_INSTANCES; count++) {
|
||||
for (unsigned dynamic = 0; dynamic <= 1; dynamic++) {
|
||||
struct amdgpu_device device = fixture(version,count,dynamic);
|
||||
union nps_info output;
|
||||
memset(&output,0xa5,sizeof(output));
|
||||
assert(!amdgpu_discovery_refresh_nps_info(&device,&output));
|
||||
assert(device.reads == 6);
|
||||
assert(!memcmp(&output,nps(&device),nps(&device)->header.size_bytes));
|
||||
for (size_t i = nps(&device)->header.size_bytes; i < sizeof(output); i++)
|
||||
assert(!((uint8_t *)&output)[i]);
|
||||
accepted++;
|
||||
}
|
||||
}
|
||||
for (unsigned omitted = 1; omitted <= 6; omitted++) {
|
||||
struct amdgpu_device device = fixture(version,2,true);
|
||||
device.omit_read = omitted; reject(&device);
|
||||
}
|
||||
struct amdgpu_device device;
|
||||
#define RESET() (device = fixture(version,2,true))
|
||||
for (unsigned bytes = 20; bytes <= sizeof(union nps_info); bytes++) {
|
||||
RESET(); device.mm_fallback = true;
|
||||
nps(&device)->count = 0;
|
||||
nps(&device)->header.size_bytes = bytes;
|
||||
checksum(&device,version);
|
||||
/* The padded transfer can exceed the declared binary span, but
|
||||
* must stay in the actually acquired region. Checksum remains exact. */
|
||||
put16(device.vram + offsetof(struct binary_header,binary_size),128 + bytes);
|
||||
union nps_info output;
|
||||
assert(!amdgpu_discovery_refresh_nps_info(&device,&output));
|
||||
assert(output.v1.header.size_bytes == bytes && !output.v1.count);
|
||||
for (size_t i = bytes; i < sizeof(output); i++) assert(!((uint8_t *)&output)[i]);
|
||||
transfer_cases++;
|
||||
}
|
||||
RESET(); device.skip = true; reject(&device); assert(!device.reads);
|
||||
RESET(); device.discovery.bin = NULL; reject(&device); assert(!device.reads);
|
||||
RESET(); device.discovery.reserve_tmr = false; reject(&device); assert(!device.reads);
|
||||
RESET(); device.memory_mib = 0; reject(&device); assert(!device.reads);
|
||||
RESET(); device.memory_mib = U32_MAX; reject(&device); assert(!device.reads);
|
||||
RESET(); device.discovery.offset = UINT64_MAX; reject(&device); assert(!device.reads);
|
||||
RESET(); device.discovery.offset = (4u << 20) - 8; reject(&device); assert(!device.reads);
|
||||
RESET(); device.discovery.size = 15; reject(&device); assert(!device.reads);
|
||||
RESET(); device.vram[0] ^= 1; reject(&device);
|
||||
RESET(); put16(device.vram + offsetof(struct binary_header,version_major),3); reject(&device);
|
||||
RESET(); put16(device.vram + offsetof(struct binary_header,binary_size),1025); reject(&device);
|
||||
RESET(); put16(device.vram + offsetof(struct binary_header,binary_size),16); reject(&device);
|
||||
RESET(); put16(&entry(&device,version)->offset,0); reject(&device);
|
||||
RESET(); put16(&entry(&device,version)->offset,8); reject(&device);
|
||||
RESET(); put16(&entry(&device,version)->offset,1020); reject(&device);
|
||||
RESET(); nps(&device)->header.table_id = 0; reject(&device);
|
||||
RESET(); nps(&device)->header.version_major = 2; reject(&device);
|
||||
const uint32_t invalid_sizes[] = {0, 12, 19, sizeof(union nps_info)+1, UINT32_MAX};
|
||||
for (size_t i = 0; i < sizeof(invalid_sizes)/sizeof(invalid_sizes[0]); i++) {
|
||||
RESET(); nps(&device)->header.size_bytes = invalid_sizes[i]; reject(&device);
|
||||
}
|
||||
RESET(); nps(&device)->count = UINT32_MAX; checksum(&device,version); reject(&device);
|
||||
RESET(); nps(&device)->count = 3; checksum(&device,version); reject(&device);
|
||||
RESET(); entry(&device,version)->checksum ^= 1; reject(&device);
|
||||
RESET(); device.change_read = 4; reject(&device);
|
||||
RESET(); device.change_read = 5; reject(&device);
|
||||
RESET(); nps(&device)->count = 0; nps(&device)->header.size_bytes = 21;
|
||||
checksum(&device,version); device.discovery.size = 149;
|
||||
put16(device.vram + offsetof(struct binary_header,binary_size),149); reject(&device);
|
||||
if (version == 2) {
|
||||
RESET(); put16(&((struct binary_header_v2 *)device.vram)->num_tables,NPS_INFO); reject(&device);
|
||||
RESET(); put16(&((struct binary_header_v2 *)device.vram)->num_tables,UINT16_MAX); reject(&device);
|
||||
}
|
||||
#undef RESET
|
||||
uint32_t state = 0x4e505300u + version;
|
||||
for (unsigned i = 0; i < 4096; i++) {
|
||||
device = fixture(version,NPS_INFO_TABLE_MAX_NUM_INSTANCES,true);
|
||||
state = state * 1664525u + 1013904223u;
|
||||
size_t at = (state >> 16) % sizeof(device.vram);
|
||||
state = state * 1664525u + 1013904223u;
|
||||
device.vram[at] ^= (uint8_t)(1u << (state >> 29));
|
||||
union nps_info output, before;
|
||||
memset(&output,0xa5,sizeof(output)); before = output;
|
||||
int status = amdgpu_discovery_refresh_nps_info(&device,&output);
|
||||
if (status) {
|
||||
assert(!memcmp(&output,&before,sizeof(output)));
|
||||
mutation_refuse++;
|
||||
} else {
|
||||
assert(output.v1.header.table_id == NPS_INFO_TABLE_ID);
|
||||
assert(output.v1.header.version_major == 1);
|
||||
assert(output.v1.header.size_bytes <= sizeof(output));
|
||||
assert(output.v1.count <= NPS_INFO_TABLE_MAX_NUM_INSTANCES);
|
||||
mutation_accept++;
|
||||
}
|
||||
}
|
||||
}
|
||||
printf("AMD actual refresh: %u accepted, %u refused, %u MM transfer sizes, mutations %u accepted/%u refused; bounded CPU acquisition model, no hardware\n",
|
||||
accepted,refused,transfer_cases,mutation_accept,mutation_refuse);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Independent original ordered-policy and instrumented shipping-C RAM model.
|
||||
* No callback below is a production provider or hardware-state claim. */
|
||||
#include "../stela/discovery_tmr.h"
|
||||
#include "../stela/discovery_binary.h"
|
||||
#include "../amdgpu/amdgpu_discovery_tmr_core.h"
|
||||
#include "../amdgpu/amdgpu_virt_bootstrap_core.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
typedef uint32_t u32;
|
||||
typedef uint64_t u64;
|
||||
#define U32_MAX UINT32_MAX
|
||||
#define le32_to_cpu(value) (value)
|
||||
#define AMD_SRIOV_MSG_IPD_TABLE_ID 0
|
||||
#define GFP_KERNEL 0
|
||||
struct event { unsigned kind, reg; uint64_t value; size_t bytes; };
|
||||
struct model {
|
||||
uint32_t regs[0x16062];
|
||||
struct event events[20000]; unsigned count, polls, ready_after;
|
||||
uint32_t signature; int acpi_status; uint64_t acpi_offset, acpi_size;
|
||||
bool oom, corrupt;
|
||||
uint64_t mm_position;
|
||||
const uint8_t *vram; size_t vram_size; uint64_t vram_offset;
|
||||
volatile uint32_t *register_base;
|
||||
};
|
||||
static struct model *active;
|
||||
static void event(unsigned kind, unsigned reg, uint64_t value, size_t bytes)
|
||||
{
|
||||
assert(active->count < sizeof(active->events)/sizeof(active->events[0]));
|
||||
active->events[active->count++] = (struct event){kind,reg,value,bytes};
|
||||
}
|
||||
static uint32_t model_read(uint32_t reg)
|
||||
{
|
||||
uint32_t value=active->regs[reg];
|
||||
if(reg==mmMP0_SMN_C2PMSG_33) value=active->polls++ >= active->ready_after ? 0x80000000u : 0;
|
||||
event(1,reg,value,4); return value;
|
||||
}
|
||||
struct amdgpu_device {
|
||||
struct { uint64_t offset; uint32_t size; void *bin;
|
||||
struct {void *data; size_t size;} debugfs_blob; } discovery;
|
||||
enum amd_asic_type asic_type;
|
||||
struct { uint32_t caps; bool is_vf, is_dynamic_crit_regn_enabled;
|
||||
struct {uint64_t offset;uint32_t size_kb;} crit_regn_tbl[1]; } virt;
|
||||
};
|
||||
#define amdgpu_sriov_vf(adev) ((adev)->virt.is_vf)
|
||||
#define RREG32(reg) ((void)adev, model_read(reg))
|
||||
static void msleep(unsigned milliseconds) {event(2,0,milliseconds,0);}
|
||||
static void amdgpu_device_vram_access(void *owner, uint64_t offset, void *data, size_t bytes, bool write)
|
||||
{ (void)owner;assert(!write && bytes==4);event(3,0,offset,bytes);memcpy(data,&active->signature,4); }
|
||||
static int amdgpu_acpi_get_tmr_info(void *owner, uint64_t *offset, uint64_t *size)
|
||||
{ (void)owner;event(4,0,0,0);*offset=active->acpi_offset;*size=active->acpi_size;return active->acpi_status; }
|
||||
static void *kzalloc(size_t size, int flags)
|
||||
{ (void)flags;event(5,0,0,size);return active->oom ? NULL : calloc(1,size); }
|
||||
#define amdgpu_discovery_get_tmr_info donor_get_tmr
|
||||
#include "discovery_tmr_reference.h"
|
||||
#undef amdgpu_discovery_get_tmr_info
|
||||
#define amdgpu_discovery_get_tmr_info actual_get_tmr
|
||||
#include "discovery-tmr-wrapper.inc"
|
||||
#undef amdgpu_discovery_get_tmr_info
|
||||
|
||||
#define AMDGPU_SRIOV_CAPS_IS_VF (1 << 2)
|
||||
#define AMDGPU_SRIOV_CAPS_ENABLE_IOV (1 << 1)
|
||||
#define AMDGPU_PASSTHROUGH_MODE (1 << 3)
|
||||
static bool is_virtual_machine(void) {return false;}
|
||||
static bool xen_initial_domain(void) {return false;}
|
||||
#include "discovery_tmr_virt_reference.h"
|
||||
static unsigned selector_cases;
|
||||
static __attribute__((unused)) void selectors(void)
|
||||
{
|
||||
for(unsigned a=0;a<CHIP_LAST;a++) {
|
||||
struct model m={0};active=&m;
|
||||
m.regs[mmRCC_IOV_FUNC_IDENTIFIER]=0x80000001u;
|
||||
m.regs[mmBIF_IOV_FUNC_IDENTIFIER]=0x80000000u;
|
||||
struct amdgpu_device d={.asic_type=a};
|
||||
uint32_t original=amdgpu_virt_init_detect_asic(&d), reg=0;
|
||||
bool has=amdgpu_virt_bootstrap_iov_register(a,®);
|
||||
assert(original==(has?m.regs[reg]:0));
|
||||
assert(m.count==(unsigned)has);
|
||||
if(has)assert(m.events[0].reg==reg);
|
||||
++selector_cases;
|
||||
}
|
||||
}
|
||||
static unsigned comparisons;
|
||||
static __attribute__((unused)) void compare(unsigned variant)
|
||||
{
|
||||
struct model a={.ready_after=variant%4==0?2000:variant%7,.signature=variant&1?BINARY_SIGNATURE:0,
|
||||
.acpi_offset=0x100000,.acpi_size=0x10000,.oom=(variant%9==0),.acpi_status=variant%11==0?-ENXIO:0};
|
||||
a.regs[mmRCC_CONFIG_MEMSIZE]=variant%5==0?UINT32_MAX:variant%3==0?0:1024;
|
||||
a.regs[mmDRIVER_SCRATCH_2]=variant%4==0?0:10240;
|
||||
a.regs[mmDRIVER_SCRATCH_0]=0x1000;a.regs[mmDRIVER_SCRATCH_1]=2;
|
||||
struct model b=a;
|
||||
struct amdgpu_device d={.discovery={.offset=variant%2?0x1000:0,.size=123},
|
||||
.virt={.is_vf=variant%4==1,.is_dynamic_crit_regn_enabled=variant%3==0,
|
||||
.crit_regn_tbl={{0x9000, variant%7==0?0:16}}}};
|
||||
struct amdgpu_device n=d;bool expected=variant%2,actual=expected;
|
||||
active=&a;int e=donor_get_tmr(&d,&expected);
|
||||
active=&b;int r=actual_get_tmr(&n,&actual);
|
||||
assert(e==r && expected==actual && d.discovery.offset==n.discovery.offset && d.discovery.size==n.discovery.size);
|
||||
assert(a.count==b.count && !memcmp(a.events,b.events,a.count*sizeof(struct event)));
|
||||
assert(!!d.discovery.bin==!!n.discovery.bin);
|
||||
if(!r) {assert(n.discovery.debugfs_blob.data==n.discovery.bin && n.discovery.debugfs_blob.size==n.discovery.size);}
|
||||
free(d.discovery.bin);free(n.discovery.bin);++comparisons;
|
||||
}
|
||||
/* Instrumented original native leaf: only actual leaf volatile expressions are
|
||||
* replaced by these test counters. Production has no injectable I/O provider. */
|
||||
uint32_t stela_amd_tmr_test_read(const volatile uint32_t *pointer)
|
||||
{
|
||||
uintptr_t base=(uintptr_t)(active->register_base?active->register_base:active->regs), address=(uintptr_t)pointer;
|
||||
assert(address>=base && address-base<sizeof(active->regs) && (address-base)%4==0);
|
||||
uint32_t reg=(uint32_t)((address-base)/4);
|
||||
if(reg==1) {
|
||||
event(6,reg,active->mm_position,4);
|
||||
if(active->vram) {assert(active->mm_position>=active->vram_offset && active->mm_position-active->vram_offset+4<=active->vram_size);uint32_t v;memcpy(&v,active->vram+active->mm_position-active->vram_offset,4);if(active->corrupt && active->mm_position==active->vram_offset+32)v^=1;return v;}
|
||||
return active->signature;
|
||||
}
|
||||
return model_read(reg);
|
||||
}
|
||||
void stela_amd_tmr_test_write(volatile uint32_t *pointer,uint32_t value)
|
||||
{
|
||||
uintptr_t base=(uintptr_t)(active->register_base?active->register_base:active->regs),address=(uintptr_t)pointer;
|
||||
assert(address>=base && address-base<sizeof(active->regs) && (address-base)%4==0);
|
||||
uint32_t reg=(uint32_t)((address-base)/4);assert(reg==0||reg==6);
|
||||
event(7,reg,value,4);
|
||||
if(reg==0) active->mm_position=(active->mm_position&~UINT64_C(0x7fffffff))|(value&0x7fffffff);
|
||||
else active->mm_position=((uint64_t)value<<31)|(active->mm_position&UINT64_C(0x7fffffff));
|
||||
}
|
||||
static void native_sleep(void *context,unsigned milliseconds)
|
||||
{assert(context==active);msleep(milliseconds);}
|
||||
extern int stela_amd_discovery_tmr_test_query(void *,size_t,uint32_t,void *,void(*)(void *,unsigned),struct stela_amd_discovery_tmr *);
|
||||
static unsigned native_cases;
|
||||
static __attribute__((unused)) void native_case(unsigned which)
|
||||
{
|
||||
struct model m={.ready_after=0,.signature=BINARY_SIGNATURE};active=&m;
|
||||
m.regs[mmRCC_CONFIG_MEMSIZE]=64;
|
||||
struct stela_amd_discovery_tmr out,before;memset(&before,0xa5,sizeof(before));out=before;
|
||||
size_t bytes=sizeof(m.regs);void *regs=m.regs;unsigned asic=CHIP_IP_DISCOVERY;
|
||||
void(*sleep)(void *,unsigned)=native_sleep;int expected=0;
|
||||
struct stela_amd_discovery_tmr *outp=&out;
|
||||
switch(which) {
|
||||
case 1:bytes-=1;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 2:regs=NULL;expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 3:regs=(uint8_t*)regs+1;expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 4:bytes=SIZE_MAX;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 5:sleep=NULL;expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 6:asic=CHIP_LAST;expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 7:m.regs[mmRCC_IOV_FUNC_IDENTIFIER]=1;expected=STELA_AMD_TMR_VF_OWNER_UNAVAILABLE;break;
|
||||
case 8:m.regs[mmRCC_CONFIG_MEMSIZE]=UINT32_MAX;expected=-ENXIO;break;
|
||||
case 9:m.regs[mmRCC_CONFIG_MEMSIZE]=0;expected=STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;break;
|
||||
case 10:m.regs[mmRCC_CONFIG_MEMSIZE]=0;m.regs[mmDRIVER_SCRATCH_2]=1024;expected=STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;break;
|
||||
case 11:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=4096;break;
|
||||
case 12:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1023;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 13:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=4097;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 14:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_1]=1;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 15:m.ready_after=2000;break;
|
||||
case 16:outp=NULL;expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 17:outp=(void*)((uint8_t*)&out+1);expected=STELA_AMD_TMR_INVALID;break;
|
||||
case 18:outp=(void*)m.regs;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 19:outp=(void*)(UINTPTR_MAX&~(uintptr_t)7);expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 20:regs=(void*)(UINTPTR_MAX&~(uintptr_t)3);expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 21:bytes=0;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 22:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=(64<<20)-1024;break;
|
||||
case 23:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1028;m.regs[mmDRIVER_SCRATCH_0]=(64<<20)-1024;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
case 24:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=4;m.regs[mmDRIVER_SCRATCH_0]=UINT32_MAX-3;m.regs[mmDRIVER_SCRATCH_1]=UINT32_MAX;expected=STELA_AMD_TMR_BOUNDS;break;
|
||||
}
|
||||
int r=stela_amd_discovery_tmr_test_query(regs,bytes,asic,&m,sleep,outp);
|
||||
assert(r==expected);
|
||||
if(r) assert(!memcmp(&out,&before,sizeof(out)));
|
||||
else {assert(out.size && out.offset+out.size<=out.vram_bytes && out.reserved==0);}
|
||||
if((which>=1&&which<=6)||(which>=16&&which<=21))assert(m.count==0);
|
||||
if(which==7)assert(m.count==1);
|
||||
if(which==15)assert(m.polls==2000); /* No invented timeout/READY. */
|
||||
++native_cases;
|
||||
}
|
||||
#ifndef STELA_TMR_RUST_MODEL
|
||||
int main(void)
|
||||
{
|
||||
selectors();
|
||||
for(unsigned i=0;i<256;i++)compare(i);
|
||||
for(unsigned i=0;i<25;i++)native_case(i);
|
||||
/* Selector fixture is exhaustive over actual original enum values. */
|
||||
for(unsigned a=0;a<CHIP_LAST;a++) {uint32_t r=0;bool has=amdgpu_virt_bootstrap_iov_register(a,&r);if(has)assert(r==0xde5||r==0x1503);}
|
||||
printf("AMD TMR: %u exact original ASIC selectors; %u original complete query/allocator/ordered-trace comparisons; %u native cases incl zero-I/O preflight, absent owners, mailbox bounds and2000 neverready; CPU models only\n",selector_cases,comparisons,native_cases);
|
||||
}
|
||||
|
||||
#else
|
||||
static struct model rust_model;
|
||||
void stela_amd_tmr_model_begin(volatile uint32_t *registers, const uint8_t *vram, size_t bytes)
|
||||
{
|
||||
rust_model=(struct model){.register_base=registers,.vram=vram,.vram_size=bytes,
|
||||
.vram_offset=(UINT64_C(64)<<20)-DISCOVERY_TMR_OFFSET};
|
||||
rust_model.regs[mmRCC_CONFIG_MEMSIZE]=64;
|
||||
active=&rust_model;
|
||||
}
|
||||
unsigned stela_amd_tmr_model_accesses(void) { return rust_model.count; }
|
||||
void stela_amd_tmr_model_delay(void) {rust_model.ready_after=1;}
|
||||
void stela_amd_tmr_model_vf(void) {rust_model.regs[mmRCC_IOV_FUNC_IDENTIFIER]=1;}
|
||||
void stela_amd_tmr_model_system(void) {rust_model.regs[mmRCC_CONFIG_MEMSIZE]=0;}
|
||||
void stela_amd_tmr_model_corrupt(void) {rust_model.corrupt=true;}
|
||||
void stela_amd_tmr_model_end(void) { active=NULL; }
|
||||
#endif
|
||||
@@ -0,0 +1,12 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Reuse existing original-format CPU fixture generation; no firmware payload. */
|
||||
#define main stela_amd_discovery_existing_fixture_main
|
||||
#include "discovery_binary_test.c"
|
||||
#undef main
|
||||
const uint8_t *stela_amd_tmr_fixture(size_t *size)
|
||||
{
|
||||
static uint8_t bytes[10240];
|
||||
struct fixture f=make_fixture(2,4,1,1,3,0);
|
||||
assert(amdgpu_discovery_binary_validate(f.binary,f.size)==AMDGPU_DISCOVERY_BINARY_OK);
|
||||
memset(bytes,0,sizeof(bytes));memcpy(bytes,f.binary,f.size);*size=sizeof(bytes);return bytes;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
/* Frozen original Linux8d3ae592 TMR query, CPU-only service model. */
|
||||
static int amdgpu_discovery_get_tmr_info(struct amdgpu_device *adev,
|
||||
bool *is_tmr_in_sysmem)
|
||||
{
|
||||
u64 vram_size, tmr_offset, tmr_size;
|
||||
u32 msg, tmr_offset_lo, tmr_offset_hi;
|
||||
int i, ret;
|
||||
|
||||
if (!amdgpu_sriov_vf(adev)) {
|
||||
/* It can take up to two second for IFWI init to complete on some dGPUs,
|
||||
* but generally it should be in the 60-100ms range. Normally this starts
|
||||
* as soon as the device gets power so by the time the OS loads this has long
|
||||
* completed. However, when a card is hotplugged via e.g., USB4, we need to
|
||||
* wait for this to complete. Once the C2PMSG is updated, we can
|
||||
* continue.
|
||||
*/
|
||||
|
||||
for (i = 0; i < 2000; i++) {
|
||||
msg = RREG32(mmMP0_SMN_C2PMSG_33);
|
||||
if (msg & 0x80000000)
|
||||
break;
|
||||
msleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
vram_size = RREG32(mmRCC_CONFIG_MEMSIZE);
|
||||
if (vram_size == U32_MAX)
|
||||
return -ENXIO;
|
||||
else if (!vram_size)
|
||||
*is_tmr_in_sysmem = true;
|
||||
else
|
||||
*is_tmr_in_sysmem = false;
|
||||
|
||||
/* init the default tmr size and offset */
|
||||
adev->discovery.size = DISCOVERY_TMR_SIZE;
|
||||
if (vram_size)
|
||||
adev->discovery.offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET;
|
||||
|
||||
if (amdgpu_sriov_vf(adev)) {
|
||||
if (adev->virt.is_dynamic_crit_regn_enabled) {
|
||||
adev->discovery.offset =
|
||||
adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset;
|
||||
adev->discovery.size =
|
||||
adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10;
|
||||
if (!adev->discovery.size)
|
||||
return -EINVAL;
|
||||
} else {
|
||||
goto out;
|
||||
}
|
||||
} else {
|
||||
if (adev->discovery.offset) {
|
||||
u32 signature;
|
||||
|
||||
/* If VRAM holds a valid discovery signature at the default
|
||||
* discovery offset, use it as-is.
|
||||
*/
|
||||
amdgpu_device_vram_access(adev, adev->discovery.offset,
|
||||
&signature, sizeof(signature),
|
||||
false);
|
||||
if (le32_to_cpu(signature) == BINARY_SIGNATURE)
|
||||
goto out;
|
||||
}
|
||||
|
||||
tmr_size = RREG32(mmDRIVER_SCRATCH_2);
|
||||
if (tmr_size) {
|
||||
/* It's preferred to transition to PSP mailbox reg interface
|
||||
* for both bare-metal and passthrough if available */
|
||||
adev->discovery.size = (u32)tmr_size;
|
||||
tmr_offset_lo = RREG32(mmDRIVER_SCRATCH_0);
|
||||
tmr_offset_hi = RREG32(mmDRIVER_SCRATCH_1);
|
||||
adev->discovery.offset = ((u64)le32_to_cpu(tmr_offset_hi) << 32 |
|
||||
le32_to_cpu(tmr_offset_lo));
|
||||
} else if (!vram_size) {
|
||||
/* fall back to apci approach to query tmr offset if vram_size is 0 */
|
||||
ret = amdgpu_acpi_get_tmr_info(adev, &tmr_offset, &tmr_size);
|
||||
if (ret)
|
||||
return ret;
|
||||
adev->discovery.size = DISCOVERY_TMR_SIZE;
|
||||
adev->discovery.offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET;
|
||||
}
|
||||
}
|
||||
out:
|
||||
adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL);
|
||||
if (!adev->discovery.bin)
|
||||
return -ENOMEM;
|
||||
adev->discovery.debugfs_blob.data = adev->discovery.bin;
|
||||
adev->discovery.debugfs_blob.size = adev->discovery.size;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#include <stdint.h>
|
||||
uint32_t stela_amd_tmr_test_read(const volatile uint32_t *);
|
||||
void stela_amd_tmr_test_write(volatile uint32_t *, uint32_t);
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2016 Advanced Micro Devices, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
/* Frozen original ASIC/IOV role observation, CPU test only. */
|
||||
static u32 amdgpu_virt_init_detect_asic(struct amdgpu_device *adev)
|
||||
{
|
||||
uint32_t reg;
|
||||
|
||||
switch (adev->asic_type) {
|
||||
case CHIP_TONGA:
|
||||
case CHIP_FIJI:
|
||||
reg = RREG32(mmBIF_IOV_FUNC_IDENTIFIER);
|
||||
break;
|
||||
case CHIP_VEGA10:
|
||||
case CHIP_VEGA20:
|
||||
case CHIP_NAVI10:
|
||||
case CHIP_NAVI12:
|
||||
case CHIP_SIENNA_CICHLID:
|
||||
case CHIP_ARCTURUS:
|
||||
case CHIP_ALDEBARAN:
|
||||
case CHIP_IP_DISCOVERY:
|
||||
reg = RREG32(mmRCC_IOV_FUNC_IDENTIFIER);
|
||||
break;
|
||||
default: /* other chip doesn't support SRIOV */
|
||||
reg = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
if (reg & 1)
|
||||
adev->virt.caps |= AMDGPU_SRIOV_CAPS_IS_VF;
|
||||
|
||||
if (reg & 0x80000000)
|
||||
adev->virt.caps |= AMDGPU_SRIOV_CAPS_ENABLE_IOV;
|
||||
|
||||
if (!reg) {
|
||||
/* passthrough mode exclus sriov mod */
|
||||
if (is_virtual_machine() && !xen_initial_domain())
|
||||
adev->virt.caps |= AMDGPU_PASSTHROUGH_MODE;
|
||||
}
|
||||
|
||||
return reg;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2008, 2022 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
/* CPU fixtures only: exact retained Linux policy donors with minimal model
|
||||
* containers. These do not initialize a device or create production BOs.
|
||||
*/
|
||||
#include "../stela/native_bar.h"
|
||||
|
||||
#ifdef __KERNEL__
|
||||
_Static_assert(sizeof(struct amdgpu_asic_type_quirk) == 6, "kernel quirk size");
|
||||
_Static_assert(__builtin_offsetof(struct amdgpu_asic_type_quirk, revision) == 2,
|
||||
"kernel revision offset");
|
||||
_Static_assert(__builtin_offsetof(struct amdgpu_asic_type_quirk, type) == 4,
|
||||
"kernel type offset");
|
||||
_Static_assert(sizeof(enum amd_asic_type) == 4, "kernel enum ABI");
|
||||
unsigned stela_amd_test_kernel_bar(enum amd_asic_type asic);
|
||||
unsigned stela_amd_test_kernel_bar(enum amd_asic_type asic)
|
||||
{
|
||||
return amdgpu_native_register_bar(asic);
|
||||
}
|
||||
#else
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
_Static_assert(sizeof(struct amdgpu_asic_type_quirk) == 6, "original quirk ABI");
|
||||
_Static_assert(offsetof(struct amdgpu_asic_type_quirk, revision) == 2, "revision ABI");
|
||||
_Static_assert(offsetof(struct amdgpu_asic_type_quirk, type) == 4, "type ABI");
|
||||
_Static_assert(sizeof(enum amd_asic_type) == 4, "original ASIC enum ABI");
|
||||
|
||||
typedef uint32_t u32;
|
||||
struct pci_dev {
|
||||
uint64_t base[6], bytes[6];
|
||||
unsigned flags;
|
||||
};
|
||||
struct amdgpu_device {
|
||||
enum amd_asic_type asic_type;
|
||||
uint64_t rmmio_base, rmmio_size;
|
||||
struct pci_dev *pdev;
|
||||
void *dev;
|
||||
struct {
|
||||
uint64_t base, size;
|
||||
uint32_t num_kernel_doorbells;
|
||||
void *kernel_doorbells, *cpu_addr;
|
||||
} doorbell;
|
||||
struct { uint32_t max_assignment; } doorbell_index;
|
||||
struct { unsigned db_start_dw_offset; } mes;
|
||||
};
|
||||
static uint64_t fixture_page, allocation_bytes;
|
||||
#define PAGE_SIZE fixture_page
|
||||
#define IORESOURCE_UNSET 1
|
||||
#define AMDGPU_GEM_DOMAIN_DOORBELL 0x1234
|
||||
#define min_t(t, a, b) ((t)(a) < (t)(b) ? (t)(a) : (t)(b))
|
||||
#define ALIGN(v, a) (((v) + (a) - 1) & ~((a) - 1))
|
||||
#define dev_err(...) ((void)0)
|
||||
static uint64_t pci_resource_start(struct pci_dev *p, unsigned n)
|
||||
{
|
||||
assert(n < 6);
|
||||
return p->base[n];
|
||||
}
|
||||
static uint64_t pci_resource_len(struct pci_dev *p, unsigned n)
|
||||
{
|
||||
assert(n < 6);
|
||||
return p->bytes[n];
|
||||
}
|
||||
static unsigned pci_resource_flags(struct pci_dev *p, unsigned n)
|
||||
{
|
||||
assert(n == 2);
|
||||
return p->flags;
|
||||
}
|
||||
static void amdgpu_asic_init_doorbell_index(struct amdgpu_device *a)
|
||||
{
|
||||
(void)a; /* Fixture supplies the exact scalar assignment under comparison. */
|
||||
}
|
||||
static int amdgpu_bo_create_kernel(struct amdgpu_device *a, uint64_t bytes, uint64_t alignment,
|
||||
unsigned domain, void **bo, void *gpu, void **cpu)
|
||||
{
|
||||
(void)a;
|
||||
(void)bo;
|
||||
(void)gpu;
|
||||
(void)cpu;
|
||||
assert(alignment == fixture_page && domain == AMDGPU_GEM_DOMAIN_DOORBELL);
|
||||
allocation_bytes = bytes;
|
||||
return 0;
|
||||
}
|
||||
/* Test-only symbol namespace: unchanged donor bodies below must never replace
|
||||
* original production device entry points when the full driver is linked. */
|
||||
#define amdgpu_doorbell_init stela_amd_test_donor_doorbell_init
|
||||
#define amdgpu_doorbell_create_kernel_doorbells stela_amd_test_donor_create_kernel_doorbells
|
||||
int amdgpu_doorbell_init(struct amdgpu_device *adev);
|
||||
int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev);
|
||||
uint32_t stela_amd_test_original_asic(unsigned which);
|
||||
uint32_t stela_amd_test_original_asic(unsigned which)
|
||||
{
|
||||
const uint32_t values[] = {CHIP_TAHITI, CHIP_BONAIRE, CHIP_VEGA10, CHIP_IP_DISCOVERY};
|
||||
assert(which < sizeof(values) / sizeof(values[0]));
|
||||
return values[which];
|
||||
}
|
||||
|
||||
/* Original register selection SHA256 f0303f65c788eb07dc545ef9da651a5b41d95c0141af21e83638a06ed16e683a */
|
||||
static void donor_register_bar(struct amdgpu_device *adev)
|
||||
{
|
||||
if (adev->asic_type >= CHIP_BONAIRE) {
|
||||
adev->rmmio_base = pci_resource_start(adev->pdev, 5);
|
||||
adev->rmmio_size = pci_resource_len(adev->pdev, 5);
|
||||
} else {
|
||||
adev->rmmio_base = pci_resource_start(adev->pdev, 2);
|
||||
adev->rmmio_size = pci_resource_len(adev->pdev, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/* Original amdgpu_doorbell_create_kernel_doorbells SHA256 f0c7e8fcd31289c8718df9bd6bc6a410219e9be168d3492dc1f25ccaffa87193 */
|
||||
int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev)
|
||||
{
|
||||
int r;
|
||||
int size;
|
||||
|
||||
/* SI HW does not have doorbells, skip allocation */
|
||||
if (adev->doorbell.num_kernel_doorbells == 0)
|
||||
return 0;
|
||||
|
||||
/* Reserve first num_kernel_doorbells (page-aligned) for kernel ops */
|
||||
size = ALIGN(adev->doorbell.num_kernel_doorbells * sizeof(u32), PAGE_SIZE);
|
||||
|
||||
/* Allocate an extra page for MES kernel usages (ring test) */
|
||||
adev->mes.db_start_dw_offset = size / sizeof(u32);
|
||||
size += PAGE_SIZE;
|
||||
|
||||
r = amdgpu_bo_create_kernel(adev,
|
||||
size,
|
||||
PAGE_SIZE,
|
||||
AMDGPU_GEM_DOMAIN_DOORBELL,
|
||||
&adev->doorbell.kernel_doorbells,
|
||||
NULL,
|
||||
(void **)&adev->doorbell.cpu_addr);
|
||||
if (r) {
|
||||
dev_err(adev->dev,
|
||||
"Failed to allocate kernel doorbells, err=%d\n", r);
|
||||
return r;
|
||||
}
|
||||
|
||||
adev->doorbell.num_kernel_doorbells = size / sizeof(u32);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Original amdgpu_doorbell_init SHA256 acab9b44336a9785900012350b38d0c1da0c2ed235dcc988b7af8b104ba6d917 */
|
||||
int amdgpu_doorbell_init(struct amdgpu_device *adev)
|
||||
{
|
||||
|
||||
/* No doorbell on SI hardware generation */
|
||||
if (adev->asic_type < CHIP_BONAIRE) {
|
||||
adev->doorbell.base = 0;
|
||||
adev->doorbell.size = 0;
|
||||
adev->doorbell.num_kernel_doorbells = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (pci_resource_flags(adev->pdev, 2) & IORESOURCE_UNSET)
|
||||
return -EINVAL;
|
||||
|
||||
amdgpu_asic_init_doorbell_index(adev);
|
||||
|
||||
/* doorbell bar mapping */
|
||||
adev->doorbell.base = pci_resource_start(adev->pdev, 2);
|
||||
adev->doorbell.size = pci_resource_len(adev->pdev, 2);
|
||||
|
||||
adev->doorbell.num_kernel_doorbells =
|
||||
min_t(u32, adev->doorbell.size / sizeof(u32),
|
||||
adev->doorbell_index.max_assignment + 1);
|
||||
if (adev->doorbell.num_kernel_doorbells == 0)
|
||||
return -EINVAL;
|
||||
|
||||
/*
|
||||
* For Vega, reserve and map two pages on doorbell BAR since SDMA
|
||||
* paging queue doorbell use the second page. The
|
||||
* AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the
|
||||
* doorbells are in the first page. So with paging queue enabled,
|
||||
* the max num_kernel_doorbells should + 1 page (0x400 in dword)
|
||||
*/
|
||||
if (adev->asic_type >= CHIP_VEGA10)
|
||||
adev->doorbell.num_kernel_doorbells += 0x400;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifndef STELA_AMD_BAR_TEST_LIBRARY
|
||||
int main(void)
|
||||
{
|
||||
unsigned cases = 0;
|
||||
const uint32_t assignments[] = {0, 31, 255, 1023, 2047, 4095};
|
||||
const uint64_t pages[] = {4096, 65536};
|
||||
for (unsigned asic = 0; asic < CHIP_LAST; asic++) {
|
||||
for (unsigned p = 0; p < 2; p++) {
|
||||
for (unsigned m = 0; m < 6; m++) {
|
||||
fixture_page = pages[p];
|
||||
struct pci_dev pci = {
|
||||
.base = {0, 0, 0x100000, 0, 0, 0x200000},
|
||||
.bytes = {0, 0, 0x100000, 0, 0, 0x40000},
|
||||
};
|
||||
struct amdgpu_device device = {
|
||||
.asic_type = asic, .pdev = &pci, .doorbell_index = {assignments[m]},
|
||||
};
|
||||
donor_register_bar(&device);
|
||||
assert(!amdgpu_doorbell_init(&device));
|
||||
allocation_bytes = 0;
|
||||
assert(!amdgpu_doorbell_create_kernel_doorbells(&device));
|
||||
struct stela_amd_bar_layout layout;
|
||||
assert(stela_amd_native_bar_layout(asic, asic < CHIP_BONAIRE ? 0 : pci.bytes[2],
|
||||
asic < CHIP_BONAIRE ? 0 : assignments[m],
|
||||
fixture_page, &layout) == STELA_AMD_BAR_OK);
|
||||
uint32_t bar = UINT32_MAX;
|
||||
assert(stela_amd_native_register_bar(asic, &bar) == STELA_AMD_BAR_OK);
|
||||
assert(bar == layout.register_bar);
|
||||
assert(device.rmmio_base == pci.base[layout.register_bar]);
|
||||
assert(device.rmmio_size == pci.bytes[layout.register_bar]);
|
||||
assert(device.doorbell.num_kernel_doorbells == layout.kernel_doorbells);
|
||||
assert(allocation_bytes == layout.kernel_doorbell_bytes);
|
||||
if (layout.kernel_doorbells)
|
||||
assert(device.mes.db_start_dw_offset * 4 == allocation_bytes - fixture_page);
|
||||
cases++;
|
||||
}
|
||||
}
|
||||
}
|
||||
struct stela_amd_bar_layout output, saved;
|
||||
memset(&output, 0xa5, sizeof(output));
|
||||
saved = output;
|
||||
const struct {
|
||||
uint32_t asic;
|
||||
uint64_t bytes;
|
||||
uint32_t max;
|
||||
uint64_t page;
|
||||
} bad[] = {
|
||||
{CHIP_LAST, 65536, 1023, 4096}, {CHIP_BONAIRE, 65536, 1023, 0},
|
||||
{CHIP_BONAIRE, 65536, 1023, 8191}, {CHIP_BONAIRE, 65536, 1023, UINT64_MAX},
|
||||
{CHIP_BONAIRE, 0, 1023, 4096}, {CHIP_BONAIRE, 3, 1023, 4096},
|
||||
{CHIP_BONAIRE, UINT64_MAX, 1023, 4096}, {CHIP_BONAIRE, 65536, UINT32_MAX, 4096},
|
||||
{CHIP_VEGA10, 65536, UINT32_MAX - 1, 4096}, {CHIP_VEGA10, 4096, 1023, 4096},
|
||||
{CHIP_BONAIRE, UINT64_C(0xffffffff) * 4, UINT32_C(0x7ffffffe), 4096},
|
||||
{CHIP_TAHITI, 4096, 0, 4096}, {CHIP_TAHITI, 0, 1, 4096},
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
|
||||
assert(stela_amd_native_bar_layout(bad[i].asic, bad[i].bytes, bad[i].max,
|
||||
bad[i].page, &output) != STELA_AMD_BAR_OK);
|
||||
assert(!memcmp(&output, &saved, sizeof(output)));
|
||||
}
|
||||
assert(stela_amd_native_bar_layout(CHIP_TAHITI, 0, 0, 4096, NULL) == STELA_AMD_BAR_INVALID);
|
||||
uint32_t bar = UINT32_MAX;
|
||||
assert(stela_amd_native_register_bar(CHIP_LAST, &bar) == STELA_AMD_BAR_INVALID);
|
||||
assert(bar == UINT32_MAX);
|
||||
assert(stela_amd_native_register_bar(CHIP_TAHITI, NULL) == STELA_AMD_BAR_INVALID);
|
||||
printf("AMD native BAR: %u exact original donor layouts, ABI and atomic bounds passed; no hardware\n", cases);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !__KERNEL__ */
|
||||
@@ -0,0 +1,570 @@
|
||||
//! Canonical-owner model in a separate test process: one real Authority::activate
|
||||
//! call, immutable synthetic PCI/resources and actual native C policy/ABI.
|
||||
//! No physical GPU, page table, cache-policy or hardware activation is modeled
|
||||
//! as completed by a production adapter.
|
||||
extern crate alloc;
|
||||
#[path = "pci.rs"]
|
||||
mod pci_tests;
|
||||
#[path = "vram.rs"]
|
||||
mod vram_tests;
|
||||
use stela_drivers::{
|
||||
Clock, bus,
|
||||
gpu::amd::{discovery, native_mmio, pci},
|
||||
};
|
||||
|
||||
use bus::{
|
||||
mmio::owned::{
|
||||
AddressSpace, Authority, CacheAttribute, Error as MmioError, InstalledMapping, MapFailure,
|
||||
MapRequest, MappingPlatform, PhysicalSpan, Protection, Resource, ResourceBacking,
|
||||
ResourceKind,
|
||||
},
|
||||
pci::{Address, ConfigSpace, Function},
|
||||
};
|
||||
use native_mmio::{AttachedBars, Error, KernelDoorbells, RegisterBar, Rollback, Stage};
|
||||
use std::{
|
||||
alloc::{Layout, alloc_zeroed, dealloc},
|
||||
collections::BTreeMap,
|
||||
ptr::NonNull,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
#[link(name = "stela-amd-bar-test", kind = "static")]
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_test_original_asic(which: u32) -> u32;
|
||||
}
|
||||
fn asic(which: u32) -> u32 {
|
||||
// SAFETY: the C fixture returns an original header enum, no hardware call.
|
||||
unsafe { stela_amd_test_original_asic(which) }
|
||||
}
|
||||
|
||||
struct Config;
|
||||
impl ConfigSpace for Config {
|
||||
fn read32(&self, offset: u16) -> u32 {
|
||||
match offset {
|
||||
0 => 0x1234_1002,
|
||||
8 => 0x1200_0000, // Original matching is not restricted to display inventory.
|
||||
_ => panic!("resource attachment must not probe or activate hardware"),
|
||||
}
|
||||
}
|
||||
fn write32(&mut self, _: u16, _: u32) {
|
||||
panic!("no PCI writes")
|
||||
}
|
||||
fn write16(&mut self, _: u16, _: u16) {
|
||||
panic!("no PCI writes")
|
||||
}
|
||||
fn write8(&mut self, _: u16, _: u8) {
|
||||
panic!("no PCI writes")
|
||||
}
|
||||
}
|
||||
fn function() -> Function<Config> {
|
||||
Function::new(
|
||||
Address {
|
||||
segment: 0,
|
||||
bus: 1,
|
||||
device: 0,
|
||||
function: 0,
|
||||
},
|
||||
Config,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Backing {
|
||||
span: PhysicalSpan,
|
||||
kind: ResourceKind,
|
||||
drops: Arc<AtomicUsize>,
|
||||
}
|
||||
impl Drop for Backing {
|
||||
fn drop(&mut self) {
|
||||
self.drops.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
// SAFETY: test-only exclusive immutable synthetic resource, retained by the
|
||||
// canonical owner. It neither stands in for physical ownership nor drives a GPU.
|
||||
unsafe impl ResourceBacking for Backing {
|
||||
fn physical_span(&self) -> PhysicalSpan {
|
||||
self.span
|
||||
}
|
||||
fn kind(&self) -> ResourceKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
fn resource(base: u64, bytes: u64, kind: ResourceKind) -> (Resource, Arc<AtomicUsize>) {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let result = Resource::new(Box::new(Backing {
|
||||
span: PhysicalSpan::new(base, bytes).unwrap(),
|
||||
kind,
|
||||
drops: Arc::clone(&drops),
|
||||
}));
|
||||
(result, drops)
|
||||
}
|
||||
fn registers(base: u64, bar: u8) -> RegisterBar {
|
||||
RegisterBar {
|
||||
index: bar,
|
||||
resource: resource(base, 16384, ResourceKind::Registers).0,
|
||||
}
|
||||
}
|
||||
fn doors(base: u64, modern: bool) -> KernelDoorbells {
|
||||
KernelDoorbells {
|
||||
index: 2,
|
||||
resource: resource(base, 65536, ResourceKind::PrefetchableMemory).0,
|
||||
offset: 4096,
|
||||
reserved_bytes: if modern { 16384 } else { 8192 },
|
||||
logical_dwords: if modern { 3072 } else { 2048 },
|
||||
max_assignment: 1023,
|
||||
}
|
||||
}
|
||||
|
||||
struct Allocation {
|
||||
address: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct ModelState {
|
||||
calls: usize,
|
||||
unmaps: usize,
|
||||
fail_map: usize,
|
||||
fail_uncertain: bool,
|
||||
fail_unmaps: usize,
|
||||
next_token: u64,
|
||||
allocations: BTreeMap<u64, Allocation>,
|
||||
requests: Vec<MapRequest>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Model(Mutex<ModelState>);
|
||||
// SAFETY: isolated CPU model. Its own aligned allocation is exact and retained
|
||||
// through acknowledged unmap or the canonical quarantine. No native root/cache
|
||||
// implementation is claimed; production requires the actual mount provider.
|
||||
unsafe impl MappingPlatform for Model {
|
||||
fn check_context(&self, _: AddressSpace) -> Result<(), MmioError> {
|
||||
Ok(())
|
||||
}
|
||||
unsafe fn map(
|
||||
&self,
|
||||
resource: &Resource,
|
||||
request: MapRequest,
|
||||
) -> Result<InstalledMapping, MapFailure> {
|
||||
assert_eq!(request.attribute, CacheAttribute::Uncached);
|
||||
assert_eq!(request.protection, Protection::ReadWrite);
|
||||
assert!(request.physical.start() >= resource.physical_span().start());
|
||||
assert!(request.physical.end() <= resource.physical_span().end());
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.calls += 1;
|
||||
state.requests.push(request);
|
||||
let failing = state.calls == state.fail_map;
|
||||
if failing && !state.fail_uncertain {
|
||||
return Err(MapFailure::Unchanged(MmioError::MappingFailed));
|
||||
}
|
||||
let bytes = usize::try_from(request.physical.bytes()).unwrap();
|
||||
let layout = Layout::from_size_align(bytes, 4096).unwrap();
|
||||
// SAFETY: nonempty checked model allocation, retained below.
|
||||
let address = NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap();
|
||||
state.next_token += 1;
|
||||
let token = state.next_token;
|
||||
state.allocations.insert(
|
||||
token,
|
||||
Allocation {
|
||||
address: address.as_ptr() as usize,
|
||||
bytes,
|
||||
},
|
||||
);
|
||||
if failing {
|
||||
return Err(MapFailure::Uncertain(MmioError::MappingFailed));
|
||||
}
|
||||
Ok(InstalledMapping {
|
||||
token,
|
||||
cpu_base: address,
|
||||
physical: request.physical,
|
||||
attribute: request.attribute,
|
||||
protection: request.protection,
|
||||
})
|
||||
}
|
||||
unsafe fn unmap(
|
||||
&self,
|
||||
request: MapRequest,
|
||||
mapping: InstalledMapping,
|
||||
) -> Result<(), MmioError> {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.unmaps += 1;
|
||||
assert_eq!(request.physical, mapping.physical);
|
||||
if state.fail_unmaps != 0 {
|
||||
state.fail_unmaps -= 1;
|
||||
return Err(MmioError::UnmapFailed);
|
||||
}
|
||||
let allocation = state.allocations.remove(&mapping.token).unwrap();
|
||||
assert_eq!(allocation.address, mapping.cpu_base.as_ptr() as usize);
|
||||
assert_eq!(allocation.bytes as u64, request.physical.bytes());
|
||||
// SAFETY: the caller's canonical model lease guarantees consumer drain;
|
||||
// this exact allocation/token has been removed once, before deallocation.
|
||||
unsafe {
|
||||
dealloc(
|
||||
allocation.address as *mut u8,
|
||||
Layout::from_size_align(allocation.bytes, 4096).unwrap(),
|
||||
)
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_amd_attachment() {
|
||||
let model = Arc::new(Model::default());
|
||||
// SAFETY: a single isolated CPU test process, complete empty model alias
|
||||
// inventory and one canonical authority. This does not activate real MMIO.
|
||||
let authority = unsafe {
|
||||
Authority::activate(
|
||||
model.clone(),
|
||||
AddressSpace {
|
||||
identity: 1,
|
||||
physical_bits: 48,
|
||||
virtual_bits: 48,
|
||||
},
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
pci_tests::original_match(&authority, &model);
|
||||
let pci = function();
|
||||
vram_tests::original_read(&authority, &pci);
|
||||
|
||||
// SI: original BAR2 and no manufactured doorbell allocation.
|
||||
// SAFETY: model function/enum/resources belong to this one isolated owner.
|
||||
let mut si = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(0),
|
||||
asic(0),
|
||||
registers(0x100000, 2),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
discovery::acquire_dynamic_ip(
|
||||
&si,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(discovery::Error::Window(Error::AdmissionRequired))
|
||||
));
|
||||
assert_eq!(si.original_plan(), None);
|
||||
assert_eq!(si.identity().address, pci.address);
|
||||
assert_eq!(si.identity().device, pci.device);
|
||||
assert_eq!(si.identity().asic_type, asic(0));
|
||||
assert_eq!(si.identity().original_flags, asic(0));
|
||||
assert_eq!(si.register_physical_span().unwrap().start(), 0x100000);
|
||||
assert!(si.doorbells().unwrap().is_none());
|
||||
{
|
||||
let window = si.registers().unwrap();
|
||||
assert_eq!(window.bytes(), 16384);
|
||||
// SAFETY: pointer is only inspected and never retained outside borrow.
|
||||
let base = unsafe { window.native_base() }.unwrap().as_ptr() as usize;
|
||||
assert_eq!(window.direct_dword(0).unwrap().as_ptr() as usize, base);
|
||||
assert_eq!(
|
||||
window.direct_dword(4095).unwrap().as_ptr() as usize,
|
||||
base + 16380
|
||||
);
|
||||
assert_eq!(
|
||||
window.direct_dword(4096).unwrap_err(),
|
||||
Error::IndirectRegisterRequired
|
||||
);
|
||||
assert_eq!(
|
||||
window.direct_dword(u32::MAX).unwrap_err(),
|
||||
Error::IndirectRegisterRequired
|
||||
);
|
||||
}
|
||||
// SAFETY: model has no device/CPU/C consumer; all borrowed views ended.
|
||||
unsafe { si.retire() }.unwrap();
|
||||
assert_eq!(si.registers().err(), Some(Error::Retired));
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
|
||||
// Actual boot ordering: registers precede discovery and kernel doorbell BO
|
||||
// creation. Retain original C's register view while attaching doors later.
|
||||
// SAFETY: same immutable synthetic original match and retained resource.
|
||||
let mut staged = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(1),
|
||||
asic(1),
|
||||
registers(0x180000, 5),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let retained = staged.registers().unwrap();
|
||||
let pointer = retained.direct_dword(0).unwrap();
|
||||
assert!(staged.doorbells().unwrap().is_none());
|
||||
{
|
||||
let mut state = model.0.lock().unwrap();
|
||||
state.fail_map = state.calls + 1;
|
||||
}
|
||||
// SAFETY: test-only original BO owner, unchanged injected doorbell failure.
|
||||
let failed =
|
||||
unsafe { staged.attach_kernel_doorbells(&authority, doors(0x190000, false)) }.unwrap_err();
|
||||
assert_eq!(failed.stage, Stage::Doorbells);
|
||||
assert_eq!(failed.rollback, Rollback::NotAttempted);
|
||||
assert_eq!(retained.direct_dword(0).unwrap(), pointer);
|
||||
assert!(staged.doorbells().unwrap().is_none());
|
||||
// SAFETY: same original owner retries actual reservation after unchanged failure.
|
||||
unsafe { staged.attach_kernel_doorbells(&authority, doors(0x190000, false)) }.unwrap();
|
||||
assert_eq!(staged.doorbells().unwrap().unwrap().bytes(), 8192);
|
||||
assert_eq!(retained.direct_dword(0).unwrap(), pointer);
|
||||
let register_maps = model
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.requests
|
||||
.iter()
|
||||
.filter(|r| r.physical.start() == 0x180000)
|
||||
.count();
|
||||
assert_eq!(register_maps, 1);
|
||||
let before = model.0.lock().unwrap().calls;
|
||||
// SAFETY: deliberately duplicate original reservation, rejected pre-map.
|
||||
assert!(unsafe { staged.attach_kernel_doorbells(&authority, doors(0x1a0000, false)) }.is_err());
|
||||
assert_eq!(model.0.lock().unwrap().calls, before);
|
||||
// SAFETY: model accesses stopped, but retained C view still pins its lease.
|
||||
assert_eq!(
|
||||
unsafe { staged.retire() },
|
||||
Err(Error::Mapping(MmioError::Busy))
|
||||
);
|
||||
drop(retained);
|
||||
// SAFETY: all original model views drained; retry removes exact register lease.
|
||||
unsafe { staged.retire() }.unwrap();
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
|
||||
// IP-discovery/Vega+ policy: actual logical extent includes paging+MES
|
||||
// pages, distinct from the deliberately larger reserved physical span.
|
||||
// SAFETY: the isolated model pins both original-role resources/reservation.
|
||||
let mut modern = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(3),
|
||||
asic(3),
|
||||
registers(0x200000, 5),
|
||||
Some(doors(0x300000, true)),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
{
|
||||
let window = modern.doorbells().unwrap().unwrap();
|
||||
assert_eq!(window.bytes(), 12288);
|
||||
assert!(window.dword(3071).is_ok());
|
||||
assert!(window.dword(3072).is_err());
|
||||
assert!(window.qword(3070).is_ok());
|
||||
assert!(window.qword(3071).is_err());
|
||||
assert!(window.qword(1).is_err());
|
||||
assert!(window.qword(u32::MAX).is_err());
|
||||
let requests = &model.0.lock().unwrap().requests;
|
||||
let door = requests.last().unwrap();
|
||||
assert_eq!(door.physical.start(), 0x301000);
|
||||
assert_eq!(door.physical.bytes(), 16384);
|
||||
}
|
||||
// Failed teardown blocks new views and retains exact canonical token for
|
||||
// acknowledged retry rather than freeing or manufacturing completion.
|
||||
model.0.lock().unwrap().fail_unmaps = 1;
|
||||
// SAFETY: no real consumers or active views in this model.
|
||||
assert_eq!(
|
||||
unsafe { modern.retire() },
|
||||
Err(Error::Mapping(MmioError::UnmapFailed))
|
||||
);
|
||||
assert_eq!(modern.registers().err(), Some(Error::Retired));
|
||||
assert_eq!(modern.doorbells().err(), Some(Error::Retired));
|
||||
// SAFETY: original model drain still holds; retry targets retained token.
|
||||
unsafe { modern.retire() }.unwrap();
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
|
||||
let calls = model.0.lock().unwrap().calls;
|
||||
let malformed = [
|
||||
(4, asic(1), Some(doors(0x400000, false))),
|
||||
(2, asic(0), Some(doors(0x400000, false))),
|
||||
(5, u32::MAX, Some(doors(0x400000, false))),
|
||||
];
|
||||
for (bar, chip, door) in malformed {
|
||||
// SAFETY: deliberately invalid model facts, expected refusal pre-map.
|
||||
let error = unsafe {
|
||||
AttachedBars::attach(&authority, &pci, chip, chip, registers(0x500000, bar), door)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.stage, Stage::Preflight);
|
||||
assert_eq!(error.rollback, Rollback::NotAttempted);
|
||||
}
|
||||
for which in 0..8 {
|
||||
let mut door = doors(0x600000, false);
|
||||
match which {
|
||||
0 => door.offset += 1,
|
||||
1 => door.reserved_bytes -= 1,
|
||||
2 => door.logical_dwords += 1,
|
||||
3 => door.resource = resource(0x500000, 65536, ResourceKind::Registers).0,
|
||||
4 => door.reserved_bytes = 4096,
|
||||
5 => door.index = 0,
|
||||
6 => door.offset = 65536,
|
||||
7 => door.reserved_bytes = usize::MAX,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
// SAFETY: deliberately malformed isolated-owner input.
|
||||
assert!(
|
||||
unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(1),
|
||||
asic(1),
|
||||
registers(0x500000, 5),
|
||||
Some(door),
|
||||
)
|
||||
}
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
// SAFETY: unaligned backing deliberately fails complete-page ownership.
|
||||
assert!(
|
||||
unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(0),
|
||||
asic(0),
|
||||
RegisterBar {
|
||||
index: 2,
|
||||
resource: resource(0x700001, 16384, ResourceKind::Registers).0,
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(model.0.lock().unwrap().calls, calls);
|
||||
|
||||
// Failed second map rolls back the first unpublished window exactly once.
|
||||
model.0.lock().unwrap().fail_map = calls + 2;
|
||||
// SAFETY: genuine isolated model ownership, platform injects unchanged error.
|
||||
let error = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(1),
|
||||
asic(1),
|
||||
registers(0x800000, 5),
|
||||
Some(doors(0x900000, false)),
|
||||
)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.stage, Stage::Doorbells);
|
||||
assert_eq!(error.rollback, Rollback::Retired);
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
|
||||
// Failed rollback leaves that real model allocation/owner quarantined.
|
||||
{
|
||||
let mut state = model.0.lock().unwrap();
|
||||
state.fail_map = state.calls + 2;
|
||||
state.fail_unmaps = 1;
|
||||
}
|
||||
let (reg, reg_drops) = resource(0xa00000, 16384, ResourceKind::Registers);
|
||||
let (door, door_drops) = resource(0xb00000, 65536, ResourceKind::Registers);
|
||||
let mut kernel = doors(0xc00000, false);
|
||||
kernel.resource = door;
|
||||
// SAFETY: owned model resources; failed unmap must preserve exact backing.
|
||||
let error = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(1),
|
||||
asic(1),
|
||||
RegisterBar {
|
||||
index: 5,
|
||||
resource: reg,
|
||||
},
|
||||
Some(kernel),
|
||||
)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
error.rollback,
|
||||
Rollback::Quarantined(MmioError::UnmapFailed)
|
||||
);
|
||||
assert_eq!(reg_drops.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(door_drops.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(authority.status().unwrap().quarantined, 1);
|
||||
|
||||
// A primary uncertain map failure has no returned window to roll back;
|
||||
// canonical ownership still quarantines its actual resource/allocation.
|
||||
{
|
||||
let mut state = model.0.lock().unwrap();
|
||||
state.fail_map = state.calls + 1;
|
||||
state.fail_uncertain = true;
|
||||
}
|
||||
let (reg, reg_drops) = resource(0xd00000, 16384, ResourceKind::Registers);
|
||||
// SAFETY: isolated model intentionally returns an uncertain partial map.
|
||||
let error = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(0),
|
||||
asic(0),
|
||||
RegisterBar {
|
||||
index: 2,
|
||||
resource: reg,
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.stage, Stage::Registers);
|
||||
assert_eq!(error.rollback, Rollback::NotAttempted);
|
||||
assert_eq!(reg_drops.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(authority.status().unwrap().quarantined, 2);
|
||||
// A late uncertain doorbell map cannot invalidate previously published
|
||||
// RMMIO. The canonical owner retains only that uncertain doorbell backing.
|
||||
// SAFETY: separate exact model resources; no hardware consumers.
|
||||
let mut late = unsafe {
|
||||
AttachedBars::attach(
|
||||
&authority,
|
||||
&pci,
|
||||
asic(1),
|
||||
asic(1),
|
||||
registers(0xe00000, 5),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let retained = late.registers().unwrap();
|
||||
let pointer = retained.direct_dword(0).unwrap();
|
||||
let (reservation, drops) = resource(0xf00000, 65536, ResourceKind::Registers);
|
||||
let mut kernel = doors(0xf00000, false);
|
||||
kernel.resource = reservation;
|
||||
{
|
||||
let mut state = model.0.lock().unwrap();
|
||||
state.fail_map = state.calls + 1;
|
||||
state.fail_uncertain = true;
|
||||
}
|
||||
// SAFETY: the model injects uncertain mapping, requiring retained ownership.
|
||||
let failed = unsafe { late.attach_kernel_doorbells(&authority, kernel) }.unwrap_err();
|
||||
assert_eq!(failed.stage, Stage::Doorbells);
|
||||
assert_eq!(failed.rollback, Rollback::NotAttempted);
|
||||
assert_eq!(retained.direct_dword(0).unwrap(), pointer);
|
||||
assert!(late.doorbells().unwrap().is_none());
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(authority.status().unwrap().quarantined, 3);
|
||||
drop(retained);
|
||||
// SAFETY: published register view drained; unrelated quarantine stays pinned.
|
||||
unsafe { late.retire() }.unwrap();
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 0);
|
||||
|
||||
println!(
|
||||
"AMD native MMIO: original policy, canonical ownership/bounds/rollback/quarantine; no hardware"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//! CPU-only original matching with actual public PCI/canonical ownership types.
|
||||
use super::*;
|
||||
use crate::pci::{Error as MatchError, IpPath, Policy, Source};
|
||||
use std::cell::Cell;
|
||||
|
||||
struct ObservedConfig {
|
||||
words: [u32; 16],
|
||||
reads: Cell<u64>,
|
||||
}
|
||||
impl ConfigSpace for ObservedConfig {
|
||||
fn read32(&self, offset: u16) -> u32 {
|
||||
assert!(offset.is_multiple_of(4));
|
||||
self.reads.set(self.reads.get() | (1 << (offset / 4)));
|
||||
self.words[usize::from(offset / 4)]
|
||||
}
|
||||
fn write32(&mut self, _: u16, _: u32) {
|
||||
panic!("original admission performs no config writes")
|
||||
}
|
||||
fn write16(&mut self, _: u16, _: u16) {
|
||||
panic!("original admission performs no config writes")
|
||||
}
|
||||
fn write8(&mut self, _: u16, _: u8) {
|
||||
panic!("original admission performs no config writes")
|
||||
}
|
||||
}
|
||||
fn observed(device: u16, class: u32, revision: u8) -> Function<ObservedConfig> {
|
||||
let mut words = [0; 16];
|
||||
words[0] = (u32::from(device) << 16) | 0x1002;
|
||||
words[2] = (class << 8) | u32::from(revision);
|
||||
words[11] = 0x5678_abcd;
|
||||
Function::new(
|
||||
Address {
|
||||
segment: 4,
|
||||
bus: 0x81,
|
||||
device: 2,
|
||||
function: 0,
|
||||
},
|
||||
ObservedConfig {
|
||||
words,
|
||||
reads: Cell::new(0),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn policy() -> Policy {
|
||||
Policy {
|
||||
si_built: true,
|
||||
cik_built: true,
|
||||
radeon_built: false,
|
||||
si_support: -1,
|
||||
cik_support: -1,
|
||||
experimental: 0,
|
||||
discovery: -1,
|
||||
force_asic: -1,
|
||||
memory_encrypted: false,
|
||||
firmware_drivers_only: false,
|
||||
modeset: -1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn original_match(authority: &Authority, model: &Arc<Model>) {
|
||||
let mut function = observed(0xffff, 0x120000, 0x45);
|
||||
// SAFETY: immutable synthetic config/build inputs, no physical hardware.
|
||||
let matched = unsafe { crate::pci::identify(&mut function, policy()) }.unwrap();
|
||||
assert_eq!(matched.address().segment, 4);
|
||||
assert_eq!(matched.revision(), 0x45);
|
||||
assert_eq!(matched.subsystem_ids(), (0xabcd, 0x5678));
|
||||
assert_eq!(matched.ip_path(), IpPath::Dynamic);
|
||||
assert_eq!(matched.source(), Source::Hardware);
|
||||
assert_eq!(matched.initial_apu_flags(), 0); // Not proof of discrete hardware.
|
||||
assert_eq!(matched.matched_row(), 310); // Exact third original wildcard.
|
||||
// SAFETY: canonical model resources belong to this immutable function.
|
||||
let mut bars =
|
||||
unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1100000, 5), None) }
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
crate::discovery::acquire_dynamic_ip(
|
||||
&bars,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(crate::discovery::Error::ClockUnavailable)
|
||||
));
|
||||
assert_eq!(bars.identity().asic_type, matched.asic_type());
|
||||
assert_eq!(bars.identity().original_flags, matched.original_flags());
|
||||
assert_eq!(
|
||||
bars.original_plan(),
|
||||
Some((IpPath::Dynamic, Source::Hardware))
|
||||
);
|
||||
// SAFETY: no real effects/consumers, exact model mapping can retire.
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
// Failed matched attachment retains the original truthful rollback behavior.
|
||||
let calls = model.0.lock().unwrap().calls;
|
||||
let error =
|
||||
unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1200000, 2), None) }
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.stage, Stage::Preflight);
|
||||
assert_eq!(model.0.lock().unwrap().calls, calls);
|
||||
{
|
||||
let mut state = model.0.lock().unwrap();
|
||||
state.fail_map = state.calls + 1;
|
||||
}
|
||||
// SAFETY: explicit unchanged model map failure, no hardware resources.
|
||||
let error =
|
||||
unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1200000, 5), None) }
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.stage, Stage::Registers);
|
||||
assert_eq!(error.rollback, Rollback::NotAttempted);
|
||||
model.0.lock().unwrap().fail_map = 0;
|
||||
assert_eq!(authority.status().unwrap().live, 0);
|
||||
assert_eq!(
|
||||
function.config().reads.get(),
|
||||
(1 << 0) | (1 << 2) | (1 << 3) | (1 << 11)
|
||||
);
|
||||
|
||||
for (id, class, path, source) in [
|
||||
(0x6780, 0x020000, IpPath::SiStatic, Source::NotUsed), // class_mask0
|
||||
(
|
||||
0x6860,
|
||||
0x120000,
|
||||
IpPath::SocStatic,
|
||||
Source::Firmware(c"amdgpu/vega10_ip_discovery.bin"),
|
||||
),
|
||||
(0x13db, 0x020000, IpPath::SocStatic, Source::NotUsed),
|
||||
(0x13fe, 0x020000, IpPath::Dynamic, Source::Hardware),
|
||||
] {
|
||||
let mut function = observed(id, class, 0);
|
||||
// SAFETY: immutable model corresponds to original initial probe stage.
|
||||
let matched = unsafe { crate::pci::identify(&mut function, policy()) }.unwrap();
|
||||
assert_eq!(matched.ip_path(), path);
|
||||
assert_eq!(matched.source(), source);
|
||||
if path != IpPath::Dynamic {
|
||||
let index = if path == IpPath::SiStatic { 2 } else { 5 };
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach_matched(authority, &matched, registers(0x1300000, index), None)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
crate::discovery::acquire_dynamic_ip(
|
||||
&bars,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(crate::discovery::Error::Window(
|
||||
Error::StaticInitializationRequired
|
||||
))
|
||||
));
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
}
|
||||
}
|
||||
let mut function = observed(0xffff, 0x120000, 0);
|
||||
let mut selected_file = policy();
|
||||
selected_file.discovery = 2;
|
||||
// SAFETY: selected original file option on immutable CPU config model.
|
||||
let matched = unsafe { crate::pci::identify(&mut function, selected_file) }.unwrap();
|
||||
assert_eq!(
|
||||
matched.source(),
|
||||
Source::Firmware(c"amdgpu/ip_discovery.bin")
|
||||
);
|
||||
let mut bars =
|
||||
unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1400000, 5), None) }
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
unsafe {
|
||||
crate::discovery::acquire_dynamic_ip(
|
||||
&bars,
|
||||
&Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
Err(crate::discovery::Error::Window(
|
||||
Error::FirmwareSourceRequired
|
||||
))
|
||||
));
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
// Matching creates no file, TMR reservation, hardware fallback or GPU state.
|
||||
|
||||
let mut changed = observed(0xffff, 0x120000, 0);
|
||||
changed.device = 0x6780;
|
||||
// SAFETY: model deliberately corrupts public labels; actual config refuses it.
|
||||
assert_eq!(
|
||||
unsafe { crate::pci::identify(&mut changed, policy()) }.err(),
|
||||
Some(MatchError::IdentityChanged)
|
||||
);
|
||||
let mut bridge = observed(0xffff, 0x120000, 0);
|
||||
bridge.config().words[3] = 1 << 16;
|
||||
assert_eq!(
|
||||
unsafe { crate::pci::identify(&mut bridge, policy()) }.err(),
|
||||
Some(MatchError::UnsupportedHeader)
|
||||
);
|
||||
assert_eq!(bridge.config().reads.get() & (1 << 11), 0); // Never wrong header subsystem layout.
|
||||
let mut absent = observed(0xffff, 0x120000, 0);
|
||||
absent.config().words[0] = u32::MAX;
|
||||
assert_eq!(
|
||||
unsafe { crate::pci::identify(&mut absent, policy()) }.err(),
|
||||
Some(MatchError::Absent)
|
||||
);
|
||||
let mut nonmatch = observed(0xffff, 0x020000, 0);
|
||||
assert_eq!(
|
||||
unsafe { crate::pci::identify(&mut nonmatch, policy()) }.err(),
|
||||
Some(MatchError::Native(2))
|
||||
);
|
||||
println!(
|
||||
"AMD matched attachment: real public types, accelerator/class0/file/static/refusals/rollback; CPU model only"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/* SPDX-License-Identifier: GPL-2.0-only */
|
||||
/* Actual production query/core plus independent frozen original donor. CPU only. */
|
||||
#include "../stela/pci_match.c"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
|
||||
#define PCI_DEVICE(vend,dev) \
|
||||
.vendor = (vend), .device = (dev), .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID
|
||||
#define CONFIG_DRM_AMDGPU_SI 1
|
||||
#define CONFIG_DRM_AMDGPU_CIK 1
|
||||
#define CONFIG_DRM_RADEON 1
|
||||
static bool build_si, build_cik, build_radeon;
|
||||
#define IS_ENABLED(x) enabled_##x
|
||||
#define enabled_CONFIG_DRM_AMDGPU_SI build_si
|
||||
#define enabled_CONFIG_DRM_AMDGPU_CIK build_cik
|
||||
#define enabled_CONFIG_DRM_RADEON build_radeon
|
||||
struct device { int unused; };
|
||||
struct pci_dev { unsigned vendor, device, subsystem_vendor, subsystem_device, class, revision; struct device dev; };
|
||||
enum amd_hw_ip_block_type {
|
||||
GC_HWIP = 1,
|
||||
HDP_HWIP,
|
||||
SDMA0_HWIP,
|
||||
SDMA1_HWIP,
|
||||
SDMA2_HWIP,
|
||||
SDMA3_HWIP,
|
||||
SDMA4_HWIP,
|
||||
SDMA5_HWIP,
|
||||
SDMA6_HWIP,
|
||||
SDMA7_HWIP,
|
||||
LSDMA_HWIP,
|
||||
MMHUB_HWIP,
|
||||
ATHUB_HWIP,
|
||||
NBIO_HWIP,
|
||||
MP0_HWIP,
|
||||
MP1_HWIP,
|
||||
UVD_HWIP,
|
||||
VCN_HWIP = UVD_HWIP,
|
||||
JPEG_HWIP = VCN_HWIP,
|
||||
VCN1_HWIP,
|
||||
VCE_HWIP,
|
||||
VPE_HWIP,
|
||||
DF_HWIP,
|
||||
DCE_HWIP,
|
||||
OSSSYS_HWIP,
|
||||
SMUIO_HWIP,
|
||||
PWR_HWIP,
|
||||
NBIF_HWIP,
|
||||
THM_HWIP,
|
||||
CLK_HWIP,
|
||||
UMC_HWIP,
|
||||
RSMU_HWIP,
|
||||
XGMI_HWIP,
|
||||
DCI_HWIP,
|
||||
PCIE_HWIP,
|
||||
ISP_HWIP,
|
||||
ATU_HWIP,
|
||||
AIGC_HWIP,
|
||||
MAX_HWIP
|
||||
};
|
||||
|
||||
#define IP_VERSION(mj,mn,rv) (((unsigned)(mj)<<24)|((unsigned)(mn)<<16)|((unsigned)(rv)<<8))
|
||||
struct amdgpu_device { unsigned long flags; enum amd_asic_type asic_type; unsigned long apu_flags; struct pci_dev *pdev; struct { bool reserve_tmr; } discovery; unsigned family, num_ip_blocks;
|
||||
struct { int num_instances; unsigned sdma_mask; } sdma;
|
||||
struct { int num_umc; } gmc; struct { unsigned xcc_mask; } gfx;
|
||||
struct { unsigned num_vcn_inst; } vcn; unsigned ip_versions[MAX_HWIP][48]; void *ddev; };
|
||||
struct drm_device;
|
||||
static int amdgpu_discovery, amdgpu_si_support, amdgpu_cik_support;
|
||||
static int amdgpu_exp_hw_support, amdgpu_modeset, amdgpu_virtual_display;
|
||||
static bool encrypted, firmware_only;
|
||||
static bool drm_firmware_drivers_only(void) { return firmware_only; }
|
||||
#define CC_ATTR_MEM_ENCRYPT 1
|
||||
static bool cc_platform_has(int unused) { (void)unused; return encrypted; }
|
||||
static bool amdgpu_device_asic_has_dc_support(struct pci_dev *p, unsigned f) { (void)p; (void)f; return false; }
|
||||
static void dev_info(struct device *dev, const char *format, ...) { (void)dev; (void)format; }
|
||||
#define ENOTSUPP 524
|
||||
static int selected_path;
|
||||
#define AMDGPU_FAMILY_SI 1
|
||||
#define AMDGPU_FAMILY_KV 2
|
||||
#define AMDGPU_FAMILY_CI 3
|
||||
#define AMDGPU_FAMILY_CZ 4
|
||||
#define AMDGPU_FAMILY_VI 5
|
||||
static int si_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_SI; return 0; }
|
||||
static int cik_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_CIK; return 0; }
|
||||
static int vi_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_VI; return 0; }
|
||||
static int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_DISCOVERY; return 0; }
|
||||
static int acquisition_status, acquisition_calls;
|
||||
static int amdgpu_discovery_init(struct amdgpu_device *a) { (void)a; acquisition_calls++; return acquisition_status; }
|
||||
static int amdgpu_discovery_reg_base_init(struct amdgpu_device *a) { (void)a; acquisition_calls++; selected_path=STELA_AMD_IP_DYNAMIC; return acquisition_status; }
|
||||
#define STATIC_INIT(name) static void name(struct amdgpu_device *a) { (void)a; selected_path=STELA_AMD_IP_SOC_STATIC; }
|
||||
STATIC_INIT(vega10_reg_base_init)
|
||||
STATIC_INIT(vega20_reg_base_init)
|
||||
STATIC_INIT(arct_reg_base_init)
|
||||
STATIC_INIT(aldebaran_reg_base_init)
|
||||
STATIC_INIT(cyan_skillfish_reg_base_init)
|
||||
static void amdgpu_discovery_harvest_ip(struct amdgpu_device *a) { (void)a; }
|
||||
static void amdgpu_discovery_get_gfx_info(struct amdgpu_device *a) { (void)a; }
|
||||
static void amdgpu_discovery_get_mall_info(struct amdgpu_device *a) { (void)a; }
|
||||
static void amdgpu_discovery_get_vcn_info(struct amdgpu_device *a) { (void)a; }
|
||||
static void drm_err(void *d, const char *f, ...) { (void)d; (void)f; }
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wunused-variable"
|
||||
#pragma clang diagnostic ignored "-Wunused-but-set-variable"
|
||||
#include "pci_reference.h"
|
||||
#pragma clang diagnostic pop
|
||||
#define amdgpu_fix_asic_type linux_amdgpu_fix_asic_type
|
||||
#define amdgpu_support_enabled linux_amdgpu_support_enabled
|
||||
#define amdgpu_device_init_apu_flags linux_amdgpu_device_init_apu_flags
|
||||
#define amdgpu_discovery_get_fw_name linux_amdgpu_discovery_get_fw_name
|
||||
#include "pci-linux-wrappers.inc"
|
||||
#undef amdgpu_fix_asic_type
|
||||
#undef amdgpu_support_enabled
|
||||
#undef amdgpu_device_init_apu_flags
|
||||
#undef amdgpu_discovery_get_fw_name
|
||||
#include "pci-linux-paths.inc"
|
||||
|
||||
static struct stela_amd_pci_policy policy(void)
|
||||
{
|
||||
return (struct stela_amd_pci_policy){.si_built=1,.cik_built=1,.si_support=-1,
|
||||
.cik_support=-1,.discovery=-1,.force_asic=-1,.modeset=-1};
|
||||
}
|
||||
static void set_policy(struct stela_amd_pci_policy p)
|
||||
{
|
||||
build_si=p.si_built;build_cik=p.cik_built;build_radeon=p.radeon_built;
|
||||
amdgpu_si_support=p.si_support;amdgpu_cik_support=p.cik_support;
|
||||
amdgpu_exp_hw_support=p.experimental;amdgpu_discovery=p.discovery;
|
||||
amdgpu_modeset=p.modeset;encrypted=p.memory_encrypted;firmware_only=p.firmware_drivers_only;
|
||||
}
|
||||
static struct pci_dev device(struct stela_amd_pci_identity i)
|
||||
{
|
||||
return (struct pci_dev){.vendor=i.vendor,.device=i.device,.subsystem_vendor=i.subvendor,
|
||||
.subsystem_device=i.subdevice,.class=i.class_code,.revision=i.revision};
|
||||
}
|
||||
static size_t comparisons;
|
||||
static void compare(struct stela_amd_pci_identity i, struct stela_amd_pci_policy p)
|
||||
{
|
||||
set_policy(p);
|
||||
struct pci_dev dev=device(i);
|
||||
struct stela_amd_pci_match out, before;
|
||||
memset(&out,0xa5,sizeof(out));before=out;
|
||||
const struct pci_device_id *ref=ref_pci_match_id(ref_pciidlist,&dev);
|
||||
assert(linux_amdgpu_fix_asic_type(&dev,ref?ref->driver_data:0)==ref_amdgpu_fix_asic_type(&dev,ref?ref->driver_data:0));
|
||||
unsigned family=ref?ref->driver_data&AMD_ASIC_MASK:0;
|
||||
assert(linux_amdgpu_support_enabled(&dev.dev,family)==ref_amdgpu_support_enabled(&dev.dev,family));
|
||||
unsigned long flags=0;
|
||||
int expected=ref?ref_probe(&dev,ref,&flags):-ENODEV;
|
||||
int status=stela_amd_pci_match(&i,&p,&out);
|
||||
if (!expected && p.force_asic>=0 && p.force_asic<CHIP_LAST) {
|
||||
assert(status==STELA_AMD_PCI_OVERRIDE_UNAVAILABLE);
|
||||
} else {
|
||||
assert((status==0)==(expected==0));
|
||||
}
|
||||
if (status) {
|
||||
assert(!memcmp(&out,&before,sizeof(out)));
|
||||
} else {
|
||||
assert(out.row==(unsigned)(ref-ref_pciidlist));
|
||||
assert(out.original_flags==flags && out.asic_type==(flags&AMD_ASIC_MASK));
|
||||
struct amdgpu_device a={.flags=flags,.asic_type=flags&AMD_ASIC_MASK,.pdev=&dev};
|
||||
struct amdgpu_device b=a;
|
||||
ref_amdgpu_device_init_apu_flags(&a);
|
||||
linux_amdgpu_device_init_apu_flags(&b);
|
||||
assert(out.initial_apu_flags==a.apu_flags && a.apu_flags==b.apu_flags);
|
||||
ref_initial_path(&a);
|
||||
const char *name=NULL;
|
||||
if (selected_path==AMDGPU_INITIAL_IP_DISCOVERY) {
|
||||
acquisition_calls=0;
|
||||
assert(ref_discovery_path(&a)==0);
|
||||
assert(out.ip_path==(unsigned)selected_path);
|
||||
if (acquisition_calls) {
|
||||
name=ref_amdgpu_discovery_get_fw_name(&a);
|
||||
assert(out.discovery_source==(name?STELA_AMD_DISCOVERY_FILE:STELA_AMD_DISCOVERY_HARDWARE));
|
||||
assert((!name&&!out.filename)||(name&&out.filename&&!strcmp(name,out.filename)));
|
||||
} else {
|
||||
assert(out.discovery_source==STELA_AMD_DISCOVERY_NOT_USED && !out.filename);
|
||||
}
|
||||
} else {
|
||||
assert(out.discovery_source==STELA_AMD_DISCOVERY_NOT_USED && !out.filename);
|
||||
assert(out.ip_path==(unsigned)selected_path-1);
|
||||
}
|
||||
}
|
||||
comparisons++;
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
assert(ARRAY_SIZE(pciidlist)==312 && ARRAY_SIZE(ref_pciidlist)==312);
|
||||
assert(ARRAY_SIZE(amdgpu_unsupported_pciidlist)==702);
|
||||
assert(!memcmp(pciidlist,ref_pciidlist,sizeof(pciidlist)));
|
||||
assert(!memcmp(amdgpu_unsupported_pciidlist,ref_amdgpu_unsupported_pciidlist,sizeof(amdgpu_unsupported_pciidlist)));
|
||||
assert(!memcmp(asic_type_quirks,ref_asic_type_quirks,sizeof(asic_type_quirks)));
|
||||
const unsigned classes[]={0x030000,0x038000,0x120000,0x020000,0x030001,0x120001};
|
||||
struct stela_amd_pci_policy p=policy();
|
||||
for (unsigned c=0;c<ARRAY_SIZE(classes);c++)
|
||||
for (unsigned id=0;id<=UINT16_MAX;id++)
|
||||
compare((struct stela_amd_pci_identity){0x1002,id,0xabcd,0x1234,classes[c],0},p);
|
||||
for (unsigned revision=0;revision<=UINT8_MAX;revision++)
|
||||
compare((struct stela_amd_pci_identity){0x1002,0x67ff,0,0,0x020000,revision},p);
|
||||
for (unsigned n=0;n<ARRAY_SIZE(pciidlist)-1;n++) {
|
||||
const struct pci_device_id *id=&pciidlist[n];
|
||||
struct stela_amd_pci_identity i={0x1002,id->device==UINT32_MAX?0xffff:id->device,0,0,id->class,0xe3};
|
||||
for (unsigned built=0;built<8;built++)
|
||||
for (int option=-2;option<=2;option++) {
|
||||
struct stela_amd_pci_policy q=policy();
|
||||
q.si_built=built&1;q.cik_built=(built>>1)&1;q.radeon_built=(built>>2)&1;
|
||||
q.si_support=option;q.cik_support=option;
|
||||
q.experimental=option;q.firmware_drivers_only=(unsigned)(option&1);
|
||||
q.memory_encrypted=(unsigned)(option&1);q.modeset=option;
|
||||
compare(i,q);
|
||||
}
|
||||
}
|
||||
for (int option=-2;option<=2;option++) {
|
||||
struct stela_amd_pci_policy q=policy();q.discovery=option;
|
||||
compare((struct stela_amd_pci_identity){0x1002,0x13db,0,0,0x020000,0},q);
|
||||
}
|
||||
/* Original predicate semantics beyond today's ANY-subsystem table rows. */
|
||||
for (unsigned bits=0;bits<64;bits++) {
|
||||
struct pci_device_id id={.vendor=bits&1?PCI_ANY_ID:0x1002,.device=bits&2?PCI_ANY_ID:0x1234,
|
||||
.subvendor=bits&4?PCI_ANY_ID:0xabcd,.subdevice=bits&8?PCI_ANY_ID:0x5678,
|
||||
.class=0x120003,.class_mask=bits&16?0xffff00:0xffffff};
|
||||
struct stela_amd_pci_identity i={0x1002,0x1234,0xabcd,0x5678,bits&32?0x120004:0x120003,0};
|
||||
struct pci_dev d=device(i);
|
||||
assert((match_one(&id,&i)!=NULL)==(ref_pci_match_one_device(&id,&d)!=NULL));
|
||||
i.subvendor++;d=device(i);
|
||||
assert((match_one(&id,&i)!=NULL)==(ref_pci_match_one_device(&id,&d)!=NULL));
|
||||
}
|
||||
/* Every original source/APU state branch, including later RAVEN2 precedence
|
||||
* and seeded flags, independently of current PCI row coverage. */
|
||||
for (unsigned asic=0;asic<CHIP_LAST;asic++)
|
||||
for (unsigned flags=0;flags<128;flags++)
|
||||
for (int option=-2;option<4;option++) {
|
||||
struct amdgpu_device a={.asic_type=asic,.apu_flags=flags};
|
||||
amdgpu_discovery=option;
|
||||
const char *ref=ref_amdgpu_discovery_get_fw_name(&a);
|
||||
struct amdgpu_device b={.asic_type=asic,.apu_flags=flags};
|
||||
const char *actual=linux_amdgpu_discovery_get_fw_name(&b);
|
||||
assert(a.discovery.reserve_tmr==b.discovery.reserve_tmr);
|
||||
assert((!ref&&!actual)||(ref&&actual&&!strcmp(ref,actual)));
|
||||
assert(a.discovery.reserve_tmr==(option==2));
|
||||
}
|
||||
const unsigned apu_ids[]={0,0x15dd,0x15d8,0x1636,0x164c,0x13fe,0x143f,0xffff};
|
||||
for (unsigned asic=0;asic<CHIP_LAST;asic++)
|
||||
for (unsigned k=0;k<ARRAY_SIZE(apu_ids);k++)
|
||||
for (unsigned apu=0;apu<2;apu++) {
|
||||
struct pci_dev d={.device=apu_ids[k]};
|
||||
struct amdgpu_device a={.asic_type=asic,.flags=apu?AMD_IS_APU:0,.apu_flags=0xa5a5a5a500000000UL,.pdev=&d};
|
||||
ref_amdgpu_device_init_apu_flags(&a);
|
||||
assert(a.apu_flags==amdgpu_initial_apu_flags(apu?AMD_IS_APU:0,asic,apu_ids[k],0xa5a5a5a500000000UL));
|
||||
ref_initial_path(&a);
|
||||
int selected=selected_path;
|
||||
assert(linux_initial_path(&a)==0 && selected_path==selected);
|
||||
assert(selected_path==(int)amdgpu_initial_ip_path(asic));
|
||||
}
|
||||
for (unsigned asic=0;asic<CHIP_LAST;asic++)
|
||||
for (unsigned flag=0;flag<2;flag++)
|
||||
for (int failure=0;failure<2;failure++) {
|
||||
struct amdgpu_device a={.asic_type=asic,.apu_flags=flag?AMD_APU_IS_CYAN_SKILLFISH2:0};
|
||||
acquisition_status=failure?-EIO:0;
|
||||
struct amdgpu_device b=a;
|
||||
acquisition_calls=0;
|
||||
int status=ref_discovery_path(&a);
|
||||
int selected=selected_path, acquired=acquisition_calls;
|
||||
acquisition_calls=0;
|
||||
assert(linux_discovery_path(&b)==status && acquisition_calls==acquired);
|
||||
assert(selected_path==selected && !memcmp(a.ip_versions,b.ip_versions,sizeof(a.ip_versions)));
|
||||
bool dynamic=amdgpu_discovery_static_asic(asic)==CHIP_LAST ||
|
||||
(asic==CHIP_CYAN_SKILLFISH && flag);
|
||||
assert((selected_path==STELA_AMD_IP_DYNAMIC)==dynamic);
|
||||
assert((status!=0)==(dynamic&&failure));
|
||||
}
|
||||
acquisition_status=0;
|
||||
/* Current original rows have no experimental flag. Exercise its exact
|
||||
* shared predicate with the independent original preflight and synthetic
|
||||
* driver_data; this does not create a production table row/device. */
|
||||
for (int option=-2;option<=2;option++) {
|
||||
amdgpu_exp_hw_support=option;firmware_only=false;encrypted=false;
|
||||
struct pci_dev d={.vendor=0x1002,.device=0xffff,.class=0x120000};
|
||||
for (unsigned experiment=0;experiment<2;experiment++) {
|
||||
struct pci_device_id id={.driver_data=CHIP_IP_DISCOVERY|(experiment?AMD_EXP_HW_SUPPORT:0)};
|
||||
unsigned long flags=0;
|
||||
assert((ref_probe(&d,&id,&flags)==0)==amdgpu_pci_experimental_allowed(id.driver_data,option));
|
||||
}
|
||||
}
|
||||
struct stela_amd_pci_identity valid={0x1002,0xffff,0,0,0x120000,0};
|
||||
for (int override=-2;override<=CHIP_LAST;override++) {p=policy();p.force_asic=override;compare(valid,p);}
|
||||
struct stela_amd_pci_match out,before;memset(&out,0x6d,sizeof(out));before=out;
|
||||
assert(stela_amd_pci_match(NULL,&p,&out)==STELA_AMD_PCI_INVALID);
|
||||
assert(stela_amd_pci_match(&valid,NULL,&out)==STELA_AMD_PCI_INVALID);
|
||||
assert(stela_amd_pci_match(&valid,&p,NULL)==STELA_AMD_PCI_INVALID);
|
||||
valid.revision=256;assert(stela_amd_pci_match(&valid,&p,&out)==STELA_AMD_PCI_INVALID);
|
||||
assert(!memcmp(&out,&before,sizeof(out)));
|
||||
printf("AMD PCI: %zu frozen original probe/match comparisons, exact tables, predicates/APU/source/static policy; CPU only\n",comparisons);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,65 @@
|
||||
//! Child of the existing one-authority native_mmio test process. The actual C
|
||||
//! entry accesses only this model's owned host RAM, never physical registers.
|
||||
use super::*;
|
||||
use stela_drivers::gpu::amd::vram;
|
||||
|
||||
pub(super) fn original_read(authority: &Authority, pci: &Function<Config>) {
|
||||
let (resource, drops) = resource(0x1100_0000, 16384, ResourceKind::Registers);
|
||||
// SAFETY: genuine canonical ownership of this isolated RAM-only model;
|
||||
// no physical device, D0/reset guard or hardware readiness is asserted.
|
||||
let mut bars = unsafe {
|
||||
AttachedBars::attach(
|
||||
authority,
|
||||
pci,
|
||||
asic(0),
|
||||
asic(0),
|
||||
RegisterBar { index: 2, resource },
|
||||
None,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let window = bars.registers().unwrap();
|
||||
let data = window.direct_dword(1).unwrap();
|
||||
// SAFETY: exclusively held real host-RAM allocation returned by the model
|
||||
// mapping platform; seed its MM_DATA word, with no active Rust reference.
|
||||
unsafe { data.as_ptr().write_volatile(0x5634_1234) };
|
||||
let mut output = [0x55aa_55aa; 4];
|
||||
// SAFETY: explicitly CPU-only register model, synchronized single test
|
||||
// thread. C must reject the complete overflowing read before any access.
|
||||
assert_eq!(
|
||||
unsafe { vram::read(&window, 256, 252, &mut output) },
|
||||
Err(vram::Error::Preflight(2))
|
||||
);
|
||||
assert_eq!(output, [0x55aa_55aa; 4]);
|
||||
// SAFETY: same exclusive RAM model. Native MM-index operations are real C
|
||||
// volatile accesses to this allocation, not an emulated VRAM device.
|
||||
unsafe { vram::read(&window, 0x8000_000c, 0x7fff_fffc, &mut output) }.unwrap();
|
||||
assert_eq!(output, [0x5634_1234; 4]);
|
||||
// SAFETY: no other model accessor exists or runs concurrently.
|
||||
assert_eq!(
|
||||
unsafe { window.direct_dword(0).unwrap().as_ptr().read_volatile() },
|
||||
0x8000_0008
|
||||
);
|
||||
// SAFETY: same bounded exclusively owned RAM words, no live references.
|
||||
assert_eq!(
|
||||
unsafe { window.direct_dword(6).unwrap().as_ptr().read_volatile() },
|
||||
1
|
||||
);
|
||||
// All accesses have stopped. A borrowed view still prevents retirement;
|
||||
// no platform unmap occurs until that exact lease is released.
|
||||
// SAFETY: model accesses drained; this attempt must refuse as Busy.
|
||||
assert_eq!(
|
||||
unsafe { bars.retire() },
|
||||
Err(Error::Mapping(MmioError::Busy))
|
||||
);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 0);
|
||||
drop(window);
|
||||
// SAFETY: no view/pointer users remain and the same exact model owner is
|
||||
// retained through the acknowledged canonical retirement retry.
|
||||
unsafe { bars.retire() }.unwrap();
|
||||
drop(bars);
|
||||
assert_eq!(drops.load(Ordering::Relaxed), 1);
|
||||
println!(
|
||||
"AMD VRAM Rust/C: same canonical window lease, atomic preflight and original low-register binding; CPU RAM only"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Original frozen driver versus actual retained wrapper/shared core. Explicit
|
||||
* CPU register/lifetime model only; no real VRAM, guard, PCI or MMIO provider. */
|
||||
#ifdef NDEBUG
|
||||
#error "VRAM MM protocol tests require active assertions"
|
||||
#endif
|
||||
#include "../stela/vram_mm.h"
|
||||
#include "vram_mm_test_io.h"
|
||||
#include "../include/asic_reg/bif/bif_4_1_d.h"
|
||||
#include "../amdgpu/amdgpu_mm_access_core.h"
|
||||
#include <assert.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
_Static_assert(sizeof(enum stela_amd_vram_mm_status) == 4, "native status ABI");
|
||||
_Static_assert(sizeof(size_t) == 8 && sizeof(void *) == 8, "native x86-64 ABI");
|
||||
static unsigned native_reads, native_writes;
|
||||
uint32_t stela_amd_test_io_read(volatile uint32_t *pointer)
|
||||
{
|
||||
native_reads++; return *pointer;
|
||||
}
|
||||
void stela_amd_test_io_write(volatile uint32_t *pointer, uint32_t value)
|
||||
{
|
||||
native_writes++; *pointer=value;
|
||||
}
|
||||
struct event { uint32_t reg, value; bool write; };
|
||||
struct model {
|
||||
uint32_t low, high;
|
||||
struct event events[512];
|
||||
unsigned count, enter, exit, lock, unlock, diagnostics;
|
||||
bool available;
|
||||
};
|
||||
struct amdgpu_device { struct model *model; int mmio_idx_lock; };
|
||||
typedef int64_t loff_t;
|
||||
static uint32_t pattern(uint64_t position)
|
||||
{
|
||||
return (uint32_t)(position * UINT64_C(0x9e3779b97f4a7c15) ^ (position >> 32)) ^ 0x56abc012u;
|
||||
}
|
||||
static void record(struct model *m, uint32_t reg, uint32_t value, bool write)
|
||||
{
|
||||
assert(m->lock == m->unlock+1 && m->count < 512);
|
||||
m->events[m->count++] = (struct event){reg,value,write};
|
||||
}
|
||||
static uint32_t model_read(struct model *m, uint32_t reg)
|
||||
{
|
||||
assert(reg == mmMM_DATA);
|
||||
uint64_t position = ((uint64_t)m->high << 31) | (m->low & 0x7fffffffu);
|
||||
uint32_t value = pattern(position);
|
||||
record(m,reg,value,false); return value;
|
||||
}
|
||||
static void model_write(struct model *m, uint32_t reg, uint32_t value)
|
||||
{
|
||||
assert(reg == mmMM_INDEX || reg == mmMM_INDEX_HI || reg == mmMM_DATA);
|
||||
record(m,reg,value,true);
|
||||
if (reg == mmMM_INDEX) m->low = value;
|
||||
if (reg == mmMM_INDEX_HI) m->high = value;
|
||||
}
|
||||
static bool enter(struct amdgpu_device *adev, int *index)
|
||||
{
|
||||
adev->model->enter++; *index=0; return adev->model->available;
|
||||
}
|
||||
static struct model *active;
|
||||
#define adev_to_drm(adev) (adev)
|
||||
#define drm_dev_enter(adev, index) enter(adev,index)
|
||||
#define drm_dev_exit(index) ((void)(index), active->exit++)
|
||||
#define spin_lock_irqsave(lockptr, flags) ((void)(lockptr), (flags)=0, active->lock++)
|
||||
#define spin_unlock_irqrestore(lockptr, flags) ((void)(lockptr), (void)(flags), active->unlock++)
|
||||
#define IS_ALIGNED(value, alignment) (!((value) & ((alignment)-1)))
|
||||
#define dev_err(...) ((void)active->diagnostics++)
|
||||
#define WREG32_NO_KIQ(reg, value) model_write(adev->model,reg,value)
|
||||
#define RREG32_NO_KIQ(reg) model_read(adev->model,reg)
|
||||
#define amdgpu_device_mm_access frozen_mm_access
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wsign-compare"
|
||||
#include "vram_mm_reference.h"
|
||||
#pragma GCC diagnostic pop
|
||||
#undef amdgpu_device_mm_access
|
||||
/* Generated mechanically by the original Make recipe from the current actual
|
||||
* Linux wrapper, including its real callback and service-call ordering. */
|
||||
#include "vram-mm-wrapper.inc"
|
||||
|
||||
static void compare(const struct model *a, const struct model *b)
|
||||
{
|
||||
assert(a->low==b->low && a->high==b->high && a->count==b->count);
|
||||
assert(a->enter==b->enter && a->exit==b->exit && a->lock==b->lock &&
|
||||
a->unlock==b->unlock && a->diagnostics==b->diagnostics);
|
||||
for (unsigned i=0; i<a->count; i++) {
|
||||
assert(a->events[i].reg==b->events[i].reg &&
|
||||
a->events[i].value==b->events[i].value && a->events[i].write==b->events[i].write);
|
||||
}
|
||||
}
|
||||
static void traces(void)
|
||||
{
|
||||
const uint64_t positions[] = {0,4,28,0x7ffffff8,0x80000000,0xfffffffc,
|
||||
0x100000000,0x17ffffff8,UINT64_C(0x123456787ffffff8),
|
||||
UINT64_C(0x7fffffff7ffffffc),INT64_MAX-3};
|
||||
const size_t sizes[] = {0,4,8,12,64,128};
|
||||
unsigned cases=0;
|
||||
for (unsigned a=0; a<sizeof(positions)/sizeof(*positions); a++)
|
||||
for (unsigned b=0; b<sizeof(sizes)/sizeof(*sizes); b++) {
|
||||
if (sizes[b] > (uint64_t)INT64_MAX-positions[a]) continue;
|
||||
for (unsigned write=0; write<2; write++) {
|
||||
uint32_t before[32], after[32];
|
||||
for (unsigned i=0; i<32; i++) before[i]=after[i]=0x12345000u+i;
|
||||
struct model old={.available=true,.high=0xdeadbeef}, fresh=old;
|
||||
struct amdgpu_device original={&old,0}, current={&fresh,0};
|
||||
active=&old; frozen_mm_access(&original,(loff_t)positions[a],before,sizes[b],write!=0);
|
||||
active=&fresh; amdgpu_device_mm_access(¤t,(loff_t)positions[a],after,sizes[b],write!=0);
|
||||
compare(&old,&fresh); assert(!memcmp(before,after,sizeof(before)));
|
||||
if (!write) for (size_t i=0; i<sizes[b]/4; i++) assert(after[i]==pattern(positions[a]+i*4));
|
||||
assert(fresh.enter==1 && fresh.exit==1 && fresh.lock==1 && fresh.unlock==1);
|
||||
cases++;
|
||||
}
|
||||
}
|
||||
/* Original lifetime refusal and unaligned-input diagnostic precede locking. */
|
||||
for (unsigned mode=0; mode<3; mode++) {
|
||||
uint32_t a=99,b=99;
|
||||
struct model old={.available=mode!=0},fresh=old;
|
||||
struct amdgpu_device original={&old,0},current={&fresh,0};
|
||||
active=&old; frozen_mm_access(&original,mode==1?1:0,&a,mode==2?1:4,false);
|
||||
active=&fresh; amdgpu_device_mm_access(¤t,mode==1?1:0,&b,mode==2?1:4,false);
|
||||
compare(&old,&fresh); assert(a==99 && b==99 && !fresh.count && !fresh.lock);
|
||||
cases++;
|
||||
}
|
||||
printf("AMD MM-index: %u independent original-wrapper ordered traces/data/lifetime cases\n",cases);
|
||||
}
|
||||
static void native_bounds(void)
|
||||
{
|
||||
uint32_t registers[16], before[16], data[16], prior[16];
|
||||
for (unsigned i=0; i<16; i++) registers[i]=before[i]=data[i]=prior[i]=0x55aa00ff;
|
||||
unsigned refusals=0;
|
||||
#define REFUSE(base, window, extent, at, output, bytes, expected) do { \
|
||||
native_reads=native_writes=0; \
|
||||
assert(stela_amd_vram_mm_test_read(base,window,extent,at,output,bytes)==(expected)); \
|
||||
assert(!native_reads && !native_writes); \
|
||||
assert(stela_amd_vram_mm_read(base,window,extent,at,output,bytes)==(expected)); \
|
||||
assert(!memcmp(registers,before,sizeof(registers)) && !memcmp(data,prior,sizeof(data))); refusals++; \
|
||||
} while (0)
|
||||
REFUSE(NULL,64,256,0,data,4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE((uint8_t *)registers+1,63,256,0,data,4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,27,256,0,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,256,0,NULL,4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,64,256,0,(uint32_t *)((uint8_t *)data+1),4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,64,256,1,data,4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,64,256,0,data,3,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,64,256,256,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,256,260,data,0,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,UINT64_MAX,0,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,INT64_MAX,INT64_MAX-3,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,INT64_MAX,INT64_MAX-7,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,SIZE_MAX-3,256,0,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,INT64_MAX,0,data,SIZE_MAX-3,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE((void *)(UINTPTR_MAX-3),28,256,0,data,4,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,256,0,(uint32_t *)(UINTPTR_MAX-3),8,STELA_AMD_VRAM_MM_BOUNDS);
|
||||
REFUSE(registers,64,256,0,registers,4,STELA_AMD_VRAM_MM_INVALID);
|
||||
REFUSE(registers,64,256,0,registers+15,8,STELA_AMD_VRAM_MM_INVALID);
|
||||
#undef REFUSE
|
||||
assert(!stela_amd_vram_mm_read(registers,28,256,256,NULL,0));
|
||||
assert(!memcmp(registers,before,sizeof(registers)));
|
||||
assert(!stela_amd_vram_mm_read(registers,28,UINT64_C(0x180000004),UINT64_C(0x17ffffffc),data,8));
|
||||
assert(registers[mmMM_INDEX]==0x80000000 && registers[mmMM_INDEX_HI]==3);
|
||||
assert(data[0]==before[mmMM_DATA] && data[1]==before[mmMM_DATA]);
|
||||
for (unsigned i=2; i<16; i++) assert(data[i]==prior[i]);
|
||||
for (unsigned i=0; i<16; i++)
|
||||
if (i!=mmMM_INDEX && i!=mmMM_INDEX_HI) assert(registers[i]==before[i]);
|
||||
/* Highest first-HI value that differs from the original cache sentinel.
|
||||
* A later transition to all ones IS programmed by the original algorithm. */
|
||||
assert(!stela_amd_vram_mm_read(registers,28,INT64_MAX,
|
||||
UINT64_C(0x7fffffff7ffffffc),data,4));
|
||||
assert(registers[mmMM_INDEX_HI]==UINT32_MAX-1 && registers[mmMM_INDEX]==UINT32_MAX-3);
|
||||
assert(!stela_amd_vram_mm_read(registers,28,INT64_MAX,
|
||||
UINT64_C(0x7fffffff7ffffffc),data,8));
|
||||
assert(registers[mmMM_INDEX_HI]==UINT32_MAX && registers[mmMM_INDEX]==0x80000000u);
|
||||
native_reads=native_writes=0;
|
||||
assert(!stela_amd_vram_mm_test_read(registers,28,INT64_MAX,
|
||||
UINT64_C(0x7fffffff7ffffffc),data,4));
|
||||
assert(native_reads==1 && native_writes==2);
|
||||
native_reads=native_writes=0;
|
||||
assert(!stela_amd_vram_mm_test_read(registers,28,INT64_MAX,
|
||||
UINT64_C(0x7fffffff7ffffffc),data,8));
|
||||
assert(native_reads==2 && native_writes==4);
|
||||
printf("AMD MM-index: %u atomic native preflight refusals; empty/exact-window/high-index RAM binding checks, no hardware\n",refusals);
|
||||
}
|
||||
int main(void) { traces(); native_bounds(); }
|
||||
@@ -0,0 +1,70 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/*
|
||||
* Copyright 2008 Advanced Micro Devices, Inc.
|
||||
* Copyright 2008 Red Hat Inc.
|
||||
* Copyright 2009 Jerome Glisse.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* Authors: Dave Airlie
|
||||
* Alex Deucher
|
||||
* Jerome Glisse
|
||||
*/
|
||||
|
||||
/* Frozen exact original amdgpu_device_mm_access at Linux
|
||||
* 8d3ae59288f1e7d58d76558a6ee96d533bc5019f. Test-only MMIO/lifetime bindings.
|
||||
* Function body SHA256 b05945ca92b5878eb8bedc88dd18a62bfd45ffd953c1597e1bfe1570b48e8f91.
|
||||
*/
|
||||
void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos,
|
||||
void *buf, size_t size, bool write)
|
||||
{
|
||||
unsigned long flags;
|
||||
uint32_t hi = ~0, tmp = 0;
|
||||
uint32_t *data = buf;
|
||||
uint64_t last;
|
||||
int idx;
|
||||
|
||||
if (!drm_dev_enter(adev_to_drm(adev), &idx))
|
||||
return;
|
||||
|
||||
if (!IS_ALIGNED(pos, 4) || !IS_ALIGNED(size, 4)) {
|
||||
dev_err(adev->dev, "unaligned pos/size (pos=0x%llx, size=0x%zx)\n",
|
||||
pos, size);
|
||||
drm_dev_exit(idx);
|
||||
return;
|
||||
}
|
||||
|
||||
spin_lock_irqsave(&adev->mmio_idx_lock, flags);
|
||||
for (last = pos + size; pos < last; pos += 4) {
|
||||
tmp = pos >> 31;
|
||||
|
||||
WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
|
||||
if (tmp != hi) {
|
||||
WREG32_NO_KIQ(mmMM_INDEX_HI, tmp);
|
||||
hi = tmp;
|
||||
}
|
||||
if (write)
|
||||
WREG32_NO_KIQ(mmMM_DATA, *data++);
|
||||
else
|
||||
*data++ = RREG32_NO_KIQ(mmMM_DATA);
|
||||
}
|
||||
|
||||
spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
|
||||
drm_dev_exit(idx);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
/* Test-object-only I/O instrumentation. No shipping source/provider hook. */
|
||||
#ifndef STELA_AMD_VRAM_MM_TEST_IO_H
|
||||
#define STELA_AMD_VRAM_MM_TEST_IO_H
|
||||
#include "../stela/vram_mm.h"
|
||||
uint32_t stela_amd_test_io_read(volatile uint32_t *);
|
||||
void stela_amd_test_io_write(volatile uint32_t *, uint32_t);
|
||||
enum stela_amd_vram_mm_status
|
||||
stela_amd_vram_mm_test_read(void *, size_t, uint64_t, uint64_t, uint32_t *, size_t);
|
||||
#endif
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Native x86-64 MM-index VRAM reads through the canonical register lease.
|
||||
//! No mapping, allocator, IRQ/reset guard, TMR ownership or GPU READY is created.
|
||||
use super::native_mmio::{Error as WindowError, RegisterWindow};
|
||||
use core::ffi::{c_int, c_void};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Error {
|
||||
Window(WindowError),
|
||||
InvalidRange,
|
||||
/// Numeric preflight failed before any register or destination effect.
|
||||
Preflight(c_int),
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn stela_amd_vram_mm_read(
|
||||
registers: *mut c_void,
|
||||
register_bytes: usize,
|
||||
vram_bytes: u64,
|
||||
position: u64,
|
||||
data: *mut u32,
|
||||
size: usize,
|
||||
) -> c_int;
|
||||
}
|
||||
|
||||
/// Read through the exact original synchronous NO_KIQ MM-index protocol.
|
||||
/// Success means the original void CPU transaction loop returned, not that a
|
||||
/// device acknowledged the read or that the bytes satisfy discovery integrity.
|
||||
/// The retained window is borrowed throughout; nothing allocates or escapes.
|
||||
///
|
||||
/// # Safety
|
||||
/// The caller holds the genuine same-device D0/bridge, reset/removal and
|
||||
/// MM-index/IRQ exclusion for the WHOLE call, including every other firmware,
|
||||
/// driver and C window user. Execution is on the owner's allowed native CPU and
|
||||
/// process context. The canonical window must be UC with original ordered
|
||||
/// MMIO32 semantics; these three original low direct registers must be valid on
|
||||
/// the actual matched device. This does not permit bypassing indirect PCIe,
|
||||
/// KIQ, RLCG or XCC routing elsewhere. `vram_bytes` is actual accessible GPU VRAM
|
||||
/// in this epoch, not domain IOVA/host RAM or a guessed capacity. The caller
|
||||
/// owns/excludes writes to the requested VRAM region (including actual TMR
|
||||
/// reservation when reading discovery). Output is distinct exclusive CPU RAM.
|
||||
/// Unexpected access faults require the platform's real fail-stop/retention
|
||||
/// policy; neither this call nor Drop invents rollback after index writes.
|
||||
pub unsafe fn read(
|
||||
window: &RegisterWindow<'_>,
|
||||
vram_bytes: u64,
|
||||
position: u64,
|
||||
output: &mut [u32],
|
||||
) -> Result<(), Error> {
|
||||
let size = output
|
||||
.len()
|
||||
.checked_mul(size_of::<u32>())
|
||||
.ok_or(Error::InvalidRange)?;
|
||||
// SAFETY: the same borrowed retained lease and all genuine owner conditions
|
||||
// are required by this unsafe API; the pointer never escapes this call.
|
||||
let registers = unsafe { window.native_base() }.map_err(Error::Window)?;
|
||||
// SAFETY: exclusive slice and same live canonical window, original C width
|
||||
// and ABI; native code checks all numeric bounds before any register effect.
|
||||
let status = unsafe {
|
||||
stela_amd_vram_mm_read(
|
||||
registers.as_ptr().cast(),
|
||||
window.bytes(),
|
||||
vram_bytes,
|
||||
position,
|
||||
output.as_mut_ptr(),
|
||||
size,
|
||||
)
|
||||
};
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Preflight(status))
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,11 @@
|
||||
#ifndef __AMD_ASIC_TYPE_H__
|
||||
#define __AMD_ASIC_TYPE_H__
|
||||
|
||||
#ifdef __KERNEL__
|
||||
#include <linux/types.h>
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Supported ASIC types
|
||||
@@ -73,7 +77,11 @@ extern const char *amdgpu_asic_name[];
|
||||
|
||||
struct amdgpu_asic_type_quirk {
|
||||
unsigned short device; /* PCI device ID */
|
||||
#ifdef __KERNEL__
|
||||
u8 revision; /* revision ID */
|
||||
#else
|
||||
uint8_t revision; /* revision ID */
|
||||
#endif
|
||||
unsigned short type; /* real ASIC type */
|
||||
};
|
||||
#endif /*__AMD_ASIC_TYPE_H__ */
|
||||
@@ -23,7 +23,7 @@
|
||||
#include <linux/stddef.h>
|
||||
#include <linux/rcupdate.h>
|
||||
|
||||
#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~3))
|
||||
#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~(rb_parent_word_t)3))
|
||||
|
||||
#define rb_entry(ptr, type, member) container_of(ptr, type, member)
|
||||
|
||||
@@ -31,9 +31,9 @@
|
||||
|
||||
/* 'empty' nodes are nodes that are known not to be inserted in an rbtree */
|
||||
#define RB_EMPTY_NODE(node) \
|
||||
((node)->__rb_parent_color == (unsigned long)(node))
|
||||
((node)->__rb_parent_color == (rb_parent_word_t)(node))
|
||||
#define RB_CLEAR_NODE(node) \
|
||||
((node)->__rb_parent_color = (unsigned long)(node))
|
||||
((node)->__rb_parent_color = (rb_parent_word_t)(node))
|
||||
|
||||
#define RB_EMPTY_LINKED_NODE(lnode) RB_EMPTY_NODE(&(lnode)->node)
|
||||
#define RB_CLEAR_LINKED_NODE(lnode) ({ \
|
||||
@@ -92,7 +92,7 @@ extern void rb_replace_node_rcu(struct rb_node *victim, struct rb_node *new,
|
||||
static inline void rb_link_node(struct rb_node *node, struct rb_node *parent,
|
||||
struct rb_node **rb_link)
|
||||
{
|
||||
node->__rb_parent_color = (unsigned long)parent;
|
||||
node->__rb_parent_color = (rb_parent_word_t)parent;
|
||||
node->rb_left = node->rb_right = NULL;
|
||||
|
||||
*rb_link = node;
|
||||
@@ -101,7 +101,7 @@ static inline void rb_link_node(struct rb_node *node, struct rb_node *parent,
|
||||
static inline void rb_link_node_rcu(struct rb_node *node, struct rb_node *parent,
|
||||
struct rb_node **rb_link)
|
||||
{
|
||||
node->__rb_parent_color = (unsigned long)parent;
|
||||
node->__rb_parent_color = (rb_parent_word_t)parent;
|
||||
node->rb_left = node->rb_right = NULL;
|
||||
|
||||
rcu_assign_pointer(*rb_link, node);
|
||||
|
||||
@@ -171,7 +171,7 @@ RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME, \
|
||||
#define RB_RED 0
|
||||
#define RB_BLACK 1
|
||||
|
||||
#define __rb_parent(pc) ((struct rb_node *)(pc & ~3))
|
||||
#define __rb_parent(pc) ((struct rb_node *)(pc & ~(rb_parent_word_t)3))
|
||||
|
||||
#define __rb_color(pc) ((pc) & 1)
|
||||
#define __rb_is_black(pc) __rb_color(pc)
|
||||
@@ -182,13 +182,13 @@ RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME, \
|
||||
|
||||
static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)
|
||||
{
|
||||
rb->__rb_parent_color = rb_color(rb) + (unsigned long)p;
|
||||
rb->__rb_parent_color = rb_color(rb) + (rb_parent_word_t)p;
|
||||
}
|
||||
|
||||
static inline void rb_set_parent_color(struct rb_node *rb,
|
||||
struct rb_node *p, int color)
|
||||
{
|
||||
rb->__rb_parent_color = (unsigned long)p + color;
|
||||
rb->__rb_parent_color = (rb_parent_word_t)p + color;
|
||||
}
|
||||
|
||||
static inline void
|
||||
@@ -227,7 +227,7 @@ __rb_erase_augmented(struct rb_node *node, struct rb_root *root,
|
||||
struct rb_node *child = node->rb_right;
|
||||
struct rb_node *tmp = node->rb_left;
|
||||
struct rb_node *parent, *rebalance;
|
||||
unsigned long pc;
|
||||
rb_parent_word_t pc;
|
||||
|
||||
if (!tmp) {
|
||||
/*
|
||||
|
||||
@@ -2,11 +2,18 @@
|
||||
#ifndef _LINUX_RBTREE_TYPES_H
|
||||
#define _LINUX_RBTREE_TYPES_H
|
||||
|
||||
/* Native LLP64 targets must retain every pointer bit in the tagged word. */
|
||||
#ifdef STELA_NATIVE
|
||||
typedef __UINTPTR_TYPE__ rb_parent_word_t;
|
||||
#else
|
||||
typedef unsigned long rb_parent_word_t;
|
||||
#endif
|
||||
|
||||
struct rb_node {
|
||||
unsigned long __rb_parent_color;
|
||||
rb_parent_word_t __rb_parent_color;
|
||||
struct rb_node *rb_right;
|
||||
struct rb_node *rb_left;
|
||||
} __attribute__((aligned(sizeof(long))));
|
||||
} __attribute__((aligned(sizeof(rb_parent_word_t))));
|
||||
/* The alignment might seem pointless, but allegedly CRIS needs it */
|
||||
|
||||
struct rb_node_linked {
|
||||
|
||||
@@ -934,3 +934,9 @@ option(
|
||||
value : false,
|
||||
description : 'Build the retained AMD LLVM backend for Stela compiler targets (requires matching LLVM 23 development files)',
|
||||
)
|
||||
option(
|
||||
'stela-metal-input-library',
|
||||
type : 'string',
|
||||
value : '',
|
||||
description : 'Matching hosted Rust input static library for the optional Darwin Metal library assembler',
|
||||
)
|
||||
@@ -0,0 +1,727 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#define STELA_AIR_METADATA_INTERNAL
|
||||
#include "air_metadata.h"
|
||||
#include "llvm-c/Analysis.h"
|
||||
#include "llvm-c/BitReader.h"
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
|
||||
#define MIN2(a,b) ((a) < (b) ? (a) : (b))
|
||||
static bool
|
||||
fail(struct stela_air_metadata *t, enum stela_air_error_kind kind, const char *fmt, ...)
|
||||
{
|
||||
if (t->error->kind == STELA_AIR_OK) {
|
||||
t->error->kind = kind;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsnprintf(t->error->detail, sizeof(t->error->detail), fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_md_string(LLVMValueRef value, const char *expected)
|
||||
{
|
||||
if (!value || !LLVMIsAMDString(value))
|
||||
return false;
|
||||
unsigned length;
|
||||
const char *string = LLVMGetMDString(value, &length);
|
||||
return length == strlen(expected) && !memcmp(string, expected, length);
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_md_uint(LLVMValueRef value, unsigned *number)
|
||||
{
|
||||
if (!value || !LLVMIsAConstantInt(value) ||
|
||||
LLVMGetIntTypeWidth(LLVMTypeOf(value)) > 32)
|
||||
return false;
|
||||
*number = LLVMConstIntGetZExtValue(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_md_node(struct stela_air_metadata *t, LLVMValueRef node, LLVMValueRef *operands,
|
||||
unsigned *count)
|
||||
{
|
||||
if (!node || !LLVMIsAMDNode(node))
|
||||
return fail(t, STELA_AIR_METADATA, "expected AIR metadata node");
|
||||
*count = LLVMGetMDNodeNumOperands(node);
|
||||
if (*count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "AIR metadata operand budget exceeded");
|
||||
LLVMGetMDNodeOperands(node, operands);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_named_md(struct stela_air_metadata *t, const char *name, LLVMValueRef *operands,
|
||||
unsigned *count)
|
||||
{
|
||||
*count = LLVMGetNamedMetadataNumOperands(t->module, name);
|
||||
if (*count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "%s metadata budget exceeded", name);
|
||||
LLVMGetNamedMetadataOperands(t->module, name, operands);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_shared_profile(struct stela_air_metadata *t)
|
||||
{
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS], fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, fields_count;
|
||||
if (t->air_minor != 9 || t->language_major != 4 || t->language_minor != 1 ||
|
||||
strcmp(LLVMGetTarget(t->module), "air64_v29-apple-macosx27.2.0") ||
|
||||
!stela_air_named_md(t, "llvm.ident", nodes, &count) || count != 1 ||
|
||||
!stela_air_md_node(t, nodes[0], fields, &fields_count) || fields_count != 1 ||
|
||||
!stela_air_md_string(fields[0], "Apple metal version 32023.922 (metalfe-32023.922.4)"))
|
||||
return fail(t, STELA_AIR_METADATA, "shared-memory AIR/compiler profile is unqualified");
|
||||
if (LLVMPointerSizeForAS(t->layout, 3) != 8)
|
||||
return fail(t, STELA_AIR_TARGET, "shared-memory AIR pointers require 64-bit layout");
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
shared_storage_size(struct stela_air_metadata *t, LLVMTypeRef type, unsigned depth,
|
||||
uint64_t *size)
|
||||
{
|
||||
if (depth == 32)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared storage type nesting exceeded");
|
||||
if (LLVMGetTypeKind(type) == LLVMArrayTypeKind) {
|
||||
uint64_t element;
|
||||
if (!shared_storage_size(t, LLVMGetElementType(type), depth + 1, &element))
|
||||
return false;
|
||||
uint64_t length = LLVMGetArrayLength2(type);
|
||||
if (!length || length > UINT32_MAX / element)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared storage array extent exceeded");
|
||||
} else {
|
||||
LLVMTypeRef scalar = type;
|
||||
if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
|
||||
unsigned components = LLVMGetVectorSize(type);
|
||||
if (components < 2 || components > 4)
|
||||
return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays");
|
||||
scalar = LLVMGetElementType(type);
|
||||
}
|
||||
bool valid = LLVMGetTypeKind(scalar) == LLVMFloatTypeKind;
|
||||
if (LLVMGetTypeKind(scalar) == LLVMIntegerTypeKind) {
|
||||
unsigned bits = LLVMGetIntTypeWidth(scalar);
|
||||
valid = bits == 8 || bits == 16 || bits == 32 || bits == 64;
|
||||
}
|
||||
if (!valid)
|
||||
return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays");
|
||||
}
|
||||
/* Aggregate extents were bounded before invoking fixed-size LLVM queries. */
|
||||
*size = LLVMABISizeOfType(t->layout, type);
|
||||
return (*size && *size <= UINT32_MAX) ||
|
||||
fail(t, STELA_AIR_LIMIT, "shared storage allocation size exceeded");
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_shared_global(struct stela_air_metadata *t, LLVMValueRef global,
|
||||
uint64_t *size, unsigned *alignment)
|
||||
{
|
||||
const char *section = LLVMGetSection(global);
|
||||
LLVMValueRef initializer = LLVMGetInitializer(global);
|
||||
if (LLVMGetPointerAddressSpace(LLVMTypeOf(global)) != 3 ||
|
||||
LLVMGetLinkage(global) != LLVMInternalLinkage || LLVMIsThreadLocal(global) ||
|
||||
LLVMIsGlobalConstant(global) || LLVMIsExternallyInitialized(global) ||
|
||||
(section && *section) || !initializer || !LLVMIsUndef(initializer) || LLVMIsPoison(initializer))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported global/shared initializer or storage ABI");
|
||||
size_t metadata_count;
|
||||
LLVMValueMetadataEntry *metadata = LLVMGlobalCopyAllMetadata(global, &metadata_count);
|
||||
LLVMDisposeValueMetadataEntries(metadata);
|
||||
if (metadata_count)
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported shared global metadata");
|
||||
LLVMTypeRef type = LLVMGlobalGetValueType(global);
|
||||
if (!shared_storage_size(t, type, 0, size))
|
||||
return false;
|
||||
*alignment = LLVMGetAlignment(global);
|
||||
if (!*alignment)
|
||||
*alignment = LLVMABIAlignmentOfType(t->layout, type);
|
||||
return (*alignment && !(*alignment & (*alignment - 1))) ||
|
||||
fail(t, STELA_AIR_TYPE, "unsupported shared global alignment");
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_shared_globals(struct stela_air_metadata *t)
|
||||
{
|
||||
unsigned count = 0;
|
||||
for (LLVMValueRef global = LLVMGetFirstGlobal(t->module); global;
|
||||
global = LLVMGetNextGlobal(global)) {
|
||||
uint64_t size;
|
||||
unsigned alignment;
|
||||
if (++count > AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared global count exceeded");
|
||||
if (!stela_air_metadata_shared_global(t, global, &size, &alignment))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
version_metadata(struct stela_air_metadata *t, const char *name, bool language)
|
||||
{
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, fields_count, major, minor, patch;
|
||||
if (!stela_air_named_md(t, name, nodes, &count) || count != 1 ||
|
||||
!stela_air_md_node(t, nodes[0], fields, &fields_count))
|
||||
return fail(t, STELA_AIR_METADATA, "missing or invalid %s", name);
|
||||
unsigned base = language ? 1 : 0;
|
||||
if (fields_count != base + 3 || (language && !stela_air_md_string(fields[0], "Metal")) ||
|
||||
!stela_air_md_uint(fields[base], &major) || !stela_air_md_uint(fields[base + 1], &minor) ||
|
||||
!stela_air_md_uint(fields[base + 2], &patch) || patch != 0)
|
||||
return fail(t, STELA_AIR_METADATA, "invalid %s", name);
|
||||
bool supported = language ?
|
||||
((major == 1 && minor >= 1 && minor <= 2) ||
|
||||
(major == 2 && minor <= 4) || (major == 3 && minor <= 2) ||
|
||||
(major == 4 && minor <= 1)) : (major == 2 && (minor == 8 || minor == 9));
|
||||
/* AIR 2.8 has only been observed with Metal 4.0 here. The AIR 2.9
|
||||
* combinations below come from actual independent compiler requests. */
|
||||
if (language && t->air_minor == 8)
|
||||
supported &= major == 4 && minor == 0;
|
||||
if (!supported)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported %s %u.%u.%u", name, major, minor, patch);
|
||||
if (!language)
|
||||
t->air_minor = minor;
|
||||
else {
|
||||
t->language_major = major;
|
||||
t->language_minor = minor;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
module_flags(struct stela_air_metadata *t)
|
||||
{
|
||||
/* These are the LLVM IR serialized behavior values, not the smaller C API
|
||||
* LLVMModuleFlagBehavior enum (which does not expose Max in LLVM 23). */
|
||||
enum { IR_FLAG_ERROR = 1, IR_FLAG_MAX = 7 };
|
||||
const char *keys[] = {"wchar_size", "frame-pointer", "air.max_device_buffers",
|
||||
"air.max_constant_buffers", "air.max_threadgroup_buffers", "air.max_textures",
|
||||
"air.max_read_write_textures", "air.max_samplers"};
|
||||
LLVMValueRef flags[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, seen = 0;
|
||||
if (!stela_air_named_md(t, "llvm.module.flags", flags, &count))
|
||||
return false;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned field_count, behavior, value, key;
|
||||
if (!stela_air_md_node(t, flags[i], fields, &field_count) || field_count != 3 ||
|
||||
!stela_air_md_uint(fields[0], &behavior) || !stela_air_md_uint(fields[2], &value))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module flag shape");
|
||||
for (key = 0; key < ARRAY_SIZE(keys); key++) {
|
||||
if (stela_air_md_string(fields[1], keys[key]))
|
||||
break;
|
||||
}
|
||||
if (key == ARRAY_SIZE(keys) || (seen & (1u << key)))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported/duplicate module flag");
|
||||
seen |= 1u << key;
|
||||
if (behavior != (key == 0 ? IR_FLAG_ERROR : IR_FLAG_MAX) ||
|
||||
(key == 0 && value != 4) || (key == 1 && value > 2) ||
|
||||
(key >= 2 && !value))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module flag value: %s", keys[key]);
|
||||
if (key == 2)
|
||||
t->max_device_buffers = value;
|
||||
if (key == 4)
|
||||
t->max_threadgroup_buffers = value;
|
||||
}
|
||||
/* No linking, CPU frame operations or source wchar operations occur in the
|
||||
* implemented compute subset. Other resource kinds remain refused.
|
||||
* Device/threadgroup location bounds are enforced below, never advertised as the
|
||||
* hardware's actual Metal capability or silently removed from the input. */
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_validate(struct stela_air_metadata *t)
|
||||
{
|
||||
for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node;
|
||||
node = LLVMGetNextNamedMetadata(node)) {
|
||||
size_t size;
|
||||
const char *name = LLVMGetNamedMetadataName(node, &size);
|
||||
const char *allowed[] = {"air.version", "air.language_version",
|
||||
"air.compile_options", "air.kernel", "llvm.ident",
|
||||
"llvm.module.flags"};
|
||||
bool found = false;
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++)
|
||||
found |= size == strlen(allowed[i]) && !memcmp(name, allowed[i], size);
|
||||
if (!found)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module metadata: %.*s",
|
||||
(int)MIN2(size, 160), name);
|
||||
}
|
||||
if (!version_metadata(t, "air.version", false) ||
|
||||
!version_metadata(t, "air.language_version", true) || !module_flags(t))
|
||||
return false;
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_named_md(t, "air.compile_options", nodes, &count))
|
||||
return false;
|
||||
unsigned seen = 0;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
if (!stela_air_md_node(t, nodes[i], fields, &fields_count) || fields_count != 1 ||
|
||||
!(stela_air_md_string(fields[0], "air.compile.denorms_disable") ||
|
||||
stela_air_md_string(fields[0], "air.compile.fast_math_enable") ||
|
||||
stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_enable") ||
|
||||
stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_disable")))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported AIR compile option");
|
||||
unsigned bit = stela_air_md_string(fields[0], "air.compile.denorms_disable") ? 1 :
|
||||
stela_air_md_string(fields[0], "air.compile.fast_math_enable") ? 2 : 4;
|
||||
if (seen & bit)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate/conflicting AIR compile option");
|
||||
seen |= bit;
|
||||
}
|
||||
t->denorms_disable = seen & 1;
|
||||
t->fast_math = seen & 2;
|
||||
/* Arithmetic requires an explicit qualified FP policy for this private AIR
|
||||
* option. Exact storage/shared access and integer operations do not depend
|
||||
* on FP denorm mode. */
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_layout(struct stela_air_metadata *t)
|
||||
{
|
||||
t->layout = LLVMGetModuleDataLayout(t->module);
|
||||
const char *layout = LLVMGetDataLayoutStr(t->module);
|
||||
if (!layout || !*layout || LLVMByteOrder(t->layout) != LLVMLittleEndian ||
|
||||
LLVMPointerSizeForAS(t->layout, 0) != 8 || LLVMPointerSizeForAS(t->layout, 1) != 8)
|
||||
return fail(t, STELA_AIR_TARGET, "requires explicit little-endian 64-bit AIR layout");
|
||||
/* LLVM's C DataLayout API does not expose pointer-index width. Validate only
|
||||
* that property here; actual allocation sizes/field offsets come from LLVM.
|
||||
* Nonintegral/external-state pointers need a different NIR representation. */
|
||||
for (const char *part = layout; *part;) {
|
||||
const char *end = strchr(part, '-');
|
||||
size_t length = end ? (size_t)(end - part) : strlen(part);
|
||||
if ((length > 3 && !memcmp(part, "ni:", 3)) || (length && *part == 'P'))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported nonintegral/program address-space layout");
|
||||
if (length && *part == 'p') {
|
||||
unsigned colons = 0;
|
||||
const char *last = NULL;
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
if (part[i] == ':') {
|
||||
colons++;
|
||||
last = part + i + 1;
|
||||
}
|
||||
}
|
||||
if (colons > 4 || (colons == 4 &&
|
||||
((size_t)(part + length - last) != 2 || memcmp(last, "64", 2))))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported pointer-index width");
|
||||
}
|
||||
part += length;
|
||||
if (*part)
|
||||
part++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* This is only a conservative public-reflection classification. Unknown/struct
|
||||
* types are NOT inferred to lack argument buffers. It changes no NIR admission.
|
||||
* MSL argument buffers require structures; builtin scalar/vector buffer elements
|
||||
* cannot describe such a structure. Exact IR/layout validation remains separate. */
|
||||
static enum stela_air_primitive
|
||||
primitive_type(LLVMValueRef name, unsigned *components)
|
||||
{
|
||||
const char *scalar[] = {"char", "uchar", "short", "ushort", "int", "uint", "long", "ulong", "float"};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(scalar); i++) {
|
||||
for (unsigned n = 1; n <= 4; n++) {
|
||||
char type[16];
|
||||
if (n == 1)
|
||||
snprintf(type, sizeof(type), "%s", scalar[i]);
|
||||
else
|
||||
snprintf(type, sizeof(type), "%s%u", scalar[i], n);
|
||||
if (stela_air_md_string(name, type)) {
|
||||
*components = n;
|
||||
return STELA_AIR_CHAR + i;
|
||||
}
|
||||
}
|
||||
}
|
||||
*components = 0;
|
||||
return STELA_AIR_PRIMITIVE_UNKNOWN;
|
||||
}
|
||||
|
||||
/* This is reflection admission, not a change to executable/NIR admission.
|
||||
* Reject unknown function metadata/string attributes and unqualified globals
|
||||
* instead of claiming absent annotations/constants/static-resource reflection.
|
||||
* The known internal undef AS3 storage ABI does not add a function argument;
|
||||
* actual selected-entry allocation remains the original NIR compiler's work. The
|
||||
* accepted strings are standard LLVM code-generation/FP attributes observed in
|
||||
* the retained original AIR, not arbitrary app or compiler-name exceptions. */
|
||||
static bool
|
||||
complete_reflection(struct stela_air_metadata *m, LLVMValueRef fn,
|
||||
const struct stela_air_kernel *kernel)
|
||||
{
|
||||
if (LLVMGetFirstGlobal(m->module)) {
|
||||
/* Reflection incompleteness is observational, not an inspection failure.
|
||||
* Keep executable/profile diagnostics local to this conservative query. */
|
||||
struct stela_air_error observed_error = {0};
|
||||
struct stela_air_metadata observed = *m;
|
||||
observed.error = &observed_error;
|
||||
if (!stela_air_metadata_shared_profile(&observed) ||
|
||||
!stela_air_metadata_shared_globals(&observed))
|
||||
return false;
|
||||
}
|
||||
size_t metadata_count;
|
||||
LLVMValueMetadataEntry *metadata = LLVMGlobalCopyAllMetadata(fn, &metadata_count);
|
||||
LLVMDisposeValueMetadataEntries(metadata);
|
||||
if (metadata_count)
|
||||
return false;
|
||||
unsigned count = LLVMGetAttributeCountAtIndex(fn, LLVMAttributeFunctionIndex);
|
||||
if (count > AIR_MAX_METADATA_OPERANDS)
|
||||
return false;
|
||||
LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS];
|
||||
LLVMGetAttributesAtIndex(fn, LLVMAttributeFunctionIndex, attributes);
|
||||
const char *allowed[] = {"approx-func-fp-math", "frame-pointer", "min-legal-vector-width",
|
||||
"no-builtins", "no-infs-fp-math", "no-nans-fp-math", "no-signed-zeros-fp-math",
|
||||
"no-trapping-math", "stack-protector-buffer-size", "unsafe-fp-math"};
|
||||
for (unsigned a = 0; a < count; a++) {
|
||||
if (!LLVMIsStringAttribute(attributes[a]))
|
||||
continue;
|
||||
unsigned bytes;
|
||||
const char *key = LLVMGetStringAttributeKind(attributes[a], &bytes);
|
||||
bool found = false;
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++)
|
||||
found |= bytes == strlen(allowed[i]) && !memcmp(key, allowed[i], bytes);
|
||||
if (!found)
|
||||
return false;
|
||||
}
|
||||
for (unsigned a = 0; a < kernel->count; a++) {
|
||||
const struct stela_air_argument *arg = &kernel->arguments[a];
|
||||
if (!arg->is_buffer)
|
||||
continue;
|
||||
if (!arg->plain_buffer_type || !arg->name_bytes || arg->name_bytes > 4096 ||
|
||||
memchr(arg->name, 0, arg->name_bytes))
|
||||
return false;
|
||||
unsigned scalar = arg->primitive <= STELA_AIR_UCHAR ? 1 :
|
||||
arg->primitive <= STELA_AIR_USHORT ? 2 :
|
||||
arg->primitive == STELA_AIR_LONG || arg->primitive == STELA_AIR_ULONG ? 8 : 4;
|
||||
unsigned extent = scalar * (arg->type_components == 3 ? 4 : arg->type_components);
|
||||
if (arg->buffer.type_size != extent || arg->buffer.type_alignment != extent)
|
||||
return false;
|
||||
/* Unknown parameter string attributes could carry unimplemented source
|
||||
* reflection; only the observed AIR alias contract is recognized here. */
|
||||
count = LLVMGetAttributeCountAtIndex(fn, arg->buffer.argument + 1);
|
||||
if (count > AIR_MAX_METADATA_OPERANDS)
|
||||
return false;
|
||||
LLVMGetAttributesAtIndex(fn, arg->buffer.argument + 1, attributes);
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
if (!LLVMIsStringAttribute(attributes[i]))
|
||||
continue;
|
||||
unsigned bytes;
|
||||
const char *key = LLVMGetStringAttributeKind(attributes[i], &bytes);
|
||||
if (bytes != strlen("air-buffer-no-alias") || memcmp(key, "air-buffer-no-alias", bytes))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_metadata_kernel(struct stela_air_metadata *t, LLVMValueRef fn,
|
||||
struct stela_air_kernel *kernel)
|
||||
{
|
||||
if (!fn || LLVMIsDeclaration(fn) || LLVMGetFunctionCallConv(fn) != LLVMCCallConv ||
|
||||
LLVMGetTypeKind(LLVMGetReturnType(LLVMGlobalGetValueType(fn))) != LLVMVoidTypeKind ||
|
||||
LLVMIsFunctionVarArg(LLVMGlobalGetValueType(fn)))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "entry must be a defined nonvariadic void C-convention kernel");
|
||||
LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS], args_node = NULL;
|
||||
unsigned kernel_count;
|
||||
if (!stela_air_named_md(t, "air.kernel", kernels, &kernel_count))
|
||||
return false;
|
||||
for (unsigned i = 0; i < kernel_count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_md_node(t, kernels[i], fields, &count) || count != 3)
|
||||
return fail(t, STELA_AIR_METADATA, "invalid air.kernel descriptor");
|
||||
if (fields[0] == fn) {
|
||||
LLVMValueRef outputs[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned output_count;
|
||||
if (args_node || !stela_air_md_node(t, fields[1], outputs, &output_count) || output_count)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate kernel or nonempty compute outputs");
|
||||
args_node = fields[2];
|
||||
}
|
||||
}
|
||||
if (!args_node)
|
||||
return fail(t, STELA_AIR_METADATA, "entry is not an AIR compute kernel");
|
||||
unsigned argc = LLVMCountParams(fn);
|
||||
if (argc > AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_LIMIT, "AIR argument budget exceeded");
|
||||
LLVMValueRef args[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_md_node(t, args_node, args, &count) || count != argc)
|
||||
return fail(t, STELA_AIR_METADATA, "AIR argument descriptors do not match parameters");
|
||||
bool used[AIR_MAX_ARGUMENTS] = {false};
|
||||
bool buffer_indices[AIR_MAX_ARGUMENTS] = {false};
|
||||
bool shared_indices[AIR_MAX_ARGUMENTS] = {false};
|
||||
for (unsigned a = 0; a < argc; a++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count, index;
|
||||
if (!stela_air_md_node(t, args[a], fields, &fields_count) || fields_count < 2 ||
|
||||
!stela_air_md_uint(fields[0], &index) || index >= argc || used[index])
|
||||
return fail(t, STELA_AIR_METADATA, "invalid/duplicate argument index");
|
||||
used[index] = true;
|
||||
LLVMValueRef param = LLVMGetParam(fn, index);
|
||||
unsigned attributes_count = LLVMGetAttributeCountAtIndex(fn, index + 1);
|
||||
if (attributes_count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "argument attribute budget exceeded");
|
||||
LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS];
|
||||
LLVMGetAttributesAtIndex(fn, index + 1, attributes);
|
||||
const char *abi_attributes[] = {"sret", "byval", "byref", "inalloca",
|
||||
"preallocated", "nest", "swiftself", "swifterror", "elementtype"};
|
||||
for (unsigned attribute = 0; attribute < attributes_count; attribute++) {
|
||||
if (LLVMIsTypeAttribute(attributes[attribute]))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported typed parameter attribute");
|
||||
if (!LLVMIsEnumAttribute(attributes[attribute]))
|
||||
continue;
|
||||
unsigned kind = LLVMGetEnumAttributeKind(attributes[attribute]);
|
||||
for (unsigned k = 0; k < ARRAY_SIZE(abi_attributes); k++) {
|
||||
if (kind == LLVMGetEnumAttributeKindForName(abi_attributes[k], strlen(abi_attributes[k])))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported parameter ABI attribute: %s", abi_attributes[k]);
|
||||
}
|
||||
}
|
||||
bool buffer = stela_air_md_string(fields[1], "air.buffer");
|
||||
bool thread_id = stela_air_md_string(fields[1], "air.thread_position_in_grid");
|
||||
if (!buffer && !thread_id)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported AIR argument kind at %u", index);
|
||||
struct stela_air_buffer desc = {.argument = index};
|
||||
bool has_location = false, has_as = false, has_size = false, has_align = false;
|
||||
bool has_name = false, has_type_name = false;
|
||||
enum stela_air_primitive primitive = STELA_AIR_PRIMITIVE_UNKNOWN;
|
||||
unsigned type_components = 0;
|
||||
const char *name = NULL, *type_name = NULL;
|
||||
unsigned name_bytes = 0, type_name_bytes = 0;
|
||||
for (unsigned f = 2; f < fields_count;) {
|
||||
LLVMValueRef key = fields[f++];
|
||||
if (stela_air_md_string(key, "air.read") || stela_air_md_string(key, "air.write") ||
|
||||
stela_air_md_string(key, "air.read_write")) {
|
||||
if (!buffer || desc.access)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate/inapplicable buffer access");
|
||||
desc.access = stela_air_md_string(key, "air.read") ? STELA_AIR_READ :
|
||||
stela_air_md_string(key, "air.write") ? STELA_AIR_WRITE : STELA_AIR_READ_WRITE;
|
||||
} else if (stela_air_md_string(key, "air.location_index")) {
|
||||
unsigned locations;
|
||||
if (!buffer || has_location || f + 2 > fields_count ||
|
||||
!stela_air_md_uint(fields[f], &desc.index) || !stela_air_md_uint(fields[f + 1], &locations) ||
|
||||
locations != 1 || desc.index >= AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported/duplicate buffer location");
|
||||
has_location = true;
|
||||
f += 2;
|
||||
} else if (stela_air_md_string(key, "air.address_space")) {
|
||||
if (!buffer || has_as || f == fields_count || !stela_air_md_uint(fields[f++], &desc.address_space))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid buffer address space");
|
||||
has_as = true;
|
||||
} else if (stela_air_md_string(key, "air.arg_type_size") || stela_air_md_string(key, "air.arg_type_align_size")) {
|
||||
bool alignment = stela_air_md_string(key, "air.arg_type_align_size");
|
||||
bool *present = alignment ? &has_align : &has_size;
|
||||
unsigned *number = alignment ? &desc.type_alignment : &desc.type_size;
|
||||
if (!buffer || *present || f == fields_count || !stela_air_md_uint(fields[f++], number) ||
|
||||
(alignment && (!*number || (*number & (*number - 1)))))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid argument size/alignment");
|
||||
*present = true;
|
||||
} else if (stela_air_md_string(key, "air.arg_name") || stela_air_md_string(key, "air.arg_type_name")) {
|
||||
bool *present = stela_air_md_string(key, "air.arg_name") ? &has_name : &has_type_name;
|
||||
if (*present || f == fields_count || !fields[f] || !LLVMIsAMDString(fields[f]))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid argument reflection string");
|
||||
if (present == &has_type_name) {
|
||||
primitive = primitive_type(fields[f], &type_components);
|
||||
type_name = LLVMGetMDString(fields[f], &type_name_bytes);
|
||||
} else {
|
||||
name = LLVMGetMDString(fields[f], &name_bytes);
|
||||
}
|
||||
f++;
|
||||
*present = true;
|
||||
} else {
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported argument metadata at %u", index);
|
||||
}
|
||||
}
|
||||
unsigned components = 0;
|
||||
if (buffer) {
|
||||
LLVMTypeRef type = LLVMTypeOf(param);
|
||||
if (!has_location || !has_as || !desc.access ||
|
||||
(desc.address_space != 1 && desc.address_space != 3) ||
|
||||
LLVMGetTypeKind(type) != LLVMPointerTypeKind ||
|
||||
LLVMGetPointerAddressSpace(type) != desc.address_space)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported buffer %u", index);
|
||||
bool shared = desc.address_space == 3;
|
||||
bool *indices = shared ? shared_indices : buffer_indices;
|
||||
unsigned limit = shared ? t->max_threadgroup_buffers : t->max_device_buffers;
|
||||
if (indices[desc.index] || (limit && desc.index >= limit))
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate buffer or location exceeds AIR module limit");
|
||||
indices[desc.index] = true;
|
||||
if (shared && (!has_size || !has_align || !desc.type_size || !desc.type_alignment))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "invalid/unbound threadgroup buffer %u", index);
|
||||
} else {
|
||||
LLVMTypeRef type = LLVMTypeOf(param);
|
||||
components = 1;
|
||||
if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
|
||||
components = LLVMGetVectorSize(type);
|
||||
if (components != 3)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position vector width");
|
||||
type = LLVMGetElementType(type);
|
||||
}
|
||||
if (LLVMGetTypeKind(type) != LLVMIntegerTypeKind || LLVMGetIntTypeWidth(type) != 32 ||
|
||||
(components != 1 && components != 3))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position type");
|
||||
}
|
||||
kernel->arguments[a] = (struct stela_air_argument) {
|
||||
.value = param, .buffer = desc, .is_buffer = buffer, .components = components,
|
||||
.plain_buffer_type = primitive != STELA_AIR_PRIMITIVE_UNKNOWN,
|
||||
.name = name, .name_bytes = name_bytes, .type_name = type_name, .type_name_bytes = type_name_bytes,
|
||||
.primitive = primitive, .type_components = type_components, .used = LLVMGetFirstUse(param) != NULL,
|
||||
};
|
||||
}
|
||||
kernel->count = argc;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void
|
||||
inspection_diagnostic(LLVMDiagnosticInfoRef info, void *data)
|
||||
{
|
||||
struct stela_air_metadata *m = data;
|
||||
if (LLVMGetDiagInfoSeverity(info) != LLVMDSError)
|
||||
return;
|
||||
char *message = LLVMGetDiagInfoDescription(info);
|
||||
fail(m, STELA_AIR_BITCODE, "%s", message ? message : "LLVM bitcode diagnostic");
|
||||
LLVMDisposeMessage(message);
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_inspect(const void *bitcode, size_t size, unsigned max_entries,
|
||||
stela_air_visit_entry visit, void *data,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
struct stela_air_error local = {0};
|
||||
if (!error)
|
||||
error = &local;
|
||||
*error = (struct stela_air_error){0};
|
||||
struct stela_air_metadata m = {.error = error};
|
||||
if (!bitcode || size < 4 || size > AIR_MAX_BITCODE_BYTES ||
|
||||
memcmp(bitcode, "BC\xc0\xde", 4) || !max_entries ||
|
||||
max_entries > AIR_MAX_METADATA_OPERANDS || !visit)
|
||||
return fail(&m, STELA_AIR_INPUT, "invalid AIR inspection input/budget");
|
||||
unsigned major, minor, patch;
|
||||
LLVMGetVersion(&major, &minor, &patch);
|
||||
if (major != 23)
|
||||
return fail(&m, STELA_AIR_LLVM_VERSION, "requires LLVM 23 C ABI, found %u.%u.%u", major, minor, patch);
|
||||
LLVMContextRef context = LLVMContextCreate();
|
||||
if (!context)
|
||||
return fail(&m, STELA_AIR_ALLOCATION, "LLVM context unavailable");
|
||||
LLVMContextSetDiagnosticHandler(context, inspection_diagnostic, &m);
|
||||
LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(bitcode, size, "Metal input");
|
||||
if (!buffer) {
|
||||
LLVMContextDispose(context);
|
||||
return fail(&m, STELA_AIR_ALLOCATION, "LLVM buffer unavailable");
|
||||
}
|
||||
bool parsed = !LLVMParseBitcodeInContext2(context, buffer, &m.module);
|
||||
LLVMDisposeMemoryBuffer(buffer);
|
||||
bool success = false;
|
||||
struct decoded_entry {
|
||||
LLVMValueRef fn;
|
||||
const char *name;
|
||||
size_t name_bytes;
|
||||
struct stela_air_kernel kernel;
|
||||
} *entries = NULL;
|
||||
if (!parsed || error->kind != STELA_AIR_OK) {
|
||||
fail(&m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode");
|
||||
goto done;
|
||||
}
|
||||
char *verification = NULL;
|
||||
if (LLVMVerifyModule(m.module, LLVMReturnStatusAction, &verification)) {
|
||||
fail(&m, STELA_AIR_VERIFY, "%s", verification ? verification : "invalid LLVM module");
|
||||
LLVMDisposeMessage(verification);
|
||||
goto done;
|
||||
}
|
||||
LLVMDisposeMessage(verification);
|
||||
const char *target = LLVMGetTarget(m.module);
|
||||
size_t assembly;
|
||||
LLVMGetModuleInlineAsm(m.module, &assembly);
|
||||
if (strncmp(target, "air64_v", 7) || assembly || LLVMGetFirstGlobalAlias(m.module) ||
|
||||
LLVMGetFirstGlobalIFunc(m.module)) {
|
||||
fail(&m, STELA_AIR_TARGET, "unsupported target/globals/inline assembly");
|
||||
goto done;
|
||||
}
|
||||
if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m))
|
||||
goto done;
|
||||
char prefix[40];
|
||||
snprintf(prefix, sizeof(prefix), "air64_v2%u-apple-macosx", m.air_minor);
|
||||
if (strncmp(target, prefix, strlen(prefix))) {
|
||||
fail(&m, STELA_AIR_TARGET, "AIR version and target triple disagree");
|
||||
goto done;
|
||||
}
|
||||
LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_named_md(&m, "air.kernel", kernels, &count))
|
||||
goto done;
|
||||
if (!count || count > max_entries) {
|
||||
fail(&m, STELA_AIR_LIMIT, "no executable compute entries or entry budget exceeded");
|
||||
goto done;
|
||||
}
|
||||
entries = calloc(count, sizeof(*entries));
|
||||
if (!entries) {
|
||||
fail(&m, STELA_AIR_ALLOCATION, "entry manifest allocation failed");
|
||||
goto done;
|
||||
}
|
||||
/* Validate the complete manifest BEFORE the first callback. A later invalid
|
||||
* entry cannot publish a partially accepted library through this interface. */
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
if (!stela_air_md_node(&m, kernels[i], fields, &fields_count) || fields_count != 3 ||
|
||||
!fields[0] || !LLVMIsAFunction(fields[0])) {
|
||||
fail(&m, STELA_AIR_METADATA, "invalid AIR kernel manifest entry");
|
||||
goto done;
|
||||
}
|
||||
entries[i].fn = fields[0];
|
||||
entries[i].name = LLVMGetValueName2(fields[0], &entries[i].name_bytes);
|
||||
if (!entries[i].name_bytes || entries[i].name_bytes > 4096 ||
|
||||
memchr(entries[i].name, 0, entries[i].name_bytes)) {
|
||||
fail(&m, STELA_AIR_METADATA, "invalid/oversized AIR entry name");
|
||||
goto done;
|
||||
}
|
||||
for (unsigned j = 0; j < i; j++) {
|
||||
if (entries[j].fn == entries[i].fn) {
|
||||
fail(&m, STELA_AIR_METADATA, "duplicate AIR kernel manifest entry");
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
if (!stela_air_metadata_kernel(&m, entries[i].fn, &entries[i].kernel))
|
||||
goto done;
|
||||
}
|
||||
struct stela_air_inspection info = {
|
||||
.target = target, .target_bytes = strlen(target), .air_minor = m.air_minor,
|
||||
.language_major = m.language_major, .language_minor = m.language_minor,
|
||||
.denorms_disable = m.denorms_disable, .fast_math = m.fast_math,
|
||||
};
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
struct stela_air_argument_info args[AIR_MAX_ARGUMENTS];
|
||||
for (unsigned a = 0; a < entries[i].kernel.count; a++) {
|
||||
const struct stela_air_argument *arg = &entries[i].kernel.arguments[a];
|
||||
args[a] = (struct stela_air_argument_info) {
|
||||
.buffer = arg->buffer, .kind = arg->is_buffer ? 1 : 2, .components = arg->components,
|
||||
.plain_buffer_type = arg->plain_buffer_type,
|
||||
.name = arg->name, .name_bytes = arg->name_bytes,
|
||||
.type_name = arg->type_name, .type_name_bytes = arg->type_name_bytes,
|
||||
.primitive = arg->primitive, .type_components = arg->type_components, .used = arg->used,
|
||||
};
|
||||
}
|
||||
struct stela_air_entry entry = {
|
||||
.name = entries[i].name, .name_bytes = entries[i].name_bytes,
|
||||
.argument_count = entries[i].kernel.count, .arguments = args,
|
||||
.reflection_complete = complete_reflection(&m, entries[i].fn, &entries[i].kernel),
|
||||
};
|
||||
if (!visit(&info, &entry, data)) {
|
||||
fail(&m, STELA_AIR_LIMIT, "AIR manifest receiver refused entry");
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
success = true;
|
||||
done:
|
||||
free(entries);
|
||||
if (m.module)
|
||||
LLVMDisposeModule(m.module);
|
||||
LLVMContextDispose(context);
|
||||
return success;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#ifndef STELA_AIR_METADATA_H
|
||||
#define STELA_AIR_METADATA_H
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define AIR_MAX_ARGUMENTS 128
|
||||
#define AIR_MAX_METADATA_OPERANDS 256
|
||||
#define AIR_MAX_BITCODE_BYTES (64u * 1024u * 1024u)
|
||||
|
||||
enum stela_air_error_kind {
|
||||
STELA_AIR_OK,
|
||||
STELA_AIR_INPUT,
|
||||
STELA_AIR_LLVM_VERSION,
|
||||
STELA_AIR_BITCODE,
|
||||
STELA_AIR_VERIFY,
|
||||
STELA_AIR_TARGET,
|
||||
STELA_AIR_METADATA,
|
||||
STELA_AIR_ARGUMENT,
|
||||
STELA_AIR_CONTROL_FLOW,
|
||||
STELA_AIR_INSTRUCTION,
|
||||
STELA_AIR_TYPE,
|
||||
STELA_AIR_MEMORY,
|
||||
STELA_AIR_LIMIT,
|
||||
STELA_AIR_ALLOCATION,
|
||||
};
|
||||
|
||||
struct stela_air_error {
|
||||
enum stela_air_error_kind kind;
|
||||
unsigned instruction; /* Zero-based instruction ordinal, not source line. */
|
||||
char detail[256];
|
||||
};
|
||||
|
||||
enum stela_air_buffer_access {
|
||||
STELA_AIR_READ = 1,
|
||||
STELA_AIR_WRITE = 2,
|
||||
STELA_AIR_READ_WRITE = 3,
|
||||
};
|
||||
|
||||
struct stela_air_buffer {
|
||||
unsigned argument;
|
||||
unsigned index; /* air.location_index; not an LLVM parameter byte offset. */
|
||||
unsigned address_space;
|
||||
enum stela_air_buffer_access access;
|
||||
unsigned type_size; /* Zero when the input omits this optional reflection. */
|
||||
unsigned type_alignment;
|
||||
};
|
||||
|
||||
|
||||
/* Borrowed callback views expire on callback return. Inspection validates LLVM,
|
||||
* module/entry ABI and metadata, not executable-body support, bindings, GPU
|
||||
* capability, or compiler provenance. Only actual air.kernel entries are
|
||||
* exposed; unsupported metadata/stages remain explicit. */
|
||||
struct stela_air_inspection {
|
||||
const char *target;
|
||||
size_t target_bytes;
|
||||
unsigned air_minor, language_major, language_minor;
|
||||
bool denorms_disable, fast_math;
|
||||
};
|
||||
enum stela_air_primitive {
|
||||
STELA_AIR_PRIMITIVE_UNKNOWN,
|
||||
STELA_AIR_CHAR, STELA_AIR_UCHAR, STELA_AIR_SHORT, STELA_AIR_USHORT,
|
||||
STELA_AIR_INT, STELA_AIR_UINT, STELA_AIR_LONG, STELA_AIR_ULONG, STELA_AIR_FLOAT,
|
||||
};
|
||||
|
||||
struct stela_air_argument_info {
|
||||
struct stela_air_buffer buffer;
|
||||
unsigned kind; /* 1=buffer, 2=thread_position_in_grid. */
|
||||
unsigned components;
|
||||
bool plain_buffer_type;
|
||||
const char *name, *type_name;
|
||||
size_t name_bytes, type_name_bytes;
|
||||
enum stela_air_primitive primitive;
|
||||
unsigned type_components; /* 1..4 only for known reflected builtin types. */
|
||||
bool used; /* Actual uses in this AIR module, not a final machine-code liveness claim. */
|
||||
};
|
||||
struct stela_air_entry {
|
||||
const char *name;
|
||||
size_t name_bytes;
|
||||
unsigned argument_count;
|
||||
const struct stela_air_argument_info *arguments;
|
||||
bool reflection_complete; /* Bounded plain-resource reflection; see README. */
|
||||
};
|
||||
typedef bool (*stela_air_visit_entry)(const struct stela_air_inspection *,
|
||||
const struct stela_air_entry *, void *);
|
||||
bool stela_air_inspect(const void *bitcode, size_t size, unsigned max_entries,
|
||||
stela_air_visit_entry visit, void *data,
|
||||
struct stela_air_error *error);
|
||||
/* Compiler implementation only. Ordinary metadata consumers need no LLVM or
|
||||
* NIR headers and receive no LLVM objects. Define before the first include. */
|
||||
#ifdef STELA_AIR_METADATA_INTERNAL
|
||||
#include "llvm-c/Core.h"
|
||||
#include "llvm-c/Target.h"
|
||||
/* Shared decoder state, borrowed from the caller's real LLVM module. No NIR,
|
||||
* resource mapping or GPU/Metal object is created by metadata inspection. */
|
||||
struct stela_air_metadata {
|
||||
LLVMModuleRef module;
|
||||
LLVMTargetDataRef layout;
|
||||
struct stela_air_error *error;
|
||||
unsigned air_minor, language_major, language_minor;
|
||||
unsigned max_device_buffers, max_threadgroup_buffers;
|
||||
bool denorms_disable, fast_math;
|
||||
};
|
||||
|
||||
bool stela_air_md_string(LLVMValueRef value, const char *expected);
|
||||
bool stela_air_md_uint(LLVMValueRef value, unsigned *number);
|
||||
bool stela_air_md_node(struct stela_air_metadata *m, LLVMValueRef node,
|
||||
LLVMValueRef *operands, unsigned *count);
|
||||
bool stela_air_named_md(struct stela_air_metadata *m, const char *name,
|
||||
LLVMValueRef *operands, unsigned *count);
|
||||
bool stela_air_metadata_layout(struct stela_air_metadata *m);
|
||||
bool stela_air_metadata_validate(struct stela_air_metadata *m);
|
||||
/* One LLVM-only storage validator shared by conservative reflection and NIR.
|
||||
* These describe the qualified ABI, not compiler provenance or GPU limits.
|
||||
* No shared storage is allocated here; only actually used globals are lowered
|
||||
* by the selected entry's original NIR path. Errors use m->error; observational
|
||||
* consumers must supply their own local error state. */
|
||||
bool stela_air_metadata_shared_profile(struct stela_air_metadata *m);
|
||||
bool stela_air_metadata_shared_global(struct stela_air_metadata *m, LLVMValueRef global,
|
||||
uint64_t *size, unsigned *alignment);
|
||||
bool stela_air_metadata_shared_globals(struct stela_air_metadata *m);
|
||||
|
||||
struct stela_air_argument {
|
||||
LLVMValueRef value; /* Borrowed, decoder/compiler internal only. */
|
||||
struct stela_air_buffer buffer;
|
||||
bool is_buffer;
|
||||
unsigned components; /* Scalar/uint3 thread-position input. */
|
||||
bool plain_buffer_type; /* Reflected MSL builtin scalar/vector, not a struct. */
|
||||
const char *name, *type_name;
|
||||
size_t name_bytes, type_name_bytes;
|
||||
enum stela_air_primitive primitive;
|
||||
unsigned type_components;
|
||||
bool used;
|
||||
};
|
||||
struct stela_air_kernel {
|
||||
unsigned count;
|
||||
struct stela_air_argument arguments[AIR_MAX_ARGUMENTS];
|
||||
};
|
||||
bool stela_air_metadata_kernel(struct stela_air_metadata *m, LLVMValueRef fn,
|
||||
struct stela_air_kernel *kernel);
|
||||
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,4 +1,5 @@
|
||||
/* SPDX-License-Identifier: MIT */
|
||||
#define STELA_AIR_METADATA_INTERNAL
|
||||
#include "air_to_nir.h"
|
||||
#include "llvm-c/Analysis.h"
|
||||
#include "llvm-c/BitReader.h"
|
||||
@@ -10,9 +11,6 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define AIR_MAX_ARGUMENTS 128
|
||||
#define AIR_MAX_METADATA_OPERANDS 256
|
||||
#define AIR_MAX_BITCODE_BYTES (64u * 1024u * 1024u)
|
||||
#define AIR_MAX_BLOCKS 128
|
||||
#define AIR_MAX_CONTROL_DEPTH 32
|
||||
#define AIR_MAX_MERGE_PHIS 128
|
||||
@@ -58,6 +56,7 @@ struct translator {
|
||||
LLVMContextRef context;
|
||||
LLVMModuleRef module;
|
||||
LLVMTargetDataRef layout; /* Borrowed from module. */
|
||||
struct stela_air_metadata metadata;
|
||||
nir_builder b;
|
||||
struct hash_table *values;
|
||||
const struct stela_air_options *options;
|
||||
@@ -101,171 +100,17 @@ diagnostic(LLVMDiagnosticInfoRef info, void *data)
|
||||
LLVMDisposeMessage(message);
|
||||
}
|
||||
|
||||
#define md_string stela_air_md_string
|
||||
#define md_uint stela_air_md_uint
|
||||
static bool
|
||||
md_string(LLVMValueRef value, const char *expected)
|
||||
md_node(struct translator *t, LLVMValueRef node, LLVMValueRef *operands, unsigned *count)
|
||||
{
|
||||
if (!value || !LLVMIsAMDString(value))
|
||||
return false;
|
||||
unsigned length;
|
||||
const char *string = LLVMGetMDString(value, &length);
|
||||
return length == strlen(expected) && !memcmp(string, expected, length);
|
||||
return stela_air_md_node(&t->metadata, node, operands, count);
|
||||
}
|
||||
|
||||
static bool
|
||||
md_uint(LLVMValueRef value, unsigned *number)
|
||||
named_md(struct translator *t, const char *name, LLVMValueRef *operands, unsigned *count)
|
||||
{
|
||||
if (!value || !LLVMIsAConstantInt(value) ||
|
||||
LLVMGetIntTypeWidth(LLVMTypeOf(value)) > 32)
|
||||
return false;
|
||||
*number = LLVMConstIntGetZExtValue(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
md_node(struct translator *t, LLVMValueRef node, LLVMValueRef *operands,
|
||||
unsigned *count)
|
||||
{
|
||||
if (!node || !LLVMIsAMDNode(node))
|
||||
return fail(t, STELA_AIR_METADATA, "expected AIR metadata node");
|
||||
*count = LLVMGetMDNodeNumOperands(node);
|
||||
if (*count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "AIR metadata operand budget exceeded");
|
||||
LLVMGetMDNodeOperands(node, operands);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
named_md(struct translator *t, const char *name, LLVMValueRef *operands,
|
||||
unsigned *count)
|
||||
{
|
||||
*count = LLVMGetNamedMetadataNumOperands(t->module, name);
|
||||
if (*count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "%s metadata budget exceeded", name);
|
||||
LLVMGetNamedMetadataOperands(t->module, name, operands);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
version_metadata(struct translator *t, const char *name, bool language)
|
||||
{
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, fields_count, major, minor, patch;
|
||||
if (!named_md(t, name, nodes, &count) || count != 1 ||
|
||||
!md_node(t, nodes[0], fields, &fields_count))
|
||||
return fail(t, STELA_AIR_METADATA, "missing or invalid %s", name);
|
||||
unsigned base = language ? 1 : 0;
|
||||
if (fields_count != base + 3 || (language && !md_string(fields[0], "Metal")) ||
|
||||
!md_uint(fields[base], &major) || !md_uint(fields[base + 1], &minor) ||
|
||||
!md_uint(fields[base + 2], &patch) || patch != 0)
|
||||
return fail(t, STELA_AIR_METADATA, "invalid %s", name);
|
||||
bool supported = language ?
|
||||
((major == 1 && minor >= 1 && minor <= 2) ||
|
||||
(major == 2 && minor <= 4) || (major == 3 && minor <= 2) ||
|
||||
(major == 4 && minor <= 1)) : (major == 2 && (minor == 8 || minor == 9));
|
||||
/* AIR 2.8 has only been observed with Metal 4.0 here. The AIR 2.9
|
||||
* combinations below come from actual independent compiler requests. */
|
||||
if (language && t->air_minor == 8)
|
||||
supported &= major == 4 && minor == 0;
|
||||
if (!supported)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported %s %u.%u.%u", name, major, minor, patch);
|
||||
if (!language)
|
||||
t->air_minor = minor;
|
||||
else {
|
||||
t->language_major = major;
|
||||
t->language_minor = minor;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
module_flags(struct translator *t)
|
||||
{
|
||||
/* These are the LLVM IR serialized behavior values, not the smaller C API
|
||||
* LLVMModuleFlagBehavior enum (which does not expose Max in LLVM 23). */
|
||||
enum { IR_FLAG_ERROR = 1, IR_FLAG_MAX = 7 };
|
||||
const char *keys[] = {"wchar_size", "frame-pointer", "air.max_device_buffers",
|
||||
"air.max_constant_buffers", "air.max_threadgroup_buffers", "air.max_textures",
|
||||
"air.max_read_write_textures", "air.max_samplers"};
|
||||
LLVMValueRef flags[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, seen = 0;
|
||||
if (!named_md(t, "llvm.module.flags", flags, &count))
|
||||
return false;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned field_count, behavior, value, key;
|
||||
if (!md_node(t, flags[i], fields, &field_count) || field_count != 3 ||
|
||||
!md_uint(fields[0], &behavior) || !md_uint(fields[2], &value))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module flag shape");
|
||||
for (key = 0; key < ARRAY_SIZE(keys); key++) {
|
||||
if (md_string(fields[1], keys[key]))
|
||||
break;
|
||||
}
|
||||
if (key == ARRAY_SIZE(keys) || (seen & (1u << key)))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported/duplicate module flag");
|
||||
seen |= 1u << key;
|
||||
if (behavior != (key == 0 ? IR_FLAG_ERROR : IR_FLAG_MAX) ||
|
||||
(key == 0 && value != 4) || (key == 1 && value > 2) ||
|
||||
(key >= 2 && !value))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module flag value: %s", keys[key]);
|
||||
if (key == 2)
|
||||
t->max_device_buffers = value;
|
||||
if (key == 4)
|
||||
t->max_threadgroup_buffers = value;
|
||||
}
|
||||
/* No linking, CPU frame operations or source wchar operations occur in the
|
||||
* implemented compute subset. Other resource kinds remain refused.
|
||||
* Device/threadgroup location bounds are enforced below, never advertised as the
|
||||
* hardware's actual Metal capability or silently removed from the input. */
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
module_metadata(struct translator *t)
|
||||
{
|
||||
for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node;
|
||||
node = LLVMGetNextNamedMetadata(node)) {
|
||||
size_t size;
|
||||
const char *name = LLVMGetNamedMetadataName(node, &size);
|
||||
const char *allowed[] = {"air.version", "air.language_version",
|
||||
"air.compile_options", "air.kernel", "llvm.ident",
|
||||
"llvm.module.flags"};
|
||||
bool found = false;
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++)
|
||||
found |= size == strlen(allowed[i]) && !memcmp(name, allowed[i], size);
|
||||
if (!found)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported module metadata: %.*s",
|
||||
(int)MIN2(size, 160), name);
|
||||
}
|
||||
if (!version_metadata(t, "air.version", false) ||
|
||||
!version_metadata(t, "air.language_version", true) || !module_flags(t))
|
||||
return false;
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!named_md(t, "air.compile_options", nodes, &count))
|
||||
return false;
|
||||
unsigned seen = 0;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
if (!md_node(t, nodes[i], fields, &fields_count) || fields_count != 1 ||
|
||||
!(md_string(fields[0], "air.compile.denorms_disable") ||
|
||||
md_string(fields[0], "air.compile.fast_math_enable") ||
|
||||
md_string(fields[0], "air.compile.framebuffer_fetch_enable") ||
|
||||
md_string(fields[0], "air.compile.framebuffer_fetch_disable")))
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported AIR compile option");
|
||||
unsigned bit = md_string(fields[0], "air.compile.denorms_disable") ? 1 :
|
||||
md_string(fields[0], "air.compile.fast_math_enable") ? 2 : 4;
|
||||
if (seen & bit)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate/conflicting AIR compile option");
|
||||
seen |= bit;
|
||||
}
|
||||
t->denorms_disable = seen & 1;
|
||||
t->fast_math = seen & 2;
|
||||
/* Arithmetic requires an explicit qualified FP policy for this private AIR
|
||||
* option. Exact storage/shared access and integer operations do not depend
|
||||
* on FP denorm mode. */
|
||||
return true;
|
||||
return stela_air_named_md(&t->metadata, name, operands, count);
|
||||
}
|
||||
|
||||
static bool
|
||||
@@ -426,127 +271,25 @@ get_value(struct translator *t, LLVMValueRef llvm)
|
||||
static bool
|
||||
kernel_arguments(struct translator *t, LLVMValueRef fn)
|
||||
{
|
||||
LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS], args_node = NULL;
|
||||
unsigned kernel_count;
|
||||
if (!named_md(t, "air.kernel", kernels, &kernel_count))
|
||||
struct stela_air_kernel kernel;
|
||||
if (!stela_air_metadata_kernel(&t->metadata, fn, &kernel))
|
||||
return false;
|
||||
for (unsigned i = 0; i < kernel_count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!md_node(t, kernels[i], fields, &count) || count != 3)
|
||||
return fail(t, STELA_AIR_METADATA, "invalid air.kernel descriptor");
|
||||
if (fields[0] == fn) {
|
||||
LLVMValueRef outputs[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned output_count;
|
||||
if (args_node || !md_node(t, fields[1], outputs, &output_count) || output_count)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate kernel or nonempty compute outputs");
|
||||
args_node = fields[2];
|
||||
}
|
||||
}
|
||||
if (!args_node)
|
||||
return fail(t, STELA_AIR_METADATA, "entry is not an AIR compute kernel");
|
||||
unsigned argc = LLVMCountParams(fn);
|
||||
if (argc > AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_LIMIT, "AIR argument budget exceeded");
|
||||
LLVMValueRef args[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!md_node(t, args_node, args, &count) || count != argc)
|
||||
return fail(t, STELA_AIR_METADATA, "AIR argument descriptors do not match parameters");
|
||||
bool used[AIR_MAX_ARGUMENTS] = {false};
|
||||
bool buffer_indices[AIR_MAX_ARGUMENTS] = {false};
|
||||
bool shared_indices[AIR_MAX_ARGUMENTS] = {false};
|
||||
bool ssbo_slots[UINT8_MAX + 1] = {false};
|
||||
for (unsigned a = 0; a < argc; a++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count, index;
|
||||
if (!md_node(t, args[a], fields, &fields_count) || fields_count < 2 ||
|
||||
!md_uint(fields[0], &index) || index >= argc || used[index])
|
||||
return fail(t, STELA_AIR_METADATA, "invalid/duplicate argument index");
|
||||
used[index] = true;
|
||||
LLVMValueRef param = LLVMGetParam(fn, index);
|
||||
unsigned attributes_count = LLVMGetAttributeCountAtIndex(fn, index + 1);
|
||||
if (attributes_count > AIR_MAX_METADATA_OPERANDS)
|
||||
return fail(t, STELA_AIR_LIMIT, "argument attribute budget exceeded");
|
||||
LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS];
|
||||
LLVMGetAttributesAtIndex(fn, index + 1, attributes);
|
||||
const char *abi_attributes[] = {"sret", "byval", "byref", "inalloca",
|
||||
"preallocated", "nest", "swiftself", "swifterror", "elementtype"};
|
||||
for (unsigned attribute = 0; attribute < attributes_count; attribute++) {
|
||||
if (LLVMIsTypeAttribute(attributes[attribute]))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported typed parameter attribute");
|
||||
if (!LLVMIsEnumAttribute(attributes[attribute]))
|
||||
continue;
|
||||
unsigned kind = LLVMGetEnumAttributeKind(attributes[attribute]);
|
||||
for (unsigned k = 0; k < ARRAY_SIZE(abi_attributes); k++) {
|
||||
if (kind == LLVMGetEnumAttributeKindForName(abi_attributes[k], strlen(abi_attributes[k])))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported parameter ABI attribute: %s", abi_attributes[k]);
|
||||
}
|
||||
}
|
||||
bool buffer = md_string(fields[1], "air.buffer");
|
||||
bool thread_id = md_string(fields[1], "air.thread_position_in_grid");
|
||||
if (!buffer && !thread_id)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported AIR argument kind at %u", index);
|
||||
struct stela_air_buffer desc = {.argument = index};
|
||||
bool has_location = false, has_as = false, has_size = false, has_align = false;
|
||||
bool has_name = false, has_type_name = false;
|
||||
for (unsigned f = 2; f < fields_count;) {
|
||||
LLVMValueRef key = fields[f++];
|
||||
if (md_string(key, "air.read") || md_string(key, "air.write") ||
|
||||
md_string(key, "air.read_write")) {
|
||||
if (!buffer || desc.access)
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate/inapplicable buffer access");
|
||||
desc.access = md_string(key, "air.read") ? STELA_AIR_READ :
|
||||
md_string(key, "air.write") ? STELA_AIR_WRITE : STELA_AIR_READ_WRITE;
|
||||
} else if (md_string(key, "air.location_index")) {
|
||||
unsigned locations;
|
||||
if (!buffer || has_location || f + 2 > fields_count ||
|
||||
!md_uint(fields[f], &desc.index) || !md_uint(fields[f + 1], &locations) ||
|
||||
locations != 1 || desc.index >= AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported/duplicate buffer location");
|
||||
has_location = true;
|
||||
f += 2;
|
||||
} else if (md_string(key, "air.address_space")) {
|
||||
if (!buffer || has_as || f == fields_count || !md_uint(fields[f++], &desc.address_space))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid buffer address space");
|
||||
has_as = true;
|
||||
} else if (md_string(key, "air.arg_type_size") || md_string(key, "air.arg_type_align_size")) {
|
||||
bool alignment = md_string(key, "air.arg_type_align_size");
|
||||
bool *present = alignment ? &has_align : &has_size;
|
||||
unsigned *number = alignment ? &desc.type_alignment : &desc.type_size;
|
||||
if (!buffer || *present || f == fields_count || !md_uint(fields[f++], number) ||
|
||||
(alignment && (!*number || (*number & (*number - 1)))))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid argument size/alignment");
|
||||
*present = true;
|
||||
} else if (md_string(key, "air.arg_name") || md_string(key, "air.arg_type_name")) {
|
||||
bool *present = md_string(key, "air.arg_name") ? &has_name : &has_type_name;
|
||||
if (*present || f == fields_count || !fields[f] || !LLVMIsAMDString(fields[f++]))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid argument reflection string");
|
||||
*present = true;
|
||||
} else {
|
||||
return fail(t, STELA_AIR_METADATA, "unsupported argument metadata at %u", index);
|
||||
}
|
||||
}
|
||||
for (unsigned a = 0; a < kernel.count; a++) {
|
||||
const struct stela_air_argument *argument = &kernel.arguments[a];
|
||||
LLVMValueRef param = argument->value;
|
||||
struct stela_air_buffer desc = argument->buffer;
|
||||
unsigned index = desc.argument, components = argument->components;
|
||||
bool buffer = argument->is_buffer;
|
||||
nir_def *def;
|
||||
unsigned ssbo_slot = 0;
|
||||
nir_variable *shared = NULL;
|
||||
unsigned shared_size = 0;
|
||||
if (buffer) {
|
||||
LLVMTypeRef type = LLVMTypeOf(param);
|
||||
if (!has_location || !has_as || !desc.access ||
|
||||
(desc.address_space != 1 && desc.address_space != 3) ||
|
||||
LLVMGetTypeKind(type) != LLVMPointerTypeKind ||
|
||||
LLVMGetPointerAddressSpace(type) != desc.address_space)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported buffer %u", index);
|
||||
bool threadgroup = desc.address_space == 3;
|
||||
bool *indices = threadgroup ? shared_indices : buffer_indices;
|
||||
unsigned limit = threadgroup ? t->max_threadgroup_buffers : t->max_device_buffers;
|
||||
if (indices[desc.index] || (limit && desc.index >= limit))
|
||||
return fail(t, STELA_AIR_METADATA, "duplicate buffer or location exceeds AIR module limit");
|
||||
indices[desc.index] = true;
|
||||
if (threadgroup) {
|
||||
struct stela_air_threadgroup_view view = {0};
|
||||
if (!has_size || !has_align || !desc.type_size || !desc.type_alignment ||
|
||||
!t->options->bind_threadgroup ||
|
||||
if (!t->options->bind_threadgroup ||
|
||||
!t->options->bind_threadgroup(&desc, &view, t->options->binding_data) ||
|
||||
view.size < desc.type_size || view.alignment < desc.type_alignment ||
|
||||
view.available_access < STELA_AIR_READ || view.available_access > STELA_AIR_READ_WRITE ||
|
||||
@@ -572,10 +315,6 @@ kernel_arguments(struct translator *t, LLVMValueRef fn)
|
||||
return fail(t, STELA_AIR_ARGUMENT, "binding callback refused/invalid buffer %u", index);
|
||||
}
|
||||
} else {
|
||||
unsigned components, bits;
|
||||
if (!shape(LLVMTypeOf(param), &components, &bits) || bits != 32 ||
|
||||
(components != 1 && components != 3))
|
||||
return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position type");
|
||||
/* Metal's grid starts at zero, with no dispatch-base parameter.
|
||||
* Form its ID directly from existing NIR workgroup/local builtins;
|
||||
* a generic global-ID lowering may add an OpenCL/Vulkan base input. */
|
||||
@@ -602,42 +341,6 @@ kernel_arguments(struct translator *t, LLVMValueRef fn)
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
address_layout(struct translator *t)
|
||||
{
|
||||
t->layout = LLVMGetModuleDataLayout(t->module);
|
||||
const char *layout = LLVMGetDataLayoutStr(t->module);
|
||||
if (!layout || !*layout || LLVMByteOrder(t->layout) != LLVMLittleEndian ||
|
||||
LLVMPointerSizeForAS(t->layout, 0) != 8 || LLVMPointerSizeForAS(t->layout, 1) != 8)
|
||||
return fail(t, STELA_AIR_TARGET, "requires explicit little-endian 64-bit AIR layout");
|
||||
/* LLVM's C DataLayout API does not expose pointer-index width. Validate only
|
||||
* that property here; actual allocation sizes/field offsets come from LLVM.
|
||||
* Nonintegral/external-state pointers need a different NIR representation. */
|
||||
for (const char *part = layout; *part;) {
|
||||
const char *end = strchr(part, '-');
|
||||
size_t length = end ? (size_t)(end - part) : strlen(part);
|
||||
if ((length > 3 && !memcmp(part, "ni:", 3)) || (length && *part == 'P'))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported nonintegral/program address-space layout");
|
||||
if (length && *part == 'p') {
|
||||
unsigned colons = 0;
|
||||
const char *last = NULL;
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
if (part[i] == ':') {
|
||||
colons++;
|
||||
last = part + i + 1;
|
||||
}
|
||||
}
|
||||
if (colons > 4 || (colons == 4 &&
|
||||
((size_t)(part + length - last) != 2 || memcmp(last, "64", 2))))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported pointer-index width");
|
||||
}
|
||||
part += length;
|
||||
if (*part)
|
||||
part++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
fixed_storage_type(struct translator *t, LLVMTypeRef type, unsigned depth,
|
||||
unsigned *budget)
|
||||
@@ -677,17 +380,7 @@ fixed_storage_type(struct translator *t, LLVMTypeRef type, unsigned depth,
|
||||
static bool
|
||||
shared_profile(struct translator *t)
|
||||
{
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS], fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count, fields_count;
|
||||
if (t->air_minor != 9 || t->language_major != 4 || t->language_minor != 1 ||
|
||||
strcmp(LLVMGetTarget(t->module), "air64_v29-apple-macosx27.2.0") ||
|
||||
!named_md(t, "llvm.ident", nodes, &count) || count != 1 ||
|
||||
!md_node(t, nodes[0], fields, &fields_count) || fields_count != 1 ||
|
||||
!md_string(fields[0], "Apple metal version 32023.922 (metalfe-32023.922.4)"))
|
||||
return fail(t, STELA_AIR_METADATA, "shared-memory AIR/compiler profile is unqualified");
|
||||
if (LLVMPointerSizeForAS(t->layout, 3) != 8)
|
||||
return fail(t, STELA_AIR_TARGET, "shared-memory AIR pointers require 64-bit layout");
|
||||
return true;
|
||||
return stela_air_metadata_shared_profile(&t->metadata);
|
||||
}
|
||||
|
||||
static nir_variable *
|
||||
@@ -716,65 +409,17 @@ shared_resource(struct translator *t, uint64_t size, unsigned alignment)
|
||||
return var;
|
||||
}
|
||||
|
||||
static bool
|
||||
shared_storage_size(struct translator *t, LLVMTypeRef type, unsigned depth,
|
||||
uint64_t *size)
|
||||
{
|
||||
if (depth == 32)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared storage type nesting exceeded");
|
||||
if (LLVMGetTypeKind(type) == LLVMArrayTypeKind) {
|
||||
uint64_t element;
|
||||
if (!shared_storage_size(t, LLVMGetElementType(type), depth + 1, &element))
|
||||
return false;
|
||||
uint64_t length = LLVMGetArrayLength2(type);
|
||||
if (!length || length > UINT32_MAX / element)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared storage array extent exceeded");
|
||||
} else {
|
||||
unsigned components, bits;
|
||||
if (!value_shape(type, &components, &bits) || bits < 8)
|
||||
return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays");
|
||||
}
|
||||
/* Aggregate extents were bounded before invoking fixed-size LLVM queries. */
|
||||
*size = LLVMABISizeOfType(t->layout, type);
|
||||
return (*size && *size <= UINT32_MAX) ||
|
||||
fail(t, STELA_AIR_LIMIT, "shared storage allocation size exceeded");
|
||||
}
|
||||
|
||||
static bool
|
||||
shared_global_info(struct translator *t, LLVMValueRef global,
|
||||
uint64_t *size, unsigned *alignment)
|
||||
uint64_t *size, unsigned *alignment)
|
||||
{
|
||||
const char *section = LLVMGetSection(global);
|
||||
LLVMValueRef initializer = LLVMGetInitializer(global);
|
||||
if (LLVMGetPointerAddressSpace(LLVMTypeOf(global)) != 3 ||
|
||||
LLVMGetLinkage(global) != LLVMInternalLinkage || LLVMIsThreadLocal(global) ||
|
||||
LLVMIsGlobalConstant(global) || LLVMIsExternallyInitialized(global) ||
|
||||
(section && *section) || !initializer || !LLVMIsUndef(initializer) || LLVMIsPoison(initializer))
|
||||
return fail(t, STELA_AIR_TARGET, "unsupported global/shared initializer or storage ABI");
|
||||
LLVMTypeRef type = LLVMGlobalGetValueType(global);
|
||||
if (!shared_storage_size(t, type, 0, size))
|
||||
return false;
|
||||
*alignment = LLVMGetAlignment(global);
|
||||
if (!*alignment)
|
||||
*alignment = LLVMABIAlignmentOfType(t->layout, type);
|
||||
return (*alignment && !(*alignment & (*alignment - 1))) ||
|
||||
fail(t, STELA_AIR_TYPE, "unsupported shared global alignment");
|
||||
return stela_air_metadata_shared_global(&t->metadata, global, size, alignment);
|
||||
}
|
||||
|
||||
static bool
|
||||
shared_globals(struct translator *t)
|
||||
{
|
||||
unsigned count = 0;
|
||||
for (LLVMValueRef global = LLVMGetFirstGlobal(t->module); global;
|
||||
global = LLVMGetNextGlobal(global)) {
|
||||
uint64_t size;
|
||||
unsigned alignment;
|
||||
if (++count > AIR_MAX_ARGUMENTS)
|
||||
return fail(t, STELA_AIR_LIMIT, "shared global count exceeded");
|
||||
if (!shared_global_info(t, global, &size, &alignment))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return stela_air_metadata_shared_globals(&t->metadata);
|
||||
}
|
||||
|
||||
static nir_def *
|
||||
@@ -1709,7 +1354,18 @@ stela_air_to_nir(const void *bitcode, size_t size, const char *entry,
|
||||
fail(&t, STELA_AIR_TARGET, "unsupported target/globals/inline assembly");
|
||||
goto done;
|
||||
}
|
||||
if (!address_layout(&t) || !module_metadata(&t) || !shared_globals(&t))
|
||||
t.metadata = (struct stela_air_metadata){.module = t.module, .error = error};
|
||||
if (!stela_air_metadata_layout(&t.metadata) || !stela_air_metadata_validate(&t.metadata))
|
||||
goto done;
|
||||
t.layout = t.metadata.layout;
|
||||
t.air_minor = t.metadata.air_minor;
|
||||
t.language_major = t.metadata.language_major;
|
||||
t.language_minor = t.metadata.language_minor;
|
||||
t.max_device_buffers = t.metadata.max_device_buffers;
|
||||
t.max_threadgroup_buffers = t.metadata.max_threadgroup_buffers;
|
||||
t.denorms_disable = t.metadata.denorms_disable;
|
||||
t.fast_math = t.metadata.fast_math;
|
||||
if (!shared_globals(&t))
|
||||
goto done;
|
||||
char target_prefix[40];
|
||||
snprintf(target_prefix, sizeof(target_prefix), "air64_v2%u-apple-macosx", t.air_minor);
|
||||
|
||||
@@ -3,50 +3,13 @@
|
||||
#define STELA_AIR_TO_NIR_H
|
||||
|
||||
#include "compiler/nir/nir_builder.h"
|
||||
#include "air_metadata.h"
|
||||
#include <stddef.h>
|
||||
|
||||
/* User-space compiler boundary. LLVM and Mesa must be built for this process's
|
||||
* architecture and linked with their normal runtime services. No GPU access,
|
||||
* IOKit call, Metal device registration, or command submission happens here.
|
||||
*/
|
||||
enum stela_air_error_kind {
|
||||
STELA_AIR_OK,
|
||||
STELA_AIR_INPUT,
|
||||
STELA_AIR_LLVM_VERSION,
|
||||
STELA_AIR_BITCODE,
|
||||
STELA_AIR_VERIFY,
|
||||
STELA_AIR_TARGET,
|
||||
STELA_AIR_METADATA,
|
||||
STELA_AIR_ARGUMENT,
|
||||
STELA_AIR_CONTROL_FLOW,
|
||||
STELA_AIR_INSTRUCTION,
|
||||
STELA_AIR_TYPE,
|
||||
STELA_AIR_MEMORY,
|
||||
STELA_AIR_LIMIT,
|
||||
STELA_AIR_ALLOCATION,
|
||||
};
|
||||
|
||||
struct stela_air_error {
|
||||
enum stela_air_error_kind kind;
|
||||
unsigned instruction; /* Zero-based instruction ordinal, not source line. */
|
||||
char detail[256];
|
||||
};
|
||||
|
||||
enum stela_air_buffer_access {
|
||||
STELA_AIR_READ = 1,
|
||||
STELA_AIR_WRITE = 2,
|
||||
STELA_AIR_READ_WRITE = 3,
|
||||
};
|
||||
|
||||
struct stela_air_buffer {
|
||||
unsigned argument;
|
||||
unsigned index; /* air.location_index; not an LLVM parameter byte offset. */
|
||||
unsigned address_space;
|
||||
enum stela_air_buffer_access access;
|
||||
unsigned type_size; /* Zero when the input omits this optional reflection. */
|
||||
unsigned type_alignment;
|
||||
};
|
||||
|
||||
/* Resolve a validated Metal buffer binding to a 64-bit device virtual address.
|
||||
* The caller owns resource lifetime, size/access validation, actual allocation,
|
||||
* residency and runtime argument ABI. Returning NULL refuses compilation. This
|
||||
|
||||
@@ -1759,11 +1759,253 @@ nak_codegen(const char *body, const char *label, bool ieee)
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool
|
||||
inspect_entry(const struct stela_air_inspection *info, const struct stela_air_entry *entry, void *data)
|
||||
{
|
||||
unsigned *count = data;
|
||||
CHECK(info->air_minor == 8 && info->language_major == 4 && info->language_minor == 0);
|
||||
CHECK(info->denorms_disable && info->fast_math && info->target_bytes == strlen(info->target));
|
||||
CHECK(entry->name_bytes == 6 && !memcmp(entry->name, "kernel", 6) && entry->argument_count == 2);
|
||||
CHECK(entry->reflection_complete);
|
||||
const struct stela_air_argument_info *arg = &entry->arguments[1];
|
||||
CHECK(entry->arguments[0].kind == 2 && entry->arguments[0].components == 1);
|
||||
CHECK(arg->kind == 1 && arg->buffer.argument == 1 && arg->buffer.index == 7 &&
|
||||
arg->buffer.address_space == 1 && arg->buffer.access == STELA_AIR_READ_WRITE &&
|
||||
arg->buffer.type_size == 4 && arg->buffer.type_alignment == 4 && arg->plain_buffer_type);
|
||||
CHECK(arg->primitive == STELA_AIR_UINT && arg->type_components == 1 &&
|
||||
arg->name_bytes == 6 && !memcmp(arg->name, "output", 6) &&
|
||||
arg->type_name_bytes == 4 && !memcmp(arg->type_name, "uint", 4));
|
||||
(*count)++;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct reflection_expectation {
|
||||
bool complete, used;
|
||||
enum stela_air_primitive primitive;
|
||||
unsigned components;
|
||||
};
|
||||
static bool
|
||||
inspect_reflection(const struct stela_air_inspection *info, const struct stela_air_entry *entry, void *data)
|
||||
{
|
||||
(void)info;
|
||||
const struct reflection_expectation *expected = data;
|
||||
CHECK(entry->argument_count == 2);
|
||||
const struct stela_air_argument_info *arg = &entry->arguments[1];
|
||||
CHECK(entry->reflection_complete == expected->complete && arg->used == expected->used &&
|
||||
arg->primitive == expected->primitive && arg->type_components == expected->components);
|
||||
return true;
|
||||
}
|
||||
static void
|
||||
reflection_inspection_case(const char *prefix, const char *body, const char *metadata, const char *extra,
|
||||
bool complete, bool used, enum stela_air_primitive primitive, unsigned components)
|
||||
{
|
||||
struct stela_air_error error;
|
||||
struct reflection_expectation expected = {complete, used, primitive, components};
|
||||
LLVMMemoryBufferRef input = stela_air_test_custom_bitcode(prefix, body, metadata, extra);
|
||||
CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8,
|
||||
inspect_reflection, &expected, &error));
|
||||
CHECK(error.kind == STELA_AIR_OK);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
static void
|
||||
reflection_inspection_tests(void)
|
||||
{
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, stela_air_test_metadata,
|
||||
"", true, true, STELA_AIR_UINT, 1);
|
||||
const char *scalars[] = {"char", "uchar", "short", "ushort", "int", "uint", "long", "ulong", "float"};
|
||||
const unsigned scalar_sizes[] = {1,1,2,2,4,4,8,8,4};
|
||||
for (unsigned scalar = 0; scalar < 9; scalar++) {
|
||||
for (unsigned components = 1; components <= 4; components++) {
|
||||
char reflected[96], layout[128];
|
||||
if (components == 1)
|
||||
snprintf(reflected, sizeof(reflected), "!\"%s\", !\"air.arg_name\", !\"output\"", scalars[scalar]);
|
||||
else
|
||||
snprintf(reflected, sizeof(reflected), "!\"%s%u\", !\"air.arg_name\", !\"output\"", scalars[scalar], components);
|
||||
unsigned extent = scalar_sizes[scalar] * (components == 3 ? 4 : components);
|
||||
snprintf(layout, sizeof(layout), "!\"air.arg_type_size\", i32 %u, !\"air.arg_type_align_size\", i32 %u", extent, extent);
|
||||
char *typed = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"", reflected);
|
||||
char *sized = replace_once(typed, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4", layout);
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, sized,
|
||||
"", true, true, STELA_AIR_CHAR + scalar, components);
|
||||
free(typed); free(sized);
|
||||
}
|
||||
}
|
||||
/* AIR use facts are preserved even for a currently unused formal parameter. */
|
||||
reflection_inspection_case(stela_air_test_prefix, "ret void\n", stela_air_test_metadata,
|
||||
"", true, false, STELA_AIR_UINT, 1);
|
||||
char *metadata = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"",
|
||||
"!\"UnqualifiedStructure\", !\"air.arg_name\", !\"output\"");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata,
|
||||
"", false, true, STELA_AIR_PRIMITIVE_UNKNOWN, 0);
|
||||
free(metadata);
|
||||
metadata = replace_once(stela_air_test_metadata, ", !\"air.arg_name\", !\"output\"", "");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata,
|
||||
"", false, true, STELA_AIR_UINT, 1);
|
||||
free(metadata);
|
||||
metadata = replace_once(stela_air_test_metadata, "!\"output\"", "!\"out\\00put\"");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata,
|
||||
"", false, true, STELA_AIR_UINT, 1);
|
||||
free(metadata);
|
||||
metadata = replace_once(stela_air_test_metadata, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4,", "");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata,
|
||||
"", false, true, STELA_AIR_UINT, 1);
|
||||
free(metadata);
|
||||
/* MSL vector3 has four lanes of storage/alignment; no packed-layout guess. */
|
||||
metadata = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"",
|
||||
"!\"uint3\", !\"air.arg_name\", !\"output\"");
|
||||
char *sized = replace_once(metadata, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4",
|
||||
"!\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, sized,
|
||||
"", true, true, STELA_AIR_UINT, 3);
|
||||
char *packed = replace_once(sized, "!\"air.arg_type_size\", i32 16", "!\"air.arg_type_size\", i32 12");
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, packed,
|
||||
"", false, true, STELA_AIR_UINT, 3);
|
||||
free(metadata); free(sized); free(packed);
|
||||
char *prefix = replace_once(stela_air_test_prefix, " %out)", " \"unknown-reflection\" %out)");
|
||||
reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata,
|
||||
"", false, true, STELA_AIR_UINT, 1);
|
||||
free(prefix);
|
||||
prefix = replace_once(stela_air_test_prefix, ") {", ") #0 {");
|
||||
reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata,
|
||||
"attributes #0 = { \"unqualified-annotation\"=\"text\" }\n", false, true, STELA_AIR_UINT, 1);
|
||||
free(prefix);
|
||||
prefix = replace_once(stela_air_test_prefix, ") {", ") !custom !11 {");
|
||||
reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata,
|
||||
"!11 = !{!\"annotation\"}\n", false, true, STELA_AIR_UINT, 1);
|
||||
free(prefix);
|
||||
reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, stela_air_test_metadata,
|
||||
"@unqualified = constant i32 1\n", false, true, STELA_AIR_UINT, 1);
|
||||
}
|
||||
|
||||
static void
|
||||
shared_reflection_case(const char *extra, bool complete)
|
||||
{
|
||||
LLVMMemoryBufferRef input = shared_bitcode("ret void\n", false, extra);
|
||||
struct reflection_expectation expected = {complete, false, STELA_AIR_UINT, 1};
|
||||
struct stela_air_error error;
|
||||
CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8,
|
||||
inspect_reflection, &expected, &error));
|
||||
/* A conservative absent-reflection result must not leak its local failure
|
||||
* into otherwise successful original LLVM/module inspection. */
|
||||
CHECK(error.kind == STELA_AIR_OK && !error.detail[0]);
|
||||
if (complete) {
|
||||
struct shared_bindings bindings = {0};
|
||||
nir_shader *nir = shared_translate(input, &test_nir_options, &bindings, 0, &error);
|
||||
CHECK(nir && !nir->info.shared_size && !bindings.shared);
|
||||
check_shared_operations(nir, 0, 0, 0);
|
||||
ralloc_free(nir);
|
||||
}
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
static void
|
||||
shared_reflection_tests(void)
|
||||
{
|
||||
const char *good[] = {
|
||||
"@s = internal addrspace(3) global i8 undef, align 1\n",
|
||||
"@s = internal addrspace(3) global <3 x i16> undef, align 8\n",
|
||||
"@s = internal addrspace(3) global [3 x [4 x <4 x float>]] undef, align 16\n",
|
||||
"@s = internal unnamed_addr addrspace(3) global [32 x i32] undef, align 4\n",
|
||||
"@s = internal addrspace(3) global i64 undef\n", /* Original ABI alignment. */
|
||||
};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(good); i++)
|
||||
shared_reflection_case(good[i], true);
|
||||
const char *bad[] = {
|
||||
"@s = internal addrspace(1) global i32 undef, align 4\n",
|
||||
"@s = internal addrspace(3) constant i32 undef, align 4\n",
|
||||
"@s = external addrspace(3) global i32\n",
|
||||
"@s = internal thread_local addrspace(3) global i32 undef, align 4\n",
|
||||
"@s = internal addrspace(3) externally_initialized global i32 undef, align 4\n",
|
||||
"@s = internal addrspace(3) global i32 0, align 4\n",
|
||||
"@s = internal addrspace(3) global i32 poison, align 4\n",
|
||||
"@s = internal addrspace(3) global i32 undef, section \"unqualified\", align 4\n",
|
||||
"@s = internal addrspace(3) global i32 undef, align 4, !custom !77\n!77 = !{!\"unqualified\"}\n",
|
||||
"@s = internal addrspace(3) global [0 x i32] undef, align 4\n",
|
||||
"@s = internal addrspace(3) global [4294967296 x i32] undef, align 4\n",
|
||||
"@s = internal addrspace(3) global {i32,i32} undef, align 4\n",
|
||||
"@s = internal addrspace(3) global half undef, align 2\n",
|
||||
"@s = internal addrspace(3) global i1 undef, align 1\n",
|
||||
"@s = internal addrspace(3) global <8 x i32> undef, align 32\n",
|
||||
};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(bad); i++)
|
||||
shared_reflection_case(bad[i], false);
|
||||
shared_refusal("ret void\n", bad[8], STELA_AIR_TARGET);
|
||||
/* Recursion/count are bounded before target-layout size/alignment queries. */
|
||||
char nested[1024] = "@s = internal addrspace(3) global ";
|
||||
for (unsigned i = 0; i < 33; i++) strcat(nested, "[1 x ");
|
||||
strcat(nested, "i32");
|
||||
for (unsigned i = 0; i < 33; i++) strcat(nested, "]");
|
||||
strcat(nested, " undef, align 4\n");
|
||||
shared_reflection_case(nested, false);
|
||||
shared_refusal("ret void\n", nested, STELA_AIR_LIMIT);
|
||||
char globals[16384] = {0};
|
||||
size_t used = 0;
|
||||
for (unsigned i = 0; i <= AIR_MAX_ARGUMENTS; i++) {
|
||||
int n = snprintf(globals + used, sizeof(globals) - used,
|
||||
"@s%u = internal addrspace(3) global i32 undef, align 4\n", i);
|
||||
CHECK(n > 0 && (size_t)n < sizeof(globals) - used); used += (size_t)n;
|
||||
}
|
||||
shared_reflection_case(globals, false);
|
||||
shared_refusal("ret void\n", globals, STELA_AIR_LIMIT);
|
||||
/* Old AIR2.8 unused shared globals still allocate nothing in the executable
|
||||
* path; they cannot gain a new qualified reflection profile by this change. */
|
||||
reflection_inspection_case(stela_air_test_prefix, "ret void\n", stela_air_test_metadata,
|
||||
good[3], false, false, STELA_AIR_UINT, 1);
|
||||
LLVMMemoryBufferRef input = stela_air_test_bitcode("ret void\n", good[3]);
|
||||
struct shared_bindings bindings = {0}; struct stela_air_error error;
|
||||
nir_shader *nir = shared_translate(input, &test_nir_options, &bindings, 0, &error);
|
||||
CHECK(nir && !nir->info.shared_size); ralloc_free(nir); LLVMDisposeMemoryBuffer(input);
|
||||
puts("AIR static-shared reflection, observational diagnostics, bounds and unused-allocation tests passed");
|
||||
}
|
||||
|
||||
static void
|
||||
inspection_tests(void)
|
||||
{
|
||||
struct stela_air_error error;
|
||||
unsigned calls = 0;
|
||||
LLVMMemoryBufferRef input = stela_air_test_bitcode(stela_air_test_store_body, "");
|
||||
CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error));
|
||||
CHECK(calls == 1 && error.kind == STELA_AIR_OK);
|
||||
CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 0, inspect_entry, &calls, &error));
|
||||
CHECK(error.kind == STELA_AIR_INPUT && calls == 1);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
char *metadata = replace_once(stela_air_test_metadata, "!air.kernel = !{!2}", "!air.kernel = !{!2, !2}");
|
||||
input = stela_air_test_custom_bitcode(stela_air_test_prefix, stela_air_test_store_body, metadata, "");
|
||||
calls = 0;
|
||||
CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error));
|
||||
CHECK(error.kind == STELA_AIR_METADATA && calls == 0); /* No partial manifest. */
|
||||
LLVMDisposeMemoryBuffer(input); free(metadata);
|
||||
metadata = replace_once(stela_air_test_metadata, "i32 7, i32 1", "i32 128, i32 1");
|
||||
input = stela_air_test_custom_bitcode(stela_air_test_prefix, stela_air_test_store_body, metadata, "");
|
||||
CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error));
|
||||
CHECK(error.kind == STELA_AIR_METADATA && calls == 0);
|
||||
LLVMDisposeMemoryBuffer(input); free(metadata);
|
||||
/* Preserve the original integer shape rule: a scalar or uint3 builtin,
|
||||
* never a one-lane LLVM vector masquerading as a scalar argument. */
|
||||
char *prefix = replace_once(stela_air_test_prefix, "i32 %tid", "<1 x i32> %tid");
|
||||
input = stela_air_test_custom_bitcode(prefix, "ret void\n", stela_air_test_metadata, "");
|
||||
CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error));
|
||||
CHECK(error.kind == STELA_AIR_ARGUMENT && calls == 0);
|
||||
nir_shader *invalid_shape = translate(input, &test_nir_options, 100, &error);
|
||||
CHECK(!invalid_shape && error.kind == STELA_AIR_ARGUMENT);
|
||||
LLVMDisposeMemoryBuffer(input); free(prefix);
|
||||
/* Inspection is NOT a promise that a body/resource/pipeline can compile. */
|
||||
input = stela_air_test_bitcode("call void @unknown()\nret void\n", "declare void @unknown()\n");
|
||||
CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error));
|
||||
CHECK(calls == 1);
|
||||
nir_shader *nir = translate(input, &test_nir_options, 100, &error);
|
||||
CHECK(!nir && error.kind == STELA_AIR_INSTRUCTION);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
glsl_type_singleton_init_or_ref();
|
||||
tests();
|
||||
inspection_tests();
|
||||
reflection_inspection_tests();
|
||||
shared_reflection_tests();
|
||||
#ifdef STELA_AIR_TEST_NAK
|
||||
nak_codegen(stela_air_test_store_body, "integer", false);
|
||||
nak_codegen(conditional_body, "nested-conditional", false);
|
||||
|
||||
@@ -19,6 +19,20 @@ stela_apple_source_test = executable(
|
||||
)
|
||||
test('stela_apple_source_boundary', stela_apple_source_test, suite : 'stela')
|
||||
|
||||
# Value normalization owns no LLVM, NIR or driver state.
|
||||
stela_metal_threadgroup = static_library(
|
||||
'stela_metal_threadgroup',
|
||||
'../../../../metal/compiler/threadgroup.c',
|
||||
c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'],
|
||||
)
|
||||
stela_metal_threadgroup_test = executable(
|
||||
'stela_metal_threadgroup_test',
|
||||
'../../../../metal/compiler/tests/threadgroup.c',
|
||||
link_with : stela_metal_threadgroup,
|
||||
c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'],
|
||||
)
|
||||
test('stela_metal_threadgroup_values', stela_metal_threadgroup_test, suite : 'stela')
|
||||
|
||||
if with_stela_amd_llvm
|
||||
stela_amd_llvm_float = static_library(
|
||||
'stela_amd_llvm_float',
|
||||
@@ -52,16 +66,50 @@ if stela_air_llvm != ''
|
||||
)
|
||||
stela_air = static_library(
|
||||
'stela_air_to_nir',
|
||||
'air_to_nir.c',
|
||||
['air_to_nir.c', 'air_metadata.c'],
|
||||
include_directories : [inc_include, inc_src],
|
||||
dependencies : [idep_nir, idep_mesautil, stela_air_llvm_dep],
|
||||
c_args : ['-Werror'],
|
||||
)
|
||||
stela_metal_input = get_option('stela-metal-input-library')
|
||||
if stela_metal_input != ''
|
||||
if host_machine.system() != 'darwin' or not fs.is_absolute(stela_metal_input) or not fs.is_file(stela_metal_input)
|
||||
error('Metal assembly requires a matching Darwin Rust input static library')
|
||||
endif
|
||||
stela_metal_assembly = static_library(
|
||||
'stela_metal_assembly',
|
||||
'../../../../metal/compiler/library_assembly.c',
|
||||
dependencies : [stela_air_llvm_dep],
|
||||
c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'],
|
||||
)
|
||||
# Ordinary archive extraction pulls the shared metadata inspector alone;
|
||||
# this local owner does not depend on NIR or any vendor compiler backend.
|
||||
stela_metal_assembly_test = executable(
|
||||
'stela_metal_assembly_test',
|
||||
'../../../../metal/compiler/tests/library_assembly.c',
|
||||
dependencies : [stela_air_llvm_dep, dependency('appleframeworks', modules : ['CoreFoundation'])],
|
||||
link_with : [stela_metal_assembly, stela_air, stela_apple_source],
|
||||
link_args : [stela_metal_input, '-lresolv', '-liconv'],
|
||||
c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'],
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
test('stela_metal_library_assembly', stela_metal_assembly_test, suite : 'stela')
|
||||
endif
|
||||
idep_stela_air = declare_dependency(
|
||||
link_with : [stela_air],
|
||||
include_directories : include_directories('.'),
|
||||
dependencies : [idep_nir, idep_mesautil, stela_air_llvm_dep],
|
||||
)
|
||||
stela_metal_threadgroup_nir_test = executable(
|
||||
'stela_metal_threadgroup_nir_test',
|
||||
'../../../../metal/compiler/tests/threadgroup_nir.c',
|
||||
include_directories : [inc_include, inc_src],
|
||||
dependencies : [idep_stela_air],
|
||||
link_with : stela_metal_threadgroup,
|
||||
c_args : ['-Wall', '-Wextra', '-Werror', '-Wno-missing-field-initializers'],
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
test('stela_metal_threadgroup_nir', stela_metal_threadgroup_nir_test, suite : 'stela')
|
||||
stela_air_test_dependencies = [idep_stela_air]
|
||||
stela_air_test_links = []
|
||||
stela_air_test_args = ['-Werror']
|
||||
@@ -226,6 +274,29 @@ if with_stela_nvidia
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
endif
|
||||
if stela_air_llvm != '' and stela_metal_input != ''
|
||||
stela_nv_air = static_library(
|
||||
'stela_nv_air',
|
||||
'../../../../nvidia/stela/hosted/air_compile.c',
|
||||
include_directories : [inc_include, inc_src, include_directories('../nouveau/headers')],
|
||||
dependencies : [idep_stela_air, idep_nak, idep_nir_headers],
|
||||
link_with : [stela_metal_assembly, stela_metal_threadgroup, _libnak_rs],
|
||||
c_args : ['-Werror'],
|
||||
)
|
||||
stela_nv_air_compile_test = executable(
|
||||
'stela_nv_air_compile_test',
|
||||
'../../../../nvidia/stela/tests/air_compile.c',
|
||||
include_directories : [inc_include, inc_src,
|
||||
include_directories('../nouveau/headers', '../nouveau/headers/nvidia/classes')],
|
||||
dependencies : [idep_stela_air, idep_nak, idep_nir_headers,
|
||||
dependency('appleframeworks', modules : ['CoreFoundation'])],
|
||||
link_with : [stela_nv_air, stela_nv_compute, stela_apple_source, _libnak_rs],
|
||||
link_args : [stela_metal_input, '-lresolv', '-liconv'],
|
||||
c_args : ['-Werror'],
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
test('stela_nv_air_owned', stela_nv_air_compile_test, suite : 'stela')
|
||||
endif
|
||||
stela_nak_probe = executable(
|
||||
'stela_nak_probe',
|
||||
'nak_probe.c',
|
||||
@@ -443,6 +514,37 @@ if with_stela_intel
|
||||
)
|
||||
test('stela_intel_legacy_compute_program', stela_intel_legacy_compute_program_probe,
|
||||
suite : 'stela')
|
||||
if stela_air_llvm != '' and stela_metal_input != ''
|
||||
stela_intel_air = static_library(
|
||||
'stela_intel_air',
|
||||
['../../../../intel/stela/hosted/air_compile.c',
|
||||
'../../../../intel/stela/hosted/air_validate_elk.c'],
|
||||
include_directories : [inc_include, inc_src, inc_intel],
|
||||
dependencies : [idep_stela_air, idep_intel_compiler_brw,
|
||||
idep_intel_compiler_elk, idep_intel_compiler_gen,
|
||||
idep_intel_dev, idep_mesautil],
|
||||
link_with : [stela_metal_assembly, stela_metal_threadgroup],
|
||||
c_args : ['-Werror'],
|
||||
)
|
||||
stela_intel_air_compile_test = executable(
|
||||
'stela_intel_air_compile_test',
|
||||
'../../../../intel/stela/tests/air_compile.c',
|
||||
include_directories : [inc_include, inc_src, inc_intel,
|
||||
include_directories('../../../../intel/stela/hosted')],
|
||||
dependencies : [idep_stela_air, idep_intel_compiler_brw,
|
||||
idep_intel_compiler_elk, idep_intel_compiler_gen,
|
||||
idep_intel_dev, idep_mesautil,
|
||||
dependency('appleframeworks', modules : ['CoreFoundation'])],
|
||||
link_with : [stela_intel_air, stela_intel_surface,
|
||||
stela_intel_compute_policy, stela_intel_compute_native,
|
||||
stela_intel_legacy_compute, stela_intel_gpgpu_native,
|
||||
libisl, stela_apple_source],
|
||||
link_args : [stela_metal_input, '-lresolv', '-liconv'] + stela_intel_policy_gc,
|
||||
c_args : ['-Werror'],
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
test('stela_intel_air_owned', stela_intel_air_compile_test, suite : 'stela')
|
||||
endif
|
||||
if stela_air_llvm != ''
|
||||
stela_intel_fp_controls_probe = executable(
|
||||
'stela_intel_fp_controls_probe',
|
||||
@@ -643,6 +745,30 @@ if with_stela_amd
|
||||
c_args : ['-Werror', '-DSTELA_AMD_TEST_LLVM=' + (with_stela_amd_llvm ? '1' : '0')],
|
||||
)
|
||||
test('stela_amd_compute', stela_amd_compute_probe, suite : 'stela')
|
||||
if stela_air_llvm != '' and stela_metal_input != ''
|
||||
stela_amd_air = static_library(
|
||||
'stela_amd_air',
|
||||
'../../../../amd/stela/air_compile.c',
|
||||
include_directories : [inc_include, inc_src, inc_amd, inc_amd_common],
|
||||
dependencies : [idep_stela_air, idep_aco, idep_amd_generated_headers] +
|
||||
(with_stela_amd_llvm ? [dep_llvm] : []),
|
||||
link_with : [stela_metal_assembly, stela_metal_threadgroup, stela_amd_buffer, libamd_compiler_support],
|
||||
c_args : ['-Werror'],
|
||||
)
|
||||
stela_amd_air_compile_test = executable(
|
||||
'stela_amd_air_compile_test',
|
||||
'../../../../amd/tests/air_compile.c',
|
||||
include_directories : [inc_include, inc_src, inc_amd, inc_amd_common],
|
||||
dependencies : [idep_stela_air, idep_aco, idep_amd_generated_headers,
|
||||
dependency('appleframeworks', modules : ['CoreFoundation'])] +
|
||||
(with_stela_amd_llvm ? [dep_llvm] : []),
|
||||
link_with : [stela_amd_air, stela_amd_compute, stela_apple_source],
|
||||
link_args : [stela_metal_input, '-lresolv', '-liconv'],
|
||||
c_args : ['-Werror'],
|
||||
build_rpath : fs.parent(stela_air_llvm),
|
||||
)
|
||||
test('stela_amd_air_owned', stela_amd_air_compile_test, suite : 'stela')
|
||||
endif
|
||||
if stela_air_llvm != '' and with_stela_amd_llvm
|
||||
stela_amd_air_threadgroup_probe = executable(
|
||||
'stela_amd_air_threadgroup_probe',
|
||||
|
||||
@@ -2,7 +2,13 @@
|
||||
//! does not initialize a device, map GPU memory, submit jobs or expose Metal.
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub mod activation;
|
||||
pub mod ct_storage;
|
||||
pub mod firmware;
|
||||
pub mod ggtt;
|
||||
pub mod guc_reset;
|
||||
pub mod pat;
|
||||
pub mod wopcm;
|
||||
|
||||
/// The actual VM's supported width, supplied by the device/VM owner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
//! Native owned BAR0/device-facts/root-GT probe; not firmware or job readiness.
|
||||
use crate::bus::mmio::owned::{
|
||||
Authority, CacheAttribute, Error as MappingError, Mapping, MappingView, Protection, Resource,
|
||||
ResourceKind,
|
||||
};
|
||||
use alloc::{alloc::alloc_zeroed, alloc::dealloc, boxed::Box};
|
||||
use core::{alloc::Layout, ffi::c_void, marker::PhantomData, ptr::NonNull};
|
||||
use triomphe::UniqueArc;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct PciIdentity {
|
||||
pub vendor: u16,
|
||||
pub device: u16,
|
||||
pub class: u32,
|
||||
pub revision: u8,
|
||||
pub virtual_function: bool,
|
||||
pub bar0_start: u64,
|
||||
pub bar0_bytes: u64,
|
||||
}
|
||||
|
||||
/// Exclusive native PCI/power/bridge/reset epoch, supplied by the real mount.
|
||||
/// No implementation or fallback is supplied by this GPU module.
|
||||
///
|
||||
/// # Safety
|
||||
/// Identity/resource metadata is immutable and describes the SAME actual PCI
|
||||
/// function and exclusive reservation. The ResourceBacking must itself pin all
|
||||
/// teardown-critical root/reset/power state: canonical failed-map quarantine
|
||||
/// can retain it independently of this wrapper. This owner retains D0/bridge power,
|
||||
/// excludes removal/relocation/other resets, every other driver/firmware access and all
|
||||
/// IRQ/submission/DMA/CT users throughout this probe. GuC-only reset is an
|
||||
/// explicit permitted operation within this exclusive actual epoch; it never
|
||||
/// substitutes for draining an active driver or excluding other resets. These
|
||||
/// prerequisites are not inferred from cleared software flags. `prepare` performs
|
||||
/// required original device-WA and PCODE/lmem readiness, not a success flag in their place.
|
||||
/// Ordered naturally-aligned MMIO32 operations must use the provided canonical
|
||||
/// CPU pointer, honor original read-flush WA and posting/ordering semantics,
|
||||
/// never conflate it with a physical/guest address and never fail/unwind.
|
||||
/// The clock is qualified monotonic nonnegative nanoseconds, sufficiently below
|
||||
/// i64::MAX for a 100ms deadline. Delay honors atomic/sleepable context. All calls
|
||||
/// and final Drop occur on the allowed native CPU/process context; no callback
|
||||
/// may reenter, activate guest services, or manufacture power/IRQ/coherence.
|
||||
/// `finish` drains actual probe accesses/posted writes and prevents new accesses
|
||||
/// but keeps ownership retained until the canonical mapping retires. Error
|
||||
/// leaves the owner/reservations intact for retry/quarantine. Partial drain
|
||||
/// effects on error are allowed; finish retries must safely complete that drain.
|
||||
/// Once retirement begins no other device operations resume. `fatal` fail-stops.
|
||||
pub unsafe trait ProbeOwner {
|
||||
/// Check CPU/process/retained epoch without accessing BAR mappings. This
|
||||
/// also runs during an uncertain-unmap retry when BAR access is forbidden.
|
||||
fn check_context(&self) -> Result<(), i32>;
|
||||
fn identity(&self) -> PciIdentity;
|
||||
fn bar0(&self) -> Resource;
|
||||
/// Actual same-function canonical configuration space, retained in this
|
||||
/// exclusive power/reset epoch. Unsupported capability is an explicit Err.
|
||||
fn config_space(&self) -> Result<&dyn crate::bus::pci::ConfigSpace, i32>;
|
||||
/// # Safety
|
||||
/// Live canonical UC GSM pointer, naturally aligned/bounded to eight bytes.
|
||||
/// Perform one genuinely ordered 64-bit MMIO read with the original readq
|
||||
/// semantics. No paired-32 fallback, guest access, unwind or fabricated value.
|
||||
/// Err means the width/capability is unavailable before any read; actual
|
||||
/// unexpected device-access faults obey the owner's fail-stop contract.
|
||||
unsafe fn read64(&self, pointer: NonNull<u64>) -> Result<u64, i32>;
|
||||
/// Borrow the same retained UC register mapping for actual original
|
||||
/// PCODE/lmem/WA preparation. Any retained view must be released by finish.
|
||||
fn prepare(
|
||||
&self,
|
||||
registers: &MappingView,
|
||||
platform: u32,
|
||||
revision: u32,
|
||||
discrete: bool,
|
||||
) -> Result<(), i32>;
|
||||
/// # Safety
|
||||
/// Pointer is a live canonical UC, aligned, bounded device register.
|
||||
unsafe fn read32(&self, pointer: NonNull<u32>) -> u32;
|
||||
/// # Safety
|
||||
/// Same retained mapping and exclusive ordered-access contract as read32.
|
||||
unsafe fn write32(&self, pointer: NonNull<u32>, value: u32);
|
||||
fn now_ns(&self) -> i64;
|
||||
fn delay_us(&self, minimum: u32, maximum: u32, atomic: bool);
|
||||
fn report(&self, domains: u32, wake: bool, status: i32, value: u32);
|
||||
fn finish(&self) -> Result<(), i32>;
|
||||
fn fatal(&self) -> !;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Error {
|
||||
Mapping(MappingError),
|
||||
InvalidOwner,
|
||||
OutOfMemory,
|
||||
InvalidLayout,
|
||||
Native(i32),
|
||||
Closing,
|
||||
Awake,
|
||||
}
|
||||
impl From<MappingError> for Error {
|
||||
fn from(value: MappingError) -> Self {
|
||||
Self::Mapping(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct Facts {
|
||||
pub platform: u32,
|
||||
pub subplatform: u32,
|
||||
pub graphics_verx100: u32,
|
||||
pub media_verx100: u32,
|
||||
pub graphics_revision: u32,
|
||||
pub media_revision: u32,
|
||||
pub pci_revision: u32,
|
||||
pub tile_count: u32,
|
||||
pub dma_bits: u32,
|
||||
pub va_bits: u32,
|
||||
pub max_gt_per_tile: u32,
|
||||
pub discrete: u32,
|
||||
pub force_probe_required: u32,
|
||||
pub gt_control: u32,
|
||||
pub gt_ack: u32,
|
||||
pub initialized: u32,
|
||||
pub awake: u32,
|
||||
pub has_llc: u32,
|
||||
pub gt_type: u32,
|
||||
}
|
||||
|
||||
const _: () = assert!(core::mem::size_of::<Facts>() == 76);
|
||||
const _: () = assert!(core::mem::offset_of!(Facts, has_llc) == 68);
|
||||
const _: () = assert!(core::mem::offset_of!(Facts, gt_type) == 72);
|
||||
#[repr(C)]
|
||||
struct Io {
|
||||
check_context: extern "C" fn(*mut c_void) -> i32,
|
||||
prepare: extern "C" fn(*mut c_void, u32, u32, bool) -> i32,
|
||||
read32: extern "C" fn(*mut c_void, u32) -> u32,
|
||||
write32: extern "C" fn(*mut c_void, u32, u32),
|
||||
now_ns: extern "C" fn(*mut c_void) -> i64,
|
||||
delay_us: extern "C" fn(*mut c_void, u32, u32, bool),
|
||||
invariant: extern "C" fn(*mut c_void, bool),
|
||||
report: extern "C" fn(*mut c_void, u32, bool, i32, u32),
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn stela_intel_activation_guc_reset(
|
||||
state: *mut c_void,
|
||||
result: &mut super::guc_reset::NativeResult,
|
||||
) -> i32;
|
||||
fn stela_intel_activation_pat(state: *mut c_void, result: &mut super::pat::NativeResult)
|
||||
-> i32;
|
||||
fn stela_intel_activation_wopcm(
|
||||
state: *mut c_void,
|
||||
bytes: *const u8,
|
||||
size: usize,
|
||||
output: &mut super::wopcm::NativeResult,
|
||||
) -> i32;
|
||||
fn stela_intel_activation_size() -> usize;
|
||||
fn stela_intel_activation_alignment() -> usize;
|
||||
fn stela_intel_activation_match(
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
class: u32,
|
||||
vf: bool,
|
||||
force_probe: bool,
|
||||
) -> i32;
|
||||
fn stela_intel_activation_init(
|
||||
storage: *mut c_void,
|
||||
bytes: usize,
|
||||
io: &Io,
|
||||
context: *mut c_void,
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
class: u32,
|
||||
revision: u32,
|
||||
bar_bytes: u64,
|
||||
vf: bool,
|
||||
force_probe: bool,
|
||||
) -> i32;
|
||||
fn stela_intel_activation_facts(storage: *const c_void, facts: &mut Facts) -> i32;
|
||||
fn stela_intel_activation_wake(storage: *mut c_void) -> i32;
|
||||
fn stela_intel_activation_sleep(storage: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
struct State {
|
||||
pointer: NonNull<u8>,
|
||||
layout: Layout,
|
||||
}
|
||||
impl State {
|
||||
fn new() -> Result<Self, Error> {
|
||||
// SAFETY: scalar layout queries have no context or device effects.
|
||||
let layout = Layout::from_size_align(unsafe { stela_intel_activation_size() }, unsafe {
|
||||
stela_intel_activation_alignment()
|
||||
})
|
||||
.map_err(|_| Error::InvalidLayout)?;
|
||||
if layout.size() == 0 {
|
||||
return Err(Error::InvalidLayout);
|
||||
}
|
||||
// SAFETY: nonzero validated layout; standard allocator, no GPU allocator.
|
||||
let pointer = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(Error::OutOfMemory)?;
|
||||
Ok(Self { pointer, layout })
|
||||
}
|
||||
fn pointer(&self) -> *mut c_void {
|
||||
self.pointer.as_ptr().cast()
|
||||
}
|
||||
}
|
||||
impl Drop for State {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: no C calls remain; exact original standard allocation/layout.
|
||||
unsafe { dealloc(self.pointer.as_ptr(), self.layout) };
|
||||
}
|
||||
}
|
||||
|
||||
struct Context {
|
||||
owner: Box<dyn ProbeOwner>,
|
||||
view: Option<MappingView>,
|
||||
}
|
||||
impl Context {
|
||||
fn pointer(&self, offset: u32) -> NonNull<u32> {
|
||||
let pointer = self
|
||||
.view
|
||||
.as_ref()
|
||||
.and_then(|v| v.address(offset as usize, 4).ok());
|
||||
match pointer {
|
||||
Some(p) if (p.as_ptr() as usize).is_multiple_of(4) => p.cast(),
|
||||
_ => self.owner.fatal(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn context<'a>(pointer: *mut c_void) -> &'a Context {
|
||||
// SAFETY: private IO table is reachable only with its pinned unique context.
|
||||
unsafe { &*pointer.cast::<Context>() }
|
||||
}
|
||||
extern "C" fn prepare(p: *mut c_void, platform: u32, revision: u32, discrete: bool) -> i32 {
|
||||
let c = context(p);
|
||||
let view = c.view.as_ref().unwrap_or_else(|| c.owner.fatal());
|
||||
c.owner
|
||||
.prepare(view, platform, revision, discrete)
|
||||
.err()
|
||||
.map_or(0, |e| if e < 0 { e } else { -22 })
|
||||
}
|
||||
extern "C" fn check_context(p: *mut c_void) -> i32 {
|
||||
context(p)
|
||||
.owner
|
||||
.check_context()
|
||||
.err()
|
||||
.map_or(0, |e| if e < 0 { e } else { -22 })
|
||||
}
|
||||
extern "C" fn read32(p: *mut c_void, offset: u32) -> u32 {
|
||||
let c = context(p);
|
||||
// SAFETY: retained bounded canonical view, actual owner, exclusive probe.
|
||||
unsafe { c.owner.read32(c.pointer(offset)) }
|
||||
}
|
||||
extern "C" fn write32(p: *mut c_void, offset: u32, value: u32) {
|
||||
let c = context(p);
|
||||
// SAFETY: same ownership/order proof as read32, original access width32.
|
||||
unsafe { c.owner.write32(c.pointer(offset), value) };
|
||||
}
|
||||
extern "C" fn now_ns(p: *mut c_void) -> i64 {
|
||||
context(p).owner.now_ns()
|
||||
}
|
||||
extern "C" fn delay_us(p: *mut c_void, min: u32, max: u32, atomic: bool) {
|
||||
context(p).owner.delay_us(min, max, atomic);
|
||||
}
|
||||
extern "C" fn invariant(p: *mut c_void, valid: bool) {
|
||||
if !valid {
|
||||
context(p).owner.fatal();
|
||||
}
|
||||
}
|
||||
extern "C" fn report(p: *mut c_void, domains: u32, wake: bool, status: i32, value: u32) {
|
||||
context(p).owner.report(domains, wake, status, value);
|
||||
}
|
||||
static IO: Io = Io {
|
||||
check_context,
|
||||
prepare,
|
||||
read32,
|
||||
write32,
|
||||
now_ns,
|
||||
delay_us,
|
||||
invariant,
|
||||
report,
|
||||
};
|
||||
|
||||
struct Bundle {
|
||||
state: State,
|
||||
context: UniqueArc<Context>,
|
||||
mapping: Mapping,
|
||||
}
|
||||
impl Bundle {
|
||||
fn quarantine(self) {
|
||||
let Self {
|
||||
state,
|
||||
context,
|
||||
mapping,
|
||||
} = self;
|
||||
// Canonical Drop records/retains the mapping quarantine. Independently
|
||||
// retain callback storage and the real power/reset owner as well.
|
||||
drop(mapping);
|
||||
core::mem::forget(context);
|
||||
core::mem::forget(state);
|
||||
}
|
||||
}
|
||||
/// No Send/Sync: one real CPU-affine exclusive probe, no firmware/IRQ/users.
|
||||
/// Drop quarantines rather than inventing successful sleep/drain/unmap.
|
||||
pub struct Device {
|
||||
bundle: Option<Bundle>,
|
||||
closing: bool,
|
||||
drained: bool,
|
||||
poisoned: bool,
|
||||
awake: bool,
|
||||
_affinity: PhantomData<*mut ()>,
|
||||
}
|
||||
impl Device {
|
||||
pub fn open(
|
||||
authority: &Authority,
|
||||
owner: Box<dyn ProbeOwner>,
|
||||
force_probe: bool,
|
||||
) -> Result<Self, Error> {
|
||||
let pci = owner.identity();
|
||||
owner.check_context().map_err(Error::Native)?;
|
||||
// SAFETY: pure source-table policy; no mapping/owner/device effects.
|
||||
let matched = unsafe {
|
||||
stela_intel_activation_match(
|
||||
u32::from(pci.vendor),
|
||||
u32::from(pci.device),
|
||||
pci.class,
|
||||
pci.virtual_function,
|
||||
force_probe,
|
||||
)
|
||||
};
|
||||
if matched != 0 {
|
||||
return Err(Error::Native(matched));
|
||||
}
|
||||
let resource = owner.bar0();
|
||||
if resource.kind() != ResourceKind::Registers
|
||||
|| resource.physical_span().start() != pci.bar0_start
|
||||
|| resource.physical_span().bytes() != pci.bar0_bytes
|
||||
|| pci.class > 0xffffff
|
||||
|| pci.bar0_bytes < 16 * 1024 * 1024
|
||||
{
|
||||
return Err(Error::InvalidOwner);
|
||||
}
|
||||
// Reserve only the actual register extent. GSM at BAR+8MiB has a
|
||||
// separate same-resource grant/lease; mapping the entire BAR here would
|
||||
// overlap it under the canonical mapping authority.
|
||||
let bytes = 4 * 1024 * 1024;
|
||||
let state = State::new()?;
|
||||
// Reserve the maintained alloc-only owner before any mapping effect.
|
||||
// Failure drops both the already reserved State and the original owner.
|
||||
let mut context_storage =
|
||||
UniqueArc::<Context>::try_new_uninit().map_err(|_| Error::OutOfMemory)?;
|
||||
let context_address =
|
||||
context_storage.write(Context { owner, view: None }) as *mut Context as usize;
|
||||
// SAFETY: write initialized the complete Context exactly once. The
|
||||
// UniqueArc conversion retains its allocation and stable C address.
|
||||
let mut context = unsafe { UniqueArc::assume_init(context_storage) };
|
||||
debug_assert_eq!(context_address, &*context as *const Context as usize);
|
||||
let mapping = match authority.map(
|
||||
resource,
|
||||
0,
|
||||
bytes,
|
||||
CacheAttribute::Uncached,
|
||||
Protection::ReadWrite,
|
||||
) {
|
||||
Ok(mapping) => mapping,
|
||||
Err(error) => {
|
||||
// The canonical Error intentionally does not certify whether
|
||||
// a failed provider call left mappings behind. Retain the
|
||||
// actual power/reset epoch even for an ambiguous failure;
|
||||
// no CPU access or fictitious rollback may follow it.
|
||||
core::mem::forget(context);
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
let view = match mapping.view(0..4 * 1024 * 1024) {
|
||||
Ok(view) => view,
|
||||
Err(e) => {
|
||||
drop(mapping);
|
||||
core::mem::forget(context);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
context.view = Some(view);
|
||||
// SAFETY: allocated/aligned private storage; context/owner/Mapping pinned.
|
||||
// C validates original table selection before MMIO; no object escapes.
|
||||
let result = unsafe {
|
||||
stela_intel_activation_init(
|
||||
state.pointer(),
|
||||
state.layout.size(),
|
||||
&IO,
|
||||
(&mut *context as *mut Context).cast(),
|
||||
u32::from(pci.vendor),
|
||||
u32::from(pci.device),
|
||||
pci.class,
|
||||
u32::from(pci.revision),
|
||||
pci.bar0_bytes,
|
||||
pci.virtual_function,
|
||||
force_probe,
|
||||
)
|
||||
};
|
||||
let bundle = Bundle {
|
||||
state,
|
||||
context,
|
||||
mapping,
|
||||
};
|
||||
if result != 0 {
|
||||
// prepare may have had genuine hardware effects; no fake rollback.
|
||||
bundle.quarantine();
|
||||
return Err(Error::Native(result));
|
||||
}
|
||||
Ok(Self {
|
||||
bundle: Some(bundle),
|
||||
closing: false,
|
||||
drained: false,
|
||||
poisoned: false,
|
||||
awake: false,
|
||||
_affinity: PhantomData,
|
||||
})
|
||||
}
|
||||
fn live(&self) -> Result<&Bundle, Error> {
|
||||
if self.closing {
|
||||
return Err(Error::Closing);
|
||||
}
|
||||
self.bundle.as_ref().ok_or(Error::Closing)
|
||||
}
|
||||
pub fn facts(&self) -> Result<Facts, Error> {
|
||||
let mut result = Facts::default();
|
||||
// SAFETY: live immutable C state and exact scalar output layout.
|
||||
let status =
|
||||
unsafe { stela_intel_activation_facts(self.live()?.state.pointer(), &mut result) };
|
||||
if status == 0 {
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::Native(status))
|
||||
}
|
||||
}
|
||||
/// Issue the original direct XeLP PAT sequence in this exclusive live
|
||||
/// root-primary epoch. No readback, ACK, CPU cache or BO state is implied.
|
||||
pub fn program_pat(&mut self) -> Result<super::pat::Programming<'_>, Error> {
|
||||
let state = self.live()?.state.pointer();
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
let mut result = super::pat::NativeResult::default();
|
||||
// SAFETY: actual State retains same canonical view, descriptor/GT role,
|
||||
// exclusive owner and acknowledged wake; stack output before effects.
|
||||
let status = unsafe { stela_intel_activation_pat(state, &mut result) };
|
||||
if status != 0 {
|
||||
if result.writes != 0 {
|
||||
self.gsm_poison();
|
||||
}
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
Ok(super::pat::Programming::from_native(self, result))
|
||||
}
|
||||
/// Explicit original GuC-only reset handshake under the actual owner's
|
||||
/// exclusive no-DMA/no-IRQ/no-CT/no-submission epoch. This is not whole uC
|
||||
/// sanitize, driver initialization, software job drain or firmware loading.
|
||||
/// A failed exposed reset permanently closes and quarantines this epoch;
|
||||
/// no retry, Drop, sleep or finish may release uncertain reset ownership.
|
||||
pub fn reset_guc(&mut self) -> Result<super::guc_reset::Handshake<'_>, Error> {
|
||||
let state = self.live()?.state.pointer();
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
let mut result = super::guc_reset::NativeResult::default();
|
||||
// SAFETY: same actual owned State/view and stable Context; acknowledged
|
||||
// GT wake, qualified clock/context and exclusive real epoch exclude all
|
||||
// active users before entry. Stack metadata exists before any effect.
|
||||
let status = unsafe { stela_intel_activation_guc_reset(state, &mut result) };
|
||||
if status != 0 {
|
||||
if result.writes != 0 {
|
||||
self.gsm_poison();
|
||||
}
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
Ok(super::guc_reset::Handshake::from_native(self, result))
|
||||
}
|
||||
/// Acquire the original PF GSM geometry and a separate real same-BAR UC
|
||||
/// mapping. Requires acknowledged root GT wake and actual config-space/
|
||||
/// mapping capabilities; establishes neither GGTT initialization nor PAT.
|
||||
pub fn probe_gsm<'device>(
|
||||
&'device mut self,
|
||||
authority: &Authority,
|
||||
) -> Result<super::ggtt::Probe<'device>, Error> {
|
||||
self.live()?;
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
let facts = self.facts()?;
|
||||
let bundle = self.live()?;
|
||||
bundle
|
||||
.context
|
||||
.owner
|
||||
.check_context()
|
||||
.map_err(Error::Native)?;
|
||||
let mut offset = 0;
|
||||
// SAFETY: original CPU-only policy; checked live device facts.
|
||||
let config =
|
||||
unsafe { super::ggtt::stela_intel_gsm_config(facts.graphics_verx100, &mut offset) };
|
||||
let gmch = match config {
|
||||
0 => bundle
|
||||
.context
|
||||
.owner
|
||||
.config_space()
|
||||
.map_err(Error::Native)?
|
||||
.read16(offset),
|
||||
1 => 0,
|
||||
error => return Err(Error::Native(error)),
|
||||
};
|
||||
let identity = bundle.context.owner.identity();
|
||||
let geometry =
|
||||
super::ggtt::Geometry::from_facts(facts, identity.bar0_bytes, config == 0, gmch)?;
|
||||
let resource = bundle.context.owner.bar0();
|
||||
if resource.kind() != ResourceKind::Registers
|
||||
|| resource.physical_span().start() != identity.bar0_start
|
||||
|| resource.physical_span().bytes() != identity.bar0_bytes
|
||||
{
|
||||
return Err(Error::InvalidOwner);
|
||||
}
|
||||
let bytes = usize::try_from(geometry.gsm_bytes).map_err(|_| Error::InvalidOwner)?;
|
||||
let offset = usize::try_from(geometry.gsm_offset).map_err(|_| Error::InvalidOwner)?;
|
||||
let mapping = match authority.map(
|
||||
resource,
|
||||
offset,
|
||||
bytes,
|
||||
CacheAttribute::Uncached,
|
||||
Protection::ReadOnly,
|
||||
) {
|
||||
Ok(mapping) => mapping,
|
||||
Err(error) => {
|
||||
// Error does not certify a safe rollback. Existing backing and
|
||||
// preallocated Context keep reset/power/forcewake pinned, with
|
||||
// no allocation or device access in this uncertainty path.
|
||||
self.gsm_poison();
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
let view = match mapping.view(0..bytes) {
|
||||
Ok(view) => view,
|
||||
Err(error) => {
|
||||
self.gsm_poison();
|
||||
drop(mapping); // canonical quarantine; never assume unmap.
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
Ok(super::ggtt::Probe::from_native(
|
||||
self, geometry, mapping, view,
|
||||
))
|
||||
}
|
||||
pub(super) fn gsm_check_context(&self) -> Result<(), Error> {
|
||||
self.bundle
|
||||
.as_ref()
|
||||
.ok_or(Error::Closing)?
|
||||
.context
|
||||
.owner
|
||||
.check_context()
|
||||
.map_err(Error::Native)
|
||||
}
|
||||
pub(super) fn gsm_poison(&mut self) {
|
||||
self.closing = true;
|
||||
self.poisoned = true;
|
||||
}
|
||||
pub(super) fn gsm_read64(&self, view: &MappingView, offset: usize) -> Result<u64, Error> {
|
||||
let bundle = self.live()?;
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
bundle
|
||||
.context
|
||||
.owner
|
||||
.check_context()
|
||||
.map_err(Error::Native)?;
|
||||
let pointer = view.address(offset, 8)?;
|
||||
if !(pointer.as_ptr() as usize).is_multiple_of(8) {
|
||||
return Err(Error::InvalidOwner);
|
||||
}
|
||||
// SAFETY: actual retained same-resource UC lease; checked complete width,
|
||||
// original PTE index and native owner/context; exclusive Device borrow.
|
||||
unsafe { bundle.context.owner.read64(pointer.cast()) }.map_err(Error::Native)
|
||||
}
|
||||
/// Original default GuC metadata request, bound to this retained live
|
||||
/// native root main-GT owner. No firmware is uploaded or authenticated.
|
||||
pub fn guc_firmware(&self) -> Result<super::firmware::Request<'_>, super::firmware::Error> {
|
||||
let identity = self.live()?.context.owner.identity();
|
||||
let facts = self.facts()?;
|
||||
super::firmware::Request::from_native(self, identity, facts)
|
||||
}
|
||||
/// Original default HuC request, retaining this actual root main-GT owner.
|
||||
/// Host parsing never establishes firmware availability or WOPCM readiness.
|
||||
pub fn huc_firmware(&self) -> Result<super::firmware::HucRequest<'_>, super::firmware::Error> {
|
||||
let identity = self.live()?.context.owner.identity();
|
||||
let facts = self.facts()?;
|
||||
super::firmware::HucRequest::from_native(self, identity, facts)
|
||||
}
|
||||
/// Partition/read back actual root-GT WOPCM using the original algorithm.
|
||||
/// Requires acknowledged wake. An exposed write failure permanently closes
|
||||
/// this epoch and retains its canonical owner/view; no cleanup can release
|
||||
/// forcewake/reset ownership. All result storage is on the stack before IO.
|
||||
pub fn prepare_wopcm<'device, 'provider>(
|
||||
&'device mut self,
|
||||
provider: &'provider dyn crate::firmware::Provider,
|
||||
) -> Result<super::wopcm::Preparation<'device, 'provider>, super::wopcm::Error> {
|
||||
self.live()?;
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake.into());
|
||||
}
|
||||
let (image, metadata, identity, facts) = {
|
||||
let request = self.guc_firmware()?;
|
||||
let loaded = request.load(provider)?;
|
||||
(
|
||||
loaded.image(),
|
||||
loaded.metadata(),
|
||||
loaded.identity(),
|
||||
loaded.facts(),
|
||||
)
|
||||
};
|
||||
let mut result = super::wopcm::NativeResult::default();
|
||||
// SAFETY: SAME private owned C state and actual immutable provider CPU
|
||||
// span. C independently checks acknowledged GT/role/firmware bounds.
|
||||
// Existing State/Context/mapping storage was reserved before all IO;
|
||||
// no allocation or owner release follows an exposed failure.
|
||||
let status = unsafe {
|
||||
stela_intel_activation_wopcm(
|
||||
self.live()?.state.pointer(),
|
||||
image.bytes().as_ptr(),
|
||||
image.bytes().len(),
|
||||
&mut result,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
if result.writes != 0 {
|
||||
self.poisoned = true;
|
||||
self.closing = true;
|
||||
}
|
||||
return Err(result.error(status));
|
||||
}
|
||||
Ok(super::wopcm::Preparation::from_native(
|
||||
self, image, metadata, identity, facts, result,
|
||||
))
|
||||
}
|
||||
pub fn wake(&mut self) -> Result<(), Error> {
|
||||
let storage = self.live()?.state.pointer();
|
||||
if self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
// SAFETY: &mut plus CPU affinity and actual ProbeOwner exclude all users.
|
||||
let status = unsafe { stela_intel_activation_wake(storage) };
|
||||
if status != 0 {
|
||||
self.poisoned = true;
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
self.awake = true;
|
||||
Ok(())
|
||||
}
|
||||
pub fn sleep(&mut self) -> Result<(), Error> {
|
||||
let storage = self.live()?.state.pointer();
|
||||
if !self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
// SAFETY: same actual exclusive native scope; no concurrent firmware.
|
||||
let status = unsafe { stela_intel_activation_sleep(storage) };
|
||||
if status != 0 {
|
||||
self.poisoned = true;
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
self.awake = false;
|
||||
Ok(())
|
||||
}
|
||||
pub fn retire(&mut self) -> Result<(), Error> {
|
||||
if self.awake || self.poisoned {
|
||||
return Err(Error::Awake);
|
||||
}
|
||||
let bundle = self.bundle.as_mut().ok_or(Error::Closing)?;
|
||||
bundle
|
||||
.context
|
||||
.owner
|
||||
.check_context()
|
||||
.map_err(Error::Native)?;
|
||||
// A real drain can have partial effects before returning an error.
|
||||
// Freeze all public device/C operations BEFORE attempting it, retaining
|
||||
// the live mapping/view and owners until the drain actually succeeds.
|
||||
self.closing = true;
|
||||
if !self.drained {
|
||||
bundle.context.owner.finish().map_err(Error::Native)?;
|
||||
self.drained = true;
|
||||
// No future C/CPU accesses; release our view before actual unmap.
|
||||
drop(bundle.context.view.take());
|
||||
}
|
||||
// SAFETY: acknowledged sleep, actual owner drain, no IRQ/submission,
|
||||
// CPU-affine &mut exclusion. Failed mappings stay retained for retry.
|
||||
unsafe { bundle.mapping.retire()? };
|
||||
self.bundle = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Device {
|
||||
fn drop(&mut self) {
|
||||
if let Some(bundle) = self.bundle.take() {
|
||||
bundle.quarantine();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
//! Provider-borrowed GuC/HuC metadata selected by a live native Xe device.
|
||||
//! No BO, firmware status, authentication or hardware upload is established.
|
||||
use super::activation::{self, Device, Facts, PciIdentity};
|
||||
use crate::firmware::{Image, Provider, Requirement, Target};
|
||||
use core::fmt::{self, Write};
|
||||
|
||||
const CSS_HEADER_BYTES: usize = 128;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Device(activation::Error),
|
||||
Selection(i32),
|
||||
InvalidNativeIdentity,
|
||||
InvalidCatalogName,
|
||||
IdentityEncoding,
|
||||
Provider(crate::firmware::Error),
|
||||
WrongImage,
|
||||
HucAbsent(HucDisposition),
|
||||
Parse {
|
||||
status: i32,
|
||||
diagnostics: Diagnostics,
|
||||
},
|
||||
}
|
||||
impl From<activation::Error> for Error {
|
||||
fn from(value: activation::Error) -> Self {
|
||||
Self::Device(value)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub struct Version {
|
||||
pub major: u32,
|
||||
pub minor: u32,
|
||||
pub patch: u32,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(transparent)]
|
||||
pub struct Diagnostics(u32);
|
||||
impl Diagnostics {
|
||||
pub const GUC_TOO_OLD: u32 = 1 << 0;
|
||||
pub const VERSION_MISMATCH: u32 = 1 << 1;
|
||||
pub const RECOMMENDED_NEWER: u32 = 1 << 2;
|
||||
pub const SHORT_HEADER: u32 = 1 << 3;
|
||||
pub const HEADER_SIZE: u32 = 1 << 4;
|
||||
pub const SHORT_IMAGE: u32 = 1 << 5;
|
||||
pub const CPD_HEADER_LENGTH: u32 = 1 << 8;
|
||||
pub const CPD_SHORT_IMAGE: u32 = 1 << 9;
|
||||
pub const CPD_MISSING_MANIFEST: u32 = 1 << 10;
|
||||
pub const UNREPRESENTABLE: u32 = 1 << 31;
|
||||
pub fn bits(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub struct Metadata {
|
||||
pub release: Version,
|
||||
pub submission: Version,
|
||||
pub ucode_bytes: u32,
|
||||
pub rsa_bytes: u32,
|
||||
pub upload_bytes: u32,
|
||||
pub private_bytes: u32,
|
||||
pub build_type: u32,
|
||||
pub diagnostics: Diagnostics,
|
||||
}
|
||||
#[repr(C)]
|
||||
struct Selection {
|
||||
name: [u8; 64],
|
||||
wanted: Version,
|
||||
full_version: u32,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<Selection>() == 80);
|
||||
const _: () = assert!(core::mem::size_of::<Metadata>() == 48);
|
||||
const _: () = assert!(core::mem::offset_of!(Selection, wanted) == 64);
|
||||
const _: () = assert!(core::mem::offset_of!(Selection, full_version) == 76);
|
||||
const _: () = assert!(core::mem::offset_of!(Metadata, submission) == 12);
|
||||
const _: () = assert!(core::mem::offset_of!(Metadata, ucode_bytes) == 24);
|
||||
const _: () = assert!(core::mem::offset_of!(Metadata, diagnostics) == 44);
|
||||
unsafe extern "C" {
|
||||
fn stela_intel_guc_select(platform: u32, output: &mut Selection) -> i32;
|
||||
fn stela_intel_guc_parse(
|
||||
platform: u32,
|
||||
bytes: *const u8,
|
||||
size: usize,
|
||||
output: &mut Metadata,
|
||||
diagnostics: &mut u32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
// Only bounded Intel identity formatting; no allocation or general registry.
|
||||
struct Label<const N: usize> {
|
||||
bytes: [u8; N],
|
||||
used: usize,
|
||||
}
|
||||
impl<const N: usize> Label<N> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
bytes: [0; N],
|
||||
used: 0,
|
||||
}
|
||||
}
|
||||
fn as_str(&self) -> &str {
|
||||
// SAFETY: only write_str copies valid UTF-8, preserving whole fragments.
|
||||
unsafe { core::str::from_utf8_unchecked(&self.bytes[..self.used]) }
|
||||
}
|
||||
}
|
||||
impl<const N: usize> Write for Label<N> {
|
||||
fn write_str(&mut self, value: &str) -> fmt::Result {
|
||||
let end = self
|
||||
.used
|
||||
.checked_add(value.len())
|
||||
.filter(|&v| v <= N)
|
||||
.ok_or(fmt::Error)?;
|
||||
self.bytes[self.used..end].copy_from_slice(value.as_bytes());
|
||||
self.used = end;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn identity_labels(identity: PciIdentity, facts: Facts) -> Result<(Label<16>, Label<96>), Error> {
|
||||
let mut hardware = Label::new();
|
||||
write!(
|
||||
hardware,
|
||||
"pci-{:04x}-{:04x}",
|
||||
identity.vendor, identity.device
|
||||
)
|
||||
.map_err(|_| Error::IdentityEncoding)?;
|
||||
let mut revision = Label::new();
|
||||
write!(
|
||||
revision,
|
||||
"pci-{:02x};gfx-{}.{};media-{}.{};gt-main;tile-0",
|
||||
identity.revision,
|
||||
facts.graphics_verx100,
|
||||
facts.graphics_revision,
|
||||
facts.media_verx100,
|
||||
facts.media_revision
|
||||
)
|
||||
.map_err(|_| Error::IdentityEncoding)?;
|
||||
Ok((hardware, revision))
|
||||
}
|
||||
|
||||
/// Exact default request from the actual retained root main-GT device.
|
||||
/// The setup manifest must use this same filename and exact target tuple.
|
||||
pub struct Request<'device> {
|
||||
device: &'device Device,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
selection: Selection,
|
||||
name_bytes: usize,
|
||||
hardware: Label<16>,
|
||||
revision: Label<96>,
|
||||
}
|
||||
impl<'device> Request<'device> {
|
||||
pub(super) fn from_native(
|
||||
device: &'device Device,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
) -> Result<Self, Error> {
|
||||
if identity.vendor != 0x8086 || identity.virtual_function || facts.graphics_verx100 == 0 {
|
||||
return Err(Error::InvalidNativeIdentity);
|
||||
}
|
||||
let mut selection = Selection {
|
||||
name: [0; 64],
|
||||
wanted: Version::default(),
|
||||
full_version: 0,
|
||||
};
|
||||
// SAFETY: private scalar output, exact C layout; source catalog only.
|
||||
let status = unsafe { stela_intel_guc_select(facts.platform, &mut selection) };
|
||||
if status != 0 {
|
||||
return Err(Error::Selection(status));
|
||||
}
|
||||
let name_bytes = selection
|
||||
.name
|
||||
.iter()
|
||||
.position(|&v| v == 0)
|
||||
.filter(|&n| n != 0)
|
||||
.ok_or(Error::InvalidCatalogName)?;
|
||||
core::str::from_utf8(&selection.name[..name_bytes])
|
||||
.map_err(|_| Error::InvalidCatalogName)?;
|
||||
let (hardware, revision) = identity_labels(identity, facts)?;
|
||||
Ok(Self {
|
||||
device,
|
||||
identity,
|
||||
facts,
|
||||
selection,
|
||||
name_bytes,
|
||||
hardware,
|
||||
revision,
|
||||
})
|
||||
}
|
||||
pub fn name(&self) -> &str {
|
||||
// SAFETY: constructor validates this immutable, private native copy.
|
||||
unsafe { core::str::from_utf8_unchecked(&self.selection.name[..self.name_bytes]) }
|
||||
}
|
||||
pub fn wanted(&self) -> Version {
|
||||
self.selection.wanted
|
||||
}
|
||||
pub fn full_version_required(&self) -> bool {
|
||||
self.selection.full_version != 0
|
||||
}
|
||||
pub fn target(&self) -> Target<'_> {
|
||||
Target {
|
||||
driver: "intel-xe-guc",
|
||||
hardware: self.hardware.as_str(),
|
||||
revision: self.revision.as_str(),
|
||||
board: None,
|
||||
}
|
||||
}
|
||||
pub fn requirement(&self) -> Requirement<'_> {
|
||||
Requirement {
|
||||
name: self.name(),
|
||||
target: self.target(),
|
||||
minimum_bytes: CSS_HEADER_BYTES,
|
||||
}
|
||||
}
|
||||
pub fn load<'provider>(
|
||||
&self,
|
||||
provider: &'provider dyn Provider,
|
||||
) -> Result<GucImage<'device, 'provider>, Error> {
|
||||
let image = provider.load(self.requirement()).map_err(Error::Provider)?;
|
||||
// A safe third-party Provider cannot manufacture Image, but could
|
||||
// delegate to a catalog using the wrong requirement. Recheck its reply.
|
||||
if image.name() != self.name() || image.target() != self.target() {
|
||||
return Err(Error::WrongImage);
|
||||
}
|
||||
let mut metadata = Metadata::default();
|
||||
let mut diagnostics = 0;
|
||||
// SAFETY: provider-owned immutable single-allocation CPU slice; packed
|
||||
// CSS ABI and checked native extents, exact output layout, no device IO.
|
||||
let status = unsafe {
|
||||
stela_intel_guc_parse(
|
||||
self.facts.platform,
|
||||
image.bytes().as_ptr(),
|
||||
image.bytes().len(),
|
||||
&mut metadata,
|
||||
&mut diagnostics,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Parse {
|
||||
status,
|
||||
diagnostics: Diagnostics(diagnostics),
|
||||
});
|
||||
}
|
||||
Ok(GucImage {
|
||||
_device: self.device,
|
||||
image,
|
||||
identity: self.identity,
|
||||
facts: self.facts,
|
||||
wanted: self.wanted(),
|
||||
metadata,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Format-checked host image with original provenance and borrowed lifetimes.
|
||||
/// It is not authenticated, GGTT-pinned, loadable or running firmware.
|
||||
pub struct GucImage<'device, 'provider> {
|
||||
_device: &'device Device,
|
||||
image: Image<'provider>,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
wanted: Version,
|
||||
metadata: Metadata,
|
||||
}
|
||||
impl<'provider> GucImage<'_, 'provider> {
|
||||
pub fn image(&self) -> Image<'provider> {
|
||||
self.image
|
||||
}
|
||||
pub fn identity(&self) -> PciIdentity {
|
||||
self.identity
|
||||
}
|
||||
pub fn facts(&self) -> Facts {
|
||||
self.facts
|
||||
}
|
||||
pub fn wanted(&self) -> Version {
|
||||
self.wanted
|
||||
}
|
||||
pub fn metadata(&self) -> Metadata {
|
||||
self.metadata
|
||||
}
|
||||
}
|
||||
|
||||
/// Original default catalog/GT-role disposition, never a load status.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HucDisposition {
|
||||
Selected,
|
||||
AbsentRole,
|
||||
AbsentCatalog,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub struct HucMetadata {
|
||||
pub release: Version,
|
||||
pub ucode_bytes: u32,
|
||||
pub rsa_bytes: u32,
|
||||
pub upload_bytes: u32,
|
||||
pub css_offset: u32,
|
||||
format: u32,
|
||||
pub diagnostics: Diagnostics,
|
||||
}
|
||||
impl HucMetadata {
|
||||
pub fn has_gsc_headers(self) -> bool {
|
||||
self.format == 2
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
struct HucSelection {
|
||||
disposition: u32,
|
||||
name: [u8; 64],
|
||||
wanted: Version,
|
||||
full_version: u32,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<HucSelection>() == 84);
|
||||
const _: () = assert!(core::mem::offset_of!(HucSelection, wanted) == 68);
|
||||
const _: () = assert!(core::mem::size_of::<HucMetadata>() == 36);
|
||||
const _: () = assert!(core::mem::offset_of!(HucMetadata, css_offset) == 24);
|
||||
const _: () = assert!(core::mem::offset_of!(HucMetadata, diagnostics) == 32);
|
||||
unsafe extern "C" {
|
||||
fn stela_intel_huc_select_default(
|
||||
platform: u32,
|
||||
graphics_verx100: u32,
|
||||
media_gt: bool,
|
||||
output: &mut HucSelection,
|
||||
) -> i32;
|
||||
fn stela_intel_huc_parse(
|
||||
platform: u32,
|
||||
graphics_verx100: u32,
|
||||
media_gt: bool,
|
||||
bytes: *const u8,
|
||||
size: usize,
|
||||
output: &mut HucMetadata,
|
||||
diagnostics: &mut u32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
/// Actual retained root-main-GT default. Missing role/catalog never performs a
|
||||
/// Provider lookup, while failure of a selected image remains a real error.
|
||||
/// Every request borrows the same live Device; no copied identity is a device.
|
||||
pub struct HucRequest<'device> {
|
||||
device: &'device Device,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
selection: HucSelection,
|
||||
disposition: HucDisposition,
|
||||
name_bytes: usize,
|
||||
hardware: Label<16>,
|
||||
revision: Label<96>,
|
||||
}
|
||||
impl<'device> HucRequest<'device> {
|
||||
pub(super) fn from_native(
|
||||
device: &'device Device,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
) -> Result<Self, Error> {
|
||||
if identity.vendor != 0x8086 || identity.virtual_function || facts.graphics_verx100 == 0 {
|
||||
return Err(Error::InvalidNativeIdentity);
|
||||
}
|
||||
let mut selection = HucSelection {
|
||||
disposition: 0,
|
||||
name: [0; 64],
|
||||
wanted: Version::default(),
|
||||
full_version: 0,
|
||||
};
|
||||
// SAFETY: actual device facts and exact private C scalar output layout.
|
||||
let status = unsafe {
|
||||
stela_intel_huc_select_default(
|
||||
facts.platform,
|
||||
facts.graphics_verx100,
|
||||
false,
|
||||
&mut selection,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Selection(status));
|
||||
}
|
||||
let disposition = match selection.disposition {
|
||||
1 => HucDisposition::Selected,
|
||||
2 => HucDisposition::AbsentRole,
|
||||
3 => HucDisposition::AbsentCatalog,
|
||||
_ => return Err(Error::InvalidNativeIdentity),
|
||||
};
|
||||
let name_bytes = if disposition == HucDisposition::Selected {
|
||||
let n = selection
|
||||
.name
|
||||
.iter()
|
||||
.position(|&v| v == 0)
|
||||
.filter(|&n| n != 0)
|
||||
.ok_or(Error::InvalidCatalogName)?;
|
||||
core::str::from_utf8(&selection.name[..n]).map_err(|_| Error::InvalidCatalogName)?;
|
||||
n
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (hardware, revision) = identity_labels(identity, facts)?;
|
||||
Ok(Self {
|
||||
device,
|
||||
identity,
|
||||
facts,
|
||||
selection,
|
||||
disposition,
|
||||
name_bytes,
|
||||
hardware,
|
||||
revision,
|
||||
})
|
||||
}
|
||||
pub fn disposition(&self) -> HucDisposition {
|
||||
self.disposition
|
||||
}
|
||||
pub fn name(&self) -> Option<&str> {
|
||||
(self.disposition == HucDisposition::Selected).then(|| {
|
||||
// SAFETY: constructor validated the immutable private native copy.
|
||||
unsafe { core::str::from_utf8_unchecked(&self.selection.name[..self.name_bytes]) }
|
||||
})
|
||||
}
|
||||
pub fn wanted(&self) -> Option<Version> {
|
||||
self.name().map(|_| self.selection.wanted)
|
||||
}
|
||||
pub fn full_version_required(&self) -> bool {
|
||||
self.selection.full_version != 0
|
||||
}
|
||||
pub fn target(&self) -> Target<'_> {
|
||||
Target {
|
||||
driver: "intel-xe-huc",
|
||||
hardware: self.hardware.as_str(),
|
||||
revision: self.revision.as_str(),
|
||||
board: None,
|
||||
}
|
||||
}
|
||||
pub fn requirement(&self) -> Result<Requirement<'_>, Error> {
|
||||
Ok(Requirement {
|
||||
name: self.name().ok_or(Error::HucAbsent(self.disposition))?,
|
||||
target: self.target(),
|
||||
minimum_bytes: CSS_HEADER_BYTES,
|
||||
})
|
||||
}
|
||||
pub fn load<'provider>(
|
||||
&self,
|
||||
provider: &'provider dyn Provider,
|
||||
) -> Result<HucImage<'device, 'provider>, Error> {
|
||||
let requirement = self.requirement()?;
|
||||
let image = provider.load(requirement).map_err(Error::Provider)?;
|
||||
if image.name() != requirement.name || image.target() != requirement.target {
|
||||
return Err(Error::WrongImage);
|
||||
}
|
||||
let mut metadata = HucMetadata::default();
|
||||
let mut diagnostics = 0;
|
||||
// SAFETY: original immutable provider CPU span; checked packed parser
|
||||
// and exact scalar output. No MMIO, BO status or device DMA is accessed.
|
||||
let status = unsafe {
|
||||
stela_intel_huc_parse(
|
||||
self.facts.platform,
|
||||
self.facts.graphics_verx100,
|
||||
false,
|
||||
image.bytes().as_ptr(),
|
||||
image.bytes().len(),
|
||||
&mut metadata,
|
||||
&mut diagnostics,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Parse {
|
||||
status,
|
||||
diagnostics: Diagnostics(diagnostics),
|
||||
});
|
||||
}
|
||||
Ok(HucImage {
|
||||
_device: self.device,
|
||||
image,
|
||||
identity: self.identity,
|
||||
facts: self.facts,
|
||||
wanted: self.selection.wanted,
|
||||
metadata,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Format-checked host HuC image retaining canonical provenance and the same
|
||||
/// Device/provider borrows. This is neither cryptographic authentication nor
|
||||
/// AVAILABLE/LOADABLE, BO/GGTT storage, DMA completion or WOPCM admission.
|
||||
/// A later Device-owned bootstrap can retain the independent Image borrow
|
||||
/// (like GuC preparation) before consuming mutable device ownership; no lifetime
|
||||
/// erasure or replacement physical/native identity is needed.
|
||||
pub struct HucImage<'device, 'provider> {
|
||||
_device: &'device Device,
|
||||
image: Image<'provider>,
|
||||
identity: PciIdentity,
|
||||
facts: Facts,
|
||||
wanted: Version,
|
||||
metadata: HucMetadata,
|
||||
}
|
||||
impl<'provider> HucImage<'_, 'provider> {
|
||||
pub fn image(&self) -> Image<'provider> {
|
||||
self.image
|
||||
}
|
||||
pub fn identity(&self) -> PciIdentity {
|
||||
self.identity
|
||||
}
|
||||
pub fn facts(&self) -> Facts {
|
||||
self.facts
|
||||
}
|
||||
pub fn wanted(&self) -> Version {
|
||||
self.wanted
|
||||
}
|
||||
pub fn metadata(&self) -> HucMetadata {
|
||||
self.metadata
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Owned read-only Xe PF GSM probe. No GGTT/PAT/BO initialization or PTE writes.
|
||||
use super::activation::{Device, Error, Facts};
|
||||
use crate::bus::mmio::owned::{Mapping, MappingView};
|
||||
|
||||
/// Original immutable scalar geometry. It is not a mapping or allocation token.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct Geometry {
|
||||
pub gsm_offset: u64,
|
||||
pub gsm_bytes: u64,
|
||||
pub ggtt_start: u64,
|
||||
pub ggtt_bytes: u64,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<Geometry>() == 32);
|
||||
const _: () = assert!(core::mem::offset_of!(Geometry, ggtt_start) == 16);
|
||||
unsafe extern "C" {
|
||||
pub(super) fn stela_intel_gsm_config(graphics_verx100: u32, offset: &mut u16) -> i32;
|
||||
fn stela_intel_gsm_geometry(
|
||||
platform: u32,
|
||||
graphics_verx100: u32,
|
||||
discrete: bool,
|
||||
actual_bar_bytes: u64,
|
||||
config_present: bool,
|
||||
gmch: u16,
|
||||
output: &mut Geometry,
|
||||
) -> i32;
|
||||
fn stela_intel_gsm_pte_offset(geometry: &Geometry, address: u64, offset: &mut usize) -> i32;
|
||||
}
|
||||
impl Geometry {
|
||||
pub(super) fn from_facts(
|
||||
facts: Facts,
|
||||
bar_bytes: u64,
|
||||
present: bool,
|
||||
gmch: u16,
|
||||
) -> Result<Self, Error> {
|
||||
let mut result = Self::default();
|
||||
// SAFETY: CPU-only original policy and complete scalar ABI; actual live
|
||||
// device facts, whole BAR extent and same-function configuration input.
|
||||
let status = unsafe {
|
||||
stela_intel_gsm_geometry(
|
||||
facts.platform,
|
||||
facts.graphics_verx100,
|
||||
facts.discrete != 0,
|
||||
bar_bytes,
|
||||
present,
|
||||
gmch,
|
||||
&mut result,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
/// Exclusive live Device borrow retains forcewake/reset/power throughout reads
|
||||
/// and canonical teardown. No raw pointer escapes. Explicit successful retire
|
||||
/// releases this lease before the caller can sleep/finish the Device. Drop or
|
||||
/// uncertain teardown permanently poisons that epoch and quarantines ownership;
|
||||
/// retry can retire the SAME mapping but can never reopen device operations.
|
||||
pub struct Probe<'device> {
|
||||
device: &'device mut Device,
|
||||
geometry: Geometry,
|
||||
mapping: Option<Mapping>,
|
||||
view: Option<MappingView>,
|
||||
closing: bool,
|
||||
}
|
||||
impl<'device> Probe<'device> {
|
||||
pub(super) fn from_native(
|
||||
device: &'device mut Device,
|
||||
geometry: Geometry,
|
||||
mapping: Mapping,
|
||||
view: MappingView,
|
||||
) -> Self {
|
||||
Self {
|
||||
device,
|
||||
geometry,
|
||||
mapping: Some(mapping),
|
||||
view: Some(view),
|
||||
closing: false,
|
||||
}
|
||||
}
|
||||
pub fn geometry(&self) -> Geometry {
|
||||
self.geometry
|
||||
}
|
||||
/// Raw original readq result; does not validate PTE contents or readiness.
|
||||
/// Address is an original GGTT page address, never an IOVA or CPU pointer.
|
||||
pub fn read_pte(&self, address: u64) -> Result<u64, Error> {
|
||||
if self.closing {
|
||||
return Err(Error::Closing);
|
||||
}
|
||||
let mut offset = 0;
|
||||
// SAFETY: immutable native-produced geometry, checked original index and
|
||||
// complete eight-byte span before pointer formation or owner access.
|
||||
let status = unsafe { stela_intel_gsm_pte_offset(&self.geometry, address, &mut offset) };
|
||||
if status != 0 {
|
||||
return Err(Error::Native(status));
|
||||
}
|
||||
self.device
|
||||
.gsm_read64(self.view.as_ref().ok_or(Error::Closing)?, offset)
|
||||
}
|
||||
pub fn retire(&mut self) -> Result<(), Error> {
|
||||
self.device.gsm_check_context()?; // pure context check, including retries.
|
||||
let mapping = self.mapping.as_mut().ok_or(Error::Closing)?;
|
||||
self.closing = true;
|
||||
drop(self.view.take());
|
||||
// SAFETY: no escaped pointers or firmware/DMA/IRQ users; exclusive actual
|
||||
// owner remains awake/pinned, no outstanding CPU accesses after &mut.
|
||||
if let Err(error) = unsafe { mapping.retire() } {
|
||||
self.device.gsm_poison();
|
||||
return Err(error.into());
|
||||
}
|
||||
self.mapping = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Probe<'_> {
|
||||
fn drop(&mut self) {
|
||||
if self.mapping.is_some() {
|
||||
self.device.gsm_poison();
|
||||
drop(self.view.take());
|
||||
drop(self.mapping.take()); // existing canonical quarantine.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Observed original GuC-only hardware reset, retaining the actual Device epoch.
|
||||
use super::activation::Device;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub(super) struct NativeResult {
|
||||
pub writes: u32,
|
||||
pub warnings: u32,
|
||||
pub gdrst: u32,
|
||||
pub guc_status: u32,
|
||||
pub ready_status: u32,
|
||||
pub sram_status: u32,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<NativeResult>() == 24);
|
||||
const _: () = assert!(core::mem::offset_of!(NativeResult, guc_status) == 12);
|
||||
|
||||
/// The original GDRST clear and MIA-in-reset observations from this explicit
|
||||
/// operation. The exclusive borrow retains the same canonical owner and wake.
|
||||
/// This does not implement `xe_uc_sanitize_reset` or establish whole-device DMA
|
||||
/// quiescence, CT/job drain, firmware authentication or GGTT readiness. Drop
|
||||
/// performs no reset, rollback, sleep or implicit cleanup.
|
||||
pub struct Handshake<'device> {
|
||||
_device: &'device mut Device,
|
||||
result: NativeResult,
|
||||
}
|
||||
impl<'device> Handshake<'device> {
|
||||
pub(super) fn from_native(device: &'device mut Device, result: NativeResult) -> Self {
|
||||
Self {
|
||||
_device: device,
|
||||
result,
|
||||
}
|
||||
}
|
||||
pub fn writes_issued(&self) -> u32 {
|
||||
self.result.writes
|
||||
}
|
||||
pub fn gdrst_observed(&self) -> u32 {
|
||||
self.result.gdrst
|
||||
}
|
||||
pub fn guc_status_observed(&self) -> u32 {
|
||||
self.result.guc_status
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Original direct XeLP PAT writes, bound to a live actual Device epoch.
|
||||
use super::activation::Device;
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub(super) struct NativeResult {
|
||||
pub writes: u32,
|
||||
pub n_entries: u32,
|
||||
pub cache_none: u16,
|
||||
pub cache_wt: u16,
|
||||
pub cache_wb: u16,
|
||||
pub cache_none_compression: u16,
|
||||
pub cache_wb_compression: u16,
|
||||
pub reserved: u16,
|
||||
pub entries: [u32; 4],
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<NativeResult>() == 36);
|
||||
const _: () = assert!(core::mem::offset_of!(NativeResult, entries) == 20);
|
||||
/// Exact original issued sequence and cache policy. The borrow retains the real
|
||||
/// epoch; this is not an installed/ACK/READY, PTE, DMA or reset-survival token.
|
||||
/// Drop performs no implicit rollback, sleep or cleanup. Subsequent bootstrap
|
||||
/// must use this same Device, not a copied numeric index or success boolean.
|
||||
pub struct Programming<'device> {
|
||||
_device: &'device mut Device,
|
||||
result: NativeResult,
|
||||
}
|
||||
impl<'device> Programming<'device> {
|
||||
pub(super) fn from_native(device: &'device mut Device, result: NativeResult) -> Self {
|
||||
Self {
|
||||
_device: device,
|
||||
result,
|
||||
}
|
||||
}
|
||||
pub fn writes_issued(&self) -> u32 {
|
||||
self.result.writes
|
||||
}
|
||||
pub fn entries(&self) -> &[u32; 4] {
|
||||
&self.result.entries
|
||||
}
|
||||
pub fn cache_none(&self) -> u16 {
|
||||
self.result.cache_none
|
||||
}
|
||||
pub fn cache_wt(&self) -> u16 {
|
||||
self.result.cache_wt
|
||||
}
|
||||
pub fn cache_wb(&self) -> u16 {
|
||||
self.result.cache_wb
|
||||
}
|
||||
}
|
||||
Loaded 100 of 277 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user