diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f6facf9b08..feb7632791 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -689,9 +689,7 @@ impl Em { } } self.dynamic_f16_rm = writes_nonzero_dp && self.has_f16_round_op && !self.has_f64_round_op; - self.safe_barrier = has_s_barrier - && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) - && std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"); + self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) && safe_barrier_enabled(); } pub fn take(&mut self) -> String { @@ -6078,6 +6076,19 @@ uint2 xcl_x_ballot_local(bool b) { uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; +/// Whether multi-wave Compute / Mesh `s_barrier`s become `xcl_s_barrier` (`PRELUDE_SAFE_BARRIER`): +/// `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_enabled() -> bool { + match std::env::var("XCL_SAFE_BARRIER") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + } +} + /// Early-exit-safe, bounded workgroup barrier for multi-warp Compute / Mesh `s_barrier`. /// /// On RDNA2, `S_ENDPGM` decrements the CU's active wave count so remaining waves executing diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 60a1bf1d25..a8ed672a0e 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -8761,7 +8761,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_enabled() { 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)); @@ -8808,6 +8808,57 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { } } +/// `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] 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");