Skip to content
Closed
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
186 changes: 171 additions & 15 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock};
struct Pending {
/// the build, until a worker – or a bind that cannot wait for the queue – takes it
job: Mutex<Option<Job>>,
/// a second copy of the build, for a bind that waits too long on the worker building `job`
second: Mutex<Option<Job>>,
/// the build went to the workers (a lazy one goes on its first `resolve`)
sent: std::sync::atomic::AtomicBool,
/// the real pipeline state (raw pointer), 0 while building or when building failed
Expand All @@ -40,28 +42,44 @@ impl Pending {
/// stand-in handed to the title → its real pipeline
static PENDING: Mutex<Option<HashMap<usize, Arc<Pending>>>> = Mutex::new(None);

/// The build is done (`real`: its pipeline, 0 = failed).
/// The build is done (`real`: its pipeline, 0 = failed). The first build that *succeeds* is the
/// pipeline: a bind's second copy and the worker's may both end, and a failure does not take
/// the place of a success that is still coming (the later pipeline is released).
fn complete(p: &Pending, real: usize) {
let mut done = p.done.lock().unwrap();
// a failure after any result, or a result after a successful one: not this pipeline
if *done && (real == 0 || p.real.load(Ordering::Acquire) != 0) {
drop(done);
release(real);
return;
}
if real == 0 {
FAILED.fetch_add(1, Ordering::Relaxed);
} else {
BUILT.fetch_add(1, Ordering::Relaxed);
}
let orphan = {
let mut done = p.done.lock().unwrap();
let orphan = p.orphan.load(Ordering::Acquire);
if !orphan {
p.real.store(real, Ordering::Release);
}
*done = true;
p.cv.notify_all();
orphan
};
let orphan = p.orphan.load(Ordering::Acquire);
if !orphan {
p.real.store(real, Ordering::Release);
}
*done = true;
p.cv.notify_all();
drop(done);
// the copy is not wanted any more: it holds the descriptor the build reads
if real != 0 {
let _ = p.second.lock().unwrap().take();
}
// outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`)
if orphan {
release(real);
}
}

/// How long a bind waits for the worker that is building its pipeline before it builds a
/// second copy itself (`XCL_PSO_HELP_MS`; 0: never).
static HELP_AFTER: std::sync::LazyLock<std::time::Duration> = std::sync::LazyLock::new(|| {
std::time::Duration::from_millis(std::env::var("XCL_PSO_HELP_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(250))
});
static BUILT: AtomicUsize = AtomicUsize::new(0);
static FAILED: AtomicUsize = AtomicUsize::new(0);

Expand Down Expand Up @@ -124,8 +142,15 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) {
}

fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) {
submit_second(standin, compute, job, send, key, None)
}

/// `submit_as` with a build of a second copy: a bind that waits longer than `HELP_AFTER` on
/// the worker building `job` builds it itself (`resolve_wait`).
pub fn submit_second(standin: usize, compute: bool, job: Job, send: bool, key: u64, second: Option<Job>) {
let p = Arc::new(Pending {
job: Mutex::new(Some(job)),
second: Mutex::new(second),
sent: std::sync::atomic::AtomicBool::new(send),
real: AtomicUsize::new(0),
done: Mutex::new(false),
Expand Down Expand Up @@ -319,6 +344,106 @@ mod used_tests {
}
}

#[cfg(test)]
mod help_tests {
use super::*;
use std::sync::atomic::AtomicBool;

/// A bind that waits on a worker whose build is slow makes a second copy after the grace
/// period and is done long before the worker; the worker's late result is not the pipeline.
#[test]
fn a_bind_waiting_on_a_slow_worker_builds_a_second_copy() {
let slow = 0x7E57_7011usize;
let started = std::sync::Arc::new(AtomicBool::new(false));
let finished = std::sync::Arc::new(AtomicBool::new(false));
let (s, e) = (started.clone(), finished.clone());
// the worker's build takes 3 s and then has failed (0: nothing to release)
let worker = Box::new(move || {
s.store(true, Ordering::Release);
std::thread::sleep(std::time::Duration::from_secs(3));
e.store(true, Ordering::Release);
0usize
});
submit_second(slow, true, worker, true, 0, Some(Box::new(|| 0x5556)));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !started.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert!(started.load(Ordering::Acquire), "a worker is building it");
let start = std::time::Instant::now();
let real = resolve_wait(slow);
let waited = start.elapsed();
assert_eq!(real, 0x5556, "the second copy's build is the pipeline");
assert!(waited < std::time::Duration::from_millis(1500), "not held up by the worker: {waited:?}");
// the worker's build ends afterwards and does not replace it
while !finished.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(5));
}
std::thread::sleep(std::time::Duration::from_millis(50));
assert_eq!(resolve(slow), 0x5556);
released(slow);
}

/// A second copy that fails decides nothing: the worker's build is still the pipeline, and
/// the bind returns it (a copy that ran short of commit used to leave the pipeline failed
/// for the rest of the run, so every dispatch of it was skipped).
#[test]
fn a_second_copy_that_fails_leaves_the_workers_build_to_decide() {
let pso = 0x7E57_7012usize;
let started = std::sync::Arc::new(AtomicBool::new(false));
let s = started.clone();
let worker = Box::new(move || {
s.store(true, Ordering::Release);
std::thread::sleep(std::time::Duration::from_millis(700));
0x7777usize
});
submit_second(pso, true, worker, true, 0, Some(Box::new(|| 0)));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !started.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert!(started.load(Ordering::Acquire), "a worker is building it");
assert_eq!(resolve_wait(pso), 0x7777, "the worker's build, not the copy's failure");
assert_eq!(resolve(pso), 0x7777);
released(pso);
}

/// A pipeline with a second copy is still lazy: it waits for its first use, as
/// `submit_lazy` does. `go_background` passed the wrong `send` once and every pipeline a
/// title made went to the workers at creation, which is what `lazy` exists to avoid
/// (~51 000 of them, ~400 KB each in the driver).
#[test]
fn a_lazy_pipeline_with_a_second_copy_waits_for_its_first_use() {
let (lazy_pso, eager) = (0x7E57_7013usize, 0x7E57_7014usize);
let built = std::sync::Arc::new(AtomicBool::new(false));
let b = built.clone();
submit_second(lazy_pso, false, Box::new(move || {
b.store(true, Ordering::Release);
0x8881
}), false, 0, Some(Box::new(|| 0x8882)));
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(!built.load(Ordering::Acquire), "nothing built it before its first use");
assert!(is_pending(lazy_pso));
// its first use sends it to the workers
assert_eq!(resolve_wait(lazy_pso), 0x8881);
assert!(built.load(Ordering::Acquire));
// and `send` builds one straight away, with no use at all
let done = std::sync::Arc::new(AtomicBool::new(false));
let d = done.clone();
submit_second(eager, false, Box::new(move || {
d.store(true, Ordering::Release);
0x8883
}), true, 0, None);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !done.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(done.load(Ordering::Acquire), "an eager one is built by a worker without a use");
released(lazy_pso);
released(eager);
}
}

fn entry(pso: usize) -> Option<Arc<Pending>> {
PENDING.lock().unwrap().as_ref()?.get(&pso).cloned()
}
Expand All @@ -341,16 +466,47 @@ pub fn resolve(pso: usize) -> usize {

/// `resolve`, waiting for a pipeline still being built – built here if no worker has started
/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now).
/// When a worker has it and is still not done after `HELP_AFTER`, a second copy of the build
/// goes to a thread of its own and the first of the two to finish is the pipeline: a worker
/// held up before its build (the one big driver compile at a time, the commit and DXC gates)
/// otherwise keeps the title's thread waiting with the machine idle. The copy builds on its
/// own thread, not this one: translation recurses deeply and a title's thread may have a
/// small stack, and waiting inside the build would miss the worker finishing first.
pub fn resolve_wait(pso: usize) -> usize {
let Some(p) = entry(pso) else { return pso };
p.note_use();
let job = p.job.lock().unwrap().take();
if let Some(job) = job {
complete(&p, job());
}
let mut done = p.done.lock().unwrap();
while !*done {
done = p.cv.wait(done).unwrap();
} else {
let start = std::time::Instant::now();
let mut done = p.done.lock().unwrap();
while !*done && start.elapsed() < *HELP_AFTER {
(done, _) = p.cv.wait_timeout(done, *HELP_AFTER - start.elapsed()).unwrap();
}
// (None: already built, another bind took it, there is none, or help is off)
let second = if *done || HELP_AFTER.is_zero() { None } else { p.second.lock().unwrap().take() };
drop(done);
if let Some(job) = second {
let p = p.clone();
// `xcl-pso-help`: the big-driver-compile slot and the commit gate take it for one
// of theirs (`real::translated_compute_pso`), and 64 MB for the translation
let spawned = std::thread::Builder::new().name("xcl-pso-help".into()).stack_size(64 << 20).spawn(move || {
// a copy that fails decides nothing: the worker's own build still completes it
let real = job();
if real != 0 {
complete(&p, real);
}
});
if let Err(e) = spawned {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| crate::xlog_warn!("D3D12.X: no thread for a second copy of a pipeline's build ({e}) – waiting for the worker"));
}
}
let mut done = p.done.lock().unwrap();
while !*done {
done = p.cv.wait(done).unwrap();
}
}
match p.real.load(Ordering::Acquire) {
0 => pso,
Expand Down
44 changes: 30 additions & 14 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3956,6 +3956,18 @@ unsafe fn standin_stream(this: *mut c_void, f: PsoFn, desc: *const c_void, riid:
finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv)
}

/// `OwnedDesc` shared by a worker's build and the second copy a bind may make of it: both
/// only read it.
#[derive(Clone)]
struct SharedDesc(std::sync::Arc<OwnedDesc>);
unsafe impl Send for SharedDesc {}
unsafe impl Sync for SharedDesc {}
impl SharedDesc {
fn get(&self) -> &OwnedDesc {
&self.0
}
}

/// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker.
unsafe fn go_background(
this: *mut c_void,
Expand All @@ -3976,21 +3988,25 @@ unsafe fn go_background(
}
return None;
}
let dev = Dev(this as usize, f as usize);
let key = owned.shaders_key();
let job: super::pso_async::Job = Box::new(move || {
let mut out: *mut c_void = std::ptr::null_mut();
if unsafe { build(dev, &owned, &mut out) } && !out.is_null() {
out as usize
} else {
0
}
});
if super::pso_async::lazy() {
super::pso_async::submit_lazy(*ppv as usize, compute, job, key);
} else {
super::pso_async::submit(*ppv as usize, compute, job);
}
// the worker's build, and one of a second copy a bind makes when it waits too long on
// that worker (`pso_async::resolve_wait`)
let owned = SharedDesc(std::sync::Arc::new(owned));
let dev = Dev(this as usize, f as usize);
let once = |owned: SharedDesc| -> super::pso_async::Job {
Box::new(move || {
let mut out: *mut c_void = std::ptr::null_mut();
if unsafe { build(dev, owned.get(), &mut out) } && !out.is_null() {
out as usize
} else {
0
}
})
};
let (job, second) = (once(owned.clone()), Some(once(owned)));
// `send`: a lazy pipeline goes to the workers on its first `resolve`, an eager one now
let lazy = super::pso_async::lazy();
super::pso_async::submit_second(*ppv as usize, compute, job, !lazy, if lazy { key } else { 0 }, second);
Some(hr)
}

Expand Down
Loading