XCL_ADAPTER: choose the D3D12 adapter, for titles and the GPU tests

The title's device took the first hardware adapter in high-performance
order and the GPU test bench always took adapter 0, so on a machine with
two GPUs only one of them could be tested.

`d3d12_adapter` in xcl.toml now also takes a number (that hardware
adapter in high-performance order) or a part of the adapter's name
("radeon", "rtx 3080"), and XCL_ADAPTER overrides it, as XCL_RAYTRACING
does for `raytracing`. gpu::adapter holds the choice; hle::d3d12x::real
and gpu::recomp::runner both use it. A name that matches no adapter is
logged with the adapters there are and the title falls back to auto;
the test bench reports it as the reason its GPU tests are skipped.
This commit is contained in:
Graham Calihan
2026-11-22 14:48:05 -05:00
parent cf08a50ace
commit 2dd04da71a
6 changed files with 172 additions and 20 deletions
+2 -1
View File
@@ -43,7 +43,8 @@ pub struct Config {
pub stub_returns: BTreeMap<String, String>,
/// "d3d12" (real GPU, default) or "null" (no rendering).
pub graphics: String,
/// "auto" (high-performance GPU, then WARP) or "warp".
/// "auto" (high-performance GPU, then WARP), "warp", a number (that hardware adapter in
/// high-performance order) or a part of the adapter's name ("radeon"). `XCL_ADAPTER` overrides.
pub d3d12_adapter: String,
/// Enable the D3D12 debug layer (needs Graphics Tools).
pub d3d12_debug: bool,
+110
View File
@@ -0,0 +1,110 @@
//! Which D3D12 adapter XCL uses: `d3d12_adapter` in `xcl.toml`, overridden by `XCL_ADAPTER`.
//!
//! - `auto` (or empty): the hardware adapters in high-performance order, the first one that
//! creates a device;
//! - `warp`: the software renderer;
//! - a number `N`: the N-th hardware adapter in high-performance order (0 = the first);
//! - anything else: the hardware adapters whose name contains it (case-insensitive), e.g.
//! `radeon` or `rtx 3080`.
//!
//! The same choice drives the title's device (`hle::d3d12x::real`) and the GPU test bench
//! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn.
use std::fmt;
use windows::Win32::Graphics::Dxgi::*;
/// The environment variable that overrides `d3d12_adapter`.
pub const ENV: &str = "XCL_ADAPTER";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Selector {
Auto,
Warp,
/// Position among the hardware adapters in high-performance order.
Index(usize),
/// Lower-case part of the adapter's name.
Name(String),
}
impl Selector {
pub fn parse(s: &str) -> Selector {
let s = s.trim();
if s.is_empty() || s.eq_ignore_ascii_case("auto") {
Selector::Auto
} else if s.eq_ignore_ascii_case("warp") {
Selector::Warp
} else if let Ok(n) = s.parse::<usize>() {
Selector::Index(n)
} else {
Selector::Name(s.to_lowercase())
}
}
/// `XCL_ADAPTER` if set (and not empty), otherwise `configured`.
pub fn from_env_or(configured: &str) -> Selector {
match std::env::var(ENV) {
Ok(v) if !v.trim().is_empty() => Selector::parse(&v),
_ => Selector::parse(configured),
}
}
/// Whether the hardware adapter at `index` (high-performance order) named `name` is chosen.
pub fn allows(&self, index: usize, name: &str) -> bool {
match self {
Selector::Auto => true,
Selector::Warp => false,
Selector::Index(n) => *n == index,
Selector::Name(part) => name.to_lowercase().contains(part.as_str()),
}
}
}
impl fmt::Display for Selector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Selector::Auto => f.write_str("auto"),
Selector::Warp => f.write_str("warp"),
Selector::Index(n) => write!(f, "{n}"),
Selector::Name(s) => write!(f, "\"{s}\""),
}
}
}
/// The adapter's name from its description.
pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String {
let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
String::from_utf16_lossy(&desc.Description[..n])
}
/// The hardware adapters (software ones skipped) in high-performance order.
pub fn hardware(factory: &IDXGIFactory6) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> {
let mut out = Vec::new();
let mut i = 0;
unsafe {
while let Ok(adapter) = factory.EnumAdapterByGpuPreference::<IDXGIAdapter1>(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) {
i += 1;
let Ok(desc) = adapter.GetDesc1() else { continue };
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
continue;
}
out.push((adapter, desc));
}
}
out
}
/// The hardware adapters `sel` allows, in high-performance order (empty for `warp`).
pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> {
hardware(factory).into_iter().enumerate().filter(|(i, (_, d))| sel.allows(*i, &name(d))).map(|(_, a)| a).collect()
}
/// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips.
pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String {
let have: Vec<String> = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect();
format!("{ENV} / d3d12_adapter {sel} matches no hardware adapter (have: {})", have.join(", "))
}
#[cfg(test)]
#[path = "adapter_tests.rs"]
mod tests;
+23
View File
@@ -0,0 +1,23 @@
use super::Selector;
#[test]
fn selector_parsing() {
assert_eq!(Selector::parse(""), Selector::Auto);
assert_eq!(Selector::parse(" Auto "), Selector::Auto);
assert_eq!(Selector::parse("WARP"), Selector::Warp);
assert_eq!(Selector::parse("1"), Selector::Index(1));
assert_eq!(Selector::parse("Radeon"), Selector::Name("radeon".into()));
assert_eq!(Selector::parse(" RTX 3080 "), Selector::Name("rtx 3080".into()));
}
#[test]
fn selector_matching() {
let nv = "NVIDIA GeForce RTX 3080";
let amd = "AMD Radeon(TM) Graphics";
assert!(Selector::Auto.allows(0, nv) && Selector::Auto.allows(1, amd));
assert!(!Selector::Warp.allows(0, nv));
assert!(Selector::Index(1).allows(1, amd) && !Selector::Index(1).allows(0, nv));
let radeon = Selector::parse("radeon");
assert!(radeon.allows(1, amd) && !radeon.allows(0, nv));
assert!(Selector::parse("geforce rtx").allows(0, nv));
}
+1
View File
@@ -1,6 +1,7 @@
//! GPU side of XCL: console shader capture and the RDNA2 microcode toolchain
//! (decoder / disassembler – the front-end of the shader recompiler).
pub mod adapter;
pub mod bvh;
pub mod desc;
pub mod dxbc;
+25 -4
View File
@@ -61,6 +61,8 @@ struct Gpu {
value: u64,
adapter: String,
wave64: bool,
/// mesh shader tier 1 or higher (`mesh_draw`)
mesh: bool,
}
// D3D12 objects are free-threaded; access is serialised by the mutex.
@@ -75,9 +77,17 @@ fn e(x: windows::core::Error) -> String {
fn init() -> Result<Gpu, String> {
unsafe {
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?;
let adapter: IDXGIAdapter1 = factory.EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE).map_err(e)?;
let desc = adapter.GetDesc1().map_err(e)?;
let name = String::from_utf16_lossy(&desc.Description).trim_end_matches('\0').to_string();
// `XCL_ADAPTER` picks the adapter (default: the first in high-performance order)
let sel = crate::gpu::adapter::Selector::from_env_or("auto");
let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp {
(factory.EnumWarpAdapter().map_err(e)?, "WARP (software renderer)".into())
} else {
let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel)
.into_iter()
.next()
.ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?;
(a, crate::gpu::adapter::name(&desc))
};
let mut dev: Option<ID3D12Device> = None;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).map_err(e)?;
let dev = dev.ok_or("no device")?;
@@ -93,11 +103,14 @@ fn init() -> Result<Gpu, String> {
return Err(format!("{name}: no wave operations/int64"));
}
let wave64 = o1.WaveLaneCountMin <= 64 && o1.WaveLaneCountMax >= 64;
let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
let mesh = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32).is_ok()
&& o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0;
let queue: ID3D12CommandQueue =
dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?;
let rs = root_signature(&dev, false)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64 })
Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, mesh })
}
}
@@ -337,6 +350,14 @@ pub fn wave64_supported() -> Result<bool, String> {
gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone())
}
/// Whether the adapter runs mesh shaders (`mesh_draw`); an integrated RDNA2 GPU, for one,
/// reports wave64 but no mesh shader tier.
pub fn mesh_shaders_supported() -> Result<bool, String> {
let mut g = GPU.lock().unwrap();
let gpu = g.get_or_insert_with(init);
gpu.as_ref().map(|x| x.mesh).map_err(|x| x.clone())
}
/// Run a compiled kernel (DXIL) with `state` and flat memory `mem`.
pub fn run(dxil: &[u8], state: &KernelState, mem: &[u32]) -> Result<KernelResult, String> {
run_with(dxil, state, mem, &[], &[])
+11 -15
View File
@@ -303,12 +303,8 @@ fn geometry_wave32_required(device: *mut c_void) -> bool {
}
}
fn adapter_name(desc: &DXGI_ADAPTER_DESC1) -> String {
let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
String::from_utf16_lossy(&desc.Description[..n])
}
/// Create the process-wide D3D12 device (high-performance GPU → WARP); once – later calls
/// Create the process-wide D3D12 device (the adapter `d3d12_adapter` / `XCL_ADAPTER` chooses,
/// by default the high-performance GPU → WARP); once – later calls
/// return the existing device's adapter.
pub fn init() -> Result<String, String> {
if !device_raw().is_null() {
@@ -339,16 +335,16 @@ pub fn init() -> Result<String, String> {
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?;
let mut device: Option<ID3D12Device> = None;
let mut name = String::new();
if !cfg.d3d12_adapter.eq_ignore_ascii_case("warp") {
let mut i = 0;
while let Ok(adapter) = factory.EnumAdapterByGpuPreference::<IDXGIAdapter1>(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) {
i += 1;
let Ok(desc) = adapter.GetDesc1() else { continue };
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
continue;
}
let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter);
if sel != crate::gpu::adapter::Selector::Warp {
let mut list = crate::gpu::adapter::candidates(&factory, &sel);
if list.is_empty() {
crate::xlog_warn!("D3D12: {} – using auto", crate::gpu::adapter::no_match(&factory, &sel));
list = crate::gpu::adapter::candidates(&factory, &crate::gpu::adapter::Selector::Auto);
}
for (adapter, desc) in list {
if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() {
name = format!("{} ({} MiB VRAM)", adapter_name(&desc), desc.DedicatedVideoMemory >> 20);
name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20);
break;
}
}