diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 8d4806dcb..180454670 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -4565,7 +4565,13 @@ cache is answered compile-required on both. the device shares (`metal2vulkan::pipeline::SEQ_CST_FENCE_WORD` bytes past the zero range the runtime pushes as `PushField::ZeroAddress`), at `Device` scope, which totally orders them. A threadgroup or simdgroup fence takes the same device word, so it pays the same contention, - though Metal orders it only within its threadgroup or simdgroup. Measured on device fences (a + though Metal orders it only within its threadgroup or simdgroup. A `seq_cst` atomic operation on + device or threadgroup memory takes the same barrier and add, after a store, a read-modify-write + or a compare-exchange, and before a load (so that no two loads of one thread see two other + threads' stores in the order another thread's two loads invert). Every non-explicit atomic of + MSL 4.1 (`atomic_store`, `atomic_load`, `atomic_fetch_add` and the rest) is one, as is an + `_explicit` atomic of `memory_order_seq_cst` and an LLVM atomic of `seq_cst`: a function built + for MSL 4.1 pays one contended add for each such atomic it executes. Measured on device fences (a synthetic kernel of 1,048,576 invocations, each doing N rounds of integer work, a relaxed atomic store, the fence and a relaxed atomic load; median of 9 alternated rounds, the fence alone against the fence and its add), the add costs a fixed time per fence executed: on an RTX @@ -4573,7 +4579,7 @@ cache is answered compile-required on both. times); on a Radeon RX 7900 XTX 0.0143 against 0.0205 ms at 0 (1.43 times) and 1.005 times at 64; on an Iris Xe 1.015 times at 0 and 1.032 at 64; within 1% on all three from N = 1024. A kernel that does little but such fences runs slower by that much; the threadgroup and simdgroup - fences' cost is read from these device rows, not measured apart. The add is a memory write of + fences' cost, and the atomic operations', is read from these device rows, not measured apart. The add is a memory write of the function's (`StageInterface::writes_memory`), so a function whose only write it is counts as one that writes memory: a dispatch of such a kernel runs where a kernel without writes runs nothing, such a fragment function in a pipeline of more than one sample carries diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c7d51aba4..b33e4145c 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2366; +pub const SEMANTICS_VERSION: u32 = 2367; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index e51326e9e..c15a5fd23 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -57,7 +57,8 @@ //! arena (an LLVM `syncscope("singlethread")` atomic takes the same scope, which is only stronger, //! as is an MSL 4.1 device atomic of a narrower `thread_scope`). A relaxed order (LLVM `monotonic` //! or `unordered`) has no semantics; another order names memories at the Vulkan order (`seq_cst` is -//! `AcquireRelease`; a load keeps only the acquire part and a store only the release part), with +//! `AcquireRelease` and its fence below; a load keeps only the acquire part and a store only the +//! release part), with //! `MakeAvailable`/`MakeVisible` under the Vulkan memory model (`sync::barrier::semantics`). The //! memories are the call's Metal `mem_flags` when the AIR 2.9 form carries them (`UniformMemory` //! for `mem_device`, `WorkgroupMemory` for `mem_threadgroup` and `mem_threadgroup_imageblock` in a @@ -66,7 +67,15 @@ //! the function has no tile; a vertex function has no threadgroup memory, and only an object or //! mesh function has `mem_object_data`'s, its payload, so those name nothing elsewhere), and the //! atomic's own memory (`UniformMemory` or `WorkgroupMemory`) for an AIR 2.8 or LLVM atomic. A -//! `Device`-scope atomic is reported to the memory-model family. Metal's `volatile` qualifier and +//! `Device`-scope atomic is reported to the memory-model family. A `seq_cst` operation on memory +//! another thread reaches (MSL 4.1's non-explicit atomics are `seq_cst` over every memory) also +//! takes the sequentially consistent fence (`sync::barrier`'s total order): an acquire-release +//! memory barrier at its scope over its memories, then the add on the device's fence word, after +//! a store, a read-modify-write or a compare-exchange, and before a load. Store-side fences +//! alone forbid store buffering but not two loads that see two independent stores in opposite +//! orders (independent reads of independent writes), which MSL's single total order of every +//! thread's observations forbids; the fence before a load puts one of the device word's adds +//! between such a thread's two loads. Metal's `volatile` qualifier and //! LLVM's `volatile` add nothing: an atomic is never elided or merged. A relaxed load that an exit //! of a loop holding it depends on (a spin's, [`spin`]) acquires its own memory: with robust buffer //! access, Mesa's RADV and ANV never showed a relaxed one a store that arrived after its first @@ -215,6 +224,10 @@ pub struct AtomicAccess { /// A relaxed load an exit of a loop holding it depends on ([`spin`]): it acquires its own /// memory. pub spin: bool, + /// A `seq_cst` operation on memory another thread reaches, which takes the sequentially + /// consistent fence (the module docs' total order): after a store, a read-modify-write or a + /// compare-exchange, before a load. + pub total: bool, } impl AtomicAccess { @@ -277,7 +290,13 @@ impl AtomicAccess { // The leaf's load and store around the operation. AtomicMem::Private(a) => a.leaf.cost().saturating_mul(2).saturating_add(op), }; - per.saturating_add(compare).saturating_add(16) + let total = match self.total { + true => barrier::TOTAL_ORDER_WORDS + 8, + false => 0, + }; + per.saturating_add(compare) + .saturating_add(16) + .saturating_add(total) } /// Whether the atomic opens a builder loop (a thread atomic never does: its operation is @@ -435,6 +454,8 @@ struct Request { compare: Option, order: MemoryOrder, failure: MemoryOrder, + /// The operation's order is `seq_cst` (its success order, for a compare-exchange). + seq_cst: bool, /// An AIR 2.9 atomic's `mem_flags`; `None` for an AIR 2.8 or LLVM atomic. flags: Option, } @@ -483,6 +504,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result, Error> { compare, order: order(a.order), failure: a.failure.map_or(MemoryOrder::Relaxed, order), + seq_cst: a.order == AirOrder::SeqCst, flags: a.flags, } } @@ -504,6 +526,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result, Error> { compare: None, order: llvm_order(atomic.ordering), failure: MemoryOrder::Relaxed, + seq_cst: atomic.ordering == Ordering::SeqCst, flags: None, } } @@ -529,6 +552,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result, Error> { compare: Some(CompareOperand::Value(*cmp)), order: llvm_order(success.ordering), failure: llvm_order(*failure), + seq_cst: success.ordering == Ordering::SeqCst, flags: None, } } @@ -546,6 +570,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result, Error> { compare: None, order: llvm_order(a.ordering), failure: MemoryOrder::Relaxed, + seq_cst: a.ordering == Ordering::SeqCst, flags: None, }, InstKind::Store { @@ -563,6 +588,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result, Error> { compare: None, order: llvm_order(a.ordering), failure: MemoryOrder::Relaxed, + seq_cst: a.ordering == Ordering::SeqCst, flags: None, }, _ => return Ok(None), @@ -691,6 +717,9 @@ pub fn select( }; let spin = r.kind == AtomicKind::Load && r.order == MemoryOrder::Relaxed && spin::is_spin(cx, at); + if r.seq_cst { + barrier::total_order(cx); + } Ok(Some(AtomicAccess { mem, kind: r.kind, @@ -702,6 +731,7 @@ pub fn select( order: r.order, failure: r.failure, spin, + total: r.seq_cst, // Threadgroup memory is a kernel's, an object function's, a mesh function's, and a // fragment function's tile (device memory in the pass's buffer, which emission orders as // such); a vertex function has none. The payload `mem_object_data` names is an object or @@ -766,8 +796,9 @@ fn private(cx: &mut SelectCx<'_>, inst: &Inst, r: Request) -> Result (f, a.order), None => (own, a.order), }; + // A `seq_cst` operation's fence: an acquire-release barrier at its scope over the memories + // its order applies to, then the add on the device's fence word, before a load and after any + // other operation. + let fence = a + .total + .then(|| barrier::semantics(flags, MemoryOrder::AcquireRelease, model)); + let total_fence = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, sem| -> BResult<()> { + fb.memory_barrier(scope, sem)?; + barrier::add_to_fence_word(cx, fb, sem) + }; + if let Some(sem) = fence.filter(|_| a.kind == AtomicKind::Load) { + total_fence(cx, fb, sem)?; + } let o = Op { kind: a.kind, scope, @@ -1342,6 +1386,9 @@ pub fn emit( } } }; + if let Some(sem) = fence.filter(|_| a.kind != AtomicKind::Load) { + total_fence(cx, fb, sem)?; + } let Some(old) = result else { return Ok(()); }; diff --git a/crates/metal2vulkan/src/tests/engine_air_2_9.rs b/crates/metal2vulkan/src/tests/engine_air_2_9.rs index aaa9b9e8c..276997237 100644 --- a/crates/metal2vulkan/src/tests/engine_air_2_9.rs +++ b/crates/metal2vulkan/src/tests/engine_air_2_9.rs @@ -429,9 +429,11 @@ fn under(vulkan: bool, semantics: u32) -> u32 { type Op = (&'static str, Vec); /// MSL 4.1's orders and memory flags reach SPIR-V: a non-explicit atomic is `AcquireRelease` (a -/// load's acquire, a store's release half) over every memory the stage has, and an explicit one its -/// order over the memories it names, on a device whose simdgroup is its subgroup. The kernel of -/// barrier scopes, `a27_memory_order`, holds a sequentially consistent fence and is refused. +/// load's acquire, a store's release half) over every memory the stage has, and takes the +/// sequentially consistent fence, whose add on the device's fence word has the same semantics; an +/// explicit one is its order over the memories it names, on a device whose simdgroup is its +/// subgroup. The kernel of barrier scopes, `a27_memory_order`, holds a sequentially consistent +/// fence. #[test] fn msl_4_1_orders_reach_spirv() { let path = engine_dir().join("a27_memory_order.ll"); @@ -472,18 +474,24 @@ fn msl_4_1_orders_reach_spirv() { "a27_wide_and_float", vec![ ("OpAtomicUMax", vec![1, 0]), - // The float add's compare-and-swap loop: its acquiring read, then the exchange. + // The float add's compare-and-swap loop: its acquiring read, then the exchange; + // then its fence's add, the add being `seq_cst`. ("OpAtomicLoad", vec![1, 0x2 | 0x40]), ("OpAtomicCompareExchange", vec![1, 0x8 | every, 0]), + ("OpAtomicIAdd", vec![1, 0x8 | every]), ], ), ( - // A render stage has no threadgroup memory. + // A render stage has no threadgroup memory. Each of its three `seq_cst` atomics + // takes its fence's add. "a27_fragment_atomics", vec![ ("OpAtomicIAdd", vec![1, 0x8 | render]), ("OpAtomicLoad", vec![1, 0x2 | render]), ("OpAtomicStore", vec![1, 0x4 | render]), + ("OpAtomicIAdd", vec![1, 0x8 | render]), + ("OpAtomicIAdd", vec![1, 0x8 | render]), + ("OpAtomicIAdd", vec![1, 0x8 | render]), ], ), ]; diff --git a/crates/metal2vulkan/src/tests/engine_atomics.rs b/crates/metal2vulkan/src/tests/engine_atomics.rs index 1c85c38c6..f92ec4f0e 100644 --- a/crates/metal2vulkan/src/tests/engine_atomics.rs +++ b/crates/metal2vulkan/src/tests/engine_atomics.rs @@ -150,9 +150,11 @@ fn resources(plan: &Plan, init: &[Vec], threads: u32) -> Resources { } } -/// Run in both scheduling orders; returns each order's buffers as words. +/// Run in both scheduling orders, the device's fence word mapped for the `seq_cst` operations; +/// returns each order's buffers as words. fn run_orders(m: &TypedModule, res: &Resources) -> Result>>, InterpError> { - let res = &super::identity_harness::bind(m, res.clone(), &BTreeMap::new()); + let bound = super::identity_harness::bind(m, res.clone(), &BTreeMap::new()); + let res = &super::identity_harness::with_fence_word(bound); let mut outs = Vec::new(); for order in [Order::Forward, Order::Reverse] { let cfg = Config { diff --git a/crates/metal2vulkan/src/tests/identity_harness.rs b/crates/metal2vulkan/src/tests/identity_harness.rs index 2fca6da7f..f2c9cfd78 100644 --- a/crates/metal2vulkan/src/tests/identity_harness.rs +++ b/crates/metal2vulkan/src/tests/identity_harness.rs @@ -201,6 +201,20 @@ fn fill( res } +/// `res` with the device's sequentially consistent fence word mapped: 4 zero bytes at +/// [`SEQ_CST_FENCE_WORD`] past the unmapped zero range [`fills`] names, which each `seq_cst` fence +/// and atomic operation adds to, the rest of that range still unmapped. +/// +/// [`SEQ_CST_FENCE_WORD`]: crate::pipeline::SEQ_CST_FENCE_WORD +pub(crate) fn with_fence_word(mut res: Resources) -> Resources { + res.buffers.push(Buffer { + slot: None, + address: Some(ZERO_UNMAPPED + crate::pipeline::SEQ_CST_FENCE_WORD), + bytes: vec![0; 4], + }); + res +} + /// The device address of [`with_zero`]'s zero range. pub(crate) const ZERO: u64 = 0x7_0000_0000; diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index a6f80fb70..81728a165 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -139,5 +139,4 @@ feature ProgramScopeSharedSlot rare MSL 3.2 program-scope buffers aliasing anoth feature ProgramScopeLinked rare MSL 3.2 program-scope bindings in a linked visible function or a dynamic library feature ProgramScopeRead none a read of a program-scope buffer's global that Apple's compiler is not seen to write feature GenericPointer system MSL 4.1 generic pointers held in memory or of two spaces (macOS 27 and later) -feature SeqCstFence rare a seq_cst fence in a vertex or fragment stage without its stores and atomics feature WideLines none a line under the Apple-private setLineWidth: at a width other than 1 drawn as the band, whose pipeline form the translator does not build (a selected slice or viewport, barycentric weights, multiview, synthesized geometry, too many stage outputs)