Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1628,6 +1628,16 @@ impl Host {
/// submission lock.
fn lost(&self, submitted: &mut u64, mark: &Mark) {
let lost = LOST[0].fetch_add(1, Ordering::Relaxed) + 1;
// A lane that held a lock of an emulated 64-bit atomic when the GPU
// ended its shader never frees it (`victory_shader::emit`, "Atomic
// locks"): free them all before anything else runs.
let freed = crate::shadow::free_atomic_locks();
if freed > 0 {
tracing::warn!(
freed,
"atomic locks left taken by the ended submission freed"
);
}
if self.runs(submitted, mark) {
if lost.is_power_of_two() {
tracing::warn!(
Expand Down
57 changes: 56 additions & 1 deletion crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1177,11 +1177,14 @@ unsafe impl Send for Bitmap {}
// SAFETY: as above.
unsafe impl Sync for Bitmap {}

/// The two bitmaps of [`bitmap`], each made when first asked for.
static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] =
[const { std::sync::OnceLock::new() }; 2];

/// The bitmap of other shaders, or (`memory`) of shaders that use title
/// memory, whose marks go back only while it is not withheld
/// (`crate::memory::withholding`).
fn bitmap(memory: bool) -> Option<&'static Bitmap> {
static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] = [const { std::sync::OnceLock::new() }; 2];
BITMAPS[usize::from(memory)]
.get_or_init(|| {
// Written pages, then one read mark per heap index, then the lock
Expand Down Expand Up @@ -1209,6 +1212,35 @@ pub(crate) fn view_writes(memory: bool) -> Option<u64> {
bitmap(memory).map(|b| b.gpu)
}

/// Frees the lock words of emulated 64-bit atomics (`victory_shader::emit`,
/// "Atomic locks") in the bitmaps made so far, after a submission the host
/// GPU ended: a lane that held a lock when its shader was cut short never
/// frees it, and every later atomic on that lock would wait out its bound
/// and go on without it (#240). Returns how many were taken. No submission
/// runs then, so no lane holds one.
pub(crate) fn free_atomic_locks() -> usize {
let dwords = (victory_shader::emit::VIEW_WRITES_BYTES / 4) as usize;
BITMAPS
.iter()
.filter_map(|b| b.get()?.as_ref())
.map(|b| {
// SAFETY: the mapped buffer of `dwords` dwords; the GPU is done
// with it (one submission runs at a time, and none runs now).
let words = unsafe { std::slice::from_raw_parts_mut(b.data as *mut u32, dwords) };
free_locks(words)
})
.sum()
}

/// Clears the lock words in `words`, a bitmap buffer's dwords, leaving the
/// written pages and read marks before them. Returns how many were taken.
fn free_locks(words: &mut [u32]) -> usize {
let locks = &mut words[(victory_shader::emit::ATOMIC_LOCKS_AT / 4) as usize..];
let taken = locks.iter().filter(|&&w| w != 0).count();
locks.fill(0);
taken
}

/// Heap slots whose texture views shaders read: the marks seen so far (a
/// slot's stays set in the bitmap until [`forget_read`]), and the slots to
/// clear at the next [`take_reads`].
Expand Down Expand Up @@ -2090,6 +2122,29 @@ pub(crate) mod tests {
unsafe { *(b.data as *mut u32).add((bit / 32) as usize) |= 1 << (bit % 32) };
}

/// After a submission the host GPU ended, every lock word of the
/// emulated 64-bit atomics is free again, and the written pages and read
/// marks before them stay as they were (#240).
#[test]
fn freeing_atomic_locks_keeps_pages_and_read_marks() {
let dwords = (victory_shader::emit::VIEW_WRITES_BYTES / 4) as usize;
let first = (victory_shader::emit::ATOMIC_LOCKS_AT / 4) as usize;
let mut words = vec![0xA5A5_A5A5u32; dwords];
assert_eq!(
free_locks(&mut words),
victory_shader::emit::ATOMIC_LOCKS as usize,
"every lock word counted as taken"
);
assert!(
words[..first].iter().all(|&w| w == 0xA5A5_A5A5),
"pages and read marks kept"
);
assert!(words[first..].iter().all(|&w| w == 0), "every lock free");
words[first + 7] = 1;
assert_eq!(free_locks(&mut words), 1, "one lock left taken");
assert_eq!(free_locks(&mut words), 0, "none the second time");
}

/// The title writes a constant under a range an earlier list of the
/// submission declared as written by shaders: the refresh before the
/// submission runs still brings it to the copy, a shader's write still
Expand Down
5 changes: 3 additions & 2 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5036,7 +5036,8 @@ impl<'a> Lower<'a> {
let turn = self.s.m.cmp(head, pred::EQ, me, i);
self.s.m.terminate(head, Term::CondBr(turn, spin, latch));

// Spin, bounded (past it, on without the lock).
// Spin, bounded by the stage (past it, on without the lock; see
// `atomic_lock_spins`).
let got = self.s.op(
spin,
"atomicCompareExchange.i32",
Expand All @@ -5049,7 +5050,7 @@ impl<'a> Lower<'a> {
let tries = self.s.m.phi(spin, i32t);
let more = self.s.m.bin(spin, Bin::Add, tries, one);
self.s.m.set_phi(tries, vec![(zero, head), (more, spin)]);
let limit = k(self, 1 << 16);
let limit = k(self, super::shader::atomic_lock_spins(self.x.native.stage));
let out = self.s.m.cmp(spin, pred::IUGE, more, limit);
let leave = self.s.m.bin(spin, Bin::Or, won, out);
self.s.m.terminate(spin, Term::CondBr(leave, held, spin));
Expand Down
17 changes: 12 additions & 5 deletions crates/victory-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,14 @@
//! in a branch a wave whose lanes all finished skips. On D3DMetal (M5 Pro)
//! a wave's 64-bit `umax` on distinct texels took 29 µs in turns and
//! 6 µs in rounds. In a pixel program helper lanes skip the lock in
//! rounds: their atomics are discarded, so they could never take it.
//! rounds: their atomics are discarded, so they could never take it. A
//! lane waiting for a lock another wave holds gives up after
//! [`ATOMIC_LOCK_SPINS`] tries in compute and mesh programs
//! ([`ATOMIC_LOCK_SPINS_DRAWN`] in the others, whose draws macOS ends
//! when they run long) and goes on without it, so a lock nobody frees
//! cannot hang the GPU, but that lane's update can be lost (#240). A
//! lock is left taken when the host GPU ends a shader that held it, so
//! the host frees all of them after a submission it ended.
//! * **Read marks** (with [`Options::view_marks`]; added 2026-11-25):
//! every image instruction that reads a texture shader view the program
//! takes from the resource heap itself (not through a table, whose slots
Expand Down Expand Up @@ -265,10 +272,10 @@ use crate::{ShaderError, io, ir, resource, structure};

pub use sampler::StaticSampler;
pub use shader::{
ATOMIC_LOCK_ROUNDS, ATOMIC_LOCKS, ATOMIC_LOCKS_AT, HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE,
NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE,
VIEW_MARKS, VIEW_READS, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, VIEW_WRITE_BITS,
VIEW_WRITES, VIEW_WRITES_BYTES,
ATOMIC_LOCK_ROUNDS, ATOMIC_LOCK_SPINS, ATOMIC_LOCK_SPINS_DRAWN, ATOMIC_LOCKS, ATOMIC_LOCKS_AT,
HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE,
USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_READS, VIEW_SIGNED,
VIEW_STRIDE_BITS, VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, VIEW_WRITES_BYTES,
};

/// The loop limit without an override: 2^14.
Expand Down
25 changes: 25 additions & 0 deletions crates/victory-shader/src/emit/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use super::bitcode::{Attr, Md, Module, Ty, V, pred};
use super::container::{self, Binding, Psv, SigElement};
use crate::native::HwStage;

/// Where the shader reads its user data: `b0` in this space.
pub const USER_DATA_SPACE: u32 = 0;
Expand Down Expand Up @@ -61,6 +62,30 @@ pub const ATOMIC_LOCKS: u32 = 1 << 16;
/// lanes still not done take turns (`emit`, "Atomic locks", with
/// [`Options::atomic_lock_rounds`](super::Options)).
pub const ATOMIC_LOCK_ROUNDS: u32 = 4;
/// Tries a lane of a compute or mesh program makes at a lock another wave
/// holds before it goes on without it (`emit`, "Atomic locks"). A lane that
/// waits it out can lose its update, so the bound has to outlast a busy
/// lock: at 2^16 tries, 2,048 groups adding into one texel lost adds on an
/// M5 Pro (2 of 100 runs in turns, 1 of 40 in rounds), as 8 groups did on
/// an M2 Max (#240), and at 2^22 none did in 100 runs of each. macOS does
/// not end a compute dispatch for running long, so the wait costs time only.
pub const ATOMIC_LOCK_SPINS: u32 = 1 << 22;
/// The same in the other stages, whose draws macOS ends when their pixels
/// run about 50 ms (`docs/macos.md`, "Metal ends long draws"). An ended draw
/// loses all it drew and can stop the queue, which is worse than one lost
/// update, so a lane there keeps the shorter bound.
pub const ATOMIC_LOCK_SPINS_DRAWN: u32 = 1 << 16;
const _: () = assert!(ATOMIC_LOCK_SPINS_DRAWN < ATOMIC_LOCK_SPINS);

/// How many tries a lane of `stage` makes at a held lock before it goes on
/// without it: [`ATOMIC_LOCK_SPINS`] in compute and mesh programs,
/// [`ATOMIC_LOCK_SPINS_DRAWN`] in the others.
pub const fn atomic_lock_spins(stage: HwStage) -> u32 {
match stage {
HwStage::Cs | HwStage::Ms => ATOMIC_LOCK_SPINS,
_ => ATOMIC_LOCK_SPINS_DRAWN,
}
}
/// Where the lock words start in the buffer bound at `u`[`VIEW_WRITES`], in
/// bytes: after the written pages and the read marks.
pub const ATOMIC_LOCKS_AT: u32 = (VIEW_READS + HEAP_VIEWS) / 8;
Expand Down
105 changes: 79 additions & 26 deletions crates/victory-shader/src/emit/valu_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2207,6 +2207,43 @@ fn image_atomics_of_64_bits_in_rounds_match_the_turns() {
/// in a round and then again in a turn would show here.
#[test]
fn image_atomic_adds_of_64_bits_apply_once() {
let words = adds64_words();
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for groups in [1u64, 8] {
for rounds in [false, true] {
if !adds64_apply_once(&words, groups, rounds) {
eprintln!("no SM 6.6 device; skipped");
return;
}
}
}
}

/// The adds of [`image_atomic_adds_of_64_bits_apply_once`] where 2,048
/// groups meet on one lock, 20 times in each form. A lane that waits out
/// its bound goes on without the lock and loses its add: with a bound of
/// 2^16 tries this lost adds on an M5 Pro (2 of 100 runs in turns, 1 of 40
/// in rounds) and with 8 groups on an M2 Max (patcliftongc, #240); see
/// [`super::ATOMIC_LOCK_SPINS`]. Slow on WARP; run with `--ignored` on a
/// Mac.
#[test]
#[ignore = "a stress under contention, for D3DMetal (#240)"]
fn image_atomic_adds_of_64_bits_apply_once_under_contention() {
let words = adds64_words();
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for rounds in [false, true] {
for _ in 0..20 {
if !adds64_apply_once(&words, 2048, rounds) {
eprintln!("no SM 6.6 device; skipped");
return;
}
}
}
}

/// The shader of [`image_atomic_adds_of_64_bits_apply_once`]: every lane
/// adds `0xFFFF_FFFF` into texel (0, 0), then into its own texel (l, 1).
fn adds64_words() -> Vec<u32> {
let v0 = vgpr(0);
let mut words = atomics64_prologue();
words.extend([
Expand All @@ -2222,32 +2259,48 @@ fn image_atomic_adds_of_64_bits_apply_once() {
words.extend(image_atomic(0x11, 1, 3, 8, 3, false));
words.extend(image_atomic(0x11, 1, 5, 8, 3, false));
words.push(S_ENDPGM);
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for groups in [1u64, 8] {
for rounds in [false, true] {
let Some((got, locks, label, _)) =
locked_atomics64(&words, rounds, (32, 2), groups as u32)
else {
eprintln!("no SM 6.6 device; skipped");
return;
};
let form = if rounds { "rounds" } else { "turns" };
let label = format!("{label}, {form}, {groups} groups");
let add = u64::from(u32::MAX);
assert_eq!(got[0], 32 * groups * add, "{label}: the shared texel");
assert!(
got[1..32].iter().all(|&t| t == 0),
"{label}: the rest of row 0"
);
assert!(
got[32..].iter().all(|&t| t == groups * add),
"{label}: own texels"
);
assert!(
locks.iter().all(|&w| w == 0),
"{label}: a lock left taken or a page marked"
);
}
words
}

/// Runs [`adds64_words`] as `groups` groups of 32 lanes (in rounds first if
/// `rounds`) and checks that every add applied once and no lock is left
/// taken. `false` with no SM 6.6 device.
fn adds64_apply_once(words: &[u32], groups: u64, rounds: bool) -> bool {
let Some((got, locks, label, _)) = locked_atomics64(words, rounds, (32, 2), groups as u32)
else {
return false;
};
let form = if rounds { "rounds" } else { "turns" };
let label = format!("{label}, {form}, {groups} groups");
let add = u64::from(u32::MAX);
assert_eq!(got[0], 32 * groups * add, "{label}: the shared texel");
assert!(
got[1..32].iter().all(|&t| t == 0),
"{label}: the rest of row 0"
);
assert!(
got[32..].iter().all(|&t| t == groups * add),
"{label}: own texels"
);
assert!(
locks.iter().all(|&w| w == 0),
"{label}: a lock left taken or a page marked"
);
true
}

/// Lanes of compute and mesh programs wait longer for a held lock than
/// those of the stages whose draws macOS ends when they run long (#240).
#[test]
fn atomic_lock_bound_follows_the_stage() {
use super::shader::atomic_lock_spins;
let (compute, drawn) = (super::ATOMIC_LOCK_SPINS, super::ATOMIC_LOCK_SPINS_DRAWN);
for stage in [HwStage::Cs, HwStage::Ms] {
assert_eq!(atomic_lock_spins(stage), compute, "{stage:?}");
}
let others = [HwStage::Ps, HwStage::Vs, HwStage::Gs, HwStage::Es];
for stage in others.into_iter().chain([HwStage::Hs, HwStage::Ls]) {
assert_eq!(atomic_lock_spins(stage), drawn, "{stage:?}");
}
}

Expand Down
2 changes: 1 addition & 1 deletion docs/macos.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ This was the "signed zero in minimums" difference listed here before. Each `v_mi

The merge of VIctory's changes up to 70564ae on 25 November 2026 brought new shader tests, and three of them find real differences in D3DMetal 4.0 beta 3 on an M4. The tests skip only those checks under Wine, so the rest of each test still runs.

- 64-bit image atomics. D3DMetal reports `AtomicInt64OnTypedResourceSupported` and `AtomicInt64OnDescriptorHeapResourceSupported`, but its 64-bit atomics in `image_atomics_of_64_bits` leave every texel at zero. The game's alpha prepasses use them. Under Wine the translator now emulates them (`Options::atomic_locks`, the module notes' "Atomic locks", `VICTORY_ATOMIC_LOCKS=0` or `1` to override): the lanes of a wave take turns in a loop over lane indices, and in its turn a lane takes a 32-bit lock word, reads the texel, writes the result and frees the lock. Two simpler forms failed under D3DMetal and are worth knowing about. Lanes of one wave spinning on each other's locks never finish, and `WaveIsFirstLane` and `WaveReadLaneFirst` inside a divergent loop return other lanes' values. The spin is bounded at 65536 tries so a fault can never hang the GPU. On an M2 Pro these locks cost about 6 s of a 7.4 s world frame (#240), almost all of it in the alpha prepasses' 64-bit `umax`. `VICTORY_ATOMIC_LOCK_ROUNDS=1` (opt-in while it is measured in the game) makes every lane of a wave first try its lock once in each of four rounds, all at once, so lanes whose locks differ do not wait for each other; only lanes still not done take turns, and a wave whose lanes all finished skips the turns. No lane waits on a lock inside a round, so lanes of one wave still never wait for each other's locks. On an M5 Pro with D3DMetal 4.0 beta 3 a wave's 64-bit `umax` on distinct texels took 29 µs in turns and 6 µs in rounds (`atomic_lock_rounds_timing`, ignored, run under Wine). In pixel programs the rounds leave helper lanes out: their atomics are discarded, so they could never take a lock, and in their turn they would spin to the bound.
- 64-bit image atomics. D3DMetal reports `AtomicInt64OnTypedResourceSupported` and `AtomicInt64OnDescriptorHeapResourceSupported`, but its 64-bit atomics in `image_atomics_of_64_bits` leave every texel at zero. The game's alpha prepasses use them. Under Wine the translator now emulates them (`Options::atomic_locks`, the module notes' "Atomic locks", `VICTORY_ATOMIC_LOCKS=0` or `1` to override): the lanes of a wave take turns in a loop over lane indices, and in its turn a lane takes a 32-bit lock word, reads the texel, writes the result and frees the lock. Two simpler forms failed under D3DMetal and are worth knowing about. Lanes of one wave spinning on each other's locks never finish, and `WaveIsFirstLane` and `WaveReadLaneFirst` inside a divergent loop return other lanes' values. The spin is bounded, so a lock nobody frees can never hang the GPU: 2^22 tries in compute and mesh shaders, which macOS never ends for running long, and 65536 in pixel shaders, whose draws macOS ends after about 50 ms. A lane past the bound goes on without the lock and can lose its update, which 65536 tries allowed in compute under heavy contention (2,048 groups adding into one texel lost adds in 2 of 100 runs on an M5 Pro, #240). A shader the GPU ends while one of its lanes holds a lock never frees it, so after a submission the GPU ended VIctory frees every lock. On an M2 Pro these locks cost about 6 s of a 7.4 s world frame (#240), almost all of it in the alpha prepasses' 64-bit `umax`. `VICTORY_ATOMIC_LOCK_ROUNDS=1` (opt-in while it is measured in the game) makes every lane of a wave first try its lock once in each of four rounds, all at once, so lanes whose locks differ do not wait for each other; only lanes still not done take turns, and a wave whose lanes all finished skips the turns. No lane waits on a lock inside a round, so lanes of one wave still never wait for each other's locks. On an M5 Pro with D3DMetal 4.0 beta 3 a wave's 64-bit `umax` on distinct texels took 29 µs in turns and 6 µs in rounds (`atomic_lock_rounds_timing`, ignored, run under Wine). In pixel programs the rounds leave helper lanes out: their atomics are discarded, so they could never take a lock, and in their turn they would spin to the bound.
- Sample bias in compute programs. D3DMetal ignores the bias of a sample in a compute shader: a bias of 1 reads level 1 where the console reads level 2. Under Wine the translator now runs those samples as gradient samples with the quad gradients scaled by `2^bias` (`Options::bias_as_gradients`, found by nickorlabs in #30; `VICTORY_BIAS_AS_GRADIENTS=0` or `1` overrides). The bias cases in `image_addresses_of_16_bits_and_clamps` run under Wine again and pass. Pixel shaders keep the plain biased sample.
- 24-bit depth. Apple GPUs have no 24-bit depth format, so D3DMetal keeps it as 32-bit float and rounds down when it stores 24 bits. The depth test clears to 0.75, where both roundings agree (PR #6).
- Depth bounds. D3DMetal reports `DepthBoundsTestSupported` and does not apply the test (Metal has none): in the merged VIctory test a draw whose bounds exclude the stored depth still writes. Under Wine `Host::depth_bounds_supported` is false, so pipelines are made without bounds and one warning says so, which has the same effect and keeps the plain pipeline states. The test follows the flag.
Expand Down