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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,11 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
On AMD, cold 128–256 KiB compute pipelines use a separate lane (three background / four
wanted at once on hosts with at least 32 GiB RAM, two / three below that), configurable with
`XCL_MEDIUM_PSO_CONCURRENCY` and `XCL_MEDIUM_PSO_WANTED_CONCURRENCY`.
While a background worker waits at one of these gates for a slot, a helper thread serves its
queue so the other pipelines go on being built: at most `XCL_HUGE_PSO_HANDOFFS` helpers at once
(default twice the shader compile threads, never fewer than them, at most 512), each started
only with 3 GB of commit free. Each helper builds pipelines too, so a higher value uses more
memory.
- A loop in a translated compute program run by a Dispatch (not ExecuteIndirect) is ended
after its dispatch's share of passes for each entry (between 1024 and 65 536 a thread, fewer the
more threads the dispatch has; the direct DXIL translator ends the thread's program there), so
Expand Down
246 changes: 224 additions & 22 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3192,6 +3192,8 @@ struct Stats {
built: usize,
ahead: usize,
huge: usize,
/// helpers started for workers parked at a driver-compile gate (`parked_for_big_compile`)
handed_off: usize,
/// translated ahead (`Backlog`), still in the backlog
warmed: usize,
backlog: usize,
Expand All @@ -3207,6 +3209,7 @@ fn stats() -> Stats {
built: l(&LAZY_BUILT),
ahead: l(&LAZY_AHEAD),
huge: l(&LAZY_HUGE),
handed_off: l(&HANDED_OFF),
warmed: l(&WARMED),
backlog: l(&BACKLOG),
waits: crate::hle::api_cost::totals()[crate::hle::api_cost::Call::PipelineWait as usize],
Expand All @@ -3222,12 +3225,13 @@ fn stats_line(now: &Stats, last: &Stats, huge_kb: usize) -> Option<String> {
return None;
}
Some(format!(
"D3D12.X: lazy pipelines: {} made ({} graphics), {} built ({} before their first use, {} with {huge_kb} KB of DXIL or more), {} translated ahead, {} in the build-ahead backlog; binds waited {} ms for pipelines being built ({} waits in 2 s)",
"D3D12.X: lazy pipelines: {} made ({} graphics), {} built ({} before their first use, {} with {huge_kb} KB of DXIL or more), {} workers handed off at the compile gate, {} translated ahead, {} in the build-ahead backlog; binds waited {} ms for pipelines being built ({} waits in 2 s)",
now.made,
now.graphics,
now.built,
now.ahead,
now.huge,
now.handed_off,
now.warmed,
now.backlog,
(now.waits.1 - last.waits.1) / 1000,
Expand Down Expand Up @@ -4021,33 +4025,85 @@ fn start_normal_workers() -> bool {
static PARKED_NORMAL: AtomicUsize = AtomicUsize::new(0);
static NORMAL_HELPERS: AtomicUsize = AtomicUsize::new(0);
static NORMAL_HELPERS_STARTED: AtomicUsize = AtomicUsize::new(0);
/// helpers started for normal workers parked at a driver-compile gate (huge, giant or AMD
/// medium compute; `parked_for_big_compile`; the pipeline line)
static HANDED_OFF: AtomicUsize = AtomicUsize::new(0);

/// Replacements at most for normal workers parked at the driver-compile gate
/// (`XCL_HUGE_PSO_HANDOFFS`, default twice the normal workers; never fewer than the normal
/// workers). With no more of them than normal workers, the replacements took huge builds too and
/// parked behind the same slot: on an RTX 3080 every worker and helper stood at the gate (21 huge
/// compiles of 667 KB – 1.08 MB DXIL, each waiting 90 – 213 s for 4 – 21 s in the driver) while
/// 1 000+ other pipelines stayed queued and the title drew nothing with them. Each helper builds
/// too and so takes memory: a default of 64 ran a machine out of RAM in game.
fn handoff_most() -> usize {
static V: OnceLock<usize> = OnceLock::new();
*V.get_or_init(|| handoff_most_of(std::env::var("XCL_HUGE_PSO_HANDOFFS").ok().as_deref(), crate::gpu::recomp::dxc::compile_threads()))
}

fn handoff_most_of(v: Option<&str>, workers: usize) -> usize {
let default = 2 * workers;
v.and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(default).clamp(workers, 512.max(workers))
}

/// Commit a helper is started with at least: the floor a huge compile waits for at the gate
/// (`real::big_compile_headroom`).
const HELPER_COMMIT_HEADROOM: u64 = 3 << 30;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HELPER_COMMIT_HEADROOM is documented as the floor a huge compile waits for, but huge_compile_turn uses headroom_for(bytes, late), which halves it to 1.5 GB for late builds. With 1.5-3 GB of commit left, late builds pass the gate and wanted builds bypass commit, yet top_up refuses every helper. Workers parked on slot contention get no replacement, so the queue stalls while the gate itself would let builds proceed. Both should come from the same headroom_for source.


/// A normal pipeline worker is about to wait for a huge driver-compile slot. A bounded helper
/// serves its queue until workers return; calls from title and preload threads do nothing.
fn helper_commit_free() -> bool {
super::real::big_compile_commit_free(HELPER_COMMIT_HEADROOM)
}

/// A normal pipeline worker is about to wait for a driver-compile slot: the build stays on this
/// thread (its driver call is made of what the thread holds) and waits there, and a helper takes
/// the worker's place in the queue until it returns, so the other builds go on – also when the
/// helpers' own builds park (up to `handoff_most`). A helper is started only while
/// `HELPER_COMMIT_HEADROOM` of commit is free; the waiting build tries again
/// (`ParkedWorker::top_up`). Its result is delivered as any build's. Calls from title and
/// preload threads do nothing.
pub(super) fn parked_for_big_compile() -> ParkedWorker {
park_for_big_compile(handoff_most(), helper_commit_free)
}

fn park_for_big_compile(most: usize, commit_free: fn() -> bool) -> ParkedWorker {
if !NORMAL_WORKER.get() {
return ParkedWorker(false);
}
let parked = PARKED_NORMAL.fetch_add(1, Ordering::AcqRel) + 1;
let most = parked.min(crate::gpu::recomp::dxc::compile_threads());
let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire);
while helpers < most {
match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => {
spawn_normal_helper(helpers);
break;
return ParkedWorker(None);
}
PARKED_NORMAL.fetch_add(1, Ordering::AcqRel);
let parked = ParkedWorker(Some((most, commit_free)));
parked.top_up();
parked
}

pub(super) struct ParkedWorker(Option<(usize, fn() -> bool)>);

impl ParkedWorker {
/// Start a helper if fewer serve the queue than workers are parked (at most `handoff_most`)
/// and commit allows it.
pub(super) fn top_up(&self) {
let Some((most, commit_free)) = self.0 else { return };
let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire);
while may_add_helper(helpers, PARKED_NORMAL.load(Ordering::Acquire), most, commit_free) {
match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => {
spawn_normal_helper(helpers);
return;
}
Err(now) => helpers = now,
}
Err(now) => helpers = now,
}
}
ParkedWorker(true)
}

pub(super) struct ParkedWorker(bool);
/// Whether one more helper may start: fewer than the parked workers and than `most`, and
/// commit free (asked last).
fn may_add_helper(helpers: usize, parked: usize, most: usize, commit_free: impl Fn() -> bool) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Helpers now start only with 3 GB of commit free (may_add_helper && commit_free()), which removes the old guarantee that every parked normal worker gets a replacement. With less than 3 GB of commit left (e.g. 16 GB RAM, small pagefile), every normal worker takes a huge/medium build and parks in big_compile_turn, unwanted builds also wait on commit_free, and top_up refuses a helper on every look. Nothing serves the Foreground/BoundSoon queue, so small pipelines that need no gate or headroom stand still until commit frees up. That's the freeze this PR describes. The PR also notes the commit check didn't prevent the RAM exhaustion it saw, so this check protects little and disables the fix exactly where commit is tight.

helpers < parked.min(most) && commit_free()
}

impl Drop for ParkedWorker {
fn drop(&mut self) {
if self.0 {
if self.0.is_some() {
PARKED_NORMAL.fetch_sub(1, Ordering::AcqRel);
}
}
Expand All @@ -4072,6 +4128,8 @@ fn spawn_normal_helper(k: usize) {
});
if spawned.is_err() {
NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel);
} else {
HANDED_OFF.fetch_add(1, Ordering::Relaxed);
}
}

Expand Down Expand Up @@ -10108,7 +10166,10 @@ mod used_tests {
fn graphics_first_use_carries_the_exact_serialized_recipe_identity() {
let standin = 0x7E57_7013usize;
let payload = b"canonical graphics recipe".to_vec();
submit_lazy(standin, false, Box::new(|| 0x4332), 0x5EED_0013);
// (the job builds no pipeline: the test releases its stand-in without waiting for the
// build, and a build-ahead worker that has the job then finishes an orphan, whose
// pipeline `complete` releases as a COM object - a fake one crashed the test binary)
submit_lazy(standin, false, Box::new(|| 0), 0x5EED_0013);
on_first_use_graphics(standin, payload.clone());
let pending = entry(standin).unwrap();
assert_eq!(pending.manifest_recipe.load(Ordering::Acquire), super::super::gfx_records::payload_key(&payload));
Expand All @@ -10134,7 +10195,7 @@ mod used_tests {
}

let outside = parked_for_big_compile();
assert!(!outside.0, "a title/test thread must not start a replacement");
assert!(outside.0.is_none(), "a title/test thread must not start a replacement");
drop(outside);

start_normal_workers();
Expand All @@ -10145,7 +10206,8 @@ mod used_tests {
for _ in 0..n {
let (tx, gate) = (started_tx.clone(), gate.clone());
queue().submit(Priority::Foreground, Box::new(move || {
let _parked = parked_for_big_compile();
// (commit taken as free: this test is about the queue, not the machine's commit)
let _parked = park_for_big_compile(handoff_most(), || true);
tx.send(()).unwrap();
let mut open = gate.0.lock().unwrap();
while !*open {
Expand All @@ -10170,6 +10232,146 @@ mod used_tests {
assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired");
}

/// The helpers' own builds park at the gate too: with as many parked builds as twice the
/// normal workers (each worker's and each first helper's), the queue is still served – the
/// replacements were bounded by the normal workers, and every one of them stood at the gate.
#[test]
fn helpers_parked_at_the_gate_are_replaced_too() {
let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner());
use std::time::{Duration, Instant};

struct OpenGate(Arc<(Mutex<bool>, Condvar)>);
impl Drop for OpenGate {
fn drop(&mut self) {
*self.0 .0.lock().unwrap() = true;
self.0 .1.notify_all();
}
}

start_normal_workers();
let n = crate::gpu::recomp::dxc::compile_threads();
let parking = 2 * n;
// (the bound is passed: `XCL_HUGE_PSO_HANDOFFS` in the environment does not change the test)
let handed_off = HANDED_OFF.load(Ordering::Relaxed);
let (started_tx, started_rx) = mpsc::channel();
let gate = Arc::new((Mutex::new(false), Condvar::new()));
let open = OpenGate(gate.clone());
for _ in 0..parking {
let (tx, gate) = (started_tx.clone(), gate.clone());
queue().submit(Priority::Foreground, Box::new(move || {
// (commit taken as free: this test is about the queue, not the machine's commit)
let _parked = park_for_big_compile(parking, || true);
tx.send(()).unwrap();
let mut open = gate.0.lock().unwrap();
while !*open {
open = gate.1.wait(open).unwrap();
}
})).unwrap();
}
for _ in 0..parking {
started_rx.recv_timeout(Duration::from_secs(10)).expect("every parked build started: a helper took each one's place");
}
let (ran_tx, ran_rx) = mpsc::channel();
queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap();
ran_rx.recv_timeout(Duration::from_secs(10)).expect("a build behind the parked ones ran");
assert!(HANDED_OFF.load(Ordering::Relaxed) >= handed_off + parking, "each parked build is counted as handed off");
drop(open);

let deadline = Instant::now() + Duration::from_secs(10);
while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(PARKED_NORMAL.load(Ordering::Acquire), 0);
assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired");
}

#[test]
fn the_handoff_bound_is_never_below_the_workers() {
assert_eq!(handoff_most_of(None, 15), 30, "twice the normal workers");
assert_eq!(handoff_most_of(None, 40), 80);
assert_eq!(handoff_most_of(Some(" 100 "), 15), 100);
assert_eq!(handoff_most_of(Some("2"), 15), 15, "never fewer than the normal workers");
assert_eq!(handoff_most_of(Some("lots"), 15), 30);
assert_eq!(handoff_most_of(Some("100000"), 15), 512);
}

/// A helper starts only below the parked workers, below the bound, and with commit free;
/// commit is not asked when the count already says no.
#[test]
fn a_helper_starts_only_under_the_bound_and_with_commit_free() {
assert!(may_add_helper(0, 1, 4, || true));
assert!(!may_add_helper(1, 1, 4, || true), "one helper per parked worker");
assert!(!may_add_helper(4, 9, 4, || true), "more parked than the bound: no further helper");
assert!(!may_add_helper(0, 1, 4, || false), "no commit headroom: no helper");
assert!(!may_add_helper(4, 9, 4, || panic!("commit asked although the bound is reached")));
}

/// A worker parked at the gate with no commit headroom starts no helper; with a bound of 1
/// (fewer than the 2 parked workers) exactly one starts, and the queue is still served. (Only
/// one or two workers park: with every normal worker parked and no helper, the queue other
/// tests use would stand still meanwhile and their builds go to the build-ahead workers.)
#[test]
fn parked_workers_start_no_helper_without_commit_and_none_past_the_bound() {
let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner());
use std::time::{Duration, Instant};

struct OpenGate(Arc<(Mutex<bool>, Condvar)>);
impl Drop for OpenGate {
fn drop(&mut self) {
*self.0 .0.lock().unwrap() = true;
self.0 .1.notify_all();
}
}
fn retired() -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
PARKED_NORMAL.load(Ordering::Acquire) == 0 && NORMAL_HELPERS.load(Ordering::Acquire) == 0
}
fn no_commit() -> bool {
false
}
fn commit() -> bool {
true
}

start_normal_workers();
assert!(retired(), "no helper left over from another test");
// (parked workers, bound, commit, helpers then)
let cases: [(usize, usize, fn() -> bool, usize); 2] = [(1, handoff_most(), no_commit, 0), (2, 1, commit, 1)];
for (n, most, commit_free, helpers) in cases {
let handed_off = HANDED_OFF.load(Ordering::Relaxed);
let (started_tx, started_rx) = mpsc::channel();
let gate = Arc::new((Mutex::new(false), Condvar::new()));
let open = OpenGate(gate.clone());
for _ in 0..n {
let (tx, gate) = (started_tx.clone(), gate.clone());
queue().submit(Priority::Foreground, Box::new(move || {
let _parked = park_for_big_compile(most, commit_free);
tx.send(()).unwrap();
let mut open = gate.0.lock().unwrap();
while !*open {
open = gate.1.wait(open).unwrap();
}
})).unwrap();
}
for _ in 0..n {
started_rx.recv_timeout(Duration::from_secs(10)).expect("every worker parked");
}
assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), helpers, "helpers with bound {most}");
assert_eq!(HANDED_OFF.load(Ordering::Relaxed) - handed_off, helpers, "only a started helper counts as a handoff");
// (with 2 normal workers or more one of them or the helper is still free)
if helpers > 0 && crate::gpu::recomp::dxc::compile_threads() >= 2 {
let (ran_tx, ran_rx) = mpsc::channel();
queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap();
ran_rx.recv_timeout(Duration::from_secs(10)).expect("the queue is still served");
}
drop(open);
assert!(retired(), "parked workers returned and helpers retired");
}
}

/// A queued normal worker job whose stand-in was released before a worker starts it is
/// skipped as orphaned instead of entering the compiler.
#[test]
Expand Down Expand Up @@ -10305,11 +10507,11 @@ mod used_tests {
/// The line is written when a count changed, with the waits of its 2 s only.
#[test]
fn the_pipeline_line_comes_when_a_count_changed() {
let last = Stats { made: 10, graphics: 8, built: 2, ahead: 1, huge: 0, warmed: 4, backlog: 6, waits: (3, 4_000_000) };
let last = Stats { made: 10, graphics: 8, built: 2, ahead: 1, huge: 0, handed_off: 7, warmed: 4, backlog: 6, waits: (3, 4_000_000) };
assert_eq!(stats_line(&last, &last, 256), None);
let now = Stats { built: 3, waits: (5, 6_500_000), ..last };
let line = stats_line(&now, &last, 256).unwrap();
assert!(line.contains("10 made (8 graphics), 3 built (1 before their first use, 0 with 256 KB of DXIL or more), 4 translated ahead, 6 in the build-ahead backlog"), "{line}");
assert!(line.contains("10 made (8 graphics), 3 built (1 before their first use, 0 with 256 KB of DXIL or more), 7 workers handed off at the compile gate, 4 translated ahead, 6 in the build-ahead backlog"), "{line}");
assert!(line.contains("waited 2500 ms for pipelines being built (2 waits in 2 s)"), "{line}");
}

Expand Down
Loading
Loading