ID3D12Fence::SetEventOnCompletion with a NULL event returns E_NOTIMPL instead of blocking #759

Closed
opened 2026-11-26 04:13:56 +00:00 by github-bot · 3 comments
Owner

@⁠Conrage on GitHub · 2026-11-24 09:39 UTC · original

crates/victory-gpu/src/fence.rs:90-95. In D3D12, a NULL event means "block until the fence reaches the value". We return E_NOTIMPL. The comment's reason ("nothing can reach it while no GPU work runs") no longer holds, because queues and the CPU now signal fences (fence.rs:99, queue.rs:160).

Proposed patch (formatted with the repo's rustfmt; not compiled or tested, since I have no Windows machine). It blocks on a Condvar paired with the existing waiters mutex, which signal already holds, so no wakeup is lost. The patch also updates the unit test to cover the blocking wait.

diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs
index 285e7bd..b176952 100644
--- a/crates/victory-gpu/src/fence.rs
+++ b/crates/victory-gpu/src/fence.rs
@@ -1,12 +1,12 @@
-//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a
-//! GPU yet, so only signals (the title's, later our queues') move one.
+//! Fences: a 64-bit value and the events (or threads) waiting for it.
+//! Signals, the title's and our queues', move one.
 #![allow(clippy::not_unsafe_ptr_arg_deref)]
 
 use std::ffi::c_void;
-use std::sync::Mutex;
 use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Condvar, Mutex};
 
-use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid};
+use crate::object::{self, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid};
 use crate::resource::PAGEABLE_IIDS;
 
 pub(crate) const FENCE_IIDS: [Iid; 4] = [
@@ -30,6 +30,8 @@ struct Fence {
     flags: u32,
     /// Events to set once the value reaches theirs (handles as integers).
     waiters: Mutex<Vec<(u64, usize)>>,
+    /// Woken at every signal, for threads blocked in a wait with no event.
+    reached: Condvar,
 }
 
 fn fence<'a>(this: This) -> &'a Fence {
@@ -50,6 +52,7 @@ pub(crate) extern "system" fn create(
         value: AtomicU64::new(initial),
         flags,
         waiters: Mutex::new(Vec::new()),
+        reached: Condvar::new(),
     });
     object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
 }
@@ -88,10 +91,14 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
         return S_OK;
     }
     if event.is_null() {
-        // shortcut: a null event means "block until reached"; nothing can
-        // reach it while no GPU work runs, so fail instead of hanging.
-        tracing::warn!(value, "blocking fence wait not implemented");
-        return E_NOTIMPL;
+        // A null event means "block until reached".
+        while fence.value.load(Ordering::Acquire) < value {
+            waiters = fence
+                .reached
+                .wait(waiters)
+                .unwrap_or_else(|e| e.into_inner());
+        }
+        return S_OK;
     }
     waiters.push((value, event as usize));
     S_OK
@@ -107,6 +114,7 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
         }
         !reached
     });
+    fence.reached.notify_all();
     S_OK
 }
 
@@ -161,11 +169,22 @@ mod tests {
         assert_eq!(wait(f, 5, event), S_OK, "already reached");
         // SAFETY: as above.
         assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
-        assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
+        // A wait with no event blocks until another thread signals.
+        let (at, signal_at) = (f as usize, signal as usize);
+        let signaller = std::thread::spawn(move || {
+            std::thread::sleep(std::time::Duration::from_millis(20));
+            // SAFETY: the fence's signal slot, read above.
+            let signal: extern "system" fn(This, u64) -> HRESULT =
+                unsafe { std::mem::transmute(signal_at) };
+            signal(at as This, 9)
+        });
+        assert_eq!(wait(f, 9, std::ptr::null_mut()), S_OK);
+        assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 9);
+        assert_eq!(signaller.join().unwrap(), S_OK);
         // Grand Theft Auto VI reads the value at the fence's address.
         let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f);
         // SAFETY: the fence's value.
-        assert_eq!(unsafe { *(at as *const u64) }, 5);
+        assert_eq!(unsafe { *(at as *const u64) }, 9);
         // SAFETY: ours.
         unsafe { CloseHandle(event) };
         assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);

AI use: found and written with Claude from reading the code at 8e79c80; not run on hardware.

**@⁠Conrage** on GitHub · 2026-11-24 09:39 UTC · [original](https://github.com/Marvisak/VIctory/issues/759) `crates/victory-gpu/src/fence.rs:90-95`. In D3D12, a NULL event means "block until the fence reaches the value". We return `E_NOTIMPL`. The comment's reason ("nothing can reach it while no GPU work runs") no longer holds, because queues and the CPU now signal fences (`fence.rs:99`, `queue.rs:160`). Proposed patch (formatted with the repo's rustfmt; **not compiled or tested**, since I have no Windows machine). It blocks on a `Condvar` paired with the existing `waiters` mutex, which `signal` already holds, so no wakeup is lost. The patch also updates the unit test to cover the blocking wait. ```diff diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 285e7bd..b176952 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -1,12 +1,12 @@ -//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a -//! GPU yet, so only signals (the title's, later our queues') move one. +//! Fences: a 64-bit value and the events (or threads) waiting for it. +//! Signals, the title's and our queues', move one. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::c_void; -use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex}; -use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; +use crate::object::{self, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; pub(crate) const FENCE_IIDS: [Iid; 4] = [ @@ -30,6 +30,8 @@ struct Fence { flags: u32, /// Events to set once the value reaches theirs (handles as integers). waiters: Mutex<Vec<(u64, usize)>>, + /// Woken at every signal, for threads blocked in a wait with no event. + reached: Condvar, } fn fence<'a>(this: This) -> &'a Fence { @@ -50,6 +52,7 @@ pub(crate) extern "system" fn create( value: AtomicU64::new(initial), flags, waiters: Mutex::new(Vec::new()), + reached: Condvar::new(), }); object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) } @@ -88,10 +91,14 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c return S_OK; } if event.is_null() { - // shortcut: a null event means "block until reached"; nothing can - // reach it while no GPU work runs, so fail instead of hanging. - tracing::warn!(value, "blocking fence wait not implemented"); - return E_NOTIMPL; + // A null event means "block until reached". + while fence.value.load(Ordering::Acquire) < value { + waiters = fence + .reached + .wait(waiters) + .unwrap_or_else(|e| e.into_inner()); + } + return S_OK; } waiters.push((value, event as usize)); S_OK @@ -107,6 +114,7 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { } !reached }); + fence.reached.notify_all(); S_OK } @@ -161,11 +169,22 @@ mod tests { assert_eq!(wait(f, 5, event), S_OK, "already reached"); // SAFETY: as above. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); - assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); + // A wait with no event blocks until another thread signals. + let (at, signal_at) = (f as usize, signal as usize); + let signaller = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(20)); + // SAFETY: the fence's signal slot, read above. + let signal: extern "system" fn(This, u64) -> HRESULT = + unsafe { std::mem::transmute(signal_at) }; + signal(at as This, 9) + }); + assert_eq!(wait(f, 9, std::ptr::null_mut()), S_OK); + assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 9); + assert_eq!(signaller.join().unwrap(), S_OK); // Grand Theft Auto VI reads the value at the fence's address. let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f); // SAFETY: the fence's value. - assert_eq!(unsafe { *(at as *const u64) }, 5); + assert_eq!(unsafe { *(at as *const u64) }, 9); // SAFETY: ours. unsafe { CloseHandle(event) }; assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0); ``` _AI use: found and written with Claude from reading the code at `8e79c80`; not run on hardware._
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:13:56 +00:00
Author
Owner

@⁠Yorivel on GitHub · 2026-11-24 09:43 UTC · original

Compiled and tested on Windows 11 26300 (MSVC, Rust 1.98.1, --test-threads=1): the patch applies to 8e79c80, its updated test passes 3 of 3 runs, clippy (-D warnings) and rustfmt are clean.

One gap: a list's bottom-of-pipe write (write32/write64, list.rs) can store the value straight at the fence's address (gpu_address), which moves it without signal, so the Condvar is never notified. A test that does that (Written::Value(9).write to the fence's address while another thread waits with no event) times out after 2 s with the patch as posted.

Branch with the patch plus a fix: https://github.com/Yorivel/VIctory/tree/fix/fence-blocking-wait. The wait uses wait_timeout (1 ms) so it also sees a value written without a signal; signals still wake it at once. Both tests pass 3 of 3, cargo test -p victory-gpu --lib 51 passed / 1 ignored, clippy clean, cargo xtask policy ok. The module comment no longer says only signals move a fence.

Not covered: such a write sets no waiting events either (the same path, before this patch); that needs fences findable by address and is left alone here.

Written with Claude Code.

**@⁠Yorivel** on GitHub · 2026-11-24 09:43 UTC · [original](https://github.com/Marvisak/VIctory/issues/759#issuecomment-7127795801) Compiled and tested on Windows 11 26300 (MSVC, Rust 1.98.1, `--test-threads=1`): the patch applies to `8e79c80`, its updated test passes 3 of 3 runs, clippy (`-D warnings`) and rustfmt are clean. One gap: a list's bottom-of-pipe write (`write32`/`write64`, `list.rs`) can store the value straight at the fence's address (`gpu_address`), which moves it without `signal`, so the `Condvar` is never notified. A test that does that (`Written::Value(9).write` to the fence's address while another thread waits with no event) times out after 2 s with the patch as posted. Branch with the patch plus a fix: https://github.com/Yorivel/VIctory/tree/fix/fence-blocking-wait. The wait uses `wait_timeout` (1 ms) so it also sees a value written without a signal; signals still wake it at once. Both tests pass 3 of 3, `cargo test -p victory-gpu --lib` 51 passed / 1 ignored, clippy clean, `cargo xtask policy` ok. The module comment no longer says only signals move a fence. Not covered: such a write sets no waiting *events* either (the same path, before this patch); that needs fences findable by address and is left alone here. Written with Claude Code.
Author
Owner

@⁠Conrage on GitHub · 2026-11-24 09:53 UTC · original

Thanks for compiling and testing it, @⁠Yorivel. It turns out open PR #32 already covers this: blocking NULL-event waits, and also the bottom-of-pipe wake you found missing (it registers fences by value address so list writes wake waiters). Closing as a duplicate of that PR.

**@⁠Conrage** on GitHub · 2026-11-24 09:53 UTC · [original](https://github.com/Marvisak/VIctory/issues/759#issuecomment-7128032470) Thanks for compiling and testing it, @⁠Yorivel. It turns out open PR #32 already covers this: blocking NULL-event waits, and also the bottom-of-pipe wake you found missing (it registers fences by value address so list writes wake waiters). Closing as a duplicate of that PR.
Author
Owner

@⁠AndyLatimer on GitHub · 2026-11-24 10:08 UTC · original

Open PR #32 already fixes this, including the gap @⁠Yorivel describes and the part left out there:

  • SetEventOnCompletion(value, NULL) blocks on a condition variable instead of returning E_NOTIMPL (tests blocking_wait_returns_at_once_when_reached, blocking_wait_blocks_until_signalled).
  • Live fences are registered by their value address, so a list's bottom-of-pipe write (Written::write) wakes both a blocking wait and the events waiting on that fence (bottom_of_pipe_write_releases_blocking_wait, bottom_of_pipe_write_sets_waiting_event).
  • A write straight to the fence's memory (CPU or shader) is picked up by a watcher thread that polls only while a wait is pending (direct_memory_write_sets_waiting_event).

Head 9c5328d has current main merged in. Only synthetic tests; not run against the title. AI-assisted.

**@⁠AndyLatimer** on GitHub · 2026-11-24 10:08 UTC · [original](https://github.com/Marvisak/VIctory/issues/759#issuecomment-7128371048) Open PR #32 already fixes this, including the gap @⁠Yorivel describes and the part left out there: - `SetEventOnCompletion(value, NULL)` blocks on a condition variable instead of returning `E_NOTIMPL` (tests `blocking_wait_returns_at_once_when_reached`, `blocking_wait_blocks_until_signalled`). - Live fences are registered by their value address, so a list's bottom-of-pipe write (`Written::write`) wakes both a blocking wait and the events waiting on that fence (`bottom_of_pipe_write_releases_blocking_wait`, `bottom_of_pipe_write_sets_waiting_event`). - A write straight to the fence's memory (CPU or shader) is picked up by a watcher thread that polls only while a wait is pending (`direct_memory_write_sets_waiting_event`). Head `9c5328d` has current `main` merged in. Only synthetic tests; not run against the title. AI-assisted.
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory#759
No description provided.