Skip to content
Open
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
24 changes: 21 additions & 3 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ thread_local! {
/// a backlog worker's build: whether it came from `Backlog::compute`; None once another
/// worker took this one's place (`build_parks`)
static PRELOAD_STEP: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
/// explicit late-build override for off-pool workers (e.g. `dispatch_chain`'s `xcl-pso-whole`)
static JOB_LATE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Run `p`'s build `job` on this thread (a worker's, or a bind's that took it): its time and
Expand Down Expand Up @@ -120,10 +122,26 @@ pub(super) fn build_is_wanted() -> bool {
}

/// This thread is a worker building a pipeline a bind waited for and went on without
/// (`resolve_within`): nobody waits for it now, but the title's draws or dispatches with it are
/// left out until it is built (`real::huge_compile_turn`).
/// (`resolve_within`), or a background `xcl-pso-whole` worker (`with_late_build`): nobody waits
/// for it now, but the title's draws or dispatches with it are left out until it is built
/// (`real::huge_compile_turn`).
pub(super) fn build_is_late() -> bool {
BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.late.load(Ordering::Acquire)))
JOB_LATE.with(|l| l.get())
|| BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.late.load(Ordering::Acquire)))
}

/// Run `f` with `build_is_late() == true` on the current thread, restoring the previous state on
/// return or unwind.
pub(super) fn with_late_build<R>(f: impl FnOnce() -> R) -> R {
struct Reset(bool);
impl Drop for Reset {
fn drop(&mut self) {
JOB_LATE.with(|l| l.set(self.0));
}
}
let prev = JOB_LATE.with(|l| l.replace(true));
let _reset = Reset(prev);
f()
}

/// This thread is a backlog worker building a pipeline nobody has used yet: its huge driver
Expand Down
116 changes: 97 additions & 19 deletions crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,12 @@ struct ChainRef(Arc<Chain>);
unsafe impl Send for ChainRef {}

impl Chain {
unsafe fn whole(&self) -> Result<ID3D12PipelineState, String> {
/// Build the whole form. `on_title_thread` is true only when a title thread is synchronously
/// blocked waiting for this compile (registers a long PC call).
unsafe fn whole(&self, on_title_thread: bool) -> Result<ID3D12PipelineState, String> {
if let Some(p) = self.whole.get() { return Ok(p.clone()); }
// (a driver compile on the title's thread, of the largest programs: the title is held
// while it lasts, as in any other long PC call)
let _call = super::super::pso_async::pc_call();
// (only when a title thread is held while this compile lasts, as in any other long PC call)
let _call = on_title_thread.then(super::super::pso_async::pc_call);
let _guard = self.build_whole.lock().unwrap();
if let Some(p) = self.whole.get() { return Ok(p.clone()); }
let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?;
Expand All @@ -93,6 +94,34 @@ impl Chain {
}
}

type WholeJob = Box<dyn FnOnce() + Send + 'static>;

/// Single persistent worker (`xcl-pso-whole`, 64 MiB stack) for building split programs' whole
/// forms off the title thread. A single worker avoids spawning an unbounded number of 64 MiB-stack
/// OS threads behind `real::huge_compile_turn` (which already serializes late giant compiles), and
/// runs each job under `pso_async::with_late_build` so it gets half commit headroom.
fn whole_worker() -> Option<&'static std::sync::mpsc::Sender<WholeJob>> {
static TX: OnceLock<Option<std::sync::mpsc::Sender<WholeJob>>> = OnceLock::new();
TX.get_or_init(|| {
let (tx, rx) = std::sync::mpsc::channel::<WholeJob>();
std::thread::Builder::new()
.name("xcl-pso-whole".into())
.stack_size(64 << 20)
.spawn(move || {
while let Ok(job) = rx.recv() {
super::super::pso_async::with_late_build(job);
}
})
.ok()
.map(|_| tx)
})
.as_ref()
}

fn enqueue_whole(job: WholeJob) -> bool {
whole_worker().is_some_and(|tx| tx.send(job).is_ok())
}

static CHAINS: LazyLock<Mutex<HashMap<usize, Arc<Chain>>>> = LazyLock::new(Default::default);

pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC,
Expand Down Expand Up @@ -131,7 +160,7 @@ pub(super) fn forget(pso: usize) {

pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result<Option<ID3D12PipelineState>, String> {
let chain = CHAINS.lock().unwrap().get(&pso).cloned();
chain.map(|c| c.whole()).transpose()
chain.map(|c| c.whole(true)).transpose()
}

/// The whole form of a split program for an indirect dispatch, which runs no chain (its group
Expand All @@ -140,37 +169,36 @@ pub(in crate::hle::d3d12x) enum Whole {
/// no split program: the pipeline as it is
Plain,
Ready(ID3D12PipelineState),
/// still being built on a thread of its own: this dispatch goes without it
/// still being built on the `xcl-pso-whole` worker: this dispatch goes without it
Late,
}

/// `whole` where a compute pipeline's dispatches go on without it while it is built
/// (`pso_async::cs_goes_on`): the whole form, the largest program the driver compiles, is built
/// by a thread of its own, once, and until it is there its dispatches are left out as those of
/// any late compute pipeline. Built in the call, a retail title's render thread stood in the
/// driver's compiler for it (1.1 MB of DXIL) and every other thread that dispatched it stood
/// behind `build_whole`: no frame for over two minutes after its first world frame.
/// (`pso_async::cs_goes_on`): the whole form, the largest program the driver compiles, is queued
/// onto the single `xcl-pso-whole` worker, once, and until it is there its dispatches are left out
/// as those of any late compute pipeline. Built in the call, a retail title's render thread stood
/// in the driver's compiler for it (1.1 MB of DXIL) and every other thread that dispatched it
/// stood behind `build_whole`: no frame for over two minutes after its first world frame.
pub(in crate::hle::d3d12x) unsafe fn whole_ready(pso: usize) -> Result<Whole, String> {
let chain = CHAINS.lock().unwrap().get(&pso).cloned();
let Some(chain) = chain else { return Ok(Whole::Plain) };
if let Some(p) = chain.whole.get() {
return Ok(Whole::Ready(p.clone()));
}
if !super::super::pso_async::cs_goes_on() {
return chain.whole().map(Whole::Ready);
return chain.whole(true).map(Whole::Ready);
}
if !chain.whole_sent.swap(true, Ordering::AcqRel) {
let job = ChainRef(chain.clone());
// (named as the pipeline workers: a huge compile takes its turn at the gate)
let spawned = std::thread::Builder::new().name("xcl-pso-whole".into()).stack_size(64 << 20).spawn(move || {
let queued = enqueue_whole(Box::new(move || {
let job = job;
if let Err(e) = unsafe { job.0.whole() } {
if let Err(e) = unsafe { job.0.whole(false) } {
crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its indirect dispatches stay left out");
}
});
if spawned.is_err() {
}));
if !queued {
chain.whole_sent.store(false, Ordering::Release);
return chain.whole().map(Whole::Ready);
return chain.whole(true).map(Whole::Ready);
}
}
Ok(Whole::Late)
Expand Down Expand Up @@ -299,7 +327,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList,
let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1));
let slabs = pso::dispatch_slabs(grid, most);
let Some((scratch, used)) = scratch else {
bind(list, &chain.whole()?);
bind(list, &chain.whole(true)?);
list.Dispatch(x, y, z);
return Ok(());
};
Expand Down Expand Up @@ -363,4 +391,54 @@ mod tests {
assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true));
assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true));
}

#[test]
fn whole_worker_runs_all_jobs_on_one_late_thread() {
use std::collections::HashSet;
use std::sync::{mpsc, Arc, Mutex};
use std::thread::ThreadId;

assert!(!super::super::super::pso_async::build_is_late());
let seen = Arc::new(Mutex::new(Vec::<(ThreadId, Option<String>, bool)>::new()));
let (done_tx, done_rx) = mpsc::channel();
const N: usize = 16;
for _ in 0..N {
let seen = seen.clone();
let done_tx = done_tx.clone();
assert!(super::enqueue_whole(Box::new(move || {
let id = std::thread::current().id();
let name = std::thread::current().name().map(str::to_string);
let late = super::super::super::pso_async::build_is_late();
seen.lock().unwrap().push((id, name, late));
let _ = done_tx.send(());
})));
}
for _ in 0..N {
done_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("whole worker job finished");
}
let rows = seen.lock().unwrap();
assert_eq!(rows.len(), N);
let threads: HashSet<ThreadId> = rows.iter().map(|(id, _, _)| *id).collect();
assert_eq!(threads.len(), 1, "expected all whole-PSO jobs to run on a single worker thread");
assert!(rows.iter().all(|(_, name, late)| name.as_deref() == Some("xcl-pso-whole") && *late));
}

#[test]
fn with_late_build_resets_after_return_and_panic() {
use super::super::super::pso_async::{build_is_late, with_late_build};

assert!(!build_is_late());
let inside = with_late_build(build_is_late);
assert!(inside);
assert!(!build_is_late());

let panicked = std::panic::catch_unwind(|| {
with_late_build(|| {
assert!(build_is_late());
panic!("unwind check");
});
});
assert!(panicked.is_err());
assert!(!build_is_late());
}
}
Loading