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
219 changes: 218 additions & 1 deletion d3d12/crates/leonida-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,152 @@ fn one_call() -> Option<MutexGuard<'static, ()>> {
.then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner()))
}

/// Whether driver `Create*PipelineState` calls are serialized under a mutex.
/// Defaults to `true` on AMD (`VendorId == 0x1002`), where concurrent pipeline
/// creation across worker threads triggers `0xc0000005` / `0x887A0020` inside
/// `amdxc64.dll` while keeping DXIL shader translation parallel across workers;
/// defaults to `false` on other vendors. Overridable via
/// `LEONIDA_PIPELINE_CREATE_LOCK=0|1`.
fn should_serialize_create(env: Option<&str>, vendor_id: Option<u32>) -> bool {
const AMD: u32 = 0x1002;
match env {
Some("0") => false,
Some("1") => true,
_ => vendor_id == Some(AMD),
}
}

/// Priority for [`CreateGate`], ordered from most urgent (`0`) to least (`3`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(usize)]
pub(super) enum CreatePriority {
Screen = 0,
Requested = 1,
Early = 2,
Slow = 3,
}

#[derive(Default)]
struct GateState {
busy: bool,
waiting: [usize; 4],
}

/// Priority-ordered mutex around driver `Create*PipelineState` calls so active
/// `Screen` / `Requested` draws never sit in line behind queued background
/// `Early` or `Slow` precompiles.
struct CreateGate {
state: Mutex<GateState>,
ready: std::sync::Condvar,
}

impl CreateGate {
const fn new() -> Self {
Self { state: Mutex::new(GateState { busy: false, waiting: [0; 4] }), ready: std::sync::Condvar::new() }
}

fn lock(&self, priority: CreatePriority) -> CreateGuard<'_> {
let p = priority as usize;
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
state.waiting[p] += 1;
while state.busy || state.waiting[..p].iter().any(|&n| n > 0) {
state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner());
}
state.waiting[p] -= 1;
state.busy = true;
CreateGuard(self)
}

fn is_busy(&self) -> bool {
self.state.lock().unwrap_or_else(|e| e.into_inner()).busy
}
}

pub(super) struct CreateGuard<'a>(&'a CreateGate);

impl Drop for CreateGuard<'_> {
fn drop(&mut self) {
{
let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner());
state.busy = false;
self.0.ready.notify_all();
}
if std::ptr::eq(self.0, &CREATING) {
super::make::notify_create_idle();
}
}
}

std::thread_local! {
static CURRENT_PRIORITY: std::cell::Cell<CreatePriority> =
const { std::cell::Cell::new(CreatePriority::Requested) };
}

pub(super) struct PriorityReset(CreatePriority);

impl Drop for PriorityReset {
fn drop(&mut self) {
CURRENT_PRIORITY.set(self.0);
}
}

/// Sets the [`CreatePriority`] for driver pipeline creation on the current
/// thread until the returned guard drops.
pub(super) fn with_create_priority(priority: CreatePriority) -> PriorityReset {
let prev = CURRENT_PRIORITY.replace(priority);
PriorityReset(prev)
}

static CREATING: CreateGate = CreateGate::new();

/// Whether driver `Create*PipelineState` calls are serialized on this adapter.
pub(super) fn create_is_serialized() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
let env = std::env::var("LEONIDA_PIPELINE_CREATE_LOCK").ok();
let vendor = crate::host::host().and_then(|h| h.adapter_vendor_id());
let on = should_serialize_create(env.as_deref(), vendor);
if on {
tracing::info!(
vendor = ?vendor.map(|v| format!("{v:#x}")),
"serializing host pipeline state creation (LEONIDA_PIPELINE_CREATE_LOCK)"
);
}
on
})
}

/// Test-only helper that holds [`CREATING`] directly without requiring a D3D12
/// host or AMD adapter.
#[cfg(test)]
pub(super) fn test_hold_create_gate() -> CreateGuard<'static> {
CREATING.lock(CreatePriority::Screen)
}

/// Whether a driver `Create*PipelineState` call is currently in progress
/// under the serialization gate.
///
/// `CREATING` is only ever locked when [`create_is_serialized`] is true (or by
/// `test_hold_create_gate`), so checking it directly avoids calling
/// `crate::host::host()` while callers hold `QUEUE`.
pub(super) fn create_busy() -> bool {
CREATING.is_busy()
}

fn acquire_create_lock<'a>(
enabled: bool,
gate: &'a CreateGate,
priority: CreatePriority,
) -> Option<CreateGuard<'a>> {
enabled.then(|| gate.lock(priority))
}

/// Held around driver `Create*PipelineState` calls when
/// [`should_serialize_create`] is enabled.
fn create_lock() -> Option<CreateGuard<'static>> {
acquire_create_lock(create_is_serialized(), &CREATING, CURRENT_PRIORITY.get())
}

const LIBRARY_FILE: &str = "host-pipelines.bin";
/// A saved library that could not replace [`LIBRARY_FILE`] while this run
/// had it mapped (a system that refuses to replace a mapped file): the next
Expand Down Expand Up @@ -577,6 +723,7 @@ pub(crate) fn pipeline(
create: impl FnOnce() -> windows::core::Result<ID3D12PipelineState>,
) -> windows::core::Result<ID3D12PipelineState> {
let Some((name, library)) = name.and_then(|name| library().map(|library| (name, library))) else {
let _create = create_lock();
MADE.fetch_add(1, Ordering::Relaxed);
return create();
};
Expand All @@ -603,8 +750,11 @@ pub(crate) fn pipeline(
}
Err(e) => e,
};
// Compiled outside any lock: compiles take up to seconds.
// Compiled outside the library lock (compiles take up to seconds), but
// serialized under `create_lock()` on AMD where concurrent driver PSO
// creation crashes `amdxc64.dll`.
let pso = {
let _create = create_lock();
let _call = call("make", name);
create()?
};
Expand Down Expand Up @@ -1049,4 +1199,71 @@ mod tests {
assert_eq!(final_bytes.len(), 4096);
assert!(final_bytes.iter().all(|&b| b == final_bytes[0]));
}

#[test]
fn create_lock_policy_defaults_on_for_amd_and_respects_override() {
const AMD: u32 = 0x1002;
const NVIDIA: u32 = 0x10DE;
const INTEL: u32 = 0x8086;
assert!(should_serialize_create(None, Some(AMD)));
assert!(!should_serialize_create(None, Some(NVIDIA)));
assert!(!should_serialize_create(None, Some(INTEL)));
assert!(!should_serialize_create(None, None));
assert!(!should_serialize_create(Some("0"), Some(AMD)));
assert!(should_serialize_create(Some("1"), Some(NVIDIA)));
assert!(should_serialize_create(Some("1"), None));
}

#[test]
fn create_lock_serializes_concurrent_creators() {
static TEST_GATE: CreateGate = CreateGate::new();
let in_flight = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let max_in_flight = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
std::thread::scope(|s| {
for i in 0..8 {
let in_flight = in_flight.clone();
let max_in_flight = max_in_flight.clone();
let pri = [CreatePriority::Screen, CreatePriority::Requested, CreatePriority::Early, CreatePriority::Slow][i % 4];
s.spawn(move || {
for _ in 0..50 {
let _guard = acquire_create_lock(true, &TEST_GATE, pri);
assert!(_guard.is_some());
let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
max_in_flight.fetch_max(now, Ordering::SeqCst);
std::thread::yield_now();
in_flight.fetch_sub(1, Ordering::SeqCst);
}
});
}
});
assert_eq!(max_in_flight.load(Ordering::SeqCst), 1);
assert!(acquire_create_lock(false, &TEST_GATE, CreatePriority::Requested).is_none());
}

#[test]
fn create_lock_grants_screen_and_requested_before_early_and_slow() {
static PRI_GATE: CreateGate = CreateGate::new();
let order = std::sync::Arc::new(Mutex::new(Vec::new()));
// Hold the gate while queuing waiters of every priority.
let holder = PRI_GATE.lock(CreatePriority::Slow);
std::thread::scope(|s| {
let spawn_waiter = |label: &'static str, pri: CreatePriority| {
let order = order.clone();
s.spawn(move || {
let _g = PRI_GATE.lock(pri);
order.lock().unwrap().push(label);
});
};
spawn_waiter("slow", CreatePriority::Slow);
spawn_waiter("early", CreatePriority::Early);
spawn_waiter("requested", CreatePriority::Requested);
spawn_waiter("screen", CreatePriority::Screen);
// Wait until all 4 threads are parked on the gate before releasing.
while PRI_GATE.state.lock().unwrap().waiting.iter().sum::<usize>() < 4 {
std::thread::yield_now();
}
drop(holder);
});
assert_eq!(*order.lock().unwrap(), ["screen", "requested", "early", "slow"]);
}
}
69 changes: 67 additions & 2 deletions d3d12/crates/leonida-gpu/src/pipeline/make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,19 @@ impl Pending {
}

fn make(&self) {
// `queue_state` is already set to `MAKING` by `Queue::pop`, so check `used`
// (set by `ready` / `made_or_start`) to distinguish draw-requested from
// speculative `early` compiles.
let priority = if self.screen {
super::library::CreatePriority::Screen
} else if self.used.load(Ordering::Relaxed) {
super::library::CreatePriority::Requested
} else if self.was_slow.load(Ordering::Relaxed) {
super::library::CreatePriority::Slow
} else {
super::library::CreatePriority::Early
};
let _pri = super::library::with_create_priority(priority);
self.make_with(|| {
let began = Instant::now();
let made = HostPipeline::new(&self.shaders, self.graphics.as_deref());
Expand Down Expand Up @@ -691,15 +704,22 @@ impl Queue {
true
}

#[cfg(test)]
fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> {
self.pop_with(screens_only, slow_limit, false)
}

fn pop_with(&mut self, screens_only: bool, slow_limit: usize, slow_blocked: bool) -> Option<Arc<Pending>> {
// An early entry can have been promoted and claimed already.
let unclaimed = |list: &mut VecDeque<Arc<Pending>>| {
std::iter::from_fn(|| list.pop_front()).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
};
let mut p = self.screen.pop_front();
if p.is_none() && !screens_only {
p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early));
if p.is_none() && self.slow_now < slow_limit {
// When driver creation is serialized, avoid starting speculative
// multi-second `slow` compiles while another create call holds the gate.
if p.is_none() && self.slow_now < slow_limit && !slow_blocked {
p = unclaimed(&mut self.slow);
if let Some(p) = &p {
p.was_slow.store(true, Ordering::Relaxed);
Expand Down Expand Up @@ -742,10 +762,20 @@ fn start(p: &Arc<Pending>, priority: u8) {
/// Workers that make passes over the screen alone, besides the others.
const SCREEN_WORKERS: usize = 2;

/// Wakes workers parked on a deferred `slow` queue when a driver
/// `Create*PipelineState` call releases the serialization gate (including
/// synchronous creates run on a draw thread).
pub(super) fn notify_create_idle() {
let queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
if !queue.slow.is_empty() {
AVAILABLE.notify_all();
}
}

fn next(screens_only: bool) -> Arc<Pending> {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(p) = queue.pop(screens_only, slow_limit()) {
if let Some(p) = queue.pop_with(screens_only, slow_limit(), super::library::create_busy()) {
return p;
}
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
Expand Down Expand Up @@ -972,10 +1002,45 @@ mod tests {
assert!(!asked.was_slow.load(Ordering::Relaxed));
assert!(queue.pop(false, 1).is_none());
queue.slow_now -= 1;
assert!(queue.pop_with(false, 1, true).is_none(), "slow_blocked defers speculative slow compiles");
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &longer));
assert!(queue.pop(false, 1).is_none());
}

/// While another thread (including a synchronous draw-thread create) holds
/// the driver creation gate, workers parked in `next()` defer speculative
/// `slow` work and wake as soon as the gate guard drops.
#[test]
fn next_defers_slow_while_create_gate_held_and_wakes_on_release() {
assert!(workers());
let slow = Arc::new(Pending::new(Vec::new(), None));
let hold = super::super::library::test_hold_create_gate();
{
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
if queue.push_as(&slow, EARLY, true) == Some(true) {
WAITING.fetch_add(1, Ordering::Relaxed);
AVAILABLE.notify_all();
}
}
std::thread::sleep(Duration::from_millis(50));
assert_eq!(
slow.queue_state.load(Ordering::Relaxed),
EARLY,
"workers must defer slow work while the create gate is held"
);
assert!(slow.made.get().is_none());
// Releasing the gate directly (as a draw thread does) must wake a worker.
drop(hold);
let started = Instant::now();
while slow.made.get().is_none() && started.elapsed() < Duration::from_secs(2) {
std::thread::yield_now();
}
assert!(
matches!(slow.made.get(), Some(None)),
"releasing the create gate must wake a worker parked on slow work"
);
}

/// Passes over the screen go before all others, and workers of their own
/// take nothing else.
#[test]
Expand Down
5 changes: 3 additions & 2 deletions d3d12/docs/switches.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is **
settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first,
and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.

673 names; 633 have a sentence of a comment below, the others no comment or only a bare list.
674 names; 634 have a sentence of a comment below, the others no comment or only a bare list.

- **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a
switch read some other way; its default is not given here.
Expand Down Expand Up @@ -406,6 +406,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.
| `LEONIDA_PICKED_MB` | see the code | | | | `leonida-gpu/picked.rs` | Bytes looked at in turn per frame (`LEONIDA_PICKED_MB`). |
| `LEONIDA_PICKED_WRITES` | see the code | yes | | yes | `leonida-gpu/picked.rs` | Buffers shaders write through views they pick from the heap by an index they compute (`LEONIDA_PICKED_WRITES`; on, stage 1, by default: [`stage`]). |
| `LEONIDA_PIPELINE_AWAIT_FIRST` | see the code | | | | `leonida-gpu/pipeline/make.rs` | `LEONIDA_PIPELINE_AWAIT_FIRST=0`: in the order asked, as before. |
| `LEONIDA_PIPELINE_CREATE_LOCK` | see the code | | | | `leonida-gpu/pipeline/library.rs` | ...ers; defaults to `false` on other vendors. Overridable via `LEONIDA_PIPELINE_CREATE_LOCK=0\|1`.... |
| `LEONIDA_PIPELINE_LOWEST` | see the code | | | | `leonida-gpu/pipeline/make.rs` | Below the title's own threads (loading, recording), and the streaming one, which is below normal itself (`LEONIDA_PIPELINE_LOWEST=0`: level with it, as before). |
| `LEONIDA_PIPELINE_PANIC_CATCH` | see the code | | | | `leonida-gpu/pipeline/make.rs` | `LEONIDA_PIPELINE_PANIC_CATCH=0`: the panic goes on, as before. |
| `LEONIDA_PIPELINE_SLOW` | see the code | | | | `leonida-gpu/pipeline/make.rs` | `LEONIDA_PIPELINE_SLOW=0`: in the order the title creates them, as before. |
Expand Down Expand Up @@ -470,6 +471,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.
| `LEONIDA_REMAP_BOOST` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the thread that changes a mapping runs at the highest priority while it holds title memory still (`LEONIDA_REMAP_BOOST=0`: at its own). |
| `LEONIDA_REMAP_HISTORY` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | The cursor of the single shared pass with `LEONIDA_REMAP_HISTORY=0` (as before: the heap whose pass runs first takes the ranges). |
| `LEONIDA_REMAP_SPANS` | on, `0` turns it off | yes | | yes | `leonida-gpu/texture.rs` +1 | Whether a read in place that names its range ([`title_memory_reading_range`]) waits only for the changes of mapping that touch that range (`LEONIDA_REMAP_SPANS=0`: for every change, as before; `LEONIDA_AB` can name it).... |
| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-gpu/host/menu.rs` +2 | |
| `LEONIDA_REPLAY_GBV` | see the code | | | | `leonida-gpu/replay/play.rs` | |
| `LEONIDA_REPLAY_PEEK` | see the code | | | | `leonida-gpu/replay/play/diverge.rs` | |
| `LEONIDA_RETIRE_QUEUES` | on, `0` turns it off | yes | | yes | `leonida-gpu/host.rs` | `LEONIDA_RETIRE_QUEUES=0`: every thread takes the first, as before. |
Expand Down Expand Up @@ -677,7 +679,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.
| `LEONIDA_PATCH_CLZERO` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_CLZERO=0` emulates each time, as before. |
| `LEONIDA_PATCH_WAITS` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_WAITS=0` emulates each time, as before. |
| `LEONIDA_PROFILE_ONLY` | see the code | | | yes | `leonida-loader/profile.rs` | `LEONIDA_PROFILE_ONLY=&lt;name&gt;[,&lt;name&gt;..]` samples only the threads whose name or start (`module+rva`) holds one of them, which makes the rounds short. |
| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-loader/hooks.rs` +1 | |
| `LEONIDA_SIM_MAX_STEP_MS` | see the code | | | | `leonida-loader/hooks.rs` +1 | The ceiling `LEONIDA_SIM_MAX_STEP_MS` asks for: `Some(None)` for the title's own, `None` if not one of them. |
| `LEONIDA_STACKS` | see the code | | | | `leonida-loader/profile.rs` +1 | `LEONIDA_STACKS=&lt;seconds&gt;[,&lt;seconds&gt;...]` prints each thread's unwound stack as `module+rva` that many seconds after [`dump_stacks_on_schedule`], to find what a title waits on. |

Expand Down
Loading