From 69c0b04036e78ffd576754d0cf31c5f40c8e9205 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:32:11 -0300 Subject: [PATCH 1/2] Memory: detect a macOS host under Wine (mac_host) util::mac_host(): the process runs under Wine on a Mac (CrossOver or the Game Porting Toolkit), where D3D12 is Apple's D3DMetal and the title's code runs through Rosetta 2. ntdll's wine_get_host_version names the host's system; "Darwin" is a Mac. XCL_MAC_HOST=1 / 0 overrides it. Nothing calls it yet. The Mac changes that need to know they run there (the barrier default, title textures on shared pages) build on it; until now only Ahmet-Dedeler's mac7 branch had it. Part of #258. --- crates/xcl/src/util.rs | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/xcl/src/util.rs b/crates/xcl/src/util.rs index a7609fe3ff..37b05d9354 100644 --- a/crates/xcl/src/util.rs +++ b/crates/xcl/src/util.rs @@ -132,6 +132,36 @@ pub fn under_wine() -> bool { }) } +/// The process runs under Wine on a Mac (ntdll's `wine_get_host_version` says Darwin): CrossOver +/// or the Game Porting Toolkit, where D3D12 is Apple's D3DMetal and, on Apple Silicon, the +/// title's code runs through Rosetta 2. Known from the start of the run, before there is a +/// device. `XCL_MAC_HOST=1` / `0` overrides the detection. +pub fn mac_host() -> bool { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static MAC: std::sync::OnceLock = std::sync::OnceLock::new(); + *MAC.get_or_init(|| { + let forced = std::env::var("XCL_MAC_HOST").ok(); + // SAFETY: ntdll is always loaded; Wine's export fills two pointers to static strings. + let sysname = unsafe { + GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_host_version".as_ptr() as *const u8).and_then(|f| { + let f: unsafe extern "C" fn(*mut *const u8, *mut *const u8) = std::mem::transmute(f); + let (mut sysname, mut release) = (std::ptr::null(), std::ptr::null()); + f(&mut sysname, &mut release); + from_cstr_ptr(sysname) + }) + }; + mac_host_from(forced.as_deref(), sysname.as_deref()) + }) +} + +/// `mac_host`'s answer from `XCL_MAC_HOST` (`forced`) and the host's system name, if Wine gave one. +fn mac_host_from(forced: Option<&str>, sysname: Option<&str>) -> bool { + match forced { + Some(v) => v.trim() != "0", + None => sysname.is_some_and(|s| s.eq_ignore_ascii_case("Darwin")), + } +} + /// Normalised DLL key: lower-case file name, ".dll" appended when no extension. pub fn dll_key(name: &str) -> String { let base = name.rsplit(['\\', '/']).next().unwrap_or(name); @@ -321,6 +351,20 @@ unsafe impl Sync for SendPtr {} mod tests { use super::*; + /// Darwin from Wine's host version is a Mac (in any case); Linux, Windows and no answer are + /// not; `XCL_MAC_HOST` decides when it is set, "0" for no and anything else for yes. + #[test] + fn a_mac_host_is_darwin_under_wine_unless_forced() { + assert!(mac_host_from(None, Some("Darwin"))); + assert!(mac_host_from(None, Some("darwin"))); + assert!(!mac_host_from(None, Some("Linux"))); + assert!(!mac_host_from(None, None)); + assert!(!mac_host_from(Some("0"), Some("Darwin"))); + assert!(!mac_host_from(Some(" 0 "), Some("Darwin"))); + assert!(mac_host_from(Some("1"), None)); + assert!(mac_host_from(Some("1"), Some("Linux"))); + } + #[test] fn dll_keys() { assert_eq!(dll_key("KERNELX"), "kernelx.dll"); From e69da9df790447ec1454a16a24c724c60f3d6f56 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:23:05 -0300 Subject: [PATCH 2/2] Recompiler: on a macOS host, s_barrier is the native group barrier by default xcl_s_barrier (the LDS spin barrier for multi-wave Compute / Mesh groups) starves the waves it waits for on D3DMetal: in a 1024-thread group in the split form, the one wave still working ran about 1000 times slower while the others spun, until the 2^20-poll bound gave up and the barrier let threads read LDS early (wrong output; a hang at world entry was reported in #258). D3DMetal's GroupMemoryBarrierWithGroupSync is correct in every case tried, including waves that already ran s_endpgm, LDS exchange across the two halves, barriers in loops and partial console waves. safe_barrier_wanted(): XCL_SAFE_BARRIER=0 / 1 decides; by default the spin barrier everywhere but on a macOS host (util::mac_host). It keeps deciding for both translators (the HLSL emitter and the direct translator's s_barrier) and for the compute build key, which read the variable on its own until now. translate_geometry's refusal of the split form's ES phase (#1727's pattern) is unchanged: only XCL_SAFE_BARRIER=0 lifts it (safe_barrier_set_off), on a Mac too. Windows is unchanged. gpu_s_barrier_1024_threads_waits_for_working_waves fails without this on the Mac (128 of 1024 threads read their partner's LDS word before it was written) and passes with it; with XCL_SAFE_BARRIER=1 it fails again. Part of #258. --- crates/xcl/src/gpu/dxil/geometry_tests.rs | 4 +- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 4 +- crates/xcl/src/gpu/recomp/emit.rs | 21 +++++++-- crates/xcl/src/gpu/recomp/pso.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 55 ++++++++++++++++++++++- 6 files changed, 77 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/geometry_tests.rs b/crates/xcl/src/gpu/dxil/geometry_tests.rs index efead030da..ef85c255ab 100644 --- a/crates/xcl/src/gpu/dxil/geometry_tests.rs +++ b/crates/xcl/src/gpu/dxil/geometry_tests.rs @@ -114,11 +114,11 @@ fn geometry_forms_validate() { } /// The split form's ES phase meets its other half at a group barrier at every exchange (#1727's -/// pattern; the HLSL path spins): with the safe barrier wanted the direct translator leaves such +/// pattern; the HLSL path spins): unless `XCL_SAFE_BARRIER=0` the direct translator leaves such /// a pass to the HLSL path. The GS alone (no partner) and the native wave64 form stay direct. #[test] fn split_geometry_with_an_es_phase_is_left_to_the_hlsl_path() { - if !crate::gpu::recomp::emit::safe_barrier_wanted() { + if crate::gpu::recomp::emit::safe_barrier_set_off() { return; } let (code, g) = branchy_program(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f57cf8d7c0..4dd6f994fa 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -152,7 +152,7 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res // and lane read meets at a group barrier, the pattern that hung NVIDIA GPUs (#1727). The // HLSL path's exchange spins by default: such a pass is left to it (`XCL_SAFE_BARRIER=0`: // as before). The GS alone runs in the lower half without a partner. - if o.split && g.gs_start != Some(0) && crate::gpu::recomp::emit::safe_barrier_wanted() { + if o.split && g.gs_start != Some(0) && !crate::gpu::recomp::emit::safe_barrier_set_off() { return Err("split wave64 geometry: the ES phase exchanges at group barriers".into()); } translate_geometry_unrefused(code, o, g) diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index dbe002c217..3da70b77fd 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2842,7 +2842,7 @@ mod stage_guard_tests { #[test] fn geometry_export_rejected() { - let safe_barrier = crate::gpu::recomp::emit::safe_barrier_wanted(); + let refused = !crate::gpu::recomp::emit::safe_barrier_set_off(); for en in [0xFu64, 0] { let code = prog(&[("EXP", "ENC_EXP", &[("TGT", 0), ("EN", en), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)])]); for gs_start in [Some(0), None] { @@ -2851,7 +2851,7 @@ mod stage_guard_tests { let err = kernel::translate_geometry(&code, opts(true, split), &gs) .err() .unwrap_or_else(|| panic!("geometry EXP en={en:#x} gs_start={gs_start:?} split={split} unexpectedly succeeded")); - let want = if split && gs_start != Some(0) && safe_barrier { + let want = if split && gs_start != Some(0) && refused { "split wave64 geometry: the ES phase exchanges at group barriers" } else { "export target" diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index d6b00a1861..292f0afae9 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6702,10 +6702,25 @@ uint2 xcl_x_ballot_local(bool b) { uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; -/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier -/// (`XCL_SAFE_BARRIER=0`: the plain group barrier, in both translators). +/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier, in both +/// translators: `XCL_SAFE_BARRIER=0` / `1` decides; by default yes, except on a Mac +/// (`util::mac_host`: D3DMetal). There the waves spinning in it starve the waves they wait for +/// (a 1024-thread group: a waiting wave's loop ran about 0.1 ms per iteration) until the spin +/// gives up and the barrier lets them read LDS too early (#258), while Metal's group barrier does +/// not wait for simdgroups that have exited (`gpu_safe_s_barrier_multi_warp_and_early_endpgm` +/// passes with it). pub(crate) fn safe_barrier_wanted() -> bool { - std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") + match std::env::var("XCL_SAFE_BARRIER") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + } +} + +/// Whether `XCL_SAFE_BARRIER=0` is set. Only then does `dxil::kernel::translate_geometry` take the +/// split form's ES phase directly, on a Mac too: the Mac default of `safe_barrier_wanted` changes +/// the barrier, not that refusal. +pub(crate) fn safe_barrier_set_off() -> bool { + std::env::var("XCL_SAFE_BARRIER").is_ok_and(|v| v.trim() == "0") } /// Early-exit-safe, bounded workgroup barrier for multi-warp Compute / Mesh `s_barrier`. diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f4a3b95d8c..59c71ff32a 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -58,7 +58,7 @@ pub(crate) fn compute_policy_key() -> ComputePolicyKey { structured: std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none(), precise_x64_masks: std::env::var_os("XCL_X64_ALL_MASKS").is_none(), wave64_spin: std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0"), - safe_barrier: std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"), + safe_barrier: super::emit::safe_barrier_wanted(), // The HLSL path can route enormous compute programs through the direct translator too. direct_compact: crate::gpu::dxil::kernel::compact_mode(), direct_compact_nest: crate::gpu::dxil::kernel::compact_nest_tag(), diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4f91f4c63d..e7b37a555f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4489,7 +4489,7 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() { // heap (the direct translator leaves this s_barrier of two console waves to the HLSL path) let split = translate(&code, &Options { mode: Mode::Mesh(ms.clone()), wave64: true, split_wave64: true, mem_windows: super::HEAP_WINDOWS | 16, ..Default::default() }).unwrap(); assert!(split.complete(), "split, 16 heap windows: {:?}", split.unsupported_why); - if std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") { + if super::emit::safe_barrier_wanted() { assert!(split.hlsl.contains("xcl_s_barrier();"), "split, 16 heap windows: expected xcl_s_barrier()"); } if dxc::location().is_ok() { @@ -11504,7 +11504,7 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { for wave64 in [true, false] { let t = translate(&p_all, &on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() })).unwrap(); assert!(t.complete(), "wave64={wave64}: {:?}", t.unsupported_why); - if std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") { + if super::emit::safe_barrier_wanted() { assert!(t.hlsl.contains("xcl_s_barrier();"), "wave64={wave64}: expected xcl_s_barrier()"); } let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); @@ -11823,6 +11823,57 @@ fn gpu_qsad_and_mqsad() { } } +/// `s_barrier` in a 1024-thread group (32 hardware waves in the split form) waits for waves +/// still working: every wave runs 1000 `v_readfirstlane`s (exchanges between its halves), +/// writes its LDS word, and after the barrier reads the word of the farthest wave +/// (`tid ^ 1023`). On D3DMetal (#258) the waves spinning in `xcl_s_barrier` starved the ones +/// still in the loop until the spin gave up, and the barrier let them read too early. +#[test] +fn gpu_s_barrier_1024_threads_waits_for_working_waves() { + if !gpu_ready() { + return; + } + let p = prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), // v1 = tid * 4 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 0)], Some(0x100)), // v6 = tid + 0x100 + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], Some(1023)), // v2 = tid ^ 1023 + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), // v2 *= 4 + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], Some(1000)), // s10 = 1000 + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), // s12 = 0 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V)], None), // v11 = tid + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), // loop: s10 == 0? + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 5)], None), // -> ds_write + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 129), ("VSRC1", 11)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 11)], None), // s11 = v11 of lane 0 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 11)], None), // s12 += s11 + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None), // -> loop + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 4)], None), // v4 = partner's + 1 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 1)], None), // v7 = s0 + tid * 4 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", 12)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 7)], Some(4096)), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 15), ("SADDR", 0x7D)], None), // s12 after it + ]); + let cs = super::CsInterface { threads: [1024, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let base = 0x1000usize; + let out = runner::dispatch(&dxil, [1, 1, 1], &[base as u32, 0], &vec![0u32; (base + 2048 * 4) / 4]).unwrap(); + let wrong: Vec = (0..1024).filter(|&tid| out[base / 4 + tid] != ((tid ^ 1023) + 0x101) as u32).collect(); + assert!(wrong.is_empty(), "{} threads read their partner's LDS word before it was written (first: {:?})", wrong.len(), &wrong[..wrong.len().min(8)]); + for tid in 0..1024usize { + let cw = (tid / 64) as u32; + assert_eq!(out[base / 4 + 1024 + tid], 1000 * cw * 64 + 1000 * 1001 / 2, "tid={tid}: v_readfirstlane sum"); + } +} + /// `XCL_SAMPLE_FSPX=`: every `*.bin` there that is an FSPX (driver) compute container – /// e.g. the FSR4 pipelines XCL dumps to `\shaders` – translates and compiles. #[test]