From 9b5b5bf1224374271950c939e08f20638ee1f6b3 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 11:28:24 -0800 Subject: [PATCH] D3D12.X: observe initial build completion lock free Retained deferred dispatches repeatedly took the completion mutex even after an initial build had reached terminal state. Publish terminal initial-build state through an observational release flag while keeping exact waits, generation ownership, release, and eviction serialized by the existing mutex. Add serial and parallel CPU benchmarks for shared and distinct unpromoted completion probes, with the promoted path as a control. Cross-checked debug tests and release all-target builds for x86_64-pc-windows-gnu; Windows tests and benchmarks were not run here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/benches/runtime.rs | 93 +++++++++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 127 +++++++++++++++++++++++-- 2 files changed, 209 insertions(+), 11 deletions(-) diff --git a/crates/xcl/benches/runtime.rs b/crates/xcl/benches/runtime.rs index 0497429caa..7d8ce1176c 100644 --- a/crates/xcl/benches/runtime.rs +++ b/crates/xcl/benches/runtime.rs @@ -160,7 +160,7 @@ fn allocator_benches(c: &mut Criterion) { #[cfg(feature = "pipeline-resolution-bench")] fn pipeline_resolution_benches(c: &mut Criterion) { - let fixture = xcl::hle::d3d12x::pso_async::PipelineResolutionBench::new(); + let fixture = Arc::new(xcl::hle::d3d12x::pso_async::PipelineResolutionBench::new()); let mut group = c.benchmark_group("runtime/pipeline_resolution"); group.throughput(Throughput::Elements(1)); group.bench_function("retained_ready", |b| { @@ -177,9 +177,100 @@ fn pipeline_resolution_benches(c: &mut Criterion) { group.bench_function("initial_completed_dispatch", |b| { b.iter(|| black_box(&fixture).initial_completed_dispatch()); }); + group.bench_function("initial_unpromoted_completed_probe", |b| { + b.iter(|| black_box(&fixture).initial_unpromoted_shared_probe()); + }); + + let workers = std::thread::available_parallelism().map_or(4, |count| count.get()) + .saturating_sub(1).clamp(2, 8); + group.throughput(Throughput::Elements((PIPELINE_PROBE_BATCH * workers) as u64)); + for (name, mode) in [ + ("initial_unpromoted_shared", PipelineProbeMode::UnpromotedShared), + ("initial_unpromoted_distinct", PipelineProbeMode::UnpromotedDistinct), + ("initial_promoted_control", PipelineProbeMode::Promoted), + ] { + let pool = PipelineProbeWorkers::new(fixture.clone(), workers, mode); + group.bench_function(&format!("{name}_parallel_{workers}"), |b| b.iter(|| pool.run())); + } group.finish(); } +#[cfg(feature = "pipeline-resolution-bench")] +const PIPELINE_PROBE_BATCH: usize = 4_096; + +#[cfg(feature = "pipeline-resolution-bench")] +#[derive(Clone, Copy)] +enum PipelineProbeMode { + UnpromotedShared, + UnpromotedDistinct, + Promoted, +} + +#[cfg(feature = "pipeline-resolution-bench")] +struct PipelineProbeWorkers { + start: Arc, + done: Arc, + stop: Arc, + threads: Vec>, +} + +#[cfg(feature = "pipeline-resolution-bench")] +impl PipelineProbeWorkers { + fn new( + fixture: Arc, + workers: usize, + mode: PipelineProbeMode, + ) -> Self { + let start = Arc::new(Barrier::new(workers + 1)); + let done = Arc::new(Barrier::new(workers + 1)); + let stop = Arc::new(AtomicBool::new(false)); + let threads = (0..workers) + .map(|worker| { + let fixture = fixture.clone(); + let start = start.clone(); + let done = done.clone(); + let stop = stop.clone(); + std::thread::Builder::new() + .name(format!("pipeline-probe-bench-{worker}")) + .spawn(move || loop { + start.wait(); + if stop.load(Ordering::Acquire) { + break; + } + let mut pending = 0usize; + for _ in 0..PIPELINE_PROBE_BATCH { + pending += match mode { + PipelineProbeMode::UnpromotedShared => fixture.initial_unpromoted_shared_probe(), + PipelineProbeMode::UnpromotedDistinct => fixture.initial_unpromoted_distinct_probe(worker), + PipelineProbeMode::Promoted => fixture.initial_promoted_probe(), + } as usize; + } + black_box(pending); + done.wait(); + }) + .expect("pipeline probe benchmark worker") + }) + .collect(); + Self { start, done, stop, threads } + } + + fn run(&self) { + self.start.wait(); + self.done.wait(); + } +} + +#[cfg(feature = "pipeline-resolution-bench")] +impl Drop for PipelineProbeWorkers { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + self.start.wait(); + for thread in self.threads.drain(..) { + thread.join().expect("pipeline probe benchmark worker panicked"); + } + } +} + #[cfg(feature = "pipeline-resolution-bench")] const EMISSION_BATCH: usize = 1_024; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3d1e13b9f9..980ecab0b5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -76,6 +76,9 @@ struct Build { /// Exact armed eviction visible before its native owners may be detached. Kept separate /// from recipe state so coordinator locks never overlap the build/rebuild/generation chain. eviction: Mutex>, + /// Lock-free observation that terminal state has been fully published. Exact generation, + /// release, and condvar decisions remain serialized by `done`. + completed: AtomicBool, done: Mutex, cv: Condvar, /// every stand-in interested in this build was released before it finished @@ -319,6 +322,7 @@ impl Build { completed_frame: AtomicU64::new(0), candidate_queued: AtomicBool::new(false), eviction: Mutex::new(None), + completed: AtomicBool::new(false), done: Mutex::new(false), cv: Condvar::new(), orphan: Default::default(), @@ -347,6 +351,17 @@ impl Build { } } + /// Publish terminal state after the caller has installed the result while holding `done`. + /// The release flag is observational only; waiters and exact owner transitions keep using + /// the mutex so the condvar predicate and generation lifetime cannot be separated. + fn publish_completed(&self, mut done: std::sync::MutexGuard<'_, bool>) { + debug_assert!(!*done); + *done = true; + self.finish_queued(); + self.completed.store(true, Ordering::Release); + self.cv.notify_all(); + } + fn promote(&self, priority: Priority) { if let Some(job) = self.queued.lock().unwrap().as_ref() { let _ = job.promote(priority); @@ -2099,7 +2114,7 @@ fn complete(build: &Arc, real: usize) { build.completed_frame.store(super::present::presents(), Ordering::Relaxed); } let (orphan, replaced_generation) = { - let mut done = build.done.lock().unwrap(); + let done = build.done.lock().unwrap(); let orphan = build.orphan.load(Ordering::Acquire); let mut replaced_generation = None; if !orphan { @@ -2112,9 +2127,7 @@ fn complete(build: &Arc, real: usize) { } build.real.store(real, Ordering::Release); } - *done = true; - build.finish_queued(); - build.cv.notify_all(); + build.publish_completed(done); (orphan, replaced_generation) }; // outside `done`: a pipeline Release override can re-enter pipeline bookkeeping @@ -2860,10 +2873,8 @@ fn drop_unstarted_job(build: &Arc) { if let Some(job) = job { build.cancel_queued(); { - let mut done = build.done.lock().unwrap(); - *done = true; - build.finish_queued(); - build.cv.notify_all(); + let done = build.done.lock().unwrap(); + build.publish_completed(done); } drop(job); forget_in_flight(build); @@ -4466,6 +4477,73 @@ mod used_tests { assert_eq!(native.refs.load(Ordering::Relaxed), 0); } + #[test] + fn initial_pending_probe_does_not_take_the_completion_lock() { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let pending = structured_pending(build.clone(), true); + let resolution = PipelineResolution(StructuredResolve::initial(0x7E57_D01B, pending, 0x7E57_D01B, true)); + let done = build.done.lock().unwrap(); + let (tx, rx) = mpsc::channel(); + let thread = std::thread::spawn(move || tx.send(resolution.initial_build_pending()).unwrap()); + assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).expect("completion probe took the done lock")); + drop(done); + thread.join().unwrap(); + } + + #[test] + fn terminal_paths_release_publish_completion_after_their_result() { + fn observe_after(build: Arc, publish: impl FnOnce()) -> usize { + let gate = Arc::new(std::sync::Barrier::new(2)); + let observer_gate = gate.clone(); + let observer = build.clone(); + let (tx, rx) = mpsc::channel(); + let thread = std::thread::spawn(move || { + observer_gate.wait(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !observer.completed.load(Ordering::Acquire) && std::time::Instant::now() < deadline { + std::thread::yield_now(); + } + tx.send(observer.completed.load(Ordering::Acquire).then(|| observer.real.load(Ordering::Acquire))).unwrap(); + }); + gate.wait(); + publish(); + let observed = rx.recv_timeout(std::time::Duration::from_secs(10)) + .expect("completion observer did not finish") + .expect("terminal state was not release-published"); + thread.join().unwrap(); + observed + } + + let success = Arc::new(Build::new(Box::new(|| 0xC011_E7ED), false)); + let success_job = success.job.lock().unwrap().take().unwrap(); + let observed = observe_after(success.clone(), || complete(&success, success_job())); + assert_eq!(observed, 0xC011_E7ED, "completion became visible before its result"); + success.real.store(0, Ordering::Release); + + let failed = Arc::new(Build::new(Box::new(|| 0), false)); + drop(failed.job.lock().unwrap().take()); + let observed = observe_after(failed.clone(), || complete(&failed, 0)); + assert_eq!(observed, 0, "failed completion published a native result"); + assert!(*failed.done.lock().unwrap()); + + let unstarted = Arc::new(Build::new(Box::new(|| 0), false)); + unstarted.owners.store(0, Ordering::Release); + unstarted.orphan.store(true, Ordering::Release); + drop_unstarted_job(&unstarted); + assert!(unstarted.completed.load(Ordering::Acquire)); + assert!(*unstarted.done.lock().unwrap()); + assert!(unstarted.job.lock().unwrap().is_none()); + + let running = Arc::new(Build::new(Box::new(|| 0), false)); + let running_job = running.job.lock().unwrap().take().unwrap(); + running.owners.store(0, Ordering::Release); + running.orphan.store(true, Ordering::Release); + drop_unstarted_job(&running); + assert!(!running.completed.load(Ordering::Acquire), "an orphaned running job completed before its worker"); + complete(&running, running_job()); + assert!(running.completed.load(Ordering::Acquire)); + } + #[test] fn unavailable_initial_resolution_remains_retryable_until_exact_publication() { let original = 0x7E57_D01Ausize; @@ -7792,7 +7870,7 @@ impl PipelineResolution { if promoted.get().is_none() && pending.build.owners.load(Ordering::Acquire) != 0 && !pending.build.orphan.load(Ordering::Acquire) - && !*pending.build.done.lock().unwrap()) + && !pending.build.completed.load(Ordering::Acquire)) } /// Promote this retained bind's exact initial build for a deferred submit without looking up @@ -7864,6 +7942,8 @@ fn promote_initial_choice( pub struct PipelineResolutionBench { retained_ready: PipelineResolution, initial_completed: PipelineResolution, + initial_unpromoted_shared: PipelineResolution, + initial_unpromoted_distinct: Vec, registry_original: usize, registry_pending: Arc, _raw_owners: Vec, @@ -7970,8 +8050,9 @@ impl PipelineResolutionBench { }); let finish = |pending: &Pending, raw| { drop(pending.build.job.lock().unwrap().take()); + let done = pending.build.done.lock().unwrap(); pending.build.real.store(raw, Ordering::Release); - *pending.build.done.lock().unwrap() = true; + pending.build.publish_completed(done); }; let ready_pending = make_pending(); @@ -7985,6 +8066,15 @@ impl PipelineResolutionBench { finish(&initial_pending, raws[1]); let _ = Self::consume(initial_completed.resolve_for_emission()); + let make_unpromoted = || { + let pending = make_pending(); + let resolution = PipelineResolution(classify_retained(raws[1] ^ 0x303, &pending)); + finish(&pending, raws[1]); + resolution + }; + let initial_unpromoted_shared = make_unpromoted(); + let initial_unpromoted_distinct = (0..8).map(|_| make_unpromoted()).collect(); + let registry_pending = make_pending(); finish(®istry_pending, raws[2]); let registry_original = raws[2] ^ 0x404; @@ -7995,6 +8085,8 @@ impl PipelineResolutionBench { Self { retained_ready, initial_completed, + initial_unpromoted_shared, + initial_unpromoted_distinct, registry_original, registry_pending, _raw_owners: raw_owners, @@ -8031,6 +8123,21 @@ impl PipelineResolutionBench { Self::consume(self.initial_completed.resolve_for_emission()) } + #[inline(never)] + pub fn initial_unpromoted_shared_probe(&self) -> bool { + self.initial_unpromoted_shared.initial_build_pending() + } + + #[inline(never)] + pub fn initial_unpromoted_distinct_probe(&self, worker: usize) -> bool { + self.initial_unpromoted_distinct[worker % self.initial_unpromoted_distinct.len()].initial_build_pending() + } + + #[inline(never)] + pub fn initial_promoted_probe(&self) -> bool { + self.initial_completed.initial_build_pending() + } + fn consume(choice: PipelineChoice) -> usize { match choice { PipelineChoice::Available { raw, generation } => raw.rotate_left(13) ^ generation.id() as usize,